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) |
33 Sugg::MaybeParen(ref s) |
34 Sugg::BinOp(_, ref s) => s.fmt(f),
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),
59 hir::ExprInlineAsm(..) |
62 hir::ExprMethodCall(..) |
68 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) => {
172 if sugg.starts_with('(') && sugg.ends_with(')') {
173 Sugg::MaybeParen(sugg)
175 Sugg::NonParen(format!("({})", sugg).into())
178 Sugg::BinOp(_, sugg) => Sugg::NonParen(format!("({})", sugg).into()),
183 impl<'a, 'b> std::ops::Add<Sugg<'b>> for Sugg<'a> {
184 type Output = Sugg<'static>;
185 fn add(self, rhs: Sugg<'b>) -> Sugg<'static> {
186 make_binop(ast::BinOpKind::Add, &self, &rhs)
190 impl<'a, 'b> std::ops::Sub<Sugg<'b>> for Sugg<'a> {
191 type Output = Sugg<'static>;
192 fn sub(self, rhs: Sugg<'b>) -> Sugg<'static> {
193 make_binop(ast::BinOpKind::Sub, &self, &rhs)
197 impl<'a> std::ops::Not for Sugg<'a> {
198 type Output = Sugg<'static>;
199 fn not(self) -> Sugg<'static> {
204 /// Helper type to display either `foo` or `(foo)`.
205 struct ParenHelper<T> {
206 /// Whether parenthesis are needed.
208 /// The main thing to display.
212 impl<T> ParenHelper<T> {
213 /// Build a `ParenHelper`.
214 fn new(paren: bool, wrapped: T) -> Self {
222 impl<T: Display> Display for ParenHelper<T> {
223 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
225 write!(f, "({})", self.wrapped)
232 /// Build the string for `<op><expr>` adding parenthesis when necessary.
234 /// For convenience, the operator is taken as a string because all unary operators have the same
236 pub fn make_unop(op: &str, expr: Sugg) -> Sugg<'static> {
237 Sugg::MaybeParen(format!("{}{}", op, expr.maybe_par()).into())
240 /// Build the string for `<lhs> <op> <rhs>` adding parenthesis when necessary.
242 /// Precedence of shift operator relative to other arithmetic operation is often confusing so
243 /// parenthesis will always be added for a mix of these.
244 pub fn make_assoc(op: AssocOp, lhs: &Sugg, rhs: &Sugg) -> Sugg<'static> {
245 /// Whether the operator is a shift operator `<<` or `>>`.
246 fn is_shift(op: &AssocOp) -> bool {
247 matches!(*op, AssocOp::ShiftLeft | AssocOp::ShiftRight)
250 /// Whether the operator is a arithmetic operator (`+`, `-`, `*`, `/`, `%`).
251 fn is_arith(op: &AssocOp) -> bool {
253 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide | AssocOp::Modulus)
256 /// Whether the operator `op` needs parenthesis with the operator `other` in the direction
258 fn needs_paren(op: &AssocOp, other: &AssocOp, dir: Associativity) -> bool {
259 other.precedence() < op.precedence() ||
260 (other.precedence() == op.precedence() &&
261 ((op != other && associativity(op) != dir) || (op == other && associativity(op) != Associativity::Both))) ||
262 is_shift(op) && is_arith(other) || is_shift(other) && is_arith(op)
265 let lhs_paren = if let Sugg::BinOp(ref lop, _) = *lhs {
266 needs_paren(&op, lop, Associativity::Left)
271 let rhs_paren = if let Sugg::BinOp(ref rop, _) = *rhs {
272 needs_paren(&op, rop, Associativity::Right)
277 let lhs = ParenHelper::new(lhs_paren, lhs);
278 let rhs = ParenHelper::new(rhs_paren, rhs);
279 let sugg = match op {
280 AssocOp::Add | AssocOp::BitAnd | AssocOp::BitOr | AssocOp::BitXor | AssocOp::Divide | AssocOp::Equal |
281 AssocOp::Greater | AssocOp::GreaterEqual | AssocOp::LAnd | AssocOp::LOr | AssocOp::Less |
282 AssocOp::LessEqual | AssocOp::Modulus | AssocOp::Multiply | AssocOp::NotEqual | AssocOp::ShiftLeft |
283 AssocOp::ShiftRight | AssocOp::Subtract => {
284 format!("{} {} {}", lhs, op.to_ast_binop().expect("Those are AST ops").to_string(), rhs)
286 AssocOp::Inplace => format!("in ({}) {}", lhs, rhs),
287 AssocOp::Assign => format!("{} = {}", lhs, rhs),
288 AssocOp::AssignOp(op) => format!("{} {}= {}", lhs, binop_to_string(op), rhs),
289 AssocOp::As => format!("{} as {}", lhs, rhs),
290 AssocOp::DotDot => format!("{}..{}", lhs, rhs),
291 AssocOp::DotDotDot => format!("{}...{}", lhs, rhs),
292 AssocOp::Colon => format!("{}: {}", lhs, rhs),
295 Sugg::BinOp(op, sugg.into())
298 /// Convinience wrapper arround `make_assoc` and `AssocOp::from_ast_binop`.
299 pub fn make_binop(op: ast::BinOpKind, lhs: &Sugg, rhs: &Sugg) -> Sugg<'static> {
300 make_assoc(AssocOp::from_ast_binop(op), lhs, rhs)
303 #[derive(PartialEq, Eq)]
304 /// Operator associativity.
306 /// The operator is both left-associative and right-associative.
308 /// The operator is left-associative.
310 /// The operator is not associative.
312 /// The operator is right-associative.
316 /// Return the associativity/fixity of an operator. The difference with `AssocOp::fixity` is that
317 /// an operator can be both left and right associative (such as `+`:
318 /// `a + b + c == (a + b) + c == a + (b + c)`.
320 /// Chained `as` and explicit `:` type coercion never need inner parenthesis so they are considered
322 fn associativity(op: &AssocOp) -> Associativity {
323 use syntax::util::parser::AssocOp::*;
326 Inplace | Assign | AssignOp(_) => Associativity::Right,
327 Add | BitAnd | BitOr | BitXor | LAnd | LOr | Multiply | As | Colon => Associativity::Both,
328 Divide | Equal | Greater | GreaterEqual | Less | LessEqual | Modulus | NotEqual | ShiftLeft | ShiftRight |
329 Subtract => Associativity::Left,
330 DotDot | DotDotDot => Associativity::None,
334 /// Convert a `hir::BinOp` to the corresponding assigning binary operator.
335 fn hirbinop2assignop(op: hir::BinOp) -> AssocOp {
336 use rustc::hir::BinOp_::*;
337 use syntax::parse::token::BinOpToken::*;
339 AssocOp::AssignOp(match op.node {
350 BiAnd | BiEq | BiGe | BiGt | BiLe | BiLt | BiNe | BiOr => panic!("This operator does not exist"),
354 /// Convert an `ast::BinOp` to the corresponding assigning binary operator.
355 fn astbinop2assignop(op: ast::BinOp) -> AssocOp {
356 use syntax::ast::BinOpKind::*;
357 use syntax::parse::token::BinOpToken;
359 AssocOp::AssignOp(match op.node {
360 Add => BinOpToken::Plus,
361 BitAnd => BinOpToken::And,
362 BitOr => BinOpToken::Or,
363 BitXor => BinOpToken::Caret,
364 Div => BinOpToken::Slash,
365 Mul => BinOpToken::Star,
366 Rem => BinOpToken::Percent,
367 Shl => BinOpToken::Shl,
368 Shr => BinOpToken::Shr,
369 Sub => BinOpToken::Minus,
370 And | Eq | Ge | Gt | Le | Lt | Ne | Or => panic!("This operator does not exist"),
374 /// Return the indentation before `span` if there are nothing but `[ \t]` before it on its line.
375 fn indentation<'a, T: LintContext<'a>>(cx: &T, span: Span) -> Option<String> {
376 let lo = cx.sess().codemap().lookup_char_pos(span.lo);
377 if let Some(line) = lo.file.get_line(lo.line - 1 /* line numbers in `Loc` are 1-based */) {
378 if let Some((pos, _)) = line.char_indices().find(|&(_, c)| c != ' ' && c != '\t') {
379 // we can mix char and byte positions here because we only consider `[ \t]`
380 if lo.col == CharPos(pos) {
381 Some(line[..pos].into())
393 /// Convenience extension trait for `DiagnosticBuilder`.
394 pub trait DiagnosticBuilderExt<'a, T: LintContext<'a>> {
395 /// Suggests to add an attribute to an item.
397 /// Correctly handles indentation of the attribute and item.
402 /// db.suggest_item_with_attr(cx, item, "#[derive(Default)]");
404 fn suggest_item_with_attr<D: Display + ?Sized>(&mut self, cx: &T, item: Span, msg: &str, attr: &D);
406 /// Suggest to add an item before another.
408 /// The item should not be indented (expect for inner indentation).
413 /// db.suggest_prepend_item(cx, item,
418 fn suggest_prepend_item(&mut self, cx: &T, item: Span, msg: &str, new_item: &str);
421 impl<'a, 'b, 'c, T: LintContext<'c>> DiagnosticBuilderExt<'c, T> for rustc_errors::DiagnosticBuilder<'b> {
422 fn suggest_item_with_attr<D: Display + ?Sized>(&mut self, cx: &T, item: Span, msg: &str, attr: &D) {
423 if let Some(indent) = indentation(cx, item) {
424 let span = Span { hi: item.lo, ..item };
426 self.span_suggestion(span, msg, format!("{}\n{}", attr, indent));
430 fn suggest_prepend_item(&mut self, cx: &T, item: Span, msg: &str, new_item: &str) {
431 if let Some(indent) = indentation(cx, item) {
432 let span = Span { hi: item.lo, ..item };
434 let mut first = true;
435 let new_item = new_item.lines()
441 format!("{}{}\n", indent, l)
444 .collect::<String>();
446 self.span_suggestion(span, msg, format!("{}\n{}", new_item, indent));