]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_interface/src/interface.rs
New upstream version 1.57.0+dfsg1
[rustc.git] / compiler / rustc_interface / src / interface.rs
CommitLineData
532ac7d7 1pub use crate::passes::BoxedResolver;
dfeec247 2use crate::util;
532ac7d7 3
74b04a01 4use rustc_ast::token;
3dfed10e 5use rustc_ast::{self as ast, MetaItemKind};
ba9703b0 6use rustc_codegen_ssa::traits::CodegenBackend;
dfeec247 7use rustc_data_structures::fx::{FxHashMap, FxHashSet};
532ac7d7 8use rustc_data_structures::sync::Lrc;
dfeec247 9use rustc_data_structures::OnDrop;
60c5eb7d 10use rustc_errors::registry::Registry;
6a06907d 11use rustc_errors::{ErrorReported, Handler};
dfeec247 12use rustc_lint::LintStore;
ba9703b0 13use rustc_middle::ty;
60c5eb7d 14use rustc_parse::new_parser_from_source_str;
136023e0 15use rustc_query_impl::QueryCtxt;
ba9703b0
XL
16use rustc_session::config::{self, ErrorOutputType, Input, OutputFilenames};
17use rustc_session::early_error;
18use rustc_session::lint;
74b04a01 19use rustc_session::parse::{CrateConfig, ParseSess};
ba9703b0 20use rustc_session::{DiagnosticOutput, Session};
f9f354fc 21use rustc_span::source_map::{FileLoader, FileName};
532ac7d7
XL
22use std::path::PathBuf;
23use std::result;
24use std::sync::{Arc, Mutex};
532ac7d7
XL
25
26pub type Result<T> = result::Result<T, ErrorReported>;
27
28/// Represents a compiler session.
fc512014 29///
dfeec247 30/// Can be used to run `rustc_interface` queries.
fc512014 31/// Created by passing [`Config`] to [`run_compiler`].
532ac7d7
XL
32pub struct Compiler {
33 pub(crate) sess: Lrc<Session>,
34 codegen_backend: Lrc<Box<dyn CodegenBackend>>,
532ac7d7
XL
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>,
dfeec247 39 pub(crate) register_lints: Option<Box<dyn Fn(&Session, &mut LintStore) + Send + Sync>>,
60c5eb7d 40 pub(crate) override_queries:
f035d41b 41 Option<fn(&Session, &mut ty::query::Providers, &mut ty::query::Providers)>,
532ac7d7
XL
42}
43
44impl Compiler {
45 pub fn session(&self) -> &Lrc<Session> {
46 &self.sess
47 }
48 pub fn codegen_backend(&self) -> &Lrc<Box<dyn CodegenBackend>> {
49 &self.codegen_backend
50 }
532ac7d7
XL
51 pub fn input(&self) -> &Input {
52 &self.input
53 }
54 pub fn output_dir(&self) -> &Option<PathBuf> {
55 &self.output_dir
56 }
57 pub fn output_file(&self) -> &Option<PathBuf> {
58 &self.output_file
59 }
fc512014
XL
60 pub fn register_lints(&self) -> &Option<Box<dyn Fn(&Session, &mut LintStore) + Send + Sync>> {
61 &self.register_lints
62 }
74b04a01
XL
63 pub fn build_output_filenames(
64 &self,
65 sess: &Session,
66 attrs: &[ast::Attribute],
67 ) -> OutputFilenames {
c295e0f8 68 util::build_output_filenames(&self.input, &self.output_dir, &self.output_file, attrs, sess)
74b04a01 69 }
532ac7d7
XL
70}
71
e74abb32
XL
72/// Converts strings provided as `--cfg [cfgspec]` into a `crate_cfg`.
73pub fn parse_cfgspecs(cfgspecs: Vec<String>) -> FxHashSet<(String, Option<String>)> {
136023e0 74 rustc_span::create_default_session_if_not_set_then(move |_| {
dfeec247
XL
75 let cfg = cfgspecs
76 .into_iter()
77 .map(|s| {
78 let sess = ParseSess::with_silent_emitter();
79 let filename = FileName::cfg_spec_source_code(&s);
80 let mut parser = new_parser_from_source_str(&sess, filename, s.to_string());
81
82 macro_rules! error {
83 ($reason: expr) => {
84 early_error(
85 ErrorOutputType::default(),
86 &format!(concat!("invalid `--cfg` argument: `{}` (", $reason, ")"), s),
87 );
88 };
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");
e74abb32 95 }
dfeec247
XL
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 }
e74abb32
XL
107 }
108 }
dfeec247
XL
109 Ok(..) => {}
110 Err(err) => err.cancel(),
e74abb32 111 }
dfeec247
XL
112
113 error!(r#"expected `key` or `key="value"`"#);
114 })
74b04a01 115 .collect::<CrateConfig>();
dfeec247 116 cfg.into_iter().map(|(a, b)| (a.to_string(), b.map(|b| b.to_string()))).collect()
e74abb32
XL
117 })
118}
119
532ac7d7
XL
120/// The compiler configuration
121pub struct Config {
122 /// Command line options
123 pub opts: config::Options,
124
125 /// cfg! configuration in addition to the default ones
126 pub crate_cfg: FxHashSet<(String, Option<String>)>,
127
128 pub input: Input,
129 pub input_path: Option<PathBuf>,
130 pub output_dir: Option<PathBuf>,
131 pub output_file: Option<PathBuf>,
132 pub file_loader: Option<Box<dyn FileLoader + Send + Sync>>,
133 pub diagnostic_output: DiagnosticOutput,
134
135 /// Set to capture stderr output during compiler execution
136 pub stderr: Option<Arc<Mutex<Vec<u8>>>>,
137
532ac7d7 138 pub lint_caps: FxHashMap<lint::LintId, lint::Level>,
e74abb32 139
6a06907d
XL
140 /// This is a callback from the driver that is called when [`ParseSess`] is created.
141 pub parse_sess_created: Option<Box<dyn FnOnce(&mut ParseSess) + Send>>,
142
e74abb32
XL
143 /// This is a callback from the driver that is called when we're registering lints;
144 /// it is called during plugin registration when we have the LintStore in a non-shared state.
145 ///
146 /// Note that if you find a Some here you probably want to call that function in the new
147 /// function being registered.
dfeec247 148 pub register_lints: Option<Box<dyn Fn(&Session, &mut LintStore) + Send + Sync>>,
60c5eb7d
XL
149
150 /// This is a callback from the driver that is called just after we have populated
151 /// the list of queries.
152 ///
153 /// The second parameter is local providers and the third parameter is external providers.
154 pub override_queries:
f035d41b 155 Option<fn(&Session, &mut ty::query::Providers, &mut ty::query::Providers)>,
60c5eb7d 156
1b1a35ee
XL
157 /// This is a callback from the driver that is called to create a codegen backend.
158 pub make_codegen_backend:
159 Option<Box<dyn FnOnce(&config::Options) -> Box<dyn CodegenBackend> + Send>>,
160
60c5eb7d
XL
161 /// Registry of diagnostics codes.
162 pub registry: Registry,
532ac7d7
XL
163}
164
f035d41b 165pub fn create_compiler_and_run<R>(config: Config, f: impl FnOnce(&Compiler) -> R) -> R {
60c5eb7d 166 let registry = &config.registry;
6a06907d 167 let (mut sess, codegen_backend) = util::create_session(
532ac7d7
XL
168 config.opts,
169 config.crate_cfg,
170 config.diagnostic_output,
171 config.file_loader,
172 config.input_path.clone(),
173 config.lint_caps,
1b1a35ee 174 config.make_codegen_backend,
60c5eb7d 175 registry.clone(),
532ac7d7
XL
176 );
177
6a06907d
XL
178 if let Some(parse_sess_created) = config.parse_sess_created {
179 parse_sess_created(
180 &mut Lrc::get_mut(&mut sess)
181 .expect("create_session() should never share the returned session")
182 .parse_sess,
183 );
184 }
185
532ac7d7
XL
186 let compiler = Compiler {
187 sess,
188 codegen_backend,
532ac7d7
XL
189 input: config.input,
190 input_path: config.input_path,
191 output_dir: config.output_dir,
192 output_file: config.output_file,
e74abb32 193 register_lints: config.register_lints,
60c5eb7d 194 override_queries: config.override_queries,
532ac7d7
XL
195 };
196
f035d41b
XL
197 rustc_span::with_source_map(compiler.sess.parse_sess.clone_source_map(), move || {
198 let r = {
199 let _sess_abort_error = OnDrop(|| {
200 compiler.sess.finish_diagnostics(registry);
201 });
dfeec247 202
f035d41b
XL
203 f(&compiler)
204 };
532ac7d7 205
f035d41b
XL
206 let prof = compiler.sess.prof.clone();
207 prof.generic_activity("drop_compiler").run(move || drop(compiler));
208 r
209 })
532ac7d7
XL
210}
211
60c5eb7d 212pub fn run_compiler<R: Send>(mut config: Config, f: impl FnOnce(&Compiler) -> R + Send) -> R {
3dfed10e 213 tracing::trace!("run_compiler");
532ac7d7 214 let stderr = config.stderr.take();
f035d41b 215 util::setup_callbacks_and_run_in_thread_pool_with_globals(
dc9dc135 216 config.opts.edition,
532ac7d7
XL
217 config.opts.debugging_opts.threads,
218 &stderr,
f035d41b 219 || create_compiler_and_run(config, f),
532ac7d7
XL
220 )
221}
6a06907d
XL
222
223pub fn try_print_query_stack(handler: &Handler, num_frames: Option<usize>) {
224 eprintln!("query stack during panic:");
225
226 // Be careful relying on global state here: this code is called from
227 // a panic hook, which means that the global `Handler` may be in a weird
228 // state if it was responsible for triggering the panic.
229 let i = ty::tls::with_context_opt(|icx| {
230 if let Some(icx) = icx {
136023e0 231 QueryCtxt::from_tcx(icx.tcx).try_print_query_stack(icx.query, handler, num_frames)
6a06907d
XL
232 } else {
233 0
234 }
235 });
236
237 if num_frames == None || num_frames >= Some(i) {
238 eprintln!("end of query stack");
239 } else {
240 eprintln!("we're just showing a limited slice of the query stack");
241 }
242}