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