pub fn parse_script(text: &str, options: JsParserOptions) -> Parse<JsScript>
Expand description

Parse text into a Parse which can then be turned into an untyped root JsSyntaxNode. Or turned into a typed JsScript with tree.

use biome_js_parser::{JsParserOptions, parse_script};
use biome_js_syntax::{JsSyntaxToken, JsFileSource, JsSyntaxList, JsComputedMemberExpression};
use biome_rowan::{AstNode, Direction};

let parse = parse_script("foo.bar[2]", JsParserOptions::default());
// Parse returns a JS Root which contains two lists, the directives and the statements, let's get the statements
let stmt = parse.syntax().children().nth(1).unwrap();
// The untyped syntax node of `foo.bar[2]`, the root node is `Script`.
let untyped_expr_node = stmt.first_child().unwrap();

// SyntaxNodes can be turned into a nice string representation.
println!("{:#?}", untyped_expr_node);

// You can then cast syntax nodes into a typed AST node.
let typed_ast_node = JsComputedMemberExpression::cast(untyped_expr_node.first_child().unwrap()).unwrap();

// Everything on every ast node is optional because of error recovery.
let prop = dbg!(typed_ast_node.member()).unwrap();

// You can then go back to an untyped SyntaxNode and get its range, text, parents, children, etc.
assert_eq!(prop.syntax().text(), "2");

// Util has a function for yielding all tokens of a node.
let tokens = untyped_expr_node.descendants_tokens(Direction::Next).map(|token| token.text_trimmed().to_string()).collect::<Vec<_>>();

assert_eq!(&tokens, &vec!["foo", ".", "bar", "[", "2", "]"]);