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