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