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