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