about summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
authorDropDemBits <r3usrlnd@gmail.com>2024-03-08 21:45:35 -0500
committerDropDemBits <r3usrlnd@gmail.com>2024-06-02 11:17:52 -0400
commitb9c19c1a46d345089927fb54850d320b7c2833df (patch)
treeb9af828122044ab3fdfbc5c9714d773d7866cc1a /src
parentbecd71f826f6f8c45376fa8ab9d3c60376758aa3 (diff)
downloadrust-b9c19c1a46d345089927fb54850d320b7c2833df.tar.gz
rust-b9c19c1a46d345089927fb54850d320b7c2833df.zip
Add `ast::Expr::parse`
Diffstat (limited to 'src')
-rw-r--r--src/tools/rust-analyzer/crates/syntax/src/lib.rs23
-rw-r--r--src/tools/rust-analyzer/crates/syntax/src/parsing.rs9
2 files changed, 32 insertions, 0 deletions
diff --git a/src/tools/rust-analyzer/crates/syntax/src/lib.rs b/src/tools/rust-analyzer/crates/syntax/src/lib.rs
index b8a8103cc65..58f59c384bc 100644
--- a/src/tools/rust-analyzer/crates/syntax/src/lib.rs
+++ b/src/tools/rust-analyzer/crates/syntax/src/lib.rs
@@ -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;
 
diff --git a/src/tools/rust-analyzer/crates/syntax/src/parsing.rs b/src/tools/rust-analyzer/crates/syntax/src/parsing.rs
index 420f4938e54..165109029f9 100644
--- a/src/tools/rust-analyzer/crates/syntax/src/parsing.rs
+++ b/src/tools/rust-analyzer/crates/syntax/src/parsing.rs
@@ -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,