mirror of
https://github.com/oxc-project/oxc.git
synced 2026-09-14 19:36:11 +08:00
66744f0eb9
`ParserReturn` contains a property `panicked`. The name `panicked` is misleading. The parser did _not_ panic. When `true`, it means that the parser encountered a fatal error and is unable to parse the source, because it contains an unrecoverable syntax error. Rename this property to `fatal_error`, to better describe what it means. This is a breaking change, but one that's trivial to fix in downstream code - the property doesn't change its meaning or behavior, just its name. All the changes in this PR in other crates are just reacting to this change and making everywhere use the term "fatal error" instead of "panicked", so the codebase is consistent.
61 lines
1.6 KiB
Rust
61 lines
1.6 KiB
Rust
//! # TypeScript JSX Parsing Example
|
|
//!
|
|
//! This example demonstrates parsing TypeScript files with JSX syntax.
|
|
//! It shows how to parse a simple React component and validate the parsing results.
|
|
//!
|
|
//! ## Usage
|
|
//!
|
|
//! ```bash
|
|
//! cargo run -p oxc_parser --example parser_tsx
|
|
//! ```
|
|
|
|
use oxc_allocator::Allocator;
|
|
use oxc_parser::{Parser, ParserReturn};
|
|
use oxc_span::SourceType;
|
|
|
|
/// Parse a TypeScript JSX file and validate the results
|
|
fn main() -> Result<(), String> {
|
|
let source_text = r"
|
|
import React from 'react';
|
|
|
|
/**
|
|
* A simple counter component
|
|
*/
|
|
export const Counter: React.FC = () => {
|
|
const [count, setCount] = React.useState(0);
|
|
|
|
return (
|
|
<div>
|
|
<p>Count: {count}</p>
|
|
<button onClick={() => setCount(count + 1)}>Increment</button>
|
|
<button onClick={() => setCount(count - 1)}>Decrement</button>
|
|
</div>
|
|
)
|
|
}";
|
|
|
|
// Memory arena where AST nodes get stored
|
|
let allocator = Allocator::default();
|
|
// Infers TypeScript + JSX + ESM modules
|
|
let source_type = SourceType::from_path("Counter.tsx").unwrap();
|
|
|
|
let ParserReturn {
|
|
program, // AST
|
|
diagnostics, // Syntax errors
|
|
fatal_error, // Parser encountered an error it couldn't recover from
|
|
..
|
|
} = Parser::new(&allocator, source_text, source_type).parse();
|
|
|
|
if fatal_error {
|
|
return Err("Parser encountered a fatal error".to_string());
|
|
}
|
|
|
|
if !diagnostics.is_empty() {
|
|
return Err(format!("Parsing errors: {}", diagnostics.len()));
|
|
}
|
|
|
|
assert!(!program.body.is_empty());
|
|
assert_eq!(program.comments.len(), 1);
|
|
|
|
Ok(())
|
|
}
|