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