Skip to main content

rustc_interface/
interface.rs

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