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