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