Skip to main content

Parser

Struct Parser 

Source
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>

Source

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>

Source

pub fn parse_observed(self) -> ProgramObservation<'a>

Retain one complete observation using the built-in token configuration.

Source§

impl<'a> Parser<'a, RuntimeParserConfig>

Source

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>

Source

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?
examples/visitor.rs (line 35)
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
Hide additional examples
examples/regular_expression.rs (line 25)
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}
examples/parser_tsx.rs (line 46)
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

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>

Source

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 nodes
  • source_text: Source code to parse
  • source_type: Source type (e.g. JavaScript, TypeScript, JSX, ESM Module, Script)
Examples found in repository?
examples/visitor.rs (line 35)
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
Hide additional examples
examples/regular_expression.rs (line 25)
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}
examples/parser_tsx.rs (line 46)
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>

Source

pub fn with_options(self, options: ParseOptions) -> Self

Set parse options

Examples found in repository?
examples/regular_expression.rs (line 25)
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}
Source

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> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<'a, T> FromIn<'a, T> for T

Source§

fn from_in(t: T, _: &'a Allocator) -> T

Converts to this type from the input type within the given allocator.
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<'a, T, U> IntoIn<'a, U> for T
where U: FromIn<'a, T>,

Source§

fn into_in(self, allocator: &'a Allocator) -> U

Converts this type into the (usually inferred) input type within the given allocator.
Source§

impl<D> OwoColorize for D

Source§

fn fg<C>(&self) -> FgColorDisplay<'_, C, Self>
where C: Color,

Set the foreground color generically Read more
Source§

fn bg<C>(&self) -> BgColorDisplay<'_, C, Self>
where C: Color,

Set the background color generically. Read more
Source§

fn black(&self) -> FgColorDisplay<'_, Black, Self>

Change the foreground color to black
Source§

fn on_black(&self) -> BgColorDisplay<'_, Black, Self>

Change the background color to black
Source§

fn red(&self) -> FgColorDisplay<'_, Red, Self>

Change the foreground color to red
Source§

fn on_red(&self) -> BgColorDisplay<'_, Red, Self>

Change the background color to red
Source§

fn green(&self) -> FgColorDisplay<'_, Green, Self>

Change the foreground color to green
Source§

fn on_green(&self) -> BgColorDisplay<'_, Green, Self>

Change the background color to green
Source§

fn yellow(&self) -> FgColorDisplay<'_, Yellow, Self>

Change the foreground color to yellow
Source§

fn on_yellow(&self) -> BgColorDisplay<'_, Yellow, Self>

Change the background color to yellow
Source§

fn blue(&self) -> FgColorDisplay<'_, Blue, Self>

Change the foreground color to blue
Source§

fn on_blue(&self) -> BgColorDisplay<'_, Blue, Self>

Change the background color to blue
Source§

fn magenta(&self) -> FgColorDisplay<'_, Magenta, Self>

Change the foreground color to magenta
Source§

fn on_magenta(&self) -> BgColorDisplay<'_, Magenta, Self>

Change the background color to magenta
Source§

fn purple(&self) -> FgColorDisplay<'_, Magenta, Self>

Change the foreground color to purple
Source§

fn on_purple(&self) -> BgColorDisplay<'_, Magenta, Self>

Change the background color to purple
Source§

fn cyan(&self) -> FgColorDisplay<'_, Cyan, Self>

Change the foreground color to cyan
Source§

fn on_cyan(&self) -> BgColorDisplay<'_, Cyan, Self>

Change the background color to cyan
Source§

fn white(&self) -> FgColorDisplay<'_, White, Self>

Change the foreground color to white
Source§

fn on_white(&self) -> BgColorDisplay<'_, White, Self>

Change the background color to white
Source§

fn default_color(&self) -> FgColorDisplay<'_, Default, Self>

Change the foreground color to the terminal default
Source§

fn on_default_color(&self) -> BgColorDisplay<'_, Default, Self>

Change the background color to the terminal default
Source§

fn bright_black(&self) -> FgColorDisplay<'_, BrightBlack, Self>

Change the foreground color to bright black
Source§

fn on_bright_black(&self) -> BgColorDisplay<'_, BrightBlack, Self>

Change the background color to bright black
Source§

fn bright_red(&self) -> FgColorDisplay<'_, BrightRed, Self>

Change the foreground color to bright red
Source§

fn on_bright_red(&self) -> BgColorDisplay<'_, BrightRed, Self>

Change the background color to bright red
Source§

fn bright_green(&self) -> FgColorDisplay<'_, BrightGreen, Self>

Change the foreground color to bright green
Source§

fn on_bright_green(&self) -> BgColorDisplay<'_, BrightGreen, Self>

Change the background color to bright green
Source§

fn bright_yellow(&self) -> FgColorDisplay<'_, BrightYellow, Self>

Change the foreground color to bright yellow
Source§

fn on_bright_yellow(&self) -> BgColorDisplay<'_, BrightYellow, Self>

Change the background color to bright yellow
Source§

fn bright_blue(&self) -> FgColorDisplay<'_, BrightBlue, Self>

Change the foreground color to bright blue
Source§

fn on_bright_blue(&self) -> BgColorDisplay<'_, BrightBlue, Self>

Change the background color to bright blue
Source§

fn bright_magenta(&self) -> FgColorDisplay<'_, BrightMagenta, Self>

Change the foreground color to bright magenta
Source§

fn on_bright_magenta(&self) -> BgColorDisplay<'_, BrightMagenta, Self>

Change the background color to bright magenta
Source§

fn bright_purple(&self) -> FgColorDisplay<'_, BrightMagenta, Self>

Change the foreground color to bright purple
Source§

fn on_bright_purple(&self) -> BgColorDisplay<'_, BrightMagenta, Self>

Change the background color to bright purple
Source§

fn bright_cyan(&self) -> FgColorDisplay<'_, BrightCyan, Self>

Change the foreground color to bright cyan
Source§

fn on_bright_cyan(&self) -> BgColorDisplay<'_, BrightCyan, Self>

Change the background color to bright cyan
Source§

fn bright_white(&self) -> FgColorDisplay<'_, BrightWhite, Self>

Change the foreground color to bright white
Source§

fn on_bright_white(&self) -> BgColorDisplay<'_, BrightWhite, Self>

Change the background color to bright white
Source§

fn bold(&self) -> BoldDisplay<'_, Self>

Make the text bold
Source§

fn dimmed(&self) -> DimDisplay<'_, Self>

Make the text dim
Source§

fn italic(&self) -> ItalicDisplay<'_, Self>

Make the text italicized
Source§

fn underline(&self) -> UnderlineDisplay<'_, Self>

Make the text underlined
Make the text blink
Make the text blink (but fast!)
Source§

fn reversed(&self) -> ReversedDisplay<'_, Self>

Swap the foreground and background colors
Source§

fn hidden(&self) -> HiddenDisplay<'_, Self>

Hide the text
Source§

fn strikethrough(&self) -> StrikeThroughDisplay<'_, Self>

Cross out the text
Source§

fn color<Color>(&self, color: Color) -> FgDynColorDisplay<'_, Color, Self>
where Color: DynColor,

Set the foreground color at runtime. Only use if you do not know which color will be used at compile-time. If the color is constant, use either OwoColorize::fg or a color-specific method, such as OwoColorize::green, Read more
Source§

fn on_color<Color>(&self, color: Color) -> BgDynColorDisplay<'_, Color, Self>
where Color: DynColor,

Set the background color at runtime. Only use if you do not know what color to use at compile-time. If the color is constant, use either OwoColorize::bg or a color-specific method, such as OwoColorize::on_yellow, Read more
Source§

fn fg_rgb<const R: u8, const G: u8, const B: u8>( &self, ) -> FgColorDisplay<'_, CustomColor<R, G, B>, Self>

Set the foreground color to a specific RGB value.
Source§

fn bg_rgb<const R: u8, const G: u8, const B: u8>( &self, ) -> BgColorDisplay<'_, CustomColor<R, G, B>, Self>

Set the background color to a specific RGB value.
Source§

fn truecolor(&self, r: u8, g: u8, b: u8) -> FgDynColorDisplay<'_, Rgb, Self>

Sets the foreground color to an RGB value.
Source§

fn on_truecolor(&self, r: u8, g: u8, b: u8) -> BgDynColorDisplay<'_, Rgb, Self>

Sets the background color to an RGB value.
Source§

fn style(&self, style: Style) -> Styled<&Self>

Apply a runtime-determined style
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.