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