1 use fmt_macros::{Parser, Piece, Position};
3 use crate::ty::{self, GenericParamDefKind, TyCtxt};
4 use crate::util::common::ErrorReported;
6 use rustc_data_structures::fx::FxHashMap;
7 use rustc_errors::struct_span_err;
8 use rustc_hir::def_id::DefId;
9 use rustc_span::symbol::{kw, sym, Symbol};
11 use syntax::ast::{MetaItem, NestedMetaItem};
14 use rustc_error_codes::*;
16 #[derive(Clone, Debug)]
17 pub struct OnUnimplementedFormatString(Symbol);
20 pub struct OnUnimplementedDirective {
21 pub condition: Option<MetaItem>,
22 pub subcommands: Vec<OnUnimplementedDirective>,
23 pub message: Option<OnUnimplementedFormatString>,
24 pub label: Option<OnUnimplementedFormatString>,
25 pub note: Option<OnUnimplementedFormatString>,
26 pub enclosing_scope: Option<OnUnimplementedFormatString>,
30 pub struct OnUnimplementedNote {
31 pub message: Option<String>,
32 pub label: Option<String>,
33 pub note: Option<String>,
34 pub enclosing_scope: Option<String>,
44 let mut diag = struct_span_err!(tcx.sess, span, E0232, "{}", message);
45 diag.span_label(span, label);
46 if let Some(note) = note {
53 impl<'tcx> OnUnimplementedDirective {
57 items: &[NestedMetaItem],
60 ) -> Result<Self, ErrorReported> {
61 let mut errored = false;
62 let mut item_iter = items.iter();
64 let condition = if is_root {
73 "empty `on`-clause in `#[rustc_on_unimplemented]`",
74 "empty on-clause here",
83 "invalid `on`-clause in `#[rustc_on_unimplemented]`",
84 "invalid on-clause here",
88 attr::eval_condition(cond, &tcx.sess.parse_sess, &mut |_| true);
92 let mut message = None;
95 let mut enclosing_scope = None;
96 let mut subcommands = vec![];
98 let parse_value = |value_str| {
99 OnUnimplementedFormatString::try_parse(tcx, trait_def_id, value_str, span).map(Some)
102 for item in item_iter {
103 if item.check_name(sym::message) && message.is_none() {
104 if let Some(message_) = item.value_str() {
105 message = parse_value(message_)?;
108 } else if item.check_name(sym::label) && label.is_none() {
109 if let Some(label_) = item.value_str() {
110 label = parse_value(label_)?;
113 } else if item.check_name(sym::note) && note.is_none() {
114 if let Some(note_) = item.value_str() {
115 note = parse_value(note_)?;
118 } else if item.check_name(sym::enclosing_scope) && enclosing_scope.is_none() {
119 if let Some(enclosing_scope_) = item.value_str() {
120 enclosing_scope = parse_value(enclosing_scope_)?;
123 } else if item.check_name(sym::on)
129 if let Some(items) = item.meta_item_list() {
130 if let Ok(subcommand) =
131 Self::parse(tcx, trait_def_id, &items, item.span(), false)
133 subcommands.push(subcommand);
145 "this attribute must have a valid value",
146 "expected value here",
147 Some(r#"eg `#[rustc_on_unimplemented(message="foo")]`"#),
154 Ok(OnUnimplementedDirective {
169 ) -> Result<Option<Self>, ErrorReported> {
170 let attrs = tcx.get_attrs(impl_def_id);
172 let attr = if let Some(item) = attr::find_by_name(&attrs, sym::rustc_on_unimplemented) {
178 let result = if let Some(items) = attr.meta_item_list() {
179 Self::parse(tcx, trait_def_id, &items, attr.span, true).map(Some)
180 } else if let Some(value) = attr.value_str() {
181 Ok(Some(OnUnimplementedDirective {
185 label: Some(OnUnimplementedFormatString::try_parse(
192 enclosing_scope: None,
195 return Err(ErrorReported);
197 debug!("of_item({:?}/{:?}) = {:?}", trait_def_id, impl_def_id, result);
204 trait_ref: ty::TraitRef<'tcx>,
205 options: &[(Symbol, Option<String>)],
206 ) -> OnUnimplementedNote {
207 let mut message = None;
208 let mut label = None;
210 let mut enclosing_scope = None;
211 info!("evaluate({:?}, trait_ref={:?}, options={:?})", self, trait_ref, options);
213 for command in self.subcommands.iter().chain(Some(self)).rev() {
214 if let Some(ref condition) = command.condition {
215 if !attr::eval_condition(condition, &tcx.sess.parse_sess, &mut |c| {
216 c.ident().map_or(false, |ident| {
217 options.contains(&(ident.name, c.value_str().map(|s| s.to_string())))
220 debug!("evaluate: skipping {:?} due to condition", command);
224 debug!("evaluate: {:?} succeeded", command);
225 if let Some(ref message_) = command.message {
226 message = Some(message_.clone());
229 if let Some(ref label_) = command.label {
230 label = Some(label_.clone());
233 if let Some(ref note_) = command.note {
234 note = Some(note_.clone());
237 if let Some(ref enclosing_scope_) = command.enclosing_scope {
238 enclosing_scope = Some(enclosing_scope_.clone());
242 let options: FxHashMap<Symbol, String> = options
244 .filter_map(|(k, v)| v.as_ref().map(|v| (*k, v.to_owned())))
246 OnUnimplementedNote {
247 label: label.map(|l| l.format(tcx, trait_ref, &options)),
248 message: message.map(|m| m.format(tcx, trait_ref, &options)),
249 note: note.map(|n| n.format(tcx, trait_ref, &options)),
250 enclosing_scope: enclosing_scope.map(|e_s| e_s.format(tcx, trait_ref, &options)),
255 impl<'tcx> OnUnimplementedFormatString {
261 ) -> Result<Self, ErrorReported> {
262 let result = OnUnimplementedFormatString(from);
263 result.verify(tcx, trait_def_id, err_sp)?;
272 ) -> Result<(), ErrorReported> {
273 let name = tcx.item_name(trait_def_id);
274 let generics = tcx.generics_of(trait_def_id);
275 let s = self.0.as_str();
276 let parser = Parser::new(&s, None, vec![], false);
277 let mut result = Ok(());
278 for token in parser {
280 Piece::String(_) => (), // Normal string, no need to check it
281 Piece::NextArgument(a) => match a.position {
282 // `{Self}` is allowed
283 Position::ArgumentNamed(s) if s == kw::SelfUpper => (),
284 // `{ThisTraitsName}` is allowed
285 Position::ArgumentNamed(s) if s == name => (),
286 // `{from_method}` is allowed
287 Position::ArgumentNamed(s) if s == sym::from_method => (),
288 // `{from_desugaring}` is allowed
289 Position::ArgumentNamed(s) if s == sym::from_desugaring => (),
290 // `{ItemContext}` is allowed
291 Position::ArgumentNamed(s) if s == sym::item_context => (),
292 // So is `{A}` if A is a type parameter
293 Position::ArgumentNamed(s) => {
294 match generics.params.iter().find(|param| param.name == s) {
301 "there is no parameter `{}` on trait `{}`",
306 result = Err(ErrorReported);
310 // `{:1}` and `{}` are not to be used
311 Position::ArgumentIs(_) | Position::ArgumentImplicitlyIs(_) => {
316 "only named substitution parameters are allowed"
319 result = Err(ErrorReported);
331 trait_ref: ty::TraitRef<'tcx>,
332 options: &FxHashMap<Symbol, String>,
334 let name = tcx.item_name(trait_ref.def_id);
335 let trait_str = tcx.def_path_str(trait_ref.def_id);
336 let generics = tcx.generics_of(trait_ref.def_id);
337 let generic_map = generics
340 .filter_map(|param| {
341 let value = match param.kind {
342 GenericParamDefKind::Type { .. } | GenericParamDefKind::Const => {
343 trait_ref.substs[param.index as usize].to_string()
345 GenericParamDefKind::Lifetime => return None,
347 let name = param.name;
350 .collect::<FxHashMap<Symbol, String>>();
351 let empty_string = String::new();
353 let s = self.0.as_str();
354 let parser = Parser::new(&s, None, vec![], false);
355 let item_context = (options.get(&sym::item_context)).unwrap_or(&empty_string);
358 Piece::String(s) => s,
359 Piece::NextArgument(a) => match a.position {
360 Position::ArgumentNamed(s) => match generic_map.get(&s) {
362 None if s == name => &trait_str,
364 if let Some(val) = options.get(&s) {
366 } else if s == sym::from_desugaring || s == sym::from_method {
367 // don't break messages using these two arguments incorrectly
369 } else if s == sym::item_context {
373 "broken on_unimplemented {:?} for {:?}: \
374 no argument matching {:?}",
382 _ => bug!("broken on_unimplemented {:?} - bad format arg", self.0),