Skip to content

Commit

Permalink
Rollup merge of rust-lang#77780 - calebcartwright:cast-expr-attr-span…
Browse files Browse the repository at this point in the history
…, r=oli-obk

rustc_parse: fix spans on cast and range exprs with attrs

Currently the span for cast and range expressions does not include the span of attributes associated to the lhs which is causing some issues for us in rustfmt.

```rust
fn foo() -> i64 {
    #[attr]
    1u64 as i64
}

fn bar() -> Range<i32> {
    #[attr]
    1..2
}
```

This corrects the span for cast and range expressions to fully include the span of child nodes
  • Loading branch information
Dylan-DPC authored Oct 15, 2020
2 parents a0781d4 + 4e82da4 commit 7523b4b
Showing 1 changed file with 17 additions and 7 deletions.
24 changes: 17 additions & 7 deletions compiler/rustc_parse/src/parser/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -246,11 +246,7 @@ impl<'a> Parser<'a> {
this.parse_assoc_expr_with(prec + prec_adjustment, LhsExpr::NotYetParsed)
})?;

// Make sure that the span of the parent node is larger than the span of lhs and rhs,
// including the attributes.
let lhs_span =
lhs.attrs.iter().find(|a| a.style == AttrStyle::Outer).map_or(lhs_span, |a| a.span);
let span = lhs_span.to(rhs.span);
let span = self.mk_expr_sp(&lhs, lhs_span, rhs.span);
lhs = match op {
AssocOp::Add
| AssocOp::Subtract
Expand Down Expand Up @@ -411,7 +407,7 @@ impl<'a> Parser<'a> {
None
};
let rhs_span = rhs.as_ref().map_or(cur_op_span, |x| x.span);
let span = lhs.span.to(rhs_span);
let span = self.mk_expr_sp(&lhs, lhs.span, rhs_span);
let limits =
if op == AssocOp::DotDot { RangeLimits::HalfOpen } else { RangeLimits::Closed };
Ok(self.mk_expr(span, self.mk_range(Some(lhs), rhs, limits)?, AttrVec::new()))
Expand Down Expand Up @@ -571,7 +567,11 @@ impl<'a> Parser<'a> {
expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind,
) -> PResult<'a, P<Expr>> {
let mk_expr = |this: &mut Self, rhs: P<Ty>| {
this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), AttrVec::new())
this.mk_expr(
this.mk_expr_sp(&lhs, lhs_span, rhs.span),
expr_kind(lhs, rhs),
AttrVec::new(),
)
};

// Save the state of the parser before parsing type normally, in case there is a
Expand Down Expand Up @@ -2324,4 +2324,14 @@ impl<'a> Parser<'a> {
pub(super) fn mk_expr_err(&self, span: Span) -> P<Expr> {
self.mk_expr(span, ExprKind::Err, AttrVec::new())
}

/// Create expression span ensuring the span of the parent node
/// is larger than the span of lhs and rhs, including the attributes.
fn mk_expr_sp(&self, lhs: &P<Expr>, lhs_span: Span, rhs_span: Span) -> Span {
lhs.attrs
.iter()
.find(|a| a.style == AttrStyle::Outer)
.map_or(lhs_span, |a| a.span)
.to(rhs_span)
}
}

0 comments on commit 7523b4b

Please sign in to comment.