1 use fmt_macros::{Parser, Piece, Position};
3 use crate::hir::def_id::DefId;
4 use crate::ty::{self, GenericParamDefKind, TyCtxt};
5 use crate::util::common::ErrorReported;
6 use crate::util::nodemap::FxHashMap;
9 use syntax::ast::{MetaItem, NestedMetaItem};
11 use syntax::symbol::{kw, sym, Symbol};
13 use rustc_error_codes::*;
15 #[derive(Clone, Debug)]
16 pub struct OnUnimplementedFormatString(Symbol);
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 enclosing_scope: Option<OnUnimplementedFormatString>,
29 pub struct OnUnimplementedNote {
30 pub message: Option<String>,
31 pub label: Option<String>,
32 pub note: Option<String>,
33 pub enclosing_scope: Option<String>,
43 let mut diag = struct_span_err!(tcx.sess, span, E0232, "{}", message);
44 diag.span_label(span, label);
45 if let Some(note) = note {
52 impl<'tcx> OnUnimplementedDirective {
56 items: &[NestedMetaItem],
59 ) -> Result<Self, ErrorReported> {
60 let mut errored = false;
61 let mut item_iter = items.iter();
63 let condition = if is_root {
72 "empty `on`-clause in `#[rustc_on_unimplemented]`",
73 "empty on-clause here",
82 "invalid `on`-clause in `#[rustc_on_unimplemented]`",
83 "invalid on-clause here",
87 attr::eval_condition(cond, &tcx.sess.parse_sess, &mut |_| true);
91 let mut message = None;
94 let mut enclosing_scope = None;
95 let mut subcommands = vec![];
97 let parse_value = |value_str| {
98 OnUnimplementedFormatString::try_parse(tcx, trait_def_id, value_str, span).map(Some)
101 for item in item_iter {
102 if item.check_name(sym::message) && message.is_none() {
103 if let Some(message_) = item.value_str() {
104 message = parse_value(message_)?;
107 } else if item.check_name(sym::label) && label.is_none() {
108 if let Some(label_) = item.value_str() {
109 label = parse_value(label_)?;
112 } else if item.check_name(sym::note) && note.is_none() {
113 if let Some(note_) = item.value_str() {
114 note = parse_value(note_)?;
117 } else if item.check_name(sym::enclosing_scope) && enclosing_scope.is_none() {
118 if let Some(enclosing_scope_) = item.value_str() {
119 enclosing_scope = parse_value(enclosing_scope_)?;
122 } else if item.check_name(sym::on)
128 if let Some(items) = item.meta_item_list() {
129 if let Ok(subcommand) =
130 Self::parse(tcx, trait_def_id, &items, item.span(), false)
132 subcommands.push(subcommand);
144 "this attribute must have a valid value",
145 "expected value here",
146 Some(r#"eg `#[rustc_on_unimplemented(message="foo")]`"#),
153 Ok(OnUnimplementedDirective {
168 ) -> Result<Option<Self>, ErrorReported> {
169 let attrs = tcx.get_attrs(impl_def_id);
171 let attr = if let Some(item) = attr::find_by_name(&attrs, sym::rustc_on_unimplemented) {
177 let result = if let Some(items) = attr.meta_item_list() {
178 Self::parse(tcx, trait_def_id, &items, attr.span, true).map(Some)
179 } else if let Some(value) = attr.value_str() {
180 Ok(Some(OnUnimplementedDirective {
184 label: Some(OnUnimplementedFormatString::try_parse(
191 enclosing_scope: None,
194 return Err(ErrorReported);
196 debug!("of_item({:?}/{:?}) = {:?}", trait_def_id, impl_def_id, result);
203 trait_ref: ty::TraitRef<'tcx>,
204 options: &[(Symbol, Option<String>)],
205 ) -> OnUnimplementedNote {
206 let mut message = None;
207 let mut label = None;
209 let mut enclosing_scope = None;
210 info!("evaluate({:?}, trait_ref={:?}, options={:?})", self, trait_ref, options);
212 for command in self.subcommands.iter().chain(Some(self)).rev() {
213 if let Some(ref condition) = command.condition {
214 if !attr::eval_condition(condition, &tcx.sess.parse_sess, &mut |c| {
215 c.ident().map_or(false, |ident| {
216 options.contains(&(ident.name, c.value_str().map(|s| s.to_string())))
219 debug!("evaluate: skipping {:?} due to condition", command);
223 debug!("evaluate: {:?} succeeded", command);
224 if let Some(ref message_) = command.message {
225 message = Some(message_.clone());
228 if let Some(ref label_) = command.label {
229 label = Some(label_.clone());
232 if let Some(ref note_) = command.note {
233 note = Some(note_.clone());
236 if let Some(ref enclosing_scope_) = command.enclosing_scope {
237 enclosing_scope = Some(enclosing_scope_.clone());
241 let options: FxHashMap<Symbol, String> = options
243 .filter_map(|(k, v)| v.as_ref().map(|v| (*k, v.to_owned())))
245 OnUnimplementedNote {
246 label: label.map(|l| l.format(tcx, trait_ref, &options)),
247 message: message.map(|m| m.format(tcx, trait_ref, &options)),
248 note: note.map(|n| n.format(tcx, trait_ref, &options)),
249 enclosing_scope: enclosing_scope.map(|e_s| e_s.format(tcx, trait_ref, &options)),
254 impl<'tcx> OnUnimplementedFormatString {
260 ) -> Result<Self, ErrorReported> {
261 let result = OnUnimplementedFormatString(from);
262 result.verify(tcx, trait_def_id, err_sp)?;
271 ) -> Result<(), ErrorReported> {
272 let name = tcx.item_name(trait_def_id);
273 let generics = tcx.generics_of(trait_def_id);
274 let s = self.0.as_str();
275 let parser = Parser::new(&s, None, vec![], false);
276 let mut result = Ok(());
277 for token in parser {
279 Piece::String(_) => (), // Normal string, no need to check it
280 Piece::NextArgument(a) => match a.position {
281 // `{Self}` is allowed
282 Position::ArgumentNamed(s) if s == kw::SelfUpper => (),
283 // `{ThisTraitsName}` is allowed
284 Position::ArgumentNamed(s) if s == name => (),
285 // `{from_method}` is allowed
286 Position::ArgumentNamed(s) if s == sym::from_method => (),
287 // `{from_desugaring}` is allowed
288 Position::ArgumentNamed(s) if s == sym::from_desugaring => (),
289 // `{ItemContext}` is allowed
290 Position::ArgumentNamed(s) if s == sym::item_context => (),
291 // So is `{A}` if A is a type parameter
292 Position::ArgumentNamed(s) => {
293 match generics.params.iter().find(|param| param.name == s) {
300 "there is no parameter `{}` on trait `{}`",
304 result = Err(ErrorReported);
308 // `{:1}` and `{}` are not to be used
309 Position::ArgumentIs(_) | Position::ArgumentImplicitlyIs(_) => {
314 "only named substitution parameters are allowed"
316 result = Err(ErrorReported);
328 trait_ref: ty::TraitRef<'tcx>,
329 options: &FxHashMap<Symbol, 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
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()
342 GenericParamDefKind::Lifetime => return None,
344 let name = param.name;
347 .collect::<FxHashMap<Symbol, String>>();
348 let empty_string = String::new();
350 let s = self.0.as_str();
351 let parser = Parser::new(&s, None, vec![], false);
352 let item_context = (options.get(&sym::item_context)).unwrap_or(&empty_string);
355 Piece::String(s) => s,
356 Piece::NextArgument(a) => match a.position {
357 Position::ArgumentNamed(s) => match generic_map.get(&s) {
359 None if s == name => &trait_str,
361 if let Some(val) = options.get(&s) {
363 } else if s == sym::from_desugaring || s == sym::from_method {
364 // don't break messages using these two arguments incorrectly
366 } else if s == sym::item_context {
370 "broken on_unimplemented {:?} for {:?}: \
371 no argument matching {:?}",
379 _ => bug!("broken on_unimplemented {:?} - bad format arg", self.0),