]> git.lizzy.rs Git - rust.git/blob - src/librustc_trait_selection/traits/on_unimplemented.rs
Merge branch 'master' into feature/incorporate-tracing
[rust.git] / src / librustc_trait_selection / traits / on_unimplemented.rs
1 use rustc_ast::ast::{MetaItem, NestedMetaItem};
2 use rustc_attr as attr;
3 use rustc_data_structures::fx::FxHashMap;
4 use rustc_errors::{struct_span_err, ErrorReported};
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;
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 }
23
24 #[derive(Default)]
25 pub struct OnUnimplementedNote {
26     pub message: Option<String>,
27     pub label: Option<String>,
28     pub note: Option<String>,
29     pub enclosing_scope: Option<String>,
30 }
31
32 fn parse_error(
33     tcx: TyCtxt<'_>,
34     span: Span,
35     message: &str,
36     label: &str,
37     note: Option<&str>,
38 ) -> ErrorReported {
39     let mut diag = struct_span_err!(tcx.sess, span, E0232, "{}", message);
40     diag.span_label(span, label);
41     if let Some(note) = note {
42         diag.note(note);
43     }
44     diag.emit();
45     ErrorReported
46 }
47
48 impl<'tcx> OnUnimplementedDirective {
49     fn parse(
50         tcx: TyCtxt<'tcx>,
51         trait_def_id: DefId,
52         items: &[NestedMetaItem],
53         span: Span,
54         is_root: bool,
55     ) -> Result<Self, ErrorReported> {
56         let mut errored = false;
57         let mut item_iter = items.iter();
58
59         let condition = if is_root {
60             None
61         } else {
62             let cond = item_iter
63                 .next()
64                 .ok_or_else(|| {
65                     parse_error(
66                         tcx,
67                         span,
68                         "empty `on`-clause in `#[rustc_on_unimplemented]`",
69                         "empty on-clause here",
70                         None,
71                     )
72                 })?
73                 .meta_item()
74                 .ok_or_else(|| {
75                     parse_error(
76                         tcx,
77                         span,
78                         "invalid `on`-clause in `#[rustc_on_unimplemented]`",
79                         "invalid on-clause here",
80                         None,
81                     )
82                 })?;
83             attr::eval_condition(cond, &tcx.sess.parse_sess, Some(tcx.features()), &mut |_| true);
84             Some(cond.clone())
85         };
86
87         let mut message = None;
88         let mut label = None;
89         let mut note = None;
90         let mut enclosing_scope = None;
91         let mut subcommands = vec![];
92
93         let parse_value = |value_str| {
94             OnUnimplementedFormatString::try_parse(tcx, trait_def_id, value_str, span).map(Some)
95         };
96
97         for item in item_iter {
98             if item.has_name(sym::message) && message.is_none() {
99                 if let Some(message_) = item.value_str() {
100                     message = parse_value(message_)?;
101                     continue;
102                 }
103             } else if item.has_name(sym::label) && label.is_none() {
104                 if let Some(label_) = item.value_str() {
105                     label = parse_value(label_)?;
106                     continue;
107                 }
108             } else if item.has_name(sym::note) && note.is_none() {
109                 if let Some(note_) = item.value_str() {
110                     note = parse_value(note_)?;
111                     continue;
112                 }
113             } else if item.has_name(sym::enclosing_scope) && enclosing_scope.is_none() {
114                 if let Some(enclosing_scope_) = item.value_str() {
115                     enclosing_scope = parse_value(enclosing_scope_)?;
116                     continue;
117                 }
118             } else if item.has_name(sym::on)
119                 && is_root
120                 && message.is_none()
121                 && label.is_none()
122                 && note.is_none()
123             {
124                 if let Some(items) = item.meta_item_list() {
125                     if let Ok(subcommand) =
126                         Self::parse(tcx, trait_def_id, &items, item.span(), false)
127                     {
128                         subcommands.push(subcommand);
129                     } else {
130                         errored = true;
131                     }
132                     continue;
133                 }
134             }
135
136             // nothing found
137             parse_error(
138                 tcx,
139                 item.span(),
140                 "this attribute must have a valid value",
141                 "expected value here",
142                 Some(r#"eg `#[rustc_on_unimplemented(message="foo")]`"#),
143             );
144         }
145
146         if errored {
147             Err(ErrorReported)
148         } else {
149             Ok(OnUnimplementedDirective {
150                 condition,
151                 subcommands,
152                 message,
153                 label,
154                 note,
155                 enclosing_scope,
156             })
157         }
158     }
159
160     pub fn of_item(
161         tcx: TyCtxt<'tcx>,
162         trait_def_id: DefId,
163         impl_def_id: DefId,
164     ) -> Result<Option<Self>, ErrorReported> {
165         let attrs = tcx.get_attrs(impl_def_id);
166
167         let attr = if let Some(item) = attr::find_by_name(&attrs, sym::rustc_on_unimplemented) {
168             item
169         } else {
170             return Ok(None);
171         };
172
173         let result = if let Some(items) = attr.meta_item_list() {
174             Self::parse(tcx, trait_def_id, &items, attr.span, true).map(Some)
175         } else if let Some(value) = attr.value_str() {
176             Ok(Some(OnUnimplementedDirective {
177                 condition: None,
178                 message: None,
179                 subcommands: vec![],
180                 label: Some(OnUnimplementedFormatString::try_parse(
181                     tcx,
182                     trait_def_id,
183                     value,
184                     attr.span,
185                 )?),
186                 note: None,
187                 enclosing_scope: None,
188             }))
189         } else {
190             return Err(ErrorReported);
191         };
192         debug!("of_item({:?}/{:?}) = {:?}", trait_def_id, impl_def_id, result);
193         result
194     }
195
196     pub fn evaluate(
197         &self,
198         tcx: TyCtxt<'tcx>,
199         trait_ref: ty::TraitRef<'tcx>,
200         options: &[(Symbol, Option<String>)],
201     ) -> OnUnimplementedNote {
202         let mut message = None;
203         let mut label = None;
204         let mut note = None;
205         let mut enclosing_scope = None;
206         info!("evaluate({:?}, trait_ref={:?}, options={:?})", self, trait_ref, options);
207
208         for command in self.subcommands.iter().chain(Some(self)).rev() {
209             if let Some(ref condition) = command.condition {
210                 if !attr::eval_condition(
211                     condition,
212                     &tcx.sess.parse_sess,
213                     Some(tcx.features()),
214                     &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                 ) {
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> =
243             options.iter().filter_map(|(k, v)| v.as_ref().map(|v| (*k, v.to_owned()))).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, None, false, ParseMode::Format);
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::ItemContext => (),
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                                 struct_span_err!(
296                                     tcx.sess,
297                                     span,
298                                     E0230,
299                                     "there is no parameter `{}` on trait `{}`",
300                                     s,
301                                     name
302                                 )
303                                 .emit();
304                                 result = Err(ErrorReported);
305                             }
306                         }
307                     }
308                     // `{:1}` and `{}` are not to be used
309                     Position::ArgumentIs(_) | Position::ArgumentImplicitlyIs(_) => {
310                         struct_span_err!(
311                             tcx.sess,
312                             span,
313                             E0231,
314                             "only named substitution parameters are allowed"
315                         )
316                         .emit();
317                         result = Err(ErrorReported);
318                     }
319                 },
320             }
321         }
322
323         result
324     }
325
326     pub fn format(
327         &self,
328         tcx: TyCtxt<'tcx>,
329         trait_ref: ty::TraitRef<'tcx>,
330         options: &FxHashMap<Symbol, String>,
331     ) -> String {
332         let name = tcx.item_name(trait_ref.def_id);
333         let trait_str = tcx.def_path_str(trait_ref.def_id);
334         let generics = tcx.generics_of(trait_ref.def_id);
335         let generic_map = generics
336             .params
337             .iter()
338             .filter_map(|param| {
339                 let value = match param.kind {
340                     GenericParamDefKind::Type { .. } | GenericParamDefKind::Const => {
341                         trait_ref.substs[param.index as usize].to_string()
342                     }
343                     GenericParamDefKind::Lifetime => return None,
344                 };
345                 let name = param.name;
346                 Some((name, value))
347             })
348             .collect::<FxHashMap<Symbol, String>>();
349         let empty_string = String::new();
350
351         let s = self.0.as_str();
352         let parser = Parser::new(&s, None, None, false, ParseMode::Format);
353         let item_context = (options.get(&sym::ItemContext)).unwrap_or(&empty_string);
354         parser
355             .map(|p| match p {
356                 Piece::String(s) => s,
357                 Piece::NextArgument(a) => match a.position {
358                     Position::ArgumentNamed(s) => match generic_map.get(&s) {
359                         Some(val) => val,
360                         None if s == name => &trait_str,
361                         None => {
362                             if let Some(val) = options.get(&s) {
363                                 val
364                             } else if s == sym::from_desugaring || s == sym::from_method {
365                                 // don't break messages using these two arguments incorrectly
366                                 &empty_string
367                             } else if s == sym::ItemContext {
368                                 &item_context
369                             } else {
370                                 bug!(
371                                     "broken on_unimplemented {:?} for {:?}: \
372                                       no argument matching {:?}",
373                                     self.0,
374                                     trait_ref,
375                                     s
376                                 )
377                             }
378                         }
379                     },
380                     _ => bug!("broken on_unimplemented {:?} - bad format arg", self.0),
381                 },
382             })
383             .collect()
384     }
385 }