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