]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_trait_selection/src/traits/on_unimplemented.rs
fb062ea71c4ce775bf6c74cf4c153dde6a74a1f3
[rust.git] / compiler / rustc_trait_selection / src / traits / on_unimplemented.rs
1 use rustc_ast::{MetaItem, NestedMetaItem};
2 use rustc_attr as attr;
3 use rustc_data_structures::fx::FxHashMap;
4 use rustc_errors::{struct_span_err, ErrorGuaranteed};
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, DUMMY_SP};
10
11 use crate::errors::{
12     EmptyOnClauseInOnUnimplemented, InvalidOnClauseInOnUnimplemented, NoValueInOnUnimplemented,
13 };
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 parent_label: Option<OnUnimplementedFormatString>,
26     pub append_const_msg: Option<Option<Symbol>>,
27 }
28
29 #[derive(Default)]
30 /// For the `#[rustc_on_unimplemented]` attribute
31 pub struct OnUnimplementedNote {
32     pub message: Option<String>,
33     pub label: Option<String>,
34     pub note: Option<String>,
35     pub parent_label: Option<String>,
36     /// Append a message for `~const Trait` errors. `None` means not requested and
37     /// should fallback to a generic message, `Some(None)` suggests using the default
38     /// appended message, `Some(Some(s))` suggests use the `s` message instead of the
39     /// default one..
40     pub append_const_msg: Option<Option<Symbol>>,
41 }
42
43 impl<'tcx> OnUnimplementedDirective {
44     fn parse(
45         tcx: TyCtxt<'tcx>,
46         item_def_id: DefId,
47         items: &[NestedMetaItem],
48         span: Span,
49         is_root: bool,
50     ) -> Result<Self, ErrorGuaranteed> {
51         let mut errored = None;
52         let mut item_iter = items.iter();
53
54         let parse_value = |value_str| {
55             OnUnimplementedFormatString::try_parse(tcx, item_def_id, value_str, span).map(Some)
56         };
57
58         let condition = if is_root {
59             None
60         } else {
61             let cond = item_iter
62                 .next()
63                 .ok_or_else(|| tcx.sess.emit_err(EmptyOnClauseInOnUnimplemented { span }))?
64                 .meta_item()
65                 .ok_or_else(|| tcx.sess.emit_err(InvalidOnClauseInOnUnimplemented { span }))?;
66             attr::eval_condition(cond, &tcx.sess.parse_sess, Some(tcx.features()), &mut |cfg| {
67                 if let Some(value) = cfg.value && let Err(guar) = parse_value(value) {
68                     errored = Some(guar);
69                 }
70                 true
71             });
72             Some(cond.clone())
73         };
74
75         let mut message = None;
76         let mut label = None;
77         let mut note = None;
78         let mut parent_label = None;
79         let mut subcommands = vec![];
80         let mut append_const_msg = None;
81
82         for item in item_iter {
83             if item.has_name(sym::message) && message.is_none() {
84                 if let Some(message_) = item.value_str() {
85                     message = parse_value(message_)?;
86                     continue;
87                 }
88             } else if item.has_name(sym::label) && label.is_none() {
89                 if let Some(label_) = item.value_str() {
90                     label = parse_value(label_)?;
91                     continue;
92                 }
93             } else if item.has_name(sym::note) && note.is_none() {
94                 if let Some(note_) = item.value_str() {
95                     note = parse_value(note_)?;
96                     continue;
97                 }
98             } else if item.has_name(sym::parent_label) && parent_label.is_none() {
99                 if let Some(parent_label_) = item.value_str() {
100                     parent_label = parse_value(parent_label_)?;
101                     continue;
102                 }
103             } else if item.has_name(sym::on)
104                 && is_root
105                 && message.is_none()
106                 && label.is_none()
107                 && note.is_none()
108             {
109                 if let Some(items) = item.meta_item_list() {
110                     match Self::parse(tcx, item_def_id, &items, item.span(), false) {
111                         Ok(subcommand) => subcommands.push(subcommand),
112                         Err(reported) => errored = Some(reported),
113                     };
114                     continue;
115                 }
116             } else if item.has_name(sym::append_const_msg) && append_const_msg.is_none() {
117                 if let Some(msg) = item.value_str() {
118                     append_const_msg = Some(Some(msg));
119                     continue;
120                 } else if item.is_word() {
121                     append_const_msg = Some(None);
122                     continue;
123                 }
124             }
125
126             // nothing found
127             tcx.sess.emit_err(NoValueInOnUnimplemented { span: item.span() });
128         }
129
130         if let Some(reported) = errored {
131             Err(reported)
132         } else {
133             Ok(OnUnimplementedDirective {
134                 condition,
135                 subcommands,
136                 message,
137                 label,
138                 note,
139                 parent_label,
140                 append_const_msg,
141             })
142         }
143     }
144
145     pub fn of_item(tcx: TyCtxt<'tcx>, item_def_id: DefId) -> Result<Option<Self>, ErrorGuaranteed> {
146         let Some(attr) = tcx.get_attr(item_def_id, sym::rustc_on_unimplemented) else {
147             return Ok(None);
148         };
149
150         let result = if let Some(items) = attr.meta_item_list() {
151             Self::parse(tcx, item_def_id, &items, attr.span, true).map(Some)
152         } else if let Some(value) = attr.value_str() {
153             Ok(Some(OnUnimplementedDirective {
154                 condition: None,
155                 message: None,
156                 subcommands: vec![],
157                 label: Some(OnUnimplementedFormatString::try_parse(
158                     tcx,
159                     item_def_id,
160                     value,
161                     attr.span,
162                 )?),
163                 note: None,
164                 parent_label: None,
165                 append_const_msg: None,
166             }))
167         } else {
168             let reported =
169                 tcx.sess.delay_span_bug(DUMMY_SP, "of_item: neither meta_item_list nor value_str");
170             return Err(reported);
171         };
172         debug!("of_item({:?}) = {:?}", item_def_id, result);
173         result
174     }
175
176     pub fn evaluate(
177         &self,
178         tcx: TyCtxt<'tcx>,
179         trait_ref: ty::TraitRef<'tcx>,
180         options: &[(Symbol, Option<String>)],
181     ) -> OnUnimplementedNote {
182         let mut message = None;
183         let mut label = None;
184         let mut note = None;
185         let mut parent_label = None;
186         let mut append_const_msg = None;
187         info!("evaluate({:?}, trait_ref={:?}, options={:?})", self, trait_ref, options);
188
189         let options_map: FxHashMap<Symbol, String> =
190             options.iter().filter_map(|(k, v)| v.as_ref().map(|v| (*k, v.to_owned()))).collect();
191
192         for command in self.subcommands.iter().chain(Some(self)).rev() {
193             if let Some(ref condition) = command.condition && !attr::eval_condition(
194                 condition,
195                 &tcx.sess.parse_sess,
196                 Some(tcx.features()),
197                 &mut |cfg| {
198                     let value = cfg.value.map(|v| {
199                         OnUnimplementedFormatString(v).format(tcx, trait_ref, &options_map)
200                     });
201
202                     options.contains(&(cfg.name, value))
203                 },
204             ) {
205                 debug!("evaluate: skipping {:?} due to condition", command);
206                 continue;
207             }
208             debug!("evaluate: {:?} succeeded", command);
209             if let Some(ref message_) = command.message {
210                 message = Some(message_.clone());
211             }
212
213             if let Some(ref label_) = command.label {
214                 label = Some(label_.clone());
215             }
216
217             if let Some(ref note_) = command.note {
218                 note = Some(note_.clone());
219             }
220
221             if let Some(ref parent_label_) = command.parent_label {
222                 parent_label = Some(parent_label_.clone());
223             }
224
225             append_const_msg = command.append_const_msg;
226         }
227
228         OnUnimplementedNote {
229             label: label.map(|l| l.format(tcx, trait_ref, &options_map)),
230             message: message.map(|m| m.format(tcx, trait_ref, &options_map)),
231             note: note.map(|n| n.format(tcx, trait_ref, &options_map)),
232             parent_label: parent_label.map(|e_s| e_s.format(tcx, trait_ref, &options_map)),
233             append_const_msg,
234         }
235     }
236 }
237
238 impl<'tcx> OnUnimplementedFormatString {
239     fn try_parse(
240         tcx: TyCtxt<'tcx>,
241         item_def_id: DefId,
242         from: Symbol,
243         err_sp: Span,
244     ) -> Result<Self, ErrorGuaranteed> {
245         let result = OnUnimplementedFormatString(from);
246         result.verify(tcx, item_def_id, err_sp)?;
247         Ok(result)
248     }
249
250     fn verify(
251         &self,
252         tcx: TyCtxt<'tcx>,
253         item_def_id: DefId,
254         span: Span,
255     ) -> Result<(), ErrorGuaranteed> {
256         let trait_def_id = if tcx.is_trait(item_def_id) {
257             item_def_id
258         } else {
259             tcx.trait_id_of_impl(item_def_id)
260                 .expect("expected `on_unimplemented` to correspond to a trait")
261         };
262         let trait_name = tcx.item_name(trait_def_id);
263         let generics = tcx.generics_of(item_def_id);
264         let s = self.0.as_str();
265         let parser = Parser::new(s, None, None, false, ParseMode::Format);
266         let mut result = Ok(());
267         for token in parser {
268             match token {
269                 Piece::String(_) => (), // Normal string, no need to check it
270                 Piece::NextArgument(a) => match a.position {
271                     Position::ArgumentNamed(s) => {
272                         match Symbol::intern(s) {
273                             // `{Self}` is allowed
274                             kw::SelfUpper => (),
275                             // `{ThisTraitsName}` is allowed
276                             s if s == trait_name => (),
277                             // `{from_method}` is allowed
278                             sym::from_method => (),
279                             // `{from_desugaring}` is allowed
280                             sym::from_desugaring => (),
281                             // `{ItemContext}` is allowed
282                             sym::ItemContext => (),
283                             // `{integral}` and `{integer}` and `{float}` are allowed
284                             sym::integral | sym::integer_ | sym::float => (),
285                             // So is `{A}` if A is a type parameter
286                             s => match generics.params.iter().find(|param| param.name == s) {
287                                 Some(_) => (),
288                                 None => {
289                                     let reported = struct_span_err!(
290                                         tcx.sess,
291                                         span,
292                                         E0230,
293                                         "there is no parameter `{}` on {}",
294                                         s,
295                                         if trait_def_id == item_def_id {
296                                             format!("trait `{}`", trait_name)
297                                         } else {
298                                             "impl".to_string()
299                                         }
300                                     )
301                                     .emit();
302                                     result = Err(reported);
303                                 }
304                             },
305                         }
306                     }
307                     // `{:1}` and `{}` are not to be used
308                     Position::ArgumentIs(..) | Position::ArgumentImplicitlyIs(_) => {
309                         let reported = struct_span_err!(
310                             tcx.sess,
311                             span,
312                             E0231,
313                             "only named substitution parameters are allowed"
314                         )
315                         .emit();
316                         result = Err(reported);
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, None, false, ParseMode::Format);
352         let item_context = (options.get(&sym::ItemContext)).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) => {
358                         let s = Symbol::intern(s);
359                         match generic_map.get(&s) {
360                             Some(val) => val,
361                             None if s == name => &trait_str,
362                             None => {
363                                 if let Some(val) = options.get(&s) {
364                                     val
365                                 } else if s == sym::from_desugaring || s == sym::from_method {
366                                     // don't break messages using these two arguments incorrectly
367                                     &empty_string
368                                 } else if s == sym::ItemContext {
369                                     &item_context
370                                 } else if s == sym::integral {
371                                     "{integral}"
372                                 } else if s == sym::integer_ {
373                                     "{integer}"
374                                 } else if s == sym::float {
375                                     "{float}"
376                                 } else {
377                                     bug!(
378                                         "broken on_unimplemented {:?} for {:?}: \
379                                       no argument matching {:?}",
380                                         self.0,
381                                         trait_ref,
382                                         s
383                                     )
384                                 }
385                             }
386                         }
387                     }
388                     _ => bug!("broken on_unimplemented {:?} - bad format arg", self.0),
389                 },
390             })
391             .collect()
392     }
393 }