Skip to main content

rustc_interface/
interface.rs

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