feat: 实现 parser crate

This commit is contained in:
2026-06-05 01:26:45 +08:00
parent e2a0bcbf1d
commit fd7d3b1f5e
3 changed files with 112 additions and 0 deletions
+30
View File
@@ -0,0 +1,30 @@
use std::fmt;
#[derive(Debug, Clone)]
pub struct OxideError {
pub message: String,
pub span: (usize, usize),
}
impl fmt::Display for OxideError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} at {:?}", self.message, self.span)
}
}
impl std::error::Error for OxideError {}
impl From<oxc_diagnostics::OxcDiagnostic> for OxideError {
fn from(diag: oxc_diagnostics::OxcDiagnostic) -> Self {
let span = diag
.labels
.clone()
.and_then(|labels| labels.first().map(|l| (l.offset() as usize, (l.offset() + l.len()) as usize)))
.unwrap_or((0, 0));
OxideError {
message: diag.message.to_string(),
span,
}
}
}
+28
View File
@@ -1 +1,29 @@
#![doc = "OxideJS - JavaScript parser (oxc_parser re-export)"]
mod error;
pub use error::OxideError;
pub use oxc_allocator::Allocator;
pub use oxc_ast::ast::*;
pub use oxc_span::Span;
pub fn parse<'a>(allocator: &'a Allocator, source: &'a str) -> Result<Program<'a>, Vec<OxideError>> {
use oxc_parser::Parser;
use oxc_span::SourceType;
let source_type = SourceType::default();
let ret = Parser::new(allocator, source, source_type).parse();
if ret.panicked {
return Err(vec![OxideError {
message: "Parser panicked: unrecoverable syntax error".to_string(),
span: (0, 0),
}]);
}
if !ret.errors.is_empty() {
return Err(ret.errors.into_iter().map(OxideError::from).collect());
}
Ok(ret.program)
}