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