Skip to main content

rustc_interface/
interface.rs

1use std::path::PathBuf;
2use std::result;
3use std::sync::Arc;
4
5use rustc_ast::{LitKind, MetaItemKind, token};
6use rustc_codegen_ssa::traits::CodegenBackend;
7use rustc_data_structures::fx::{FxHashMap, FxHashSet};
8use rustc_data_structures::jobserver::{self, Proxy};
9use rustc_data_structures::stable_hasher::StableHasher;
10use rustc_errors::{DiagCtxtHandle, ErrorGuaranteed};
11use rustc_lint::LintStore;
12use rustc_middle::ty;
13use rustc_middle::ty::CurrentGcx;
14use rustc_middle::util::Providers;
15use rustc_parse::lexer::StripTokens;
16use rustc_parse::new_parser_from_source_str;
17use rustc_parse::parser::Recovery;
18use rustc_parse::parser::attr::AllowLeadingUnsafe;
19use rustc_query_impl::QueryCtxt;
20use rustc_query_system::query::print_query_stack;
21use rustc_session::config::{self, Cfg, CheckCfg, ExpectedValues, Input, OutFileName};
22use rustc_session::parse::ParseSess;
23use rustc_session::{CompilerIO, EarlyDiagCtxt, Session, lint};
24use rustc_span::source_map::{FileLoader, RealFileLoader, SourceMapInputs};
25use rustc_span::{FileName, sym};
26use rustc_target::spec::Target;
27use tracing::trace;
28
29use crate::util;
30
31pub type Result<T> = result::Result<T, ErrorGuaranteed>;
32
33/// Represents a compiler session. Note that every `Compiler` contains a
34/// `Session`, but `Compiler` also contains some things that cannot be in
35/// `Session`, due to `Session` being in a crate that has many fewer
36/// dependencies than this crate.
37///
38/// Can be used to run `rustc_interface` queries.
39/// Created by passing [`Config`] to [`run_compiler`].
40pub struct Compiler {
41    pub sess: Session,
42    pub codegen_backend: Box<dyn CodegenBackend>,
43    pub(crate) override_queries: Option<fn(&Session, &mut Providers)>,
44
45    /// A reference to the current `GlobalCtxt` which we pass on to `GlobalCtxt`.
46    pub(crate) current_gcx: CurrentGcx,
47
48    /// A jobserver reference which we pass on to `GlobalCtxt`.
49    pub(crate) jobserver_proxy: Arc<Proxy>,
50}
51
52/// Converts strings provided as `--cfg [cfgspec]` into a `Cfg`.
53pub(crate) fn parse_cfg(dcx: DiagCtxtHandle<'_>, cfgs: Vec<String>) -> Cfg {
54    cfgs.into_iter()
55        .map(|s| {
56            let psess = ParseSess::emitter_with_note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this occurred on the command line: `--cfg={0}`",
                s))
    })format!(
57                "this occurred on the command line: `--cfg={s}`"
58            ));
59            let filename = FileName::cfg_spec_source_code(&s);
60
61            macro_rules! error {
62                ($reason: expr) => {
63                    dcx.fatal(format!("invalid `--cfg` argument: `{s}` ({})", $reason));
64                };
65            }
66
67            match new_parser_from_source_str(&psess, filename, s.to_string(), StripTokens::Nothing)
68            {
69                Ok(mut parser) => {
70                    parser = parser.recovery(Recovery::Forbidden);
71                    match parser.parse_meta_item(AllowLeadingUnsafe::No) {
72                        Ok(meta_item)
73                            if parser.token == token::Eof
74                                && parser.dcx().has_errors().is_none() =>
75                        {
76                            if meta_item.path.segments.len() != 1 {
77                                dcx.fatal(::alloc::__export::must_use({
            ::alloc::fmt::format(format_args!("invalid `--cfg` argument: `{1}` ({0})",
                    "argument key must be an identifier", s))
        }));error!("argument key must be an identifier");
78                            }
79                            match &meta_item.kind {
80                                MetaItemKind::List(..) => {}
81                                MetaItemKind::NameValue(lit) if !lit.kind.is_str() => {
82                                    dcx.fatal(::alloc::__export::must_use({
            ::alloc::fmt::format(format_args!("invalid `--cfg` argument: `{1}` ({0})",
                    "argument value must be a string", s))
        }));error!("argument value must be a string");
83                                }
84                                MetaItemKind::NameValue(..) | MetaItemKind::Word => {
85                                    let ident = meta_item.ident().expect("multi-segment cfg key");
86
87                                    if ident.is_path_segment_keyword() {
88                                        dcx.fatal(::alloc::__export::must_use({
            ::alloc::fmt::format(format_args!("invalid `--cfg` argument: `{1}` ({0})",
                    "malformed `cfg` input, expected a valid identifier", s))
        }));error!(
89                                            "malformed `cfg` input, expected a valid identifier"
90                                        );
91                                    }
92
93                                    return (ident.name, meta_item.value_str());
94                                }
95                            }
96                        }
97                        Ok(..) => {}
98                        Err(err) => err.cancel(),
99                    }
100                }
101                Err(errs) => errs.into_iter().for_each(|err| err.cancel()),
102            };
103
104            // If the user tried to use a key="value" flag, but is missing the quotes, provide
105            // a hint about how to resolve this.
106            if s.contains('=') && !s.contains("=\"") && !s.ends_with('"') {
107                dcx.fatal(::alloc::__export::must_use({
            ::alloc::fmt::format(format_args!("invalid `--cfg` argument: `{1}` ({0})",
                    "expected `key` or `key=\"value\"`, ensure escaping is appropriate for your shell, try \'key=\"value\"\' or key=\\\"value\\\"",
                    s))
        }));error!(concat!(
108                    r#"expected `key` or `key="value"`, ensure escaping is appropriate"#,
109                    r#" for your shell, try 'key="value"' or key=\"value\""#
110                ));
111            } else {
112                dcx.fatal(::alloc::__export::must_use({
            ::alloc::fmt::format(format_args!("invalid `--cfg` argument: `{1}` ({0})",
                    r#"expected `key` or `key="value"`"#, s))
        }));error!(r#"expected `key` or `key="value"`"#);
113            }
114        })
115        .collect::<Cfg>()
116}
117
118/// Converts strings provided as `--check-cfg [specs]` into a `CheckCfg`.
119pub(crate) fn parse_check_cfg(dcx: DiagCtxtHandle<'_>, specs: Vec<String>) -> CheckCfg {
120    // If any --check-cfg is passed then exhaustive_values and exhaustive_names
121    // are enabled by default.
122    let exhaustive_names = !specs.is_empty();
123    let exhaustive_values = !specs.is_empty();
124    let mut check_cfg = CheckCfg { exhaustive_names, exhaustive_values, ..CheckCfg::default() };
125
126    for s in specs {
127        let psess = ParseSess::emitter_with_note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this occurred on the command line: `--check-cfg={0}`",
                s))
    })format!(
128            "this occurred on the command line: `--check-cfg={s}`"
129        ));
130        let filename = FileName::cfg_spec_source_code(&s);
131
132        const VISIT: &str =
133            "visit <https://doc.rust-lang.org/nightly/rustc/check-cfg.html> for more details";
134
135        macro_rules! error {
136            ($reason:expr) => {{
137                let mut diag = dcx.struct_fatal(format!("invalid `--check-cfg` argument: `{s}`"));
138                diag.note($reason);
139                diag.note(VISIT);
140                diag.emit()
141            }};
142            (in $arg:expr, $reason:expr) => {{
143                let mut diag = dcx.struct_fatal(format!("invalid `--check-cfg` argument: `{s}`"));
144
145                let pparg = rustc_ast_pretty::pprust::meta_list_item_to_string($arg);
146                if let Some(lit) = $arg.lit() {
147                    let (lit_kind_article, lit_kind_descr) = {
148                        let lit_kind = lit.as_token_lit().kind;
149                        (lit_kind.article(), lit_kind.descr())
150                    };
151                    diag.note(format!("`{pparg}` is {lit_kind_article} {lit_kind_descr} literal"));
152                } else {
153                    diag.note(format!("`{pparg}` is invalid"));
154                }
155
156                diag.note($reason);
157                diag.note(VISIT);
158                diag.emit()
159            }};
160        }
161
162        let expected_error = || -> ! {
163            {
    let mut diag =
        dcx.struct_fatal(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("invalid `--check-cfg` argument: `{0}`",
                            s))
                }));
    diag.note("expected `cfg(name, values(\"value1\", \"value2\", ... \"valueN\"))`");
    diag.note(VISIT);
    diag.emit()
}error!("expected `cfg(name, values(\"value1\", \"value2\", ... \"valueN\"))`")
164        };
165
166        let mut parser =
167            match new_parser_from_source_str(&psess, filename, s.to_string(), StripTokens::Nothing)
168            {
169                Ok(parser) => parser.recovery(Recovery::Forbidden),
170                Err(errs) => {
171                    errs.into_iter().for_each(|err| err.cancel());
172                    expected_error();
173                }
174            };
175
176        let meta_item = match parser.parse_meta_item(AllowLeadingUnsafe::No) {
177            Ok(meta_item) if parser.token == token::Eof && parser.dcx().has_errors().is_none() => {
178                meta_item
179            }
180            Ok(..) => expected_error(),
181            Err(err) => {
182                err.cancel();
183                expected_error();
184            }
185        };
186
187        let Some(args) = meta_item.meta_item_list() else {
188            expected_error();
189        };
190
191        if !meta_item.has_name(sym::cfg) {
192            expected_error();
193        }
194
195        let mut names = Vec::new();
196        let mut values: FxHashSet<_> = Default::default();
197
198        let mut any_specified = false;
199        let mut values_specified = false;
200        let mut values_any_specified = false;
201
202        for arg in args {
203            if arg.is_word()
204                && let Some(ident) = arg.ident()
205            {
206                if values_specified {
207                    {
    let mut diag =
        dcx.struct_fatal(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("invalid `--check-cfg` argument: `{0}`",
                            s))
                }));
    diag.note("`cfg()` names cannot be after values");
    diag.note(VISIT);
    diag.emit()
};error!("`cfg()` names cannot be after values");
208                }
209
210                if ident.is_path_segment_keyword() {
211                    {
    let mut diag =
        dcx.struct_fatal(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("invalid `--check-cfg` argument: `{0}`",
                            s))
                }));
    diag.note("malformed `cfg` input, expected a valid identifier");
    diag.note(VISIT);
    diag.emit()
};error!("malformed `cfg` input, expected a valid identifier");
212                }
213
214                names.push(ident);
215            } else if let Some(boolean) = arg.boolean_literal() {
216                if values_specified {
217                    {
    let mut diag =
        dcx.struct_fatal(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("invalid `--check-cfg` argument: `{0}`",
                            s))
                }));
    diag.note("`cfg()` names cannot be after values");
    diag.note(VISIT);
    diag.emit()
};error!("`cfg()` names cannot be after values");
218                }
219                names.push(rustc_span::Ident::new(
220                    if boolean { rustc_span::kw::True } else { rustc_span::kw::False },
221                    arg.span(),
222                ));
223            } else if arg.has_name(sym::any)
224                && let Some(args) = arg.meta_item_list()
225            {
226                if any_specified {
227                    {
    let mut diag =
        dcx.struct_fatal(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("invalid `--check-cfg` argument: `{0}`",
                            s))
                }));
    diag.note("`any()` cannot be specified multiple times");
    diag.note(VISIT);
    diag.emit()
};error!("`any()` cannot be specified multiple times");
228                }
229                any_specified = true;
230                if !args.is_empty() {
231                    {
    let mut diag =
        dcx.struct_fatal(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("invalid `--check-cfg` argument: `{0}`",
                            s))
                }));
    let pparg = rustc_ast_pretty::pprust::meta_list_item_to_string(arg);
    if let Some(lit) = arg.lit() {
        let (lit_kind_article, lit_kind_descr) =
            {
                let lit_kind = lit.as_token_lit().kind;
                (lit_kind.article(), lit_kind.descr())
            };
        diag.note(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("`{0}` is {1} {2} literal",
                            pparg, lit_kind_article, lit_kind_descr))
                }));
    } else {
        diag.note(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("`{0}` is invalid",
                            pparg))
                }));
    }
    diag.note("`any()` takes no argument");
    diag.note(VISIT);
    diag.emit()
};error!(in arg, "`any()` takes no argument");
232                }
233            } else if arg.has_name(sym::values)
234                && let Some(args) = arg.meta_item_list()
235            {
236                if names.is_empty() {
237                    {
    let mut diag =
        dcx.struct_fatal(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("invalid `--check-cfg` argument: `{0}`",
                            s))
                }));
    diag.note("`values()` cannot be specified before the names");
    diag.note(VISIT);
    diag.emit()
};error!("`values()` cannot be specified before the names");
238                } else if values_specified {
239                    {
    let mut diag =
        dcx.struct_fatal(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("invalid `--check-cfg` argument: `{0}`",
                            s))
                }));
    diag.note("`values()` cannot be specified multiple times");
    diag.note(VISIT);
    diag.emit()
};error!("`values()` cannot be specified multiple times");
240                }
241                values_specified = true;
242
243                for arg in args {
244                    if let Some(LitKind::Str(s, _)) = arg.lit().map(|lit| &lit.kind) {
245                        values.insert(Some(*s));
246                    } else if arg.has_name(sym::any)
247                        && let Some(args) = arg.meta_item_list()
248                    {
249                        if values_any_specified {
250                            {
    let mut diag =
        dcx.struct_fatal(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("invalid `--check-cfg` argument: `{0}`",
                            s))
                }));
    let pparg = rustc_ast_pretty::pprust::meta_list_item_to_string(arg);
    if let Some(lit) = arg.lit() {
        let (lit_kind_article, lit_kind_descr) =
            {
                let lit_kind = lit.as_token_lit().kind;
                (lit_kind.article(), lit_kind.descr())
            };
        diag.note(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("`{0}` is {1} {2} literal",
                            pparg, lit_kind_article, lit_kind_descr))
                }));
    } else {
        diag.note(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("`{0}` is invalid",
                            pparg))
                }));
    }
    diag.note("`any()` in `values()` cannot be specified multiple times");
    diag.note(VISIT);
    diag.emit()
};error!(in arg, "`any()` in `values()` cannot be specified multiple times");
251                        }
252                        values_any_specified = true;
253                        if !args.is_empty() {
254                            {
    let mut diag =
        dcx.struct_fatal(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("invalid `--check-cfg` argument: `{0}`",
                            s))
                }));
    let pparg = rustc_ast_pretty::pprust::meta_list_item_to_string(arg);
    if let Some(lit) = arg.lit() {
        let (lit_kind_article, lit_kind_descr) =
            {
                let lit_kind = lit.as_token_lit().kind;
                (lit_kind.article(), lit_kind.descr())
            };
        diag.note(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("`{0}` is {1} {2} literal",
                            pparg, lit_kind_article, lit_kind_descr))
                }));
    } else {
        diag.note(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("`{0}` is invalid",
                            pparg))
                }));
    }
    diag.note("`any()` in `values()` takes no argument");
    diag.note(VISIT);
    diag.emit()
};error!(in arg, "`any()` in `values()` takes no argument");
255                        }
256                    } else if arg.has_name(sym::none)
257                        && let Some(args) = arg.meta_item_list()
258                    {
259                        values.insert(None);
260                        if !args.is_empty() {
261                            {
    let mut diag =
        dcx.struct_fatal(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("invalid `--check-cfg` argument: `{0}`",
                            s))
                }));
    let pparg = rustc_ast_pretty::pprust::meta_list_item_to_string(arg);
    if let Some(lit) = arg.lit() {
        let (lit_kind_article, lit_kind_descr) =
            {
                let lit_kind = lit.as_token_lit().kind;
                (lit_kind.article(), lit_kind.descr())
            };
        diag.note(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("`{0}` is {1} {2} literal",
                            pparg, lit_kind_article, lit_kind_descr))
                }));
    } else {
        diag.note(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("`{0}` is invalid",
                            pparg))
                }));
    }
    diag.note("`none()` in `values()` takes no argument");
    diag.note(VISIT);
    diag.emit()
};error!(in arg, "`none()` in `values()` takes no argument");
262                        }
263                    } else {
264                        {
    let mut diag =
        dcx.struct_fatal(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("invalid `--check-cfg` argument: `{0}`",
                            s))
                }));
    let pparg = rustc_ast_pretty::pprust::meta_list_item_to_string(arg);
    if let Some(lit) = arg.lit() {
        let (lit_kind_article, lit_kind_descr) =
            {
                let lit_kind = lit.as_token_lit().kind;
                (lit_kind.article(), lit_kind.descr())
            };
        diag.note(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("`{0}` is {1} {2} literal",
                            pparg, lit_kind_article, lit_kind_descr))
                }));
    } else {
        diag.note(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("`{0}` is invalid",
                            pparg))
                }));
    }
    diag.note("`values()` arguments must be string literals, `none()` or `any()`");
    diag.note(VISIT);
    diag.emit()
};error!(in arg, "`values()` arguments must be string literals, `none()` or `any()`");
265                    }
266                }
267            } else {
268                {
    let mut diag =
        dcx.struct_fatal(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("invalid `--check-cfg` argument: `{0}`",
                            s))
                }));
    let pparg = rustc_ast_pretty::pprust::meta_list_item_to_string(arg);
    if let Some(lit) = arg.lit() {
        let (lit_kind_article, lit_kind_descr) =
            {
                let lit_kind = lit.as_token_lit().kind;
                (lit_kind.article(), lit_kind.descr())
            };
        diag.note(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("`{0}` is {1} {2} literal",
                            pparg, lit_kind_article, lit_kind_descr))
                }));
    } else {
        diag.note(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("`{0}` is invalid",
                            pparg))
                }));
    }
    diag.note("`cfg()` arguments must be simple identifiers, `any()` or `values(...)`");
    diag.note(VISIT);
    diag.emit()
};error!(in arg, "`cfg()` arguments must be simple identifiers, `any()` or `values(...)`");
269            }
270        }
271
272        if !values_specified && !any_specified {
273            // `cfg(name)` is equivalent to `cfg(name, values(none()))` so add
274            // an implicit `none()`
275            values.insert(None);
276        } else if !values.is_empty() && values_any_specified {
277            {
    let mut diag =
        dcx.struct_fatal(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("invalid `--check-cfg` argument: `{0}`",
                            s))
                }));
    diag.note("`values()` arguments cannot specify string literals and `any()` at the same time");
    diag.note(VISIT);
    diag.emit()
};error!(
278                "`values()` arguments cannot specify string literals and `any()` at the same time"
279            );
280        }
281
282        if any_specified {
283            if names.is_empty() && values.is_empty() && !values_specified && !values_any_specified {
284                check_cfg.exhaustive_names = false;
285            } else {
286                {
    let mut diag =
        dcx.struct_fatal(::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("invalid `--check-cfg` argument: `{0}`",
                            s))
                }));
    diag.note("`cfg(any())` can only be provided in isolation");
    diag.note(VISIT);
    diag.emit()
};error!("`cfg(any())` can only be provided in isolation");
287            }
288        } else {
289            for name in names {
290                check_cfg
291                    .expecteds
292                    .entry(name.name)
293                    .and_modify(|v| match v {
294                        ExpectedValues::Some(v) if !values_any_specified =>
295                        {
296                            #[allow(rustc::potential_query_instability)]
297                            v.extend(values.clone())
298                        }
299                        ExpectedValues::Some(_) => *v = ExpectedValues::Any,
300                        ExpectedValues::Any => {}
301                    })
302                    .or_insert_with(|| {
303                        if values_any_specified {
304                            ExpectedValues::Any
305                        } else {
306                            ExpectedValues::Some(values.clone())
307                        }
308                    });
309            }
310        }
311    }
312
313    check_cfg
314}
315
316/// The compiler configuration
317pub struct Config {
318    /// Command line options
319    pub opts: config::Options,
320
321    /// Unparsed cfg! configuration in addition to the default ones.
322    pub crate_cfg: Vec<String>,
323    pub crate_check_cfg: Vec<String>,
324
325    pub input: Input,
326    pub output_dir: Option<PathBuf>,
327    pub output_file: Option<OutFileName>,
328    pub ice_file: Option<PathBuf>,
329    /// Load files from sources other than the file system.
330    ///
331    /// Has no uses within this repository, but may be used in the future by
332    /// bjorn3 for "hooking rust-analyzer's VFS into rustc at some point for
333    /// running rustc without having to save". (See #102759.)
334    pub file_loader: Option<Box<dyn FileLoader + Send + Sync>>,
335
336    pub lint_caps: FxHashMap<lint::LintId, lint::Level>,
337
338    /// This is a callback from the driver that is called when [`ParseSess`] is created.
339    pub psess_created: Option<Box<dyn FnOnce(&mut ParseSess) + Send>>,
340
341    /// This is a callback to hash otherwise untracked state used by the caller, if the
342    /// hash changes between runs the incremental cache will be cleared.
343    ///
344    /// e.g. used by Clippy to hash its config file
345    pub hash_untracked_state: Option<Box<dyn FnOnce(&Session, &mut StableHasher) + Send>>,
346
347    /// This is a callback from the driver that is called when we're registering lints;
348    /// it is called during lint loading when we have the LintStore in a non-shared state.
349    ///
350    /// Note that if you find a Some here you probably want to call that function in the new
351    /// function being registered.
352    pub register_lints: Option<Box<dyn Fn(&Session, &mut LintStore) + Send + Sync>>,
353
354    /// This is a callback from the driver that is called just after we have populated
355    /// the list of queries.
356    pub override_queries: Option<fn(&Session, &mut Providers)>,
357
358    /// An extra set of symbols to add to the symbol interner, the symbol indices
359    /// will start at [`PREDEFINED_SYMBOLS_COUNT`](rustc_span::symbol::PREDEFINED_SYMBOLS_COUNT)
360    pub extra_symbols: Vec<&'static str>,
361
362    /// This is a callback from the driver that is called to create a codegen backend.
363    ///
364    /// Has no uses within this repository, but is used by bjorn3 for "the
365    /// hotswapping branch of cg_clif" for "setting the codegen backend from a
366    /// custom driver where the custom codegen backend has arbitrary data."
367    /// (See #102759.)
368    pub make_codegen_backend:
369        Option<Box<dyn FnOnce(&config::Options, &Target) -> Box<dyn CodegenBackend> + Send>>,
370
371    /// The inner atomic value is set to true when a feature marked as `internal` is
372    /// enabled. Makes it so that "please report a bug" is hidden, as ICEs with
373    /// internal features are wontfix, and they are usually the cause of the ICEs.
374    pub using_internal_features: &'static std::sync::atomic::AtomicBool,
375}
376
377/// Initialize jobserver before getting `jobserver::client` and `build_session`.
378pub(crate) fn initialize_checked_jobserver(early_dcx: &EarlyDiagCtxt) {
379    jobserver::initialize_checked(|err| {
380        early_dcx
381            .early_struct_warn(err)
382            .with_note("the build environment is likely misconfigured")
383            .emit()
384    });
385}
386
387// JUSTIFICATION: before session exists, only config
388#[allow(rustc::bad_opt_access)]
389pub fn run_compiler<R: Send>(config: Config, f: impl FnOnce(&Compiler) -> R + Send) -> R {
390    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_interface/src/interface.rs:390",
                        "rustc_interface::interface", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_interface/src/interface.rs"),
                        ::tracing_core::__macro_support::Option::Some(390u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_interface::interface"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("run_compiler")
                                            as &dyn Value))])
            });
    } else { ; }
};trace!("run_compiler");
391
392    // Set parallel mode before thread pool creation, which will create `Lock`s.
393    rustc_data_structures::sync::set_dyn_thread_safe_mode(config.opts.unstable_opts.threads > 1);
394
395    // Check jobserver before run_in_thread_pool_with_globals, which call jobserver::acquire_thread
396    let early_dcx = EarlyDiagCtxt::new(config.opts.error_format);
397    initialize_checked_jobserver(&early_dcx);
398
399    crate::callbacks::setup_callbacks();
400
401    let target = config::build_target_config(
402        &early_dcx,
403        &config.opts.target_triple,
404        config.opts.sysroot.path(),
405        config.opts.unstable_opts.unstable_options,
406    );
407    let file_loader = config.file_loader.unwrap_or_else(|| Box::new(RealFileLoader));
408    let path_mapping = config.opts.file_path_mapping();
409    let hash_kind = config.opts.unstable_opts.src_hash_algorithm(&target);
410    let checksum_hash_kind = config.opts.unstable_opts.checksum_hash_algorithm();
411
412    util::run_in_thread_pool_with_globals(
413        &early_dcx,
414        config.opts.edition,
415        config.opts.unstable_opts.threads,
416        &config.extra_symbols,
417        SourceMapInputs { file_loader, path_mapping, hash_kind, checksum_hash_kind },
418        |current_gcx, jobserver_proxy| {
419            // The previous `early_dcx` can't be reused here because it doesn't
420            // impl `Send`. Creating a new one is fine.
421            let early_dcx = EarlyDiagCtxt::new(config.opts.error_format);
422
423            let codegen_backend = match config.make_codegen_backend {
424                None => util::get_codegen_backend(
425                    &early_dcx,
426                    &config.opts.sysroot,
427                    config.opts.unstable_opts.codegen_backend.as_deref(),
428                    &target,
429                ),
430                Some(make_codegen_backend) => {
431                    // N.B. `make_codegen_backend` takes precedence over
432                    // `target.default_codegen_backend`, which is ignored in this case.
433                    make_codegen_backend(&config.opts, &target)
434                }
435            };
436
437            let temps_dir = config.opts.unstable_opts.temps_dir.as_deref().map(PathBuf::from);
438
439            let bundle = match rustc_errors::fluent_bundle(
440                &config.opts.sysroot.all_paths().collect::<Vec<_>>(),
441                config.opts.unstable_opts.translate_lang.clone(),
442                config.opts.unstable_opts.translate_additional_ftl.as_deref(),
443                config.opts.unstable_opts.translate_directionality_markers,
444            ) {
445                Ok(bundle) => bundle,
446                Err(e) => early_dcx.early_fatal(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("failed to load fluent bundle: {0}",
                e))
    })format!("failed to load fluent bundle: {e}")),
447            };
448
449            let mut sess = rustc_session::build_session(
450                config.opts,
451                CompilerIO {
452                    input: config.input,
453                    output_dir: config.output_dir,
454                    output_file: config.output_file,
455                    temps_dir,
456                },
457                bundle,
458                config.lint_caps,
459                target,
460                util::rustc_version_str().unwrap_or("unknown"),
461                config.ice_file,
462                config.using_internal_features,
463            );
464
465            codegen_backend.init(&sess);
466            sess.replaced_intrinsics = FxHashSet::from_iter(codegen_backend.replaced_intrinsics());
467
468            let cfg = parse_cfg(sess.dcx(), config.crate_cfg);
469            let mut cfg = config::build_configuration(&sess, cfg);
470            util::add_configuration(&mut cfg, &mut sess, &*codegen_backend);
471            sess.psess.config = cfg;
472
473            let mut check_cfg = parse_check_cfg(sess.dcx(), config.crate_check_cfg);
474            check_cfg.fill_well_known(&sess.target);
475            sess.psess.check_config = check_cfg;
476
477            if let Some(psess_created) = config.psess_created {
478                psess_created(&mut sess.psess);
479            }
480
481            if let Some(hash_untracked_state) = config.hash_untracked_state {
482                let mut hasher = StableHasher::new();
483                hash_untracked_state(&sess, &mut hasher);
484                sess.opts.untracked_state_hash = hasher.finish()
485            }
486
487            // Even though the session holds the lint store, we can't build the
488            // lint store until after the session exists. And we wait until now
489            // so that `register_lints` sees the fully initialized session.
490            let mut lint_store = rustc_lint::new_lint_store(sess.enable_internal_lints());
491            if let Some(register_lints) = config.register_lints.as_deref() {
492                register_lints(&sess, &mut lint_store);
493            }
494            sess.lint_store = Some(Arc::new(lint_store));
495
496            util::check_abi_required_features(&sess);
497
498            let compiler = Compiler {
499                sess,
500                codegen_backend,
501                override_queries: config.override_queries,
502                current_gcx,
503                jobserver_proxy,
504            };
505
506            // There are two paths out of `f`.
507            // - Normal exit.
508            // - Panic, e.g. triggered by `abort_if_errors` or a fatal error.
509            //
510            // We must run `finish_diagnostics` in both cases.
511            let res = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f(&compiler)));
512
513            compiler.sess.finish_diagnostics();
514
515            // If error diagnostics have been emitted, we can't return an
516            // error directly, because the return type of this function
517            // is `R`, not `Result<R, E>`. But we need to communicate the
518            // errors' existence to the caller, otherwise the caller might
519            // mistakenly think that no errors occurred and return a zero
520            // exit code. So we abort (panic) instead, similar to if `f`
521            // had panicked.
522            if res.is_ok() {
523                compiler.sess.dcx().abort_if_errors();
524            }
525
526            // Also make sure to flush delayed bugs as if we panicked, the
527            // bugs would be flushed by the Drop impl of DiagCtxt while
528            // unwinding, which would result in an abort with
529            // "panic in a destructor during cleanup".
530            compiler.sess.dcx().flush_delayed();
531
532            let res = match res {
533                Ok(res) => res,
534                // Resume unwinding if a panic happened.
535                Err(err) => std::panic::resume_unwind(err),
536            };
537
538            let prof = compiler.sess.prof.clone();
539            prof.generic_activity("drop_compiler").run(move || drop(compiler));
540
541            res
542        },
543    )
544}
545
546pub fn try_print_query_stack(
547    dcx: DiagCtxtHandle<'_>,
548    limit_frames: Option<usize>,
549    file: Option<std::fs::File>,
550) {
551    { ::std::io::_eprint(format_args!("query stack during panic:\n")); };eprintln!("query stack during panic:");
552
553    // Be careful relying on global state here: this code is called from
554    // a panic hook, which means that the global `DiagCtxt` may be in a weird
555    // state if it was responsible for triggering the panic.
556    let all_frames = ty::tls::with_context_opt(|icx| {
557        if let Some(icx) = icx {
558            {
    {
        let _guard = ReducedQueriesGuard::new();
        {
            let _guard = ForcedImplGuard::new();
            {
                let _guard = NoTrimmedGuard::new();
                {
                    let _guard = NoVisibleGuard::new();
                    print_query_stack(QueryCtxt::new(icx.tcx), icx.query, dcx,
                        limit_frames, file)
                }
            }
        }
    }
}ty::print::with_no_queries!(print_query_stack(
559                QueryCtxt::new(icx.tcx),
560                icx.query,
561                dcx,
562                limit_frames,
563                file,
564            ))
565        } else {
566            0
567        }
568    });
569
570    if let Some(limit_frames) = limit_frames
571        && all_frames > limit_frames
572    {
573        {
    ::std::io::_eprint(format_args!("... and {0} other queries... use `env RUST_BACKTRACE=1` to see the full query stack\n",
            all_frames - limit_frames));
};eprintln!(
574            "... and {} other queries... use `env RUST_BACKTRACE=1` to see the full query stack",
575            all_frames - limit_frames
576        );
577    } else {
578        { ::std::io::_eprint(format_args!("end of query stack\n")); };eprintln!("end of query stack");
579    }
580}