pub struct Parser<'a, C: ParserConfig = NoTokensParserConfig> { /* private fields */ }Expand description
Recursive Descent Parser for ECMAScript and TypeScript
See Parser::parse for entry function.
Implementations§
Source§impl<'a> Parser<'a, NoTokensParserConfig>
impl<'a> Parser<'a, NoTokensParserConfig>
Sourcepub fn parse_observed(self) -> ProgramObservation<'a>
pub fn parse_observed(self) -> ProgramObservation<'a>
Retain the actual source/profile/options and complete result of one parse.
Only the parser’s built-in configurations can establish this authority.
A custom configuration still supports ordinary parse, but cannot
substitute lexer handlers and mint native compiler admission:
use oxc_allocator::Allocator;
use oxc_parser::{Parser, config::{NoTokensLexerConfig, ParserConfig}};
use oxc_span::SourceType;
#[derive(Default)]
struct Custom;
impl ParserConfig for Custom {
type LexerConfig = NoTokensLexerConfig;
fn lexer_config(&self) -> NoTokensLexerConfig { NoTokensLexerConfig }
}
let allocator = Allocator::default();
Parser::new(&allocator, "const value = 1;", SourceType::mjs())
.with_config(Custom).parse_observed();Source§impl<'a> Parser<'a, TokensParserConfig>
impl<'a> Parser<'a, TokensParserConfig>
Sourcepub fn parse_observed(self) -> ProgramObservation<'a>
pub fn parse_observed(self) -> ProgramObservation<'a>
Retain one complete observation using the built-in token configuration.
Source§impl<'a> Parser<'a, RuntimeParserConfig>
impl<'a> Parser<'a, RuntimeParserConfig>
Sourcepub fn parse_observed(self) -> ProgramObservation<'a>
pub fn parse_observed(self) -> ProgramObservation<'a>
Retain one complete observation using the built-in runtime configuration.
Source§impl<'a, C: ParserConfig> Parser<'a, C>
impl<'a, C: ParserConfig> Parser<'a, C>
Sourcepub fn parse_slot_parameters(self) -> Result<FormalParameters<'a>, Diagnostics>
pub fn parse_slot_parameters(self) -> Result<FormalParameters<'a>, Diagnostics>
Parse the entire original source as an arrow-function parameter list, retaining original spans, binding defaults, rest and TS annotations. This goal has an EOF delimiter; it adds no synthetic source or AST.
Sourcepub fn parse_v_for_parameters(self) -> Result<FormalParameters<'a>, Diagnostics>
pub fn parse_v_for_parameters(self) -> Result<FormalParameters<'a>, Diagnostics>
Parse a Vue v-for alias list from its original source, without the
enclosing tuple parentheses or in/of iterable. Unlike a slot’s
parameter list, this goal permits omitted alias positions. Elisions
contribute no items; every retained binding keeps its authored span.
Rest-last and trailing-comma restrictions remain in force.
Source§impl<'a, C: ParserConfig> Parser<'a, C>
impl<'a, C: ParserConfig> Parser<'a, C>
Sourcepub fn parse(self) -> ParserReturn<'a>
pub fn parse(self) -> ParserReturn<'a>
Main entry point
Returns an empty Program on unrecoverable error,
Recoverable errors are stored inside errors.
See the module-level documentation for examples and more information.
Examples found in repository?
29fn main() -> std::io::Result<()> {
30 let name = env::args().nth(1).unwrap_or_else(|| "test.js".to_string());
31 let path = Path::new(&name);
32 let source_text = std::fs::read_to_string(path)?;
33 let allocator = Allocator::default();
34 let source_type = SourceType::from_path(path).unwrap();
35 let ret = Parser::new(&allocator, &source_text, source_type).parse();
36
37 // Report any parsing errors
38 for error in ret.diagnostics {
39 let error = error.with_source_code(source_text.clone());
40 println!("{error:?}");
41 }
42
43 let program = ret.program;
44
45 // Use visitor to count different AST node types
46 let mut ast_pass = CountASTNodes::default();
47 ast_pass.visit_program(&program);
48 println!("{ast_pass:?}");
49
50 Ok(())
51}More examples
13fn main() {
14 // 1. Get the file content and parse
15 let name = env::args().nth(1).unwrap_or_else(|| "test.js".to_string());
16 let path = Path::new(&name);
17
18 let source_text: Arc<str> = Arc::from(fs::read_to_string(path).unwrap());
19 let source_type = SourceType::from_path(path).unwrap();
20
21 let allocator = Allocator::default();
22 let options = ParseOptions { parse_regular_expression: true, ..ParseOptions::default() };
23
24 let parser_ret =
25 Parser::new(&allocator, source_text.as_ref(), source_type).with_options(options).parse();
26 if !parser_ret.diagnostics.is_empty() {
27 println!("Parsing failed:");
28 for error in parser_ret.diagnostics {
29 let error = error.with_source_code(Arc::clone(&source_text));
30 println!("{error:?}");
31 }
32 return;
33 }
34
35 // Parse regular expressions
36 // - RegExpLiteral
37 // - new RegExp() with string or template literal if static
38 RegularExpressionVisitor { source_text: Arc::clone(&source_text) }
39 .visit_program(&parser_ret.program);
40}17fn main() -> Result<(), String> {
18 let source_text = r"
19import React from 'react';
20
21/**
22 * A simple counter component
23 */
24export const Counter: React.FC = () => {
25 const [count, setCount] = React.useState(0);
26
27 return (
28 <div>
29 <p>Count: {count}</p>
30 <button onClick={() => setCount(count + 1)}>Increment</button>
31 <button onClick={() => setCount(count - 1)}>Decrement</button>
32 </div>
33 )
34}";
35
36 // Memory arena where AST nodes get stored
37 let allocator = Allocator::default();
38 // Infers TypeScript + JSX + ESM modules
39 let source_type = SourceType::from_path("Counter.tsx").unwrap();
40
41 let ParserReturn {
42 program, // AST
43 diagnostics, // Syntax errors
44 panicked, // Parser encountered an error it couldn't recover from
45 ..
46 } = Parser::new(&allocator, source_text, source_type).parse();
47
48 if panicked {
49 return Err("Parser panicked".to_string());
50 }
51
52 if !diagnostics.is_empty() {
53 return Err(format!("Parsing errors: {}", diagnostics.len()));
54 }
55
56 assert!(!program.body.is_empty());
57 assert_eq!(program.comments.len(), 1);
58
59 Ok(())
60}Sourcepub fn parse_expression(self) -> Result<Expression<'a>, Diagnostics>
pub fn parse_expression(self) -> Result<Expression<'a>, Diagnostics>
Parse a single Expression.
§Example
use oxc_allocator::Allocator;
use oxc_ast::ast::Expression;
use oxc_parser::Parser;
use oxc_span::SourceType;
let src = "let x = 1 + 2;";
let allocator = Allocator::new();
let source_type = SourceType::default();
let expr: Expression<'_> = Parser::new(&allocator, src, source_type).parse_expression().unwrap();§Errors
If the source code being parsed has syntax errors.
Source§impl<'a> Parser<'a>
impl<'a> Parser<'a>
Sourcepub fn new(
allocator: &'a Allocator,
source_text: &'a str,
source_type: SourceType,
) -> Self
pub fn new( allocator: &'a Allocator, source_text: &'a str, source_type: SourceType, ) -> Self
Create a new Parser
§Parameters
allocator: Memory arena for allocating AST nodessource_text: Source code to parsesource_type: Source type (e.g. JavaScript, TypeScript, JSX, ESM Module, Script)
Examples found in repository?
29fn main() -> std::io::Result<()> {
30 let name = env::args().nth(1).unwrap_or_else(|| "test.js".to_string());
31 let path = Path::new(&name);
32 let source_text = std::fs::read_to_string(path)?;
33 let allocator = Allocator::default();
34 let source_type = SourceType::from_path(path).unwrap();
35 let ret = Parser::new(&allocator, &source_text, source_type).parse();
36
37 // Report any parsing errors
38 for error in ret.diagnostics {
39 let error = error.with_source_code(source_text.clone());
40 println!("{error:?}");
41 }
42
43 let program = ret.program;
44
45 // Use visitor to count different AST node types
46 let mut ast_pass = CountASTNodes::default();
47 ast_pass.visit_program(&program);
48 println!("{ast_pass:?}");
49
50 Ok(())
51}More examples
13fn main() {
14 // 1. Get the file content and parse
15 let name = env::args().nth(1).unwrap_or_else(|| "test.js".to_string());
16 let path = Path::new(&name);
17
18 let source_text: Arc<str> = Arc::from(fs::read_to_string(path).unwrap());
19 let source_type = SourceType::from_path(path).unwrap();
20
21 let allocator = Allocator::default();
22 let options = ParseOptions { parse_regular_expression: true, ..ParseOptions::default() };
23
24 let parser_ret =
25 Parser::new(&allocator, source_text.as_ref(), source_type).with_options(options).parse();
26 if !parser_ret.diagnostics.is_empty() {
27 println!("Parsing failed:");
28 for error in parser_ret.diagnostics {
29 let error = error.with_source_code(Arc::clone(&source_text));
30 println!("{error:?}");
31 }
32 return;
33 }
34
35 // Parse regular expressions
36 // - RegExpLiteral
37 // - new RegExp() with string or template literal if static
38 RegularExpressionVisitor { source_text: Arc::clone(&source_text) }
39 .visit_program(&parser_ret.program);
40}17fn main() -> Result<(), String> {
18 let source_text = r"
19import React from 'react';
20
21/**
22 * A simple counter component
23 */
24export const Counter: React.FC = () => {
25 const [count, setCount] = React.useState(0);
26
27 return (
28 <div>
29 <p>Count: {count}</p>
30 <button onClick={() => setCount(count + 1)}>Increment</button>
31 <button onClick={() => setCount(count - 1)}>Decrement</button>
32 </div>
33 )
34}";
35
36 // Memory arena where AST nodes get stored
37 let allocator = Allocator::default();
38 // Infers TypeScript + JSX + ESM modules
39 let source_type = SourceType::from_path("Counter.tsx").unwrap();
40
41 let ParserReturn {
42 program, // AST
43 diagnostics, // Syntax errors
44 panicked, // Parser encountered an error it couldn't recover from
45 ..
46 } = Parser::new(&allocator, source_text, source_type).parse();
47
48 if panicked {
49 return Err("Parser panicked".to_string());
50 }
51
52 if !diagnostics.is_empty() {
53 return Err(format!("Parsing errors: {}", diagnostics.len()));
54 }
55
56 assert!(!program.body.is_empty());
57 assert_eq!(program.comments.len(), 1);
58
59 Ok(())
60}Source§impl<'a, C: ParserConfig> Parser<'a, C>
impl<'a, C: ParserConfig> Parser<'a, C>
Sourcepub fn with_options(self, options: ParseOptions) -> Self
pub fn with_options(self, options: ParseOptions) -> Self
Set parse options
Examples found in repository?
13fn main() {
14 // 1. Get the file content and parse
15 let name = env::args().nth(1).unwrap_or_else(|| "test.js".to_string());
16 let path = Path::new(&name);
17
18 let source_text: Arc<str> = Arc::from(fs::read_to_string(path).unwrap());
19 let source_type = SourceType::from_path(path).unwrap();
20
21 let allocator = Allocator::default();
22 let options = ParseOptions { parse_regular_expression: true, ..ParseOptions::default() };
23
24 let parser_ret =
25 Parser::new(&allocator, source_text.as_ref(), source_type).with_options(options).parse();
26 if !parser_ret.diagnostics.is_empty() {
27 println!("Parsing failed:");
28 for error in parser_ret.diagnostics {
29 let error = error.with_source_code(Arc::clone(&source_text));
30 println!("{error:?}");
31 }
32 return;
33 }
34
35 // Parse regular expressions
36 // - RegExpLiteral
37 // - new RegExp() with string or template literal if static
38 RegularExpressionVisitor { source_text: Arc::clone(&source_text) }
39 .visit_program(&parser_ret.program);
40}Sourcepub fn with_config<Config: ParserConfig>(
self,
config: Config,
) -> Parser<'a, Config>
pub fn with_config<Config: ParserConfig>( self, config: Config, ) -> Parser<'a, Config>
Set parser config.
See ParserConfig for more details.
Auto Trait Implementations§
impl<'a, C = NoTokensParserConfig> !RefUnwindSafe for Parser<'a, C>
impl<'a, C = NoTokensParserConfig> !Send for Parser<'a, C>
impl<'a, C = NoTokensParserConfig> !Sync for Parser<'a, C>
impl<'a, C = NoTokensParserConfig> !UnwindSafe for Parser<'a, C>
impl<'a, C> Freeze for Parser<'a, C>where
C: Freeze,
impl<'a, C> Unpin for Parser<'a, C>where
C: Unpin,
impl<'a, C> UnsafeUnpin for Parser<'a, C>where
C: UnsafeUnpin,
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<D> OwoColorize for D
impl<D> OwoColorize for D
Source§fn fg<C>(&self) -> FgColorDisplay<'_, C, Self>where
C: Color,
fn fg<C>(&self) -> FgColorDisplay<'_, C, Self>where
C: Color,
Source§fn bg<C>(&self) -> BgColorDisplay<'_, C, Self>where
C: Color,
fn bg<C>(&self) -> BgColorDisplay<'_, C, Self>where
C: Color,
Source§fn black(&self) -> FgColorDisplay<'_, Black, Self>
fn black(&self) -> FgColorDisplay<'_, Black, Self>
Source§fn on_black(&self) -> BgColorDisplay<'_, Black, Self>
fn on_black(&self) -> BgColorDisplay<'_, Black, Self>
Source§fn red(&self) -> FgColorDisplay<'_, Red, Self>
fn red(&self) -> FgColorDisplay<'_, Red, Self>
Source§fn on_red(&self) -> BgColorDisplay<'_, Red, Self>
fn on_red(&self) -> BgColorDisplay<'_, Red, Self>
Source§fn green(&self) -> FgColorDisplay<'_, Green, Self>
fn green(&self) -> FgColorDisplay<'_, Green, Self>
Source§fn on_green(&self) -> BgColorDisplay<'_, Green, Self>
fn on_green(&self) -> BgColorDisplay<'_, Green, Self>
Source§fn yellow(&self) -> FgColorDisplay<'_, Yellow, Self>
fn yellow(&self) -> FgColorDisplay<'_, Yellow, Self>
Source§fn on_yellow(&self) -> BgColorDisplay<'_, Yellow, Self>
fn on_yellow(&self) -> BgColorDisplay<'_, Yellow, Self>
Source§fn blue(&self) -> FgColorDisplay<'_, Blue, Self>
fn blue(&self) -> FgColorDisplay<'_, Blue, Self>
Source§fn on_blue(&self) -> BgColorDisplay<'_, Blue, Self>
fn on_blue(&self) -> BgColorDisplay<'_, Blue, Self>
Source§fn magenta(&self) -> FgColorDisplay<'_, Magenta, Self>
fn magenta(&self) -> FgColorDisplay<'_, Magenta, Self>
Source§fn on_magenta(&self) -> BgColorDisplay<'_, Magenta, Self>
fn on_magenta(&self) -> BgColorDisplay<'_, Magenta, Self>
Source§fn purple(&self) -> FgColorDisplay<'_, Magenta, Self>
fn purple(&self) -> FgColorDisplay<'_, Magenta, Self>
Source§fn on_purple(&self) -> BgColorDisplay<'_, Magenta, Self>
fn on_purple(&self) -> BgColorDisplay<'_, Magenta, Self>
Source§fn cyan(&self) -> FgColorDisplay<'_, Cyan, Self>
fn cyan(&self) -> FgColorDisplay<'_, Cyan, Self>
Source§fn on_cyan(&self) -> BgColorDisplay<'_, Cyan, Self>
fn on_cyan(&self) -> BgColorDisplay<'_, Cyan, Self>
Source§fn white(&self) -> FgColorDisplay<'_, White, Self>
fn white(&self) -> FgColorDisplay<'_, White, Self>
Source§fn on_white(&self) -> BgColorDisplay<'_, White, Self>
fn on_white(&self) -> BgColorDisplay<'_, White, Self>
Source§fn default_color(&self) -> FgColorDisplay<'_, Default, Self>
fn default_color(&self) -> FgColorDisplay<'_, Default, Self>
Source§fn on_default_color(&self) -> BgColorDisplay<'_, Default, Self>
fn on_default_color(&self) -> BgColorDisplay<'_, Default, Self>
Source§fn bright_black(&self) -> FgColorDisplay<'_, BrightBlack, Self>
fn bright_black(&self) -> FgColorDisplay<'_, BrightBlack, Self>
Source§fn on_bright_black(&self) -> BgColorDisplay<'_, BrightBlack, Self>
fn on_bright_black(&self) -> BgColorDisplay<'_, BrightBlack, Self>
Source§fn bright_red(&self) -> FgColorDisplay<'_, BrightRed, Self>
fn bright_red(&self) -> FgColorDisplay<'_, BrightRed, Self>
Source§fn on_bright_red(&self) -> BgColorDisplay<'_, BrightRed, Self>
fn on_bright_red(&self) -> BgColorDisplay<'_, BrightRed, Self>
Source§fn bright_green(&self) -> FgColorDisplay<'_, BrightGreen, Self>
fn bright_green(&self) -> FgColorDisplay<'_, BrightGreen, Self>
Source§fn on_bright_green(&self) -> BgColorDisplay<'_, BrightGreen, Self>
fn on_bright_green(&self) -> BgColorDisplay<'_, BrightGreen, Self>
Source§fn bright_yellow(&self) -> FgColorDisplay<'_, BrightYellow, Self>
fn bright_yellow(&self) -> FgColorDisplay<'_, BrightYellow, Self>
Source§fn on_bright_yellow(&self) -> BgColorDisplay<'_, BrightYellow, Self>
fn on_bright_yellow(&self) -> BgColorDisplay<'_, BrightYellow, Self>
Source§fn bright_blue(&self) -> FgColorDisplay<'_, BrightBlue, Self>
fn bright_blue(&self) -> FgColorDisplay<'_, BrightBlue, Self>
Source§fn on_bright_blue(&self) -> BgColorDisplay<'_, BrightBlue, Self>
fn on_bright_blue(&self) -> BgColorDisplay<'_, BrightBlue, Self>
Source§fn bright_magenta(&self) -> FgColorDisplay<'_, BrightMagenta, Self>
fn bright_magenta(&self) -> FgColorDisplay<'_, BrightMagenta, Self>
Source§fn on_bright_magenta(&self) -> BgColorDisplay<'_, BrightMagenta, Self>
fn on_bright_magenta(&self) -> BgColorDisplay<'_, BrightMagenta, Self>
Source§fn bright_purple(&self) -> FgColorDisplay<'_, BrightMagenta, Self>
fn bright_purple(&self) -> FgColorDisplay<'_, BrightMagenta, Self>
Source§fn on_bright_purple(&self) -> BgColorDisplay<'_, BrightMagenta, Self>
fn on_bright_purple(&self) -> BgColorDisplay<'_, BrightMagenta, Self>
Source§fn bright_cyan(&self) -> FgColorDisplay<'_, BrightCyan, Self>
fn bright_cyan(&self) -> FgColorDisplay<'_, BrightCyan, Self>
Source§fn on_bright_cyan(&self) -> BgColorDisplay<'_, BrightCyan, Self>
fn on_bright_cyan(&self) -> BgColorDisplay<'_, BrightCyan, Self>
Source§fn bright_white(&self) -> FgColorDisplay<'_, BrightWhite, Self>
fn bright_white(&self) -> FgColorDisplay<'_, BrightWhite, Self>
Source§fn on_bright_white(&self) -> BgColorDisplay<'_, BrightWhite, Self>
fn on_bright_white(&self) -> BgColorDisplay<'_, BrightWhite, Self>
Source§fn bold(&self) -> BoldDisplay<'_, Self>
fn bold(&self) -> BoldDisplay<'_, Self>
Source§fn dimmed(&self) -> DimDisplay<'_, Self>
fn dimmed(&self) -> DimDisplay<'_, Self>
Source§fn italic(&self) -> ItalicDisplay<'_, Self>
fn italic(&self) -> ItalicDisplay<'_, Self>
Source§fn underline(&self) -> UnderlineDisplay<'_, Self>
fn underline(&self) -> UnderlineDisplay<'_, Self>
Source§fn blink(&self) -> BlinkDisplay<'_, Self>
fn blink(&self) -> BlinkDisplay<'_, Self>
Source§fn blink_fast(&self) -> BlinkFastDisplay<'_, Self>
fn blink_fast(&self) -> BlinkFastDisplay<'_, Self>
Source§fn reversed(&self) -> ReversedDisplay<'_, Self>
fn reversed(&self) -> ReversedDisplay<'_, Self>
Source§fn strikethrough(&self) -> StrikeThroughDisplay<'_, Self>
fn strikethrough(&self) -> StrikeThroughDisplay<'_, Self>
Source§fn color<Color>(&self, color: Color) -> FgDynColorDisplay<'_, Color, Self>where
Color: DynColor,
fn color<Color>(&self, color: Color) -> FgDynColorDisplay<'_, Color, Self>where
Color: DynColor,
OwoColorize::fg or
a color-specific method, such as OwoColorize::green, Read moreSource§fn on_color<Color>(&self, color: Color) -> BgDynColorDisplay<'_, Color, Self>where
Color: DynColor,
fn on_color<Color>(&self, color: Color) -> BgDynColorDisplay<'_, Color, Self>where
Color: DynColor,
OwoColorize::bg or
a color-specific method, such as OwoColorize::on_yellow, Read more