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