mirror of
https://github.com/rust-lang/rust-analyzer.git
synced 2025-09-25 03:26:19 +00:00
Add ast::Expr::parse
This commit is contained in:
parent
c4573b26f6
commit
e989f22015
2 changed files with 32 additions and 0 deletions
|
@ -175,6 +175,29 @@ impl Parse<SourceFile> {
|
|||
}
|
||||
}
|
||||
|
||||
impl ast::Expr {
|
||||
/// Parses an `ast::Expr` from `text`.
|
||||
///
|
||||
/// Note that if the parsed root node is not a valid expression, [`Parse::tree`] will panic.
|
||||
/// For example:
|
||||
/// ```rust,should_panic
|
||||
/// # use syntax::{ast, Edition};
|
||||
/// ast::Expr::parse("let fail = true;", Edition::CURRENT).tree();
|
||||
/// ```
|
||||
pub fn parse(text: &str, edition: Edition) -> Parse<ast::Expr> {
|
||||
let _p = tracing::span!(tracing::Level::INFO, "Expr::parse").entered();
|
||||
let (green, errors) = parsing::parse_text_at(text, parser::TopEntryPoint::Expr, edition);
|
||||
let root = SyntaxNode::new_root(green.clone());
|
||||
|
||||
assert!(
|
||||
ast::Expr::can_cast(root.kind()) || root.kind() == SyntaxKind::ERROR,
|
||||
"{:?} isn't an expression",
|
||||
root.kind()
|
||||
);
|
||||
Parse::new(green, errors)
|
||||
}
|
||||
}
|
||||
|
||||
/// `SourceFile` represents a parse tree for a single Rust file.
|
||||
pub use crate::ast::SourceFile;
|
||||
|
||||
|
|
|
@ -18,6 +18,15 @@ pub(crate) fn parse_text(text: &str, edition: parser::Edition) -> (GreenNode, Ve
|
|||
(node, errors)
|
||||
}
|
||||
|
||||
pub(crate) fn parse_text_at(text: &str, entry: parser::TopEntryPoint, edition: parser::Edition) -> (GreenNode, Vec<SyntaxError>) {
|
||||
let _p = tracing::span!(tracing::Level::INFO, "parse_text_at").entered();
|
||||
let lexed = parser::LexedStr::new(text);
|
||||
let parser_input = lexed.to_input();
|
||||
let parser_output = entry.parse(&parser_input, edition);
|
||||
let (node, errors, _eof) = build_tree(lexed, parser_output);
|
||||
(node, errors)
|
||||
}
|
||||
|
||||
pub(crate) fn build_tree(
|
||||
lexed: parser::LexedStr<'_>,
|
||||
parser_output: parser::Output,
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue