Skip to content

Commit

Permalink
Auto merge of #18146 - ChayimFriedman2:allow-comment, r=Veykril
Browse files Browse the repository at this point in the history
fix: Remove check that text of `parse_expr_from_str()` matches the produced parsed tree

This check is incorrect when we have comments and whitespace in the text.

We can strip comments, but then we still have whitespace, which we cannot strip without changing meaning for the parser. So instead I opt to remove the check, and wrap the expression in parentheses (asserting what produced is a parenthesized expression) to strengthen verification.

Fixes #18144.
  • Loading branch information
bors committed Sep 19, 2024
2 parents 4ed7f4b + 65f83e4 commit 814da15
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -996,4 +996,17 @@ fn BAR() {
"#,
);
}

#[test]
fn allow_with_comment() {
check_diagnostics(
r#"
#[allow(
// Yo, sup
non_snake_case
)]
fn foo(_HelloWorld: ()) {}
"#,
);
}
}
17 changes: 11 additions & 6 deletions src/tools/rust-analyzer/crates/syntax/src/hacks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,15 @@ use crate::{ast, AstNode};

pub fn parse_expr_from_str(s: &str, edition: Edition) -> Option<ast::Expr> {
let s = s.trim();
let file = ast::SourceFile::parse(&format!("const _: () = {s};"), edition);
let expr = file.syntax_node().descendants().find_map(ast::Expr::cast)?;
if expr.syntax().text() != s {
return None;
}
Some(expr)

let file = ast::SourceFile::parse(
// Need a newline because the text may contain line comments.
&format!("const _: () = ({s}\n);"),
edition,
);
let expr = file.syntax_node().descendants().find_map(ast::ParenExpr::cast)?;
// Can't check the text because the original text may contain whitespace and comments.
// Wrap in parentheses to better allow for verification. Of course, the real fix is
// to get rid of this hack.
expr.expr()
}

0 comments on commit 814da15

Please sign in to comment.