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