#[cfg(feature = "parser")]
mod parser_impl {
use crate::error::{GenError, Result};
use oxc_allocator::Allocator;
use oxc_parser::Parser;
use oxc_span::SourceType;
#[derive(Debug, Clone)]
pub struct ParseOptions {
pub source_type: SourceType,
pub allow_errors: bool,
}
impl Default for ParseOptions {
fn default() -> Self {
Self {
source_type: SourceType::mjs(),
allow_errors: false,
}
}
}
impl ParseOptions {
pub fn from_path(path: &str) -> Self {
Self {
source_type: SourceType::from_path(path).unwrap_or(SourceType::mjs()),
allow_errors: false,
}
}
pub fn typescript() -> Self {
Self {
source_type: SourceType::ts(),
allow_errors: false,
}
}
pub fn jsx() -> Self {
Self {
source_type: SourceType::jsx(),
allow_errors: false,
}
}
pub fn tsx() -> Self {
Self {
source_type: SourceType::tsx(),
allow_errors: false,
}
}
}
#[derive(Debug, Clone)]
pub struct ParseDiagnostic {
pub message: String,
pub span: Option<(u32, u32)>,
}
pub struct ParsedProgram<'a> {
pub program: oxc_ast::ast::Program<'a>,
pub diagnostics: Vec<ParseDiagnostic>,
pub source_text: &'a str,
pub allocator: &'a Allocator,
}
impl<'a> ParsedProgram<'a> {
pub fn ast(&self) -> &oxc_ast::ast::Program<'a> {
&self.program
}
pub fn ast_mut(&mut self) -> &mut oxc_ast::ast::Program<'a> {
&mut self.program
}
pub fn allocator(&self) -> &'a Allocator {
self.allocator
}
pub fn has_errors(&self) -> bool {
!self.diagnostics.is_empty()
}
}
pub fn parse<'a>(
allocator: &'a Allocator,
source: &'a str,
options: ParseOptions,
) -> Result<ParsedProgram<'a>> {
let parser = Parser::new(allocator, source, options.source_type);
let result = parser.parse();
let diagnostics: Vec<ParseDiagnostic> = result
.errors
.iter()
.map(|err| ParseDiagnostic {
message: format!("{:?}", err),
span: None, })
.collect();
if !options.allow_errors && !diagnostics.is_empty() {
return Err(GenError::CodegenFailed {
context: "Parse errors".to_string(),
reason: Some(
diagnostics
.iter()
.map(|d| d.message.clone())
.collect::<Vec<_>>()
.join(", "),
),
});
}
Ok(ParsedProgram {
program: result.program,
diagnostics,
source_text: source,
allocator,
})
}
}
#[cfg(feature = "parser")]
pub use parser_impl::*;