]> git.lizzy.rs Git - rust.git/blob - src/librustc_interface/interface.rs
Add comment about the lack of `ExpnData` serialization for proc-macro crates
[rust.git] / src / librustc_interface / interface.rs
1 pub use crate::passes::BoxedResolver;
2 use crate::util;
3
4 use rustc_ast::ast::{self, MetaItemKind};
5 use rustc_ast::token;
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;
12 use rustc_lint::LintStore;
13 use rustc_middle::ty;
14 use rustc_parse::new_parser_from_source_str;
15 use rustc_session::config::{self, ErrorOutputType, Input, OutputFilenames};
16 use rustc_session::early_error;
17 use rustc_session::lint;
18 use rustc_session::parse::{CrateConfig, ParseSess};
19 use rustc_session::{DiagnosticOutput, Session};
20 use rustc_span::edition;
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 /// Can be used to run `rustc_interface` queries.
30 /// Created by passing `Config` to `run_compiler`.
31 pub struct Compiler {
32     pub(crate) sess: Lrc<Session>,
33     codegen_backend: Lrc<Box<dyn CodegenBackend>>,
34     pub(crate) input: Input,
35     pub(crate) input_path: Option<PathBuf>,
36     pub(crate) output_dir: Option<PathBuf>,
37     pub(crate) output_file: Option<PathBuf>,
38     pub(crate) crate_name: Option<String>,
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 build_output_filenames(
61         &self,
62         sess: &Session,
63         attrs: &[ast::Attribute],
64     ) -> OutputFilenames {
65         util::build_output_filenames(
66             &self.input,
67             &self.output_dir,
68             &self.output_file,
69             &attrs,
70             &sess,
71         )
72     }
73 }
74
75 /// Converts strings provided as `--cfg [cfgspec]` into a `crate_cfg`.
76 pub fn parse_cfgspecs(cfgspecs: Vec<String>) -> FxHashSet<(String, Option<String>)> {
77     rustc_ast::with_default_session_globals(move || {
78         let cfg = cfgspecs
79             .into_iter()
80             .map(|s| {
81                 let sess = ParseSess::with_silent_emitter();
82                 let filename = FileName::cfg_spec_source_code(&s);
83                 let mut parser = new_parser_from_source_str(&sess, filename, s.to_string());
84
85                 macro_rules! error {
86                     ($reason: expr) => {
87                         early_error(
88                             ErrorOutputType::default(),
89                             &format!(concat!("invalid `--cfg` argument: `{}` (", $reason, ")"), s),
90                         );
91                     };
92                 }
93
94                 match &mut parser.parse_meta_item() {
95                     Ok(meta_item) if parser.token == token::Eof => {
96                         if meta_item.path.segments.len() != 1 {
97                             error!("argument key must be an identifier");
98                         }
99                         match &meta_item.kind {
100                             MetaItemKind::List(..) => {
101                                 error!(r#"expected `key` or `key="value"`"#);
102                             }
103                             MetaItemKind::NameValue(lit) if !lit.kind.is_str() => {
104                                 error!("argument value must be a string");
105                             }
106                             MetaItemKind::NameValue(..) | MetaItemKind::Word => {
107                                 let ident = meta_item.ident().expect("multi-segment cfg key");
108                                 return (ident.name, meta_item.value_str());
109                             }
110                         }
111                     }
112                     Ok(..) => {}
113                     Err(err) => err.cancel(),
114                 }
115
116                 error!(r#"expected `key` or `key="value"`"#);
117             })
118             .collect::<CrateConfig>();
119         cfg.into_iter().map(|(a, b)| (a.to_string(), b.map(|b| b.to_string()))).collect()
120     })
121 }
122
123 /// The compiler configuration
124 pub struct Config {
125     /// Command line options
126     pub opts: config::Options,
127
128     /// cfg! configuration in addition to the default ones
129     pub crate_cfg: FxHashSet<(String, Option<String>)>,
130
131     pub input: Input,
132     pub input_path: Option<PathBuf>,
133     pub output_dir: Option<PathBuf>,
134     pub output_file: Option<PathBuf>,
135     pub file_loader: Option<Box<dyn FileLoader + Send + Sync>>,
136     pub diagnostic_output: DiagnosticOutput,
137
138     /// Set to capture stderr output during compiler execution
139     pub stderr: Option<Arc<Mutex<Vec<u8>>>>,
140
141     pub crate_name: Option<String>,
142     pub lint_caps: FxHashMap<lint::LintId, lint::Level>,
143
144     /// This is a callback from the driver that is called when we're registering lints;
145     /// it is called during plugin registration when we have the LintStore in a non-shared state.
146     ///
147     /// Note that if you find a Some here you probably want to call that function in the new
148     /// function being registered.
149     pub register_lints: Option<Box<dyn Fn(&Session, &mut LintStore) + Send + Sync>>,
150
151     /// This is a callback from the driver that is called just after we have populated
152     /// the list of queries.
153     ///
154     /// The second parameter is local providers and the third parameter is external providers.
155     pub override_queries:
156         Option<fn(&Session, &mut ty::query::Providers, &mut ty::query::Providers)>,
157
158     /// Registry of diagnostics codes.
159     pub registry: Registry,
160 }
161
162 pub fn create_compiler_and_run<R>(config: Config, f: impl FnOnce(&Compiler) -> R) -> R {
163     let registry = &config.registry;
164     let (sess, codegen_backend) = util::create_session(
165         config.opts,
166         config.crate_cfg,
167         config.diagnostic_output,
168         config.file_loader,
169         config.input_path.clone(),
170         config.lint_caps,
171         registry.clone(),
172     );
173
174     let compiler = Compiler {
175         sess,
176         codegen_backend,
177         input: config.input,
178         input_path: config.input_path,
179         output_dir: config.output_dir,
180         output_file: config.output_file,
181         crate_name: config.crate_name,
182         register_lints: config.register_lints,
183         override_queries: config.override_queries,
184     };
185
186     rustc_span::with_source_map(compiler.sess.parse_sess.clone_source_map(), move || {
187         let r = {
188             let _sess_abort_error = OnDrop(|| {
189                 compiler.sess.finish_diagnostics(registry);
190             });
191
192             f(&compiler)
193         };
194
195         let prof = compiler.sess.prof.clone();
196         prof.generic_activity("drop_compiler").run(move || drop(compiler));
197         r
198     })
199 }
200
201 pub fn run_compiler<R: Send>(mut config: Config, f: impl FnOnce(&Compiler) -> R + Send) -> R {
202     log::trace!("run_compiler");
203     let stderr = config.stderr.take();
204     util::setup_callbacks_and_run_in_thread_pool_with_globals(
205         config.opts.edition,
206         config.opts.debugging_opts.threads,
207         &stderr,
208         || create_compiler_and_run(config, f),
209     )
210 }
211
212 pub fn setup_callbacks_and_run_in_default_thread_pool_with_globals<R: Send>(
213     edition: edition::Edition,
214     f: impl FnOnce() -> R + Send,
215 ) -> R {
216     // the 1 here is duplicating code in config.opts.debugging_opts.threads
217     // which also defaults to 1; it ultimately doesn't matter as the default
218     // isn't threaded, and just ignores this parameter
219     util::setup_callbacks_and_run_in_thread_pool_with_globals(edition, 1, &None, f)
220 }