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::print::pprust::binop_to_string;
12 use syntax::util::parser::AssocOp;
14 use utils::{higher, snippet, snippet_opt};
16 /// A helper type to build suggestion correctly handling parenthesis.
18 /// An expression that never needs parenthesis such as `1337` or `[0; 42]`.
19 NonParen(Cow<'a, str>),
20 /// An expression that does not fit in other variants.
21 MaybeParen(Cow<'a, str>),
22 /// A binary operator expression, including `as`-casts and explicit type coercion.
23 BinOp(AssocOp, Cow<'a, str>),
26 /// Literal constant `1`, for convenience.
27 pub const ONE: Sugg<'static> = Sugg::NonParen(Cow::Borrowed("1"));
29 impl<'a> Display for Sugg<'a> {
30 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
32 Sugg::NonParen(ref s) | Sugg::MaybeParen(ref s) | Sugg::BinOp(_, ref s) => {
39 #[allow(wrong_self_convention)] // ok, because of the function `as_ty` method
41 /// Prepare a suggestion from an expression.
42 pub fn hir_opt(cx: &LateContext, expr: &hir::Expr) -> Option<Sugg<'a>> {
43 snippet_opt(cx, expr.span).map(|snippet| {
44 let snippet = Cow::Owned(snippet);
48 hir::ExprClosure(..) |
51 hir::ExprMatch(..) => Sugg::MaybeParen(snippet),
58 hir::ExprInlineAsm(..) |
61 hir::ExprMethodCall(..) |
67 hir::ExprTupField(..) |
69 hir::ExprWhile(..) => Sugg::NonParen(snippet),
70 hir::ExprAssign(..) => Sugg::BinOp(AssocOp::Assign, snippet),
71 hir::ExprAssignOp(op, ..) => Sugg::BinOp(hirbinop2assignop(op), snippet),
72 hir::ExprBinary(op, ..) => Sugg::BinOp(AssocOp::from_ast_binop(higher::binop(op.node)), snippet),
73 hir::ExprCast(..) => Sugg::BinOp(AssocOp::As, snippet),
74 hir::ExprType(..) => Sugg::BinOp(AssocOp::Colon, snippet),
79 /// Convenience function around `hir_opt` for suggestions with a default text.
80 pub fn hir(cx: &LateContext, expr: &hir::Expr, default: &'a str) -> Sugg<'a> {
81 Self::hir_opt(cx, expr).unwrap_or_else(|| Sugg::NonParen(Cow::Borrowed(default)))
84 /// Prepare a suggestion from an expression.
85 pub fn ast(cx: &EarlyContext, expr: &ast::Expr, default: &'a str) -> Sugg<'a> {
86 use syntax::ast::RangeLimits;
88 let snippet = snippet(cx, expr.span, default);
91 ast::ExprKind::AddrOf(..) |
92 ast::ExprKind::Box(..) |
93 ast::ExprKind::Closure(..) |
94 ast::ExprKind::If(..) |
95 ast::ExprKind::IfLet(..) |
96 ast::ExprKind::InPlace(..) |
97 ast::ExprKind::Unary(..) |
98 ast::ExprKind::Match(..) => Sugg::MaybeParen(snippet),
99 ast::ExprKind::Block(..) |
100 ast::ExprKind::Break(..) |
101 ast::ExprKind::Call(..) |
102 ast::ExprKind::Continue(..) |
103 ast::ExprKind::Field(..) |
104 ast::ExprKind::ForLoop(..) |
105 ast::ExprKind::Index(..) |
106 ast::ExprKind::InlineAsm(..) |
107 ast::ExprKind::Lit(..) |
108 ast::ExprKind::Loop(..) |
109 ast::ExprKind::Mac(..) |
110 ast::ExprKind::MethodCall(..) |
111 ast::ExprKind::Paren(..) |
112 ast::ExprKind::Path(..) |
113 ast::ExprKind::Repeat(..) |
114 ast::ExprKind::Ret(..) |
115 ast::ExprKind::Struct(..) |
116 ast::ExprKind::Try(..) |
117 ast::ExprKind::Tup(..) |
118 ast::ExprKind::TupField(..) |
119 ast::ExprKind::Vec(..) |
120 ast::ExprKind::While(..) |
121 ast::ExprKind::WhileLet(..) => Sugg::NonParen(snippet),
122 ast::ExprKind::Range(.., RangeLimits::HalfOpen) => Sugg::BinOp(AssocOp::DotDot, snippet),
123 ast::ExprKind::Range(.., RangeLimits::Closed) => Sugg::BinOp(AssocOp::DotDotDot, snippet),
124 ast::ExprKind::Assign(..) => Sugg::BinOp(AssocOp::Assign, snippet),
125 ast::ExprKind::AssignOp(op, ..) => Sugg::BinOp(astbinop2assignop(op), snippet),
126 ast::ExprKind::Binary(op, ..) => Sugg::BinOp(AssocOp::from_ast_binop(op.node), snippet),
127 ast::ExprKind::Cast(..) => Sugg::BinOp(AssocOp::As, snippet),
128 ast::ExprKind::Type(..) => Sugg::BinOp(AssocOp::Colon, snippet),
132 /// Convenience method to create the `<lhs> && <rhs>` suggestion.
133 pub fn and(self, rhs: Self) -> Sugg<'static> {
134 make_binop(ast::BinOpKind::And, &self, &rhs)
137 /// Convenience method to create the `<lhs> as <rhs>` suggestion.
138 pub fn as_ty<R: Display>(self, rhs: R) -> Sugg<'static> {
139 make_assoc(AssocOp::As, &self, &Sugg::NonParen(rhs.to_string().into()))
142 /// Convenience method to create the `&<expr>` suggestion.
143 pub fn addr(self) -> Sugg<'static> {
147 /// Convenience method to create the `&mut <expr>` suggestion.
148 pub fn mut_addr(self) -> Sugg<'static> {
149 make_unop("&mut ", self)
152 /// Convenience method to create the `*<expr>` suggestion.
153 pub fn deref(self) -> Sugg<'static> {
157 /// Convenience method to create the `<lhs>..<rhs>` or `<lhs>...<rhs>` suggestion.
158 pub fn range(self, end: Self, limit: ast::RangeLimits) -> Sugg<'static> {
160 ast::RangeLimits::HalfOpen => make_assoc(AssocOp::DotDot, &self, &end),
161 ast::RangeLimits::Closed => make_assoc(AssocOp::DotDotDot, &self, &end),
165 /// Add parenthesis to any expression that might need them. Suitable to the `self` argument of
166 /// a method call (eg. to build `bar.foo()` or `(1 + 2).foo()`).
167 pub fn maybe_par(self) -> Self {
169 Sugg::NonParen(..) => self,
170 // (x) and (x).y() both don't need additional parens
171 Sugg::MaybeParen(sugg) => if sugg.starts_with('(') && sugg.ends_with(')') {
172 Sugg::MaybeParen(sugg)
174 Sugg::NonParen(format!("({})", sugg).into())
176 Sugg::BinOp(_, sugg) => Sugg::NonParen(format!("({})", sugg).into()),
181 impl<'a, 'b> std::ops::Add<Sugg<'b>> for Sugg<'a> {
182 type Output = Sugg<'static>;
183 fn add(self, rhs: Sugg<'b>) -> Sugg<'static> {
184 make_binop(ast::BinOpKind::Add, &self, &rhs)
188 impl<'a, 'b> std::ops::Sub<Sugg<'b>> for Sugg<'a> {
189 type Output = Sugg<'static>;
190 fn sub(self, rhs: Sugg<'b>) -> Sugg<'static> {
191 make_binop(ast::BinOpKind::Sub, &self, &rhs)
195 impl<'a> std::ops::Not for Sugg<'a> {
196 type Output = Sugg<'static>;
197 fn not(self) -> Sugg<'static> {
202 /// Helper type to display either `foo` or `(foo)`.
203 struct ParenHelper<T> {
204 /// Wether parenthesis are needed.
206 /// The main thing to display.
210 impl<T> ParenHelper<T> {
211 /// Build a `ParenHelper`.
212 fn new(paren: bool, wrapped: T) -> Self {
220 impl<T: Display> Display for ParenHelper<T> {
221 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
223 write!(f, "({})", self.wrapped)
230 /// Build the string for `<op><expr>` adding parenthesis when necessary.
232 /// For convenience, the operator is taken as a string because all unary operators have the same
234 pub fn make_unop(op: &str, expr: Sugg) -> Sugg<'static> {
235 Sugg::MaybeParen(format!("{}{}", op, expr.maybe_par()).into())
238 /// Build the string for `<lhs> <op> <rhs>` adding parenthesis when necessary.
240 /// Precedence of shift operator relative to other arithmetic operation is often confusing so
241 /// parenthesis will always be added for a mix of these.
242 pub fn make_assoc(op: AssocOp, lhs: &Sugg, rhs: &Sugg) -> Sugg<'static> {
243 /// Wether the operator is a shift operator `<<` or `>>`.
244 fn is_shift(op: &AssocOp) -> bool {
245 matches!(*op, AssocOp::ShiftLeft | AssocOp::ShiftRight)
248 /// Wether the operator is a arithmetic operator (`+`, `-`, `*`, `/`, `%`).
249 fn is_arith(op: &AssocOp) -> bool {
250 matches!(*op, AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide | AssocOp::Modulus)
253 /// Wether the operator `op` needs parenthesis with the operator `other` in the direction
255 fn needs_paren(op: &AssocOp, other: &AssocOp, dir: Associativity) -> bool {
256 other.precedence() < op.precedence() ||
257 (other.precedence() == op.precedence() &&
258 ((op != other && associativity(op) != dir) ||
259 (op == other && associativity(op) != Associativity::Both))) ||
260 is_shift(op) && is_arith(other) ||
261 is_shift(other) && is_arith(op)
264 let lhs_paren = if let Sugg::BinOp(ref lop, _) = *lhs {
265 needs_paren(&op, lop, Associativity::Left)
270 let rhs_paren = if let Sugg::BinOp(ref rop, _) = *rhs {
271 needs_paren(&op, rop, Associativity::Right)
276 let lhs = ParenHelper::new(lhs_paren, lhs);
277 let rhs = ParenHelper::new(rhs_paren, rhs);
278 let sugg = match op {
286 AssocOp::GreaterEqual |
295 AssocOp::ShiftRight |
296 AssocOp::Subtract => format!("{} {} {}", lhs, op.to_ast_binop().expect("Those are AST ops").to_string(), rhs),
297 AssocOp::Inplace => format!("in ({}) {}", lhs, rhs),
298 AssocOp::Assign => format!("{} = {}", lhs, rhs),
299 AssocOp::AssignOp(op) => format!("{} {}= {}", lhs, binop_to_string(op), rhs),
300 AssocOp::As => format!("{} as {}", lhs, rhs),
301 AssocOp::DotDot => format!("{}..{}", lhs, rhs),
302 AssocOp::DotDotDot => format!("{}...{}", lhs, rhs),
303 AssocOp::Colon => format!("{}: {}", lhs, rhs),
306 Sugg::BinOp(op, sugg.into())
309 /// Convinience wrapper arround `make_assoc` and `AssocOp::from_ast_binop`.
310 pub fn make_binop(op: ast::BinOpKind, lhs: &Sugg, rhs: &Sugg) -> Sugg<'static> {
311 make_assoc(AssocOp::from_ast_binop(op), lhs, rhs)
314 #[derive(PartialEq, Eq)]
315 /// Operator associativity.
317 /// The operator is both left-associative and right-associative.
319 /// The operator is left-associative.
321 /// The operator is not associative.
323 /// The operator is right-associative.
327 /// Return the associativity/fixity of an operator. The difference with `AssocOp::fixity` is that
328 /// an operator can be both left and right associative (such as `+`:
329 /// `a + b + c == (a + b) + c == a + (b + c)`.
331 /// Chained `as` and explicit `:` type coercion never need inner parenthesis so they are considered
333 fn associativity(op: &AssocOp) -> Associativity {
334 use syntax::util::parser::AssocOp::*;
337 Inplace | Assign | AssignOp(_) => Associativity::Right,
338 Add | BitAnd | BitOr | BitXor | LAnd | LOr | Multiply |
339 As | Colon => Associativity::Both,
340 Divide | Equal | Greater | GreaterEqual | Less | LessEqual | Modulus | NotEqual | ShiftLeft |
341 ShiftRight | Subtract => Associativity::Left,
342 DotDot | DotDotDot => Associativity::None
346 /// Convert a `hir::BinOp` to the corresponding assigning binary operator.
347 fn hirbinop2assignop(op: hir::BinOp) -> AssocOp {
348 use rustc::hir::BinOp_::*;
349 use syntax::parse::token::BinOpToken::*;
351 AssocOp::AssignOp(match op.node {
362 BiAnd | BiEq | BiGe | BiGt | BiLe | BiLt | BiNe | BiOr => panic!("This operator does not exist"),
366 /// Convert an `ast::BinOp` to the corresponding assigning binary operator.
367 fn astbinop2assignop(op: ast::BinOp) -> AssocOp {
368 use syntax::ast::BinOpKind::*;
369 use syntax::parse::token::BinOpToken;
371 AssocOp::AssignOp(match op.node {
372 Add => BinOpToken::Plus,
373 BitAnd => BinOpToken::And,
374 BitOr => BinOpToken::Or,
375 BitXor => BinOpToken::Caret,
376 Div => BinOpToken::Slash,
377 Mul => BinOpToken::Star,
378 Rem => BinOpToken::Percent,
379 Shl => BinOpToken::Shl,
380 Shr => BinOpToken::Shr,
381 Sub => BinOpToken::Minus,
382 And | Eq | Ge | Gt | Le | Lt | Ne | Or => panic!("This operator does not exist"),
386 /// Return the indentation before `span` if there are nothing but `[ \t]` before it on its line.
387 fn indentation<T: LintContext>(cx: &T, span: Span) -> Option<String> {
388 let lo = cx.sess().codemap().lookup_char_pos(span.lo);
389 if let Some(line) = lo.file.get_line(lo.line - 1 /* line numbers in `Loc` are 1-based */) {
390 if let Some((pos, _)) = line.char_indices().find(|&(_, c)| c != ' ' && c != '\t') {
391 // we can mix char and byte positions here because we only consider `[ \t]`
392 if lo.col == CharPos(pos) {
393 Some(line[..pos].into())
405 /// Convenience extension trait for `DiagnosticBuilder`.
406 pub trait DiagnosticBuilderExt<T: LintContext> {
407 /// Suggests to add an attribute to an item.
409 /// Correctly handles indentation of the attribute and item.
414 /// db.suggest_item_with_attr(cx, item, "#[derive(Default)]");
416 fn suggest_item_with_attr<D: Display+?Sized>(&mut self, cx: &T, item: Span, msg: &str, attr: &D);
418 /// Suggest to add an item before another.
420 /// The item should not be indented (expect for inner indentation).
425 /// db.suggest_prepend_item(cx, item,
430 fn suggest_prepend_item(&mut self, cx: &T, item: Span, msg: &str, new_item: &str);
433 impl<'a, 'b, T: LintContext> DiagnosticBuilderExt<T> for rustc_errors::DiagnosticBuilder<'b> {
434 fn suggest_item_with_attr<D: Display+?Sized>(&mut self, cx: &T, item: Span, msg: &str, attr: &D) {
435 if let Some(indent) = indentation(cx, item) {
441 self.span_suggestion(span, msg, format!("{}\n{}", attr, indent));
445 fn suggest_prepend_item(&mut self, cx: &T, item: Span, msg: &str, new_item: &str) {
446 if let Some(indent) = indentation(cx, item) {
452 let mut first = true;
453 let new_item = new_item.lines().map(|l| {
458 format!("{}{}\n", indent, l)
460 }).collect::<String>();
462 self.span_suggestion(span, msg, format!("{}\n{}", new_item, indent));