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