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