]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_interface/src/interface.rs
Merge commit '4c41a222ca5d1325fb4b6709395bd06e766cc042' into clippyup
[rust.git] / compiler / rustc_interface / src / interface.rs
1 pub use crate::passes::BoxedResolver;
2 use crate::util;
3
4 use rustc_ast::token;
5 use rustc_ast::{self as ast, MetaItemKind};
6 use rustc_codegen_ssa::traits::CodegenBackend;
7 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
8 use rustc_data_structures::sync::Lrc;
9 use rustc_data_structures::OnDrop;
10 use rustc_errors::registry::Registry;
11 use rustc_errors::{ErrorReported, Handler};
12 use rustc_lint::LintStore;
13 use rustc_middle::ty;
14 use rustc_parse::new_parser_from_source_str;
15 use rustc_query_impl::QueryCtxt;
16 use rustc_session::config::{self, ErrorOutputType, Input, OutputFilenames};
17 use rustc_session::early_error;
18 use rustc_session::lint;
19 use rustc_session::parse::{CrateConfig, ParseSess};
20 use rustc_session::{DiagnosticOutput, Session};
21 use rustc_span::source_map::{FileLoader, FileName};
22 use std::path::PathBuf;
23 use std::result;
24 use std::sync::{Arc, Mutex};
25
26 pub type Result<T> = result::Result<T, ErrorReported>;
27
28 /// Represents a compiler session.
29 ///
30 /// Can be used to run `rustc_interface` queries.
31 /// Created by passing [`Config`] to [`run_compiler`].
32 pub struct Compiler {
33     pub(crate) sess: Lrc<Session>,
34     codegen_backend: Lrc<Box<dyn CodegenBackend>>,
35     pub(crate) input: Input,
36     pub(crate) input_path: Option<PathBuf>,
37     pub(crate) output_dir: Option<PathBuf>,
38     pub(crate) output_file: Option<PathBuf>,
39     pub(crate) register_lints: Option<Box<dyn Fn(&Session, &mut LintStore) + Send + Sync>>,
40     pub(crate) override_queries:
41         Option<fn(&Session, &mut ty::query::Providers, &mut ty::query::Providers)>,
42 }
43
44 impl Compiler {
45     pub fn session(&self) -> &Lrc<Session> {
46         &self.sess
47     }
48     pub fn codegen_backend(&self) -> &Lrc<Box<dyn CodegenBackend>> {
49         &self.codegen_backend
50     }
51     pub fn input(&self) -> &Input {
52         &self.input
53     }
54     pub fn output_dir(&self) -> &Option<PathBuf> {
55         &self.output_dir
56     }
57     pub fn output_file(&self) -> &Option<PathBuf> {
58         &self.output_file
59     }
60     pub fn register_lints(&self) -> &Option<Box<dyn Fn(&Session, &mut LintStore) + Send + Sync>> {
61         &self.register_lints
62     }
63     pub fn build_output_filenames(
64         &self,
65         sess: &Session,
66         attrs: &[ast::Attribute],
67     ) -> OutputFilenames {
68         util::build_output_filenames(
69             &self.input,
70             &self.output_dir,
71             &self.output_file,
72             &attrs,
73             &sess,
74         )
75     }
76 }
77
78 /// Converts strings provided as `--cfg [cfgspec]` into a `crate_cfg`.
79 pub fn parse_cfgspecs(cfgspecs: Vec<String>) -> FxHashSet<(String, Option<String>)> {
80     rustc_span::create_default_session_if_not_set_then(move |_| {
81         let cfg = cfgspecs
82             .into_iter()
83             .map(|s| {
84                 let sess = ParseSess::with_silent_emitter();
85                 let filename = FileName::cfg_spec_source_code(&s);
86                 let mut parser = new_parser_from_source_str(&sess, filename, s.to_string());
87
88                 macro_rules! error {
89                     ($reason: expr) => {
90                         early_error(
91                             ErrorOutputType::default(),
92                             &format!(concat!("invalid `--cfg` argument: `{}` (", $reason, ")"), s),
93                         );
94                     };
95                 }
96
97                 match &mut parser.parse_meta_item() {
98                     Ok(meta_item) if parser.token == token::Eof => {
99                         if meta_item.path.segments.len() != 1 {
100                             error!("argument key must be an identifier");
101                         }
102                         match &meta_item.kind {
103                             MetaItemKind::List(..) => {
104                                 error!(r#"expected `key` or `key="value"`"#);
105                             }
106                             MetaItemKind::NameValue(lit) if !lit.kind.is_str() => {
107                                 error!("argument value must be a string");
108                             }
109                             MetaItemKind::NameValue(..) | MetaItemKind::Word => {
110                                 let ident = meta_item.ident().expect("multi-segment cfg key");
111                                 return (ident.name, meta_item.value_str());
112                             }
113                         }
114                     }
115                     Ok(..) => {}
116                     Err(err) => err.cancel(),
117                 }
118
119                 error!(r#"expected `key` or `key="value"`"#);
120             })
121             .collect::<CrateConfig>();
122         cfg.into_iter().map(|(a, b)| (a.to_string(), b.map(|b| b.to_string()))).collect()
123     })
124 }
125
126 /// The compiler configuration
127 pub struct Config {
128     /// Command line options
129     pub opts: config::Options,
130
131     /// cfg! configuration in addition to the default ones
132     pub crate_cfg: FxHashSet<(String, Option<String>)>,
133
134     pub input: Input,
135     pub input_path: Option<PathBuf>,
136     pub output_dir: Option<PathBuf>,
137     pub output_file: Option<PathBuf>,
138     pub file_loader: Option<Box<dyn FileLoader + Send + Sync>>,
139     pub diagnostic_output: DiagnosticOutput,
140
141     /// Set to capture stderr output during compiler execution
142     pub stderr: Option<Arc<Mutex<Vec<u8>>>>,
143
144     pub lint_caps: FxHashMap<lint::LintId, lint::Level>,
145
146     /// This is a callback from the driver that is called when [`ParseSess`] is created.
147     pub parse_sess_created: Option<Box<dyn FnOnce(&mut ParseSess) + Send>>,
148
149     /// This is a callback from the driver that is called when we're registering lints;
150     /// it is called during plugin registration when we have the LintStore in a non-shared state.
151     ///
152     /// Note that if you find a Some here you probably want to call that function in the new
153     /// function being registered.
154     pub register_lints: Option<Box<dyn Fn(&Session, &mut LintStore) + Send + Sync>>,
155
156     /// This is a callback from the driver that is called just after we have populated
157     /// the list of queries.
158     ///
159     /// The second parameter is local providers and the third parameter is external providers.
160     pub override_queries:
161         Option<fn(&Session, &mut ty::query::Providers, &mut ty::query::Providers)>,
162
163     /// This is a callback from the driver that is called to create a codegen backend.
164     pub make_codegen_backend:
165         Option<Box<dyn FnOnce(&config::Options) -> Box<dyn CodegenBackend> + Send>>,
166
167     /// Registry of diagnostics codes.
168     pub registry: Registry,
169 }
170
171 pub fn create_compiler_and_run<R>(config: Config, f: impl FnOnce(&Compiler) -> R) -> R {
172     let registry = &config.registry;
173     let (mut sess, codegen_backend) = util::create_session(
174         config.opts,
175         config.crate_cfg,
176         config.diagnostic_output,
177         config.file_loader,
178         config.input_path.clone(),
179         config.lint_caps,
180         config.make_codegen_backend,
181         registry.clone(),
182     );
183
184     if let Some(parse_sess_created) = config.parse_sess_created {
185         parse_sess_created(
186             &mut Lrc::get_mut(&mut sess)
187                 .expect("create_session() should never share the returned session")
188                 .parse_sess,
189         );
190     }
191
192     let compiler = Compiler {
193         sess,
194         codegen_backend,
195         input: config.input,
196         input_path: config.input_path,
197         output_dir: config.output_dir,
198         output_file: config.output_file,
199         register_lints: config.register_lints,
200         override_queries: config.override_queries,
201     };
202
203     rustc_span::with_source_map(compiler.sess.parse_sess.clone_source_map(), move || {
204         let r = {
205             let _sess_abort_error = OnDrop(|| {
206                 compiler.sess.finish_diagnostics(registry);
207             });
208
209             f(&compiler)
210         };
211
212         let prof = compiler.sess.prof.clone();
213         prof.generic_activity("drop_compiler").run(move || drop(compiler));
214         r
215     })
216 }
217
218 pub fn run_compiler<R: Send>(mut config: Config, f: impl FnOnce(&Compiler) -> R + Send) -> R {
219     tracing::trace!("run_compiler");
220     let stderr = config.stderr.take();
221     util::setup_callbacks_and_run_in_thread_pool_with_globals(
222         config.opts.edition,
223         config.opts.debugging_opts.threads,
224         &stderr,
225         || create_compiler_and_run(config, f),
226     )
227 }
228
229 pub fn try_print_query_stack(handler: &Handler, num_frames: Option<usize>) {
230     eprintln!("query stack during panic:");
231
232     // Be careful relying on global state here: this code is called from
233     // a panic hook, which means that the global `Handler` may be in a weird
234     // state if it was responsible for triggering the panic.
235     let i = ty::tls::with_context_opt(|icx| {
236         if let Some(icx) = icx {
237             QueryCtxt::from_tcx(icx.tcx).try_print_query_stack(icx.query, handler, num_frames)
238         } else {
239             0
240         }
241     });
242
243     if num_frames == None || num_frames >= Some(i) {
244         eprintln!("end of query stack");
245     } else {
246         eprintln!("we're just showing a limited slice of the query stack");
247     }
248 }