Skip to main content

parser_tsx/
parser_tsx.rs

1//! # TypeScript JSX Parsing Example
2//!
3//! This example demonstrates parsing TypeScript files with JSX syntax.
4//! It shows how to parse a simple React component and validate the parsing results.
5//!
6//! ## Usage
7//!
8//! ```bash
9//! cargo run -p oxc_parser --example parser_tsx
10//! ```
11
12use oxc_allocator::Allocator;
13use oxc_parser::{Parser, ParserReturn};
14use oxc_span::SourceType;
15
16/// Parse a TypeScript JSX file and validate the results
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}