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