• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 use crate::util;
2 
3 use rustc_ast::token;
4 use rustc_ast::{self as ast, LitKind, MetaItemKind};
5 use rustc_codegen_ssa::traits::CodegenBackend;
6 use rustc_data_structures::defer;
7 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
8 use rustc_data_structures::sync::Lrc;
9 use rustc_errors::registry::Registry;
10 use rustc_errors::{ErrorGuaranteed, Handler};
11 use rustc_lint::LintStore;
12 use rustc_middle::query::{ExternProviders, Providers};
13 use rustc_middle::{bug, ty};
14 use rustc_parse::maybe_new_parser_from_source_str;
15 use rustc_query_impl::QueryCtxt;
16 use rustc_query_system::query::print_query_stack;
17 use rustc_session::config::{self, CheckCfg, ExpectedValues, Input, OutFileName, OutputFilenames};
18 use rustc_session::parse::{CrateConfig, ParseSess};
19 use rustc_session::CompilerIO;
20 use rustc_session::Session;
21 use rustc_session::{lint, EarlyErrorHandler};
22 use rustc_span::source_map::{FileLoader, FileName};
23 use rustc_span::symbol::sym;
24 use std::path::PathBuf;
25 use std::result;
26 
27 pub type Result<T> = result::Result<T, ErrorGuaranteed>;
28 
29 /// Represents a compiler session. Note that every `Compiler` contains a
30 /// `Session`, but `Compiler` also contains some things that cannot be in
31 /// `Session`, due to `Session` being in a crate that has many fewer
32 /// dependencies than this crate.
33 ///
34 /// Can be used to run `rustc_interface` queries.
35 /// Created by passing [`Config`] to [`run_compiler`].
36 pub struct Compiler {
37     pub(crate) sess: Lrc<Session>,
38     codegen_backend: Lrc<dyn CodegenBackend>,
39     pub(crate) register_lints: Option<Box<dyn Fn(&Session, &mut LintStore) + Send + Sync>>,
40     pub(crate) override_queries: Option<fn(&Session, &mut Providers, &mut ExternProviders)>,
41 }
42 
43 impl Compiler {
session(&self) -> &Lrc<Session>44     pub fn session(&self) -> &Lrc<Session> {
45         &self.sess
46     }
codegen_backend(&self) -> &Lrc<dyn CodegenBackend>47     pub fn codegen_backend(&self) -> &Lrc<dyn CodegenBackend> {
48         &self.codegen_backend
49     }
register_lints(&self) -> &Option<Box<dyn Fn(&Session, &mut LintStore) + Send + Sync>>50     pub fn register_lints(&self) -> &Option<Box<dyn Fn(&Session, &mut LintStore) + Send + Sync>> {
51         &self.register_lints
52     }
build_output_filenames( &self, sess: &Session, attrs: &[ast::Attribute], ) -> OutputFilenames53     pub fn build_output_filenames(
54         &self,
55         sess: &Session,
56         attrs: &[ast::Attribute],
57     ) -> OutputFilenames {
58         util::build_output_filenames(attrs, sess)
59     }
60 }
61 
62 #[allow(rustc::bad_opt_access)]
set_thread_safe_mode(sopts: &config::UnstableOptions)63 pub fn set_thread_safe_mode(sopts: &config::UnstableOptions) {
64     rustc_data_structures::sync::set_dyn_thread_safe_mode(sopts.threads > 1);
65 }
66 
67 /// Converts strings provided as `--cfg [cfgspec]` into a `crate_cfg`.
parse_cfgspecs( handler: &EarlyErrorHandler, cfgspecs: Vec<String>, ) -> FxHashSet<(String, Option<String>)>68 pub fn parse_cfgspecs(
69     handler: &EarlyErrorHandler,
70     cfgspecs: Vec<String>,
71 ) -> FxHashSet<(String, Option<String>)> {
72     rustc_span::create_default_session_if_not_set_then(move |_| {
73         let cfg = cfgspecs
74             .into_iter()
75             .map(|s| {
76                 let sess = ParseSess::with_silent_emitter(Some(format!(
77                     "this error occurred on the command line: `--cfg={s}`"
78                 )));
79                 let filename = FileName::cfg_spec_source_code(&s);
80 
81                 macro_rules! error {
82                     ($reason: expr) => {
83                         handler.early_error(format!(
84                             concat!("invalid `--cfg` argument: `{}` (", $reason, ")"),
85                             s
86                         ));
87                     };
88                 }
89 
90                 match maybe_new_parser_from_source_str(&sess, filename, s.to_string()) {
91                     Ok(mut parser) => match parser.parse_meta_item() {
92                         Ok(meta_item) if parser.token == token::Eof => {
93                             if meta_item.path.segments.len() != 1 {
94                                 error!("argument key must be an identifier");
95                             }
96                             match &meta_item.kind {
97                                 MetaItemKind::List(..) => {}
98                                 MetaItemKind::NameValue(lit) if !lit.kind.is_str() => {
99                                     error!("argument value must be a string");
100                                 }
101                                 MetaItemKind::NameValue(..) | MetaItemKind::Word => {
102                                     let ident = meta_item.ident().expect("multi-segment cfg key");
103                                     return (ident.name, meta_item.value_str());
104                                 }
105                             }
106                         }
107                         Ok(..) => {}
108                         Err(err) => err.cancel(),
109                     },
110                     Err(errs) => drop(errs),
111                 }
112 
113                 // If the user tried to use a key="value" flag, but is missing the quotes, provide
114                 // a hint about how to resolve this.
115                 if s.contains('=') && !s.contains("=\"") && !s.ends_with('"') {
116                     error!(concat!(
117                         r#"expected `key` or `key="value"`, ensure escaping is appropriate"#,
118                         r#" for your shell, try 'key="value"' or key=\"value\""#
119                     ));
120                 } else {
121                     error!(r#"expected `key` or `key="value"`"#);
122                 }
123             })
124             .collect::<CrateConfig>();
125         cfg.into_iter().map(|(a, b)| (a.to_string(), b.map(|b| b.to_string()))).collect()
126     })
127 }
128 
129 /// Converts strings provided as `--check-cfg [specs]` into a `CheckCfg`.
parse_check_cfg(handler: &EarlyErrorHandler, specs: Vec<String>) -> CheckCfg130 pub fn parse_check_cfg(handler: &EarlyErrorHandler, specs: Vec<String>) -> CheckCfg {
131     rustc_span::create_default_session_if_not_set_then(move |_| {
132         let mut check_cfg = CheckCfg::default();
133 
134         for s in specs {
135             let sess = ParseSess::with_silent_emitter(Some(format!(
136                 "this error occurred on the command line: `--check-cfg={s}`"
137             )));
138             let filename = FileName::cfg_spec_source_code(&s);
139 
140             macro_rules! error {
141                 ($reason: expr) => {
142                     handler.early_error(format!(
143                         concat!("invalid `--check-cfg` argument: `{}` (", $reason, ")"),
144                         s
145                     ))
146                 };
147             }
148 
149             let expected_error = || {
150                 error!(
151                     "expected `names(name1, name2, ... nameN)` or \
152                         `values(name, \"value1\", \"value2\", ... \"valueN\")`"
153                 )
154             };
155 
156             match maybe_new_parser_from_source_str(&sess, filename, s.to_string()) {
157                 Ok(mut parser) => match parser.parse_meta_item() {
158                     Ok(meta_item) if parser.token == token::Eof => {
159                         if let Some(args) = meta_item.meta_item_list() {
160                             if meta_item.has_name(sym::names) {
161                                 check_cfg.exhaustive_names = true;
162                                 for arg in args {
163                                     if arg.is_word() && arg.ident().is_some() {
164                                         let ident = arg.ident().expect("multi-segment cfg key");
165                                         check_cfg
166                                             .expecteds
167                                             .entry(ident.name.to_string())
168                                             .or_insert(ExpectedValues::Any);
169                                     } else {
170                                         error!("`names()` arguments must be simple identifiers");
171                                     }
172                                 }
173                             } else if meta_item.has_name(sym::values) {
174                                 if let Some((name, values)) = args.split_first() {
175                                     if name.is_word() && name.ident().is_some() {
176                                         let ident = name.ident().expect("multi-segment cfg key");
177                                         let expected_values = check_cfg
178                                             .expecteds
179                                             .entry(ident.name.to_string())
180                                             .and_modify(|expected_values| match expected_values {
181                                                 ExpectedValues::Some(_) => {}
182                                                 ExpectedValues::Any => {
183                                                     // handle the case where names(...) was done
184                                                     // before values by changing to a list
185                                                     *expected_values =
186                                                         ExpectedValues::Some(FxHashSet::default());
187                                                 }
188                                             })
189                                             .or_insert_with(|| {
190                                                 ExpectedValues::Some(FxHashSet::default())
191                                             });
192 
193                                         let ExpectedValues::Some(expected_values) = expected_values else {
194                                             bug!("`expected_values` should be a list a values")
195                                         };
196 
197                                         for val in values {
198                                             if let Some(LitKind::Str(s, _)) =
199                                                 val.lit().map(|lit| &lit.kind)
200                                             {
201                                                 expected_values.insert(Some(s.to_string()));
202                                             } else {
203                                                 error!(
204                                                     "`values()` arguments must be string literals"
205                                                 );
206                                             }
207                                         }
208 
209                                         if values.is_empty() {
210                                             expected_values.insert(None);
211                                         }
212                                     } else {
213                                         error!(
214                                             "`values()` first argument must be a simple identifier"
215                                         );
216                                     }
217                                 } else if args.is_empty() {
218                                     check_cfg.exhaustive_values = true;
219                                 } else {
220                                     expected_error();
221                                 }
222                             } else {
223                                 expected_error();
224                             }
225                         } else {
226                             expected_error();
227                         }
228                     }
229                     Ok(..) => expected_error(),
230                     Err(err) => {
231                         err.cancel();
232                         expected_error();
233                     }
234                 },
235                 Err(errs) => {
236                     drop(errs);
237                     expected_error();
238                 }
239             }
240         }
241 
242         check_cfg
243     })
244 }
245 
246 /// The compiler configuration
247 pub struct Config {
248     /// Command line options
249     pub opts: config::Options,
250 
251     /// cfg! configuration in addition to the default ones
252     pub crate_cfg: FxHashSet<(String, Option<String>)>,
253     pub crate_check_cfg: CheckCfg,
254 
255     pub input: Input,
256     pub output_dir: Option<PathBuf>,
257     pub output_file: Option<OutFileName>,
258     pub file_loader: Option<Box<dyn FileLoader + Send + Sync>>,
259     pub locale_resources: &'static [&'static str],
260 
261     pub lint_caps: FxHashMap<lint::LintId, lint::Level>,
262 
263     /// This is a callback from the driver that is called when [`ParseSess`] is created.
264     pub parse_sess_created: Option<Box<dyn FnOnce(&mut ParseSess) + Send>>,
265 
266     /// This is a callback from the driver that is called when we're registering lints;
267     /// it is called during plugin registration when we have the LintStore in a non-shared state.
268     ///
269     /// Note that if you find a Some here you probably want to call that function in the new
270     /// function being registered.
271     pub register_lints: Option<Box<dyn Fn(&Session, &mut LintStore) + Send + Sync>>,
272 
273     /// This is a callback from the driver that is called just after we have populated
274     /// the list of queries.
275     ///
276     /// The second parameter is local providers and the third parameter is external providers.
277     pub override_queries: Option<fn(&Session, &mut Providers, &mut ExternProviders)>,
278 
279     /// This is a callback from the driver that is called to create a codegen backend.
280     pub make_codegen_backend:
281         Option<Box<dyn FnOnce(&config::Options) -> Box<dyn CodegenBackend> + Send>>,
282 
283     /// Registry of diagnostics codes.
284     pub registry: Registry,
285 }
286 
287 // JUSTIFICATION: before session exists, only config
288 #[allow(rustc::bad_opt_access)]
run_compiler<R: Send>(config: Config, f: impl FnOnce(&Compiler) -> R + Send) -> R289 pub fn run_compiler<R: Send>(config: Config, f: impl FnOnce(&Compiler) -> R + Send) -> R {
290     trace!("run_compiler");
291     util::run_in_thread_pool_with_globals(
292         config.opts.edition,
293         config.opts.unstable_opts.threads,
294         || {
295             crate::callbacks::setup_callbacks();
296 
297             let registry = &config.registry;
298 
299             let handler = EarlyErrorHandler::new(config.opts.error_format);
300 
301             let temps_dir = config.opts.unstable_opts.temps_dir.as_deref().map(PathBuf::from);
302             let (mut sess, codegen_backend) = util::create_session(
303                 &handler,
304                 config.opts,
305                 config.crate_cfg,
306                 config.crate_check_cfg,
307                 config.locale_resources,
308                 config.file_loader,
309                 CompilerIO {
310                     input: config.input,
311                     output_dir: config.output_dir,
312                     output_file: config.output_file,
313                     temps_dir,
314                 },
315                 config.lint_caps,
316                 config.make_codegen_backend,
317                 registry.clone(),
318             );
319 
320             if let Some(parse_sess_created) = config.parse_sess_created {
321                 parse_sess_created(&mut sess.parse_sess);
322             }
323 
324             let compiler = Compiler {
325                 sess: Lrc::new(sess),
326                 codegen_backend: Lrc::from(codegen_backend),
327                 register_lints: config.register_lints,
328                 override_queries: config.override_queries,
329             };
330 
331             rustc_span::set_source_map(compiler.sess.parse_sess.clone_source_map(), move || {
332                 let r = {
333                     let _sess_abort_error = defer(|| {
334                         compiler.sess.finish_diagnostics(registry);
335                     });
336 
337                     f(&compiler)
338                 };
339 
340                 let prof = compiler.sess.prof.clone();
341 
342                 prof.generic_activity("drop_compiler").run(move || drop(compiler));
343                 r
344             })
345         },
346     )
347 }
348 
try_print_query_stack(handler: &Handler, num_frames: Option<usize>)349 pub fn try_print_query_stack(handler: &Handler, num_frames: Option<usize>) {
350     eprintln!("query stack during panic:");
351 
352     // Be careful relying on global state here: this code is called from
353     // a panic hook, which means that the global `Handler` may be in a weird
354     // state if it was responsible for triggering the panic.
355     let i = ty::tls::with_context_opt(|icx| {
356         if let Some(icx) = icx {
357             ty::print::with_no_queries!(print_query_stack(
358                 QueryCtxt::new(icx.tcx),
359                 icx.query,
360                 handler,
361                 num_frames
362             ))
363         } else {
364             0
365         }
366     });
367 
368     if num_frames == None || num_frames >= Some(i) {
369         eprintln!("end of query stack");
370     } else {
371         eprintln!("we're just showing a limited slice of the query stack");
372     }
373 }
374