rust-analyzer/crates/syntax/src/hacks.rs
Chayim Refael Friedman 9ef460ba2d 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.
2024-09-19 14:18:07 +03:00

22 lines
786 B
Rust

//! Things which exist to solve practical issues, but which shouldn't exist.
//!
//! Please avoid adding new usages of the functions in this module
use parser::Edition;
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(
// 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()
}