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