1 //! Contains utility functions to generate suggestions.
2 #![deny(missing_docs_in_private_items)]
5 use rustc::lint::{EarlyContext, LateContext, LintContext};
10 use syntax::codemap::{CharPos, Span};
11 use syntax::parse::token;
12 use syntax::print::pprust::token_to_string;
13 use syntax::util::parser::AssocOp;
15 use utils::{higher, snippet, snippet_opt};
17 /// A helper type to build suggestion correctly handling parenthesis.
19 /// An expression that never needs parenthesis such as `1337` or `[0; 42]`.
20 NonParen(Cow<'a, str>),
21 /// An expression that does not fit in other variants.
22 MaybeParen(Cow<'a, str>),
23 /// A binary operator expression, including `as`-casts and explicit type coercion.
24 BinOp(AssocOp, Cow<'a, str>),
27 /// Literal constant `1`, for convenience.
28 pub const ONE: Sugg<'static> = Sugg::NonParen(Cow::Borrowed("1"));
30 impl<'a> Display for Sugg<'a> {
31 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
33 Sugg::NonParen(ref s) |
34 Sugg::MaybeParen(ref s) |
35 Sugg::BinOp(_, ref s) => s.fmt(f),
40 #[allow(wrong_self_convention)] // ok, because of the function `as_ty` method
42 /// Prepare a suggestion from an expression.
43 pub fn hir_opt(cx: &LateContext, expr: &hir::Expr) -> Option<Sugg<'a>> {
44 snippet_opt(cx, expr.span).map(|snippet| {
45 let snippet = Cow::Owned(snippet);
49 hir::ExprClosure(..) |
52 hir::ExprMatch(..) => Sugg::MaybeParen(snippet),
60 hir::ExprInlineAsm(..) |
63 hir::ExprMethodCall(..) |
69 hir::ExprTupField(..) |
70 hir::ExprWhile(..) => Sugg::NonParen(snippet),
71 hir::ExprAssign(..) => Sugg::BinOp(AssocOp::Assign, snippet),
72 hir::ExprAssignOp(op, ..) => Sugg::BinOp(hirbinop2assignop(op), snippet),
73 hir::ExprBinary(op, ..) => Sugg::BinOp(AssocOp::from_ast_binop(higher::binop(op.node)), snippet),
74 hir::ExprCast(..) => Sugg::BinOp(AssocOp::As, snippet),
75 hir::ExprType(..) => Sugg::BinOp(AssocOp::Colon, snippet),
80 /// Convenience function around `hir_opt` for suggestions with a default text.
81 pub fn hir(cx: &LateContext, expr: &hir::Expr, default: &'a str) -> Sugg<'a> {
82 Self::hir_opt(cx, expr).unwrap_or_else(|| Sugg::NonParen(Cow::Borrowed(default)))
85 /// Prepare a suggestion from an expression.
86 pub fn ast(cx: &EarlyContext, expr: &ast::Expr, default: &'a str) -> Sugg<'a> {
87 use syntax::ast::RangeLimits;
89 let snippet = snippet(cx, expr.span, default);
92 ast::ExprKind::AddrOf(..) |
93 ast::ExprKind::Box(..) |
94 ast::ExprKind::Closure(..) |
95 ast::ExprKind::If(..) |
96 ast::ExprKind::IfLet(..) |
97 ast::ExprKind::InPlace(..) |
98 ast::ExprKind::Unary(..) |
99 ast::ExprKind::Match(..) => Sugg::MaybeParen(snippet),
100 ast::ExprKind::Block(..) |
101 ast::ExprKind::Break(..) |
102 ast::ExprKind::Call(..) |
103 ast::ExprKind::Catch(..) |
104 ast::ExprKind::Continue(..) |
105 ast::ExprKind::Field(..) |
106 ast::ExprKind::ForLoop(..) |
107 ast::ExprKind::Index(..) |
108 ast::ExprKind::InlineAsm(..) |
109 ast::ExprKind::Lit(..) |
110 ast::ExprKind::Loop(..) |
111 ast::ExprKind::Mac(..) |
112 ast::ExprKind::MethodCall(..) |
113 ast::ExprKind::Paren(..) |
114 ast::ExprKind::Path(..) |
115 ast::ExprKind::Repeat(..) |
116 ast::ExprKind::Ret(..) |
117 ast::ExprKind::Struct(..) |
118 ast::ExprKind::Try(..) |
119 ast::ExprKind::Tup(..) |
120 ast::ExprKind::TupField(..) |
121 ast::ExprKind::Array(..) |
122 ast::ExprKind::While(..) |
123 ast::ExprKind::WhileLet(..) => Sugg::NonParen(snippet),
124 ast::ExprKind::Range(.., RangeLimits::HalfOpen) => Sugg::BinOp(AssocOp::DotDot, snippet),
125 ast::ExprKind::Range(.., RangeLimits::Closed) => Sugg::BinOp(AssocOp::DotDotDot, snippet),
126 ast::ExprKind::Assign(..) => Sugg::BinOp(AssocOp::Assign, snippet),
127 ast::ExprKind::AssignOp(op, ..) => Sugg::BinOp(astbinop2assignop(op), snippet),
128 ast::ExprKind::Binary(op, ..) => Sugg::BinOp(AssocOp::from_ast_binop(op.node), snippet),
129 ast::ExprKind::Cast(..) => Sugg::BinOp(AssocOp::As, snippet),
130 ast::ExprKind::Type(..) => Sugg::BinOp(AssocOp::Colon, snippet),
134 /// Convenience method to create the `<lhs> && <rhs>` suggestion.
135 pub fn and(self, rhs: Self) -> Sugg<'static> {
136 make_binop(ast::BinOpKind::And, &self, &rhs)
139 /// Convenience method to create the `<lhs> as <rhs>` suggestion.
140 pub fn as_ty<R: Display>(self, rhs: R) -> Sugg<'static> {
141 make_assoc(AssocOp::As, &self, &Sugg::NonParen(rhs.to_string().into()))
144 /// Convenience method to create the `&<expr>` suggestion.
145 pub fn addr(self) -> Sugg<'static> {
149 /// Convenience method to create the `&mut <expr>` suggestion.
150 pub fn mut_addr(self) -> Sugg<'static> {
151 make_unop("&mut ", self)
154 /// Convenience method to create the `*<expr>` suggestion.
155 pub fn deref(self) -> Sugg<'static> {
159 /// Convenience method to create the `<lhs>..<rhs>` or `<lhs>...<rhs>` suggestion.
160 pub fn range(self, end: Self, limit: ast::RangeLimits) -> Sugg<'static> {
162 ast::RangeLimits::HalfOpen => make_assoc(AssocOp::DotDot, &self, &end),
163 ast::RangeLimits::Closed => make_assoc(AssocOp::DotDotDot, &self, &end),
167 /// Add parenthesis to any expression that might need them. Suitable to the `self` argument of
168 /// a method call (eg. to build `bar.foo()` or `(1 + 2).foo()`).
169 pub fn maybe_par(self) -> Self {
171 Sugg::NonParen(..) => self,
172 // (x) and (x).y() both don't need additional parens
173 Sugg::MaybeParen(sugg) => {
174 if sugg.starts_with('(') && sugg.ends_with(')') {
175 Sugg::MaybeParen(sugg)
177 Sugg::NonParen(format!("({})", sugg).into())
180 Sugg::BinOp(_, sugg) => Sugg::NonParen(format!("({})", sugg).into()),
185 impl<'a, 'b> std::ops::Add<Sugg<'b>> for Sugg<'a> {
186 type Output = Sugg<'static>;
187 fn add(self, rhs: Sugg<'b>) -> Sugg<'static> {
188 make_binop(ast::BinOpKind::Add, &self, &rhs)
192 impl<'a, 'b> std::ops::Sub<Sugg<'b>> for Sugg<'a> {
193 type Output = Sugg<'static>;
194 fn sub(self, rhs: Sugg<'b>) -> Sugg<'static> {
195 make_binop(ast::BinOpKind::Sub, &self, &rhs)
199 impl<'a> std::ops::Not for Sugg<'a> {
200 type Output = Sugg<'static>;
201 fn not(self) -> Sugg<'static> {
206 /// Helper type to display either `foo` or `(foo)`.
207 struct ParenHelper<T> {
208 /// Whether parenthesis are needed.
210 /// The main thing to display.
214 impl<T> ParenHelper<T> {
215 /// Build a `ParenHelper`.
216 fn new(paren: bool, wrapped: T) -> Self {
224 impl<T: Display> Display for ParenHelper<T> {
225 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
227 write!(f, "({})", self.wrapped)
234 /// Build the string for `<op><expr>` adding parenthesis when necessary.
236 /// For convenience, the operator is taken as a string because all unary operators have the same
238 pub fn make_unop(op: &str, expr: Sugg) -> Sugg<'static> {
239 Sugg::MaybeParen(format!("{}{}", op, expr.maybe_par()).into())
242 /// Build the string for `<lhs> <op> <rhs>` adding parenthesis when necessary.
244 /// Precedence of shift operator relative to other arithmetic operation is often confusing so
245 /// parenthesis will always be added for a mix of these.
246 pub fn make_assoc(op: AssocOp, lhs: &Sugg, rhs: &Sugg) -> Sugg<'static> {
247 /// Whether the operator is a shift operator `<<` or `>>`.
248 fn is_shift(op: &AssocOp) -> bool {
249 matches!(*op, AssocOp::ShiftLeft | AssocOp::ShiftRight)
252 /// Whether the operator is a arithmetic operator (`+`, `-`, `*`, `/`, `%`).
253 fn is_arith(op: &AssocOp) -> bool {
255 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide | AssocOp::Modulus)
258 /// Whether the operator `op` needs parenthesis with the operator `other` in the direction
260 fn needs_paren(op: &AssocOp, other: &AssocOp, dir: Associativity) -> bool {
261 other.precedence() < op.precedence() ||
262 (other.precedence() == op.precedence() &&
263 ((op != other && associativity(op) != dir) ||
264 (op == other && associativity(op) != Associativity::Both))) || is_shift(op) && is_arith(other) ||
265 is_shift(other) && is_arith(op)
268 let lhs_paren = if let Sugg::BinOp(ref lop, _) = *lhs {
269 needs_paren(&op, lop, Associativity::Left)
274 let rhs_paren = if let Sugg::BinOp(ref rop, _) = *rhs {
275 needs_paren(&op, rop, Associativity::Right)
280 let lhs = ParenHelper::new(lhs_paren, lhs);
281 let rhs = ParenHelper::new(rhs_paren, rhs);
282 let sugg = match op {
283 AssocOp::Add | AssocOp::BitAnd | AssocOp::BitOr | AssocOp::BitXor | AssocOp::Divide | AssocOp::Equal |
284 AssocOp::Greater | AssocOp::GreaterEqual | AssocOp::LAnd | AssocOp::LOr | AssocOp::Less |
285 AssocOp::LessEqual | AssocOp::Modulus | AssocOp::Multiply | AssocOp::NotEqual | AssocOp::ShiftLeft |
286 AssocOp::ShiftRight | AssocOp::Subtract => {
287 format!("{} {} {}", lhs, op.to_ast_binop().expect("Those are AST ops").to_string(), rhs)
289 AssocOp::Inplace => format!("in ({}) {}", lhs, rhs),
290 AssocOp::Assign => format!("{} = {}", lhs, rhs),
291 AssocOp::AssignOp(op) => format!("{} {}= {}", lhs, token_to_string(&token::BinOp(op)), rhs),
292 AssocOp::As => format!("{} as {}", lhs, rhs),
293 AssocOp::DotDot => format!("{}..{}", lhs, rhs),
294 AssocOp::DotDotDot => format!("{}...{}", lhs, rhs),
295 AssocOp::Colon => format!("{}: {}", lhs, rhs),
298 Sugg::BinOp(op, sugg.into())
301 /// Convinience wrapper arround `make_assoc` and `AssocOp::from_ast_binop`.
302 pub fn make_binop(op: ast::BinOpKind, lhs: &Sugg, rhs: &Sugg) -> Sugg<'static> {
303 make_assoc(AssocOp::from_ast_binop(op), lhs, rhs)
306 #[derive(PartialEq, Eq, Clone, Copy)]
307 /// Operator associativity.
309 /// The operator is both left-associative and right-associative.
311 /// The operator is left-associative.
313 /// The operator is not associative.
315 /// The operator is right-associative.
319 /// Return the associativity/fixity of an operator. The difference with `AssocOp::fixity` is that
320 /// an operator can be both left and right associative (such as `+`:
321 /// `a + b + c == (a + b) + c == a + (b + c)`.
323 /// Chained `as` and explicit `:` type coercion never need inner parenthesis so they are considered
325 fn associativity(op: &AssocOp) -> Associativity {
326 use syntax::util::parser::AssocOp::*;
329 Inplace | Assign | AssignOp(_) => Associativity::Right,
330 Add | BitAnd | BitOr | BitXor | LAnd | LOr | Multiply | As | Colon => Associativity::Both,
331 Divide | Equal | Greater | GreaterEqual | Less | LessEqual | Modulus | NotEqual | ShiftLeft | ShiftRight |
332 Subtract => Associativity::Left,
333 DotDot | DotDotDot => Associativity::None,
337 /// Convert a `hir::BinOp` to the corresponding assigning binary operator.
338 fn hirbinop2assignop(op: hir::BinOp) -> AssocOp {
339 use rustc::hir::BinOp_::*;
340 use syntax::parse::token::BinOpToken::*;
342 AssocOp::AssignOp(match op.node {
353 BiAnd | BiEq | BiGe | BiGt | BiLe | BiLt | BiNe | BiOr => panic!("This operator does not exist"),
357 /// Convert an `ast::BinOp` to the corresponding assigning binary operator.
358 fn astbinop2assignop(op: ast::BinOp) -> AssocOp {
359 use syntax::ast::BinOpKind::*;
360 use syntax::parse::token::BinOpToken;
362 AssocOp::AssignOp(match op.node {
363 Add => BinOpToken::Plus,
364 BitAnd => BinOpToken::And,
365 BitOr => BinOpToken::Or,
366 BitXor => BinOpToken::Caret,
367 Div => BinOpToken::Slash,
368 Mul => BinOpToken::Star,
369 Rem => BinOpToken::Percent,
370 Shl => BinOpToken::Shl,
371 Shr => BinOpToken::Shr,
372 Sub => BinOpToken::Minus,
373 And | Eq | Ge | Gt | Le | Lt | Ne | Or => panic!("This operator does not exist"),
377 /// Return the indentation before `span` if there are nothing but `[ \t]` before it on its line.
378 fn indentation<'a, T: LintContext<'a>>(cx: &T, span: Span) -> Option<String> {
379 let lo = cx.sess().codemap().lookup_char_pos(span.lo);
380 if let Some(line) = lo.file.get_line(lo.line - 1 /* line numbers in `Loc` are 1-based */) {
381 if let Some((pos, _)) = line.char_indices().find(|&(_, c)| c != ' ' && c != '\t') {
382 // we can mix char and byte positions here because we only consider `[ \t]`
383 if lo.col == CharPos(pos) {
384 Some(line[..pos].into())
396 /// Convenience extension trait for `DiagnosticBuilder`.
397 pub trait DiagnosticBuilderExt<'a, T: LintContext<'a>> {
398 /// Suggests to add an attribute to an item.
400 /// Correctly handles indentation of the attribute and item.
405 /// db.suggest_item_with_attr(cx, item, "#[derive(Default)]");
407 fn suggest_item_with_attr<D: Display + ?Sized>(&mut self, cx: &T, item: Span, msg: &str, attr: &D);
409 /// Suggest to add an item before another.
411 /// The item should not be indented (expect for inner indentation).
416 /// db.suggest_prepend_item(cx, item,
421 fn suggest_prepend_item(&mut self, cx: &T, item: Span, msg: &str, new_item: &str);
424 impl<'a, 'b, 'c, T: LintContext<'c>> DiagnosticBuilderExt<'c, T> for rustc_errors::DiagnosticBuilder<'b> {
425 fn suggest_item_with_attr<D: Display + ?Sized>(&mut self, cx: &T, item: Span, msg: &str, attr: &D) {
426 if let Some(indent) = indentation(cx, item) {
427 let span = Span { hi: item.lo, ..item };
429 self.span_suggestion(span, msg, format!("{}\n{}", attr, indent));
433 fn suggest_prepend_item(&mut self, cx: &T, item: Span, msg: &str, new_item: &str) {
434 if let Some(indent) = indentation(cx, item) {
435 let span = Span { hi: item.lo, ..item };
437 let mut first = true;
438 let new_item = new_item.lines()
443 format!("{}{}\n", indent, l)
445 .collect::<String>();
447 self.span_suggestion(span, msg, format!("{}\n{}", new_item, indent));