]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_trait_selection/src/traits/on_unimplemented.rs
Rollup merge of #95346 - Aaron1011:stablize-const-extern-fn, r=pnkfelix
[rust.git] / compiler / rustc_trait_selection / src / traits / on_unimplemented.rs
1 use rustc_ast::{MetaItem, NestedMetaItem};
2 use rustc_attr as attr;
3 use rustc_data_structures::fx::FxHashMap;
4 use rustc_errors::{struct_span_err, ErrorGuaranteed};
5 use rustc_hir::def_id::DefId;
6 use rustc_middle::ty::{self, GenericParamDefKind, TyCtxt};
7 use rustc_parse_format::{ParseMode, Parser, Piece, Position};
8 use rustc_span::symbol::{kw, sym, Symbol};
9 use rustc_span::{Span, DUMMY_SP};
10
11 #[derive(Clone, Debug)]
12 pub struct OnUnimplementedFormatString(Symbol);
13
14 #[derive(Debug)]
15 pub struct OnUnimplementedDirective {
16     pub condition: Option<MetaItem>,
17     pub subcommands: Vec<OnUnimplementedDirective>,
18     pub message: Option<OnUnimplementedFormatString>,
19     pub label: Option<OnUnimplementedFormatString>,
20     pub note: Option<OnUnimplementedFormatString>,
21     pub enclosing_scope: Option<OnUnimplementedFormatString>,
22     pub append_const_msg: Option<Option<Symbol>>,
23 }
24
25 #[derive(Default)]
26 pub struct OnUnimplementedNote {
27     pub message: Option<String>,
28     pub label: Option<String>,
29     pub note: Option<String>,
30     pub enclosing_scope: Option<String>,
31     /// Append a message for `~const Trait` errors. `None` means not requested and
32     /// should fallback to a generic message, `Some(None)` suggests using the default
33     /// appended message, `Some(Some(s))` suggests use the `s` message instead of the
34     /// default one..
35     pub append_const_msg: Option<Option<Symbol>>,
36 }
37
38 fn parse_error(
39     tcx: TyCtxt<'_>,
40     span: Span,
41     message: &str,
42     label: &str,
43     note: Option<&str>,
44 ) -> ErrorGuaranteed {
45     let mut diag = struct_span_err!(tcx.sess, span, E0232, "{}", message);
46     diag.span_label(span, label);
47     if let Some(note) = note {
48         diag.note(note);
49     }
50     diag.emit()
51 }
52
53 impl<'tcx> OnUnimplementedDirective {
54     fn parse(
55         tcx: TyCtxt<'tcx>,
56         item_def_id: DefId,
57         items: &[NestedMetaItem],
58         span: Span,
59         is_root: bool,
60     ) -> Result<Self, ErrorGuaranteed> {
61         let mut errored = None;
62         let mut item_iter = items.iter();
63
64         let parse_value = |value_str| {
65             OnUnimplementedFormatString::try_parse(tcx, item_def_id, value_str, span).map(Some)
66         };
67
68         let condition = if is_root {
69             None
70         } else {
71             let cond = item_iter
72                 .next()
73                 .ok_or_else(|| {
74                     parse_error(
75                         tcx,
76                         span,
77                         "empty `on`-clause in `#[rustc_on_unimplemented]`",
78                         "empty on-clause here",
79                         None,
80                     )
81                 })?
82                 .meta_item()
83                 .ok_or_else(|| {
84                     parse_error(
85                         tcx,
86                         span,
87                         "invalid `on`-clause in `#[rustc_on_unimplemented]`",
88                         "invalid on-clause here",
89                         None,
90                     )
91                 })?;
92             attr::eval_condition(cond, &tcx.sess.parse_sess, Some(tcx.features()), &mut |item| {
93                 if let Some(symbol) = item.value_str() && let Err(guar) = parse_value(symbol) {
94                     errored = Some(guar);
95                 }
96                 true
97             });
98             Some(cond.clone())
99         };
100
101         let mut message = None;
102         let mut label = None;
103         let mut note = None;
104         let mut enclosing_scope = None;
105         let mut subcommands = vec![];
106         let mut append_const_msg = None;
107
108         for item in item_iter {
109             if item.has_name(sym::message) && message.is_none() {
110                 if let Some(message_) = item.value_str() {
111                     message = parse_value(message_)?;
112                     continue;
113                 }
114             } else if item.has_name(sym::label) && label.is_none() {
115                 if let Some(label_) = item.value_str() {
116                     label = parse_value(label_)?;
117                     continue;
118                 }
119             } else if item.has_name(sym::note) && note.is_none() {
120                 if let Some(note_) = item.value_str() {
121                     note = parse_value(note_)?;
122                     continue;
123                 }
124             } else if item.has_name(sym::enclosing_scope) && enclosing_scope.is_none() {
125                 if let Some(enclosing_scope_) = item.value_str() {
126                     enclosing_scope = parse_value(enclosing_scope_)?;
127                     continue;
128                 }
129             } else if item.has_name(sym::on)
130                 && is_root
131                 && message.is_none()
132                 && label.is_none()
133                 && note.is_none()
134             {
135                 if let Some(items) = item.meta_item_list() {
136                     match Self::parse(tcx, item_def_id, &items, item.span(), false) {
137                         Ok(subcommand) => subcommands.push(subcommand),
138                         Err(reported) => errored = Some(reported),
139                     };
140                     continue;
141                 }
142             } else if item.has_name(sym::append_const_msg) && append_const_msg.is_none() {
143                 if let Some(msg) = item.value_str() {
144                     append_const_msg = Some(Some(msg));
145                     continue;
146                 } else if item.is_word() {
147                     append_const_msg = Some(None);
148                     continue;
149                 }
150             }
151
152             // nothing found
153             parse_error(
154                 tcx,
155                 item.span(),
156                 "this attribute must have a valid value",
157                 "expected value here",
158                 Some(r#"eg `#[rustc_on_unimplemented(message="foo")]`"#),
159             );
160         }
161
162         if let Some(reported) = errored {
163             Err(reported)
164         } else {
165             Ok(OnUnimplementedDirective {
166                 condition,
167                 subcommands,
168                 message,
169                 label,
170                 note,
171                 enclosing_scope,
172                 append_const_msg,
173             })
174         }
175     }
176
177     pub fn of_item(tcx: TyCtxt<'tcx>, item_def_id: DefId) -> Result<Option<Self>, ErrorGuaranteed> {
178         let attrs = tcx.get_attrs(item_def_id);
179
180         let Some(attr) = tcx.sess.find_by_name(&attrs, sym::rustc_on_unimplemented) else {
181             return Ok(None);
182         };
183
184         let result = if let Some(items) = attr.meta_item_list() {
185             Self::parse(tcx, item_def_id, &items, attr.span, true).map(Some)
186         } else if let Some(value) = attr.value_str() {
187             Ok(Some(OnUnimplementedDirective {
188                 condition: None,
189                 message: None,
190                 subcommands: vec![],
191                 label: Some(OnUnimplementedFormatString::try_parse(
192                     tcx,
193                     item_def_id,
194                     value,
195                     attr.span,
196                 )?),
197                 note: None,
198                 enclosing_scope: None,
199                 append_const_msg: None,
200             }))
201         } else {
202             let reported =
203                 tcx.sess.delay_span_bug(DUMMY_SP, "of_item: neither meta_item_list nor value_str");
204             return Err(reported);
205         };
206         debug!("of_item({:?}) = {:?}", item_def_id, result);
207         result
208     }
209
210     pub fn evaluate(
211         &self,
212         tcx: TyCtxt<'tcx>,
213         trait_ref: ty::TraitRef<'tcx>,
214         options: &[(Symbol, Option<String>)],
215     ) -> OnUnimplementedNote {
216         let mut message = None;
217         let mut label = None;
218         let mut note = None;
219         let mut enclosing_scope = None;
220         let mut append_const_msg = None;
221         info!("evaluate({:?}, trait_ref={:?}, options={:?})", self, trait_ref, options);
222
223         let options_map: FxHashMap<Symbol, String> =
224             options.iter().filter_map(|(k, v)| v.as_ref().map(|v| (*k, v.to_owned()))).collect();
225
226         for command in self.subcommands.iter().chain(Some(self)).rev() {
227             if let Some(ref condition) = command.condition && !attr::eval_condition(
228                 condition,
229                 &tcx.sess.parse_sess,
230                 Some(tcx.features()),
231                 &mut |c| {
232                     c.ident().map_or(false, |ident| {
233                         let value = c.value_str().map(|s| {
234                             OnUnimplementedFormatString(s).format(tcx, trait_ref, &options_map)
235                         });
236
237                         options.contains(&(ident.name, value))
238                     })
239                 },
240             ) {
241                 debug!("evaluate: skipping {:?} due to condition", command);
242                 continue;
243             }
244             debug!("evaluate: {:?} succeeded", command);
245             if let Some(ref message_) = command.message {
246                 message = Some(message_.clone());
247             }
248
249             if let Some(ref label_) = command.label {
250                 label = Some(label_.clone());
251             }
252
253             if let Some(ref note_) = command.note {
254                 note = Some(note_.clone());
255             }
256
257             if let Some(ref enclosing_scope_) = command.enclosing_scope {
258                 enclosing_scope = Some(enclosing_scope_.clone());
259             }
260
261             append_const_msg = command.append_const_msg;
262         }
263
264         OnUnimplementedNote {
265             label: label.map(|l| l.format(tcx, trait_ref, &options_map)),
266             message: message.map(|m| m.format(tcx, trait_ref, &options_map)),
267             note: note.map(|n| n.format(tcx, trait_ref, &options_map)),
268             enclosing_scope: enclosing_scope.map(|e_s| e_s.format(tcx, trait_ref, &options_map)),
269             append_const_msg,
270         }
271     }
272 }
273
274 impl<'tcx> OnUnimplementedFormatString {
275     fn try_parse(
276         tcx: TyCtxt<'tcx>,
277         item_def_id: DefId,
278         from: Symbol,
279         err_sp: Span,
280     ) -> Result<Self, ErrorGuaranteed> {
281         let result = OnUnimplementedFormatString(from);
282         result.verify(tcx, item_def_id, err_sp)?;
283         Ok(result)
284     }
285
286     fn verify(
287         &self,
288         tcx: TyCtxt<'tcx>,
289         item_def_id: DefId,
290         span: Span,
291     ) -> Result<(), ErrorGuaranteed> {
292         let trait_def_id = if tcx.is_trait(item_def_id) {
293             item_def_id
294         } else {
295             tcx.trait_id_of_impl(item_def_id)
296                 .expect("expected `on_unimplemented` to correspond to a trait")
297         };
298         let trait_name = tcx.item_name(trait_def_id);
299         let generics = tcx.generics_of(item_def_id);
300         let s = self.0.as_str();
301         let parser = Parser::new(s, None, None, false, ParseMode::Format);
302         let mut result = Ok(());
303         for token in parser {
304             match token {
305                 Piece::String(_) => (), // Normal string, no need to check it
306                 Piece::NextArgument(a) => match a.position {
307                     // `{Self}` is allowed
308                     Position::ArgumentNamed(s, _) if s == kw::SelfUpper => (),
309                     // `{ThisTraitsName}` is allowed
310                     Position::ArgumentNamed(s, _) if s == trait_name => (),
311                     // `{from_method}` is allowed
312                     Position::ArgumentNamed(s, _) if s == sym::from_method => (),
313                     // `{from_desugaring}` is allowed
314                     Position::ArgumentNamed(s, _) if s == sym::from_desugaring => (),
315                     // `{ItemContext}` is allowed
316                     Position::ArgumentNamed(s, _) if s == sym::ItemContext => (),
317                     // `{integral}` and `{integer}` and `{float}` are allowed
318                     Position::ArgumentNamed(s, _)
319                         if s == sym::integral || s == sym::integer_ || s == sym::float =>
320                     {
321                         ()
322                     }
323                     // So is `{A}` if A is a type parameter
324                     Position::ArgumentNamed(s, _) => {
325                         match generics.params.iter().find(|param| param.name == s) {
326                             Some(_) => (),
327                             None => {
328                                 let reported = struct_span_err!(
329                                     tcx.sess,
330                                     span,
331                                     E0230,
332                                     "there is no parameter `{}` on {}",
333                                     s,
334                                     if trait_def_id == item_def_id {
335                                         format!("trait `{}`", trait_name)
336                                     } else {
337                                         "impl".to_string()
338                                     }
339                                 )
340                                 .emit();
341                                 result = Err(reported);
342                             }
343                         }
344                     }
345                     // `{:1}` and `{}` are not to be used
346                     Position::ArgumentIs(_) | Position::ArgumentImplicitlyIs(_) => {
347                         let reported = struct_span_err!(
348                             tcx.sess,
349                             span,
350                             E0231,
351                             "only named substitution parameters are allowed"
352                         )
353                         .emit();
354                         result = Err(reported);
355                     }
356                 },
357             }
358         }
359
360         result
361     }
362
363     pub fn format(
364         &self,
365         tcx: TyCtxt<'tcx>,
366         trait_ref: ty::TraitRef<'tcx>,
367         options: &FxHashMap<Symbol, String>,
368     ) -> String {
369         let name = tcx.item_name(trait_ref.def_id);
370         let trait_str = tcx.def_path_str(trait_ref.def_id);
371         let generics = tcx.generics_of(trait_ref.def_id);
372         let generic_map = generics
373             .params
374             .iter()
375             .filter_map(|param| {
376                 let value = match param.kind {
377                     GenericParamDefKind::Type { .. } | GenericParamDefKind::Const { .. } => {
378                         trait_ref.substs[param.index as usize].to_string()
379                     }
380                     GenericParamDefKind::Lifetime => return None,
381                 };
382                 let name = param.name;
383                 Some((name, value))
384             })
385             .collect::<FxHashMap<Symbol, String>>();
386         let empty_string = String::new();
387
388         let s = self.0.as_str();
389         let parser = Parser::new(s, None, None, false, ParseMode::Format);
390         let item_context = (options.get(&sym::ItemContext)).unwrap_or(&empty_string);
391         parser
392             .map(|p| match p {
393                 Piece::String(s) => s,
394                 Piece::NextArgument(a) => match a.position {
395                     Position::ArgumentNamed(s, _) => match generic_map.get(&s) {
396                         Some(val) => val,
397                         None if s == name => &trait_str,
398                         None => {
399                             if let Some(val) = options.get(&s) {
400                                 val
401                             } else if s == sym::from_desugaring || s == sym::from_method {
402                                 // don't break messages using these two arguments incorrectly
403                                 &empty_string
404                             } else if s == sym::ItemContext {
405                                 &item_context
406                             } else if s == sym::integral {
407                                 "{integral}"
408                             } else if s == sym::integer_ {
409                                 "{integer}"
410                             } else if s == sym::float {
411                                 "{float}"
412                             } else {
413                                 bug!(
414                                     "broken on_unimplemented {:?} for {:?}: \
415                                       no argument matching {:?}",
416                                     self.0,
417                                     trait_ref,
418                                     s
419                                 )
420                             }
421                         }
422                     },
423                     _ => bug!("broken on_unimplemented {:?} - bad format arg", self.0),
424                 },
425             })
426             .collect()
427     }
428 }