Skip to content

Commit 659c85c

Browse files
authored
Rollup merge of rust-lang#77780 - calebcartwright:cast-expr-attr-span, 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
2 parents 3cef494 + 4e82da4 commit 659c85c

File tree

1 file changed

+17
-7
lines changed
  • compiler/rustc_parse/src/parser

1 file changed

+17
-7
lines changed

compiler/rustc_parse/src/parser/expr.rs

+17-7
Original file line numberDiff line numberDiff line change
@@ -246,11 +246,7 @@ impl<'a> Parser<'a> {
246246
this.parse_assoc_expr_with(prec + prec_adjustment, LhsExpr::NotYetParsed)
247247
})?;
248248

249-
// Make sure that the span of the parent node is larger than the span of lhs and rhs,
250-
// including the attributes.
251-
let lhs_span =
252-
lhs.attrs.iter().find(|a| a.style == AttrStyle::Outer).map_or(lhs_span, |a| a.span);
253-
let span = lhs_span.to(rhs.span);
249+
let span = self.mk_expr_sp(&lhs, lhs_span, rhs.span);
254250
lhs = match op {
255251
AssocOp::Add
256252
| AssocOp::Subtract
@@ -411,7 +407,7 @@ impl<'a> Parser<'a> {
411407
None
412408
};
413409
let rhs_span = rhs.as_ref().map_or(cur_op_span, |x| x.span);
414-
let span = lhs.span.to(rhs_span);
410+
let span = self.mk_expr_sp(&lhs, lhs.span, rhs_span);
415411
let limits =
416412
if op == AssocOp::DotDot { RangeLimits::HalfOpen } else { RangeLimits::Closed };
417413
Ok(self.mk_expr(span, self.mk_range(Some(lhs), rhs, limits)?, AttrVec::new()))
@@ -571,7 +567,11 @@ impl<'a> Parser<'a> {
571567
expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind,
572568
) -> PResult<'a, P<Expr>> {
573569
let mk_expr = |this: &mut Self, rhs: P<Ty>| {
574-
this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), AttrVec::new())
570+
this.mk_expr(
571+
this.mk_expr_sp(&lhs, lhs_span, rhs.span),
572+
expr_kind(lhs, rhs),
573+
AttrVec::new(),
574+
)
575575
};
576576

577577
// Save the state of the parser before parsing type normally, in case there is a
@@ -2324,4 +2324,14 @@ impl<'a> Parser<'a> {
23242324
pub(super) fn mk_expr_err(&self, span: Span) -> P<Expr> {
23252325
self.mk_expr(span, ExprKind::Err, AttrVec::new())
23262326
}
2327+
2328+
/// Create expression span ensuring the span of the parent node
2329+
/// is larger than the span of lhs and rhs, including the attributes.
2330+
fn mk_expr_sp(&self, lhs: &P<Expr>, lhs_span: Span, rhs_span: Span) -> Span {
2331+
lhs.attrs
2332+
.iter()
2333+
.find(|a| a.style == AttrStyle::Outer)
2334+
.map_or(lhs_span, |a| a.span)
2335+
.to(rhs_span)
2336+
}
23272337
}

0 commit comments

Comments
 (0)