Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: return structured error from deno_ast::ParsedSource::transpile #236

Merged
merged 2 commits into from
Apr 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ swc_macros_common = { version = "=0.3.9", optional = true }
swc_trace_macro = { version = "=0.1.3", optional = true }
swc_visit = { version = "=0.5.9", optional = true }
swc_visit_macros = { version = "=0.5.10", optional = true }
thiserror = "1.0.58"

[dev-dependencies]
pretty_assertions = "1.3.0"
Expand Down
20 changes: 17 additions & 3 deletions src/emit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

use anyhow::Result;
use base64::Engine;
use thiserror::Error;

use crate::swc::ast::Program;
use crate::swc::codegen::text_writer::JsWriter;
Expand Down Expand Up @@ -49,14 +50,24 @@ pub struct EmittedSource {
pub source_map: Option<String>,
}

#[derive(Debug, Error)]
pub enum EmitError {
#[error(transparent)]
Utf8(#[from] std::string::FromUtf8Error),
#[error(transparent)]
SwcEmit(anyhow::Error),
#[error(transparent)]
SourceMap(anyhow::Error),
}

/// Emits the program as a string of JavaScript code, possibly with the passed
/// comments, and optionally also a source map.
pub fn emit(
program: &Program,
comments: &dyn crate::swc::common::comments::Comments,
source_map: &SourceMap,
emit_options: &EmitOptions,
) -> Result<EmittedSource> {
) -> Result<EmittedSource, EmitError> {
let source_map = source_map.inner();
let mut src_map_buf = vec![];
let mut buf = vec![];
Expand All @@ -79,7 +90,9 @@ pub fn emit(
cm: source_map.clone(),
wr: writer,
};
program.emit_with(&mut emitter)?;
program
.emit_with(&mut emitter)
.map_err(|e| EmitError::SwcEmit(e.into()))?;
}

let mut src = String::from_utf8(buf)?;
Expand All @@ -92,7 +105,8 @@ pub fn emit(
};
source_map
.build_source_map_with_config(&src_map_buf, None, source_map_config)
.to_writer(&mut buf)?;
.to_writer(&mut buf)
.map_err(|e| EmitError::SourceMap(e.into()))?;

if emit_options.source_map == SourceMapOption::Inline {
if !src.ends_with('\n') {
Expand Down
73 changes: 57 additions & 16 deletions src/transpiling/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,9 @@

use std::rc::Rc;

use anyhow::anyhow;
use anyhow::bail;
use anyhow::Result;
use swc_ecma_visit::as_folder;
use thiserror::Error;

use crate::emit;
use crate::swc::ast::Program;
Expand All @@ -24,6 +23,7 @@ use crate::swc::transforms::react;
use crate::swc::transforms::resolver;
use crate::swc::transforms::typescript;
use crate::swc::visit::FoldWith;
use crate::EmitError;
use crate::EmitOptions;
use crate::EmittedSource;
use crate::ParseDiagnostic;
Expand All @@ -36,6 +36,21 @@ use std::cell::RefCell;
mod jsx_precompile;
mod transforms;

#[derive(Debug, Error)]
pub enum TranspileError {
#[error("Can't use TranspileOptions::use_decorators_proposal and TranspileOptions::use_ts_decorators together.")]
DecoratorOptionsConflict,
/// Parse errors that prevent transpiling.
#[error(transparent)]
ParseErrors(#[from] ParseDiagnosticsError),
#[error(transparent)]
FoldProgram(#[from] FoldProgramError),
#[error("{0}")]
EmitDiagnostic(String),
#[error(transparent)]
Emit(#[from] EmitError),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ImportsNotUsedAsValues {
Remove,
Expand Down Expand Up @@ -150,11 +165,11 @@ impl ParsedSource {
&self,
transpile_options: &TranspileOptions,
emit_options: &EmitOptions,
) -> Result<EmittedSource> {
) -> Result<EmittedSource, TranspileError> {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I did this work as part of another PR to make a transpile_owned(self) method, but then ended up deciding to return the failure of Arc::try_unwrap in the Ok result to force the caller to handle it.

if transpile_options.use_decorators_proposal
&& transpile_options.use_ts_decorators
{
bail!("Can't use TranspileOptions::use_decorators_proposal and TranspileOptions::use_ts_decorators together.");
return Err(TranspileError::DecoratorOptionsConflict);
}

let program = (*self.program()).clone();
Expand All @@ -179,7 +194,7 @@ impl ParsedSource {
)
})?;

emit(&program, &comments, &source_map, emit_options)
Ok(emit(&program, &comments, &source_map, emit_options)?)
}
}

Expand All @@ -205,6 +220,14 @@ impl crate::swc::common::errors::Emitter for DiagnosticCollector {
}
}

#[derive(Debug, Error)]
pub enum FoldProgramError {
#[error(transparent)]
ParseDiagnostics(#[from] ParseDiagnosticsError),
#[error(transparent)]
Swc(#[from] SwcFoldDiagnosticsError),
}
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should switch this to actually use the diagnostics in the future. This is a very rough/sloppy first pass.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SGTM


/// Low level function for transpiling a program.
pub fn fold_program(
program: Program,
Expand All @@ -213,7 +236,7 @@ pub fn fold_program(
comments: &SingleThreadedComments,
top_level_mark: Mark,
diagnostics: &[ParseDiagnostic],
) -> Result<Program> {
) -> Result<Program, FoldProgramError> {
ensure_no_fatal_diagnostics(diagnostics)?;

let unresolved_mark = Mark::new();
Expand Down Expand Up @@ -312,26 +335,44 @@ pub fn fold_program(
})
});

let diagnostics = diagnostics_cell.borrow();
ensure_no_fatal_swc_diagnostics(source_map, diagnostics.iter())?;
let mut diagnostics = diagnostics_cell.borrow_mut();
let diagnostics = std::mem::take(&mut *diagnostics);
ensure_no_fatal_swc_diagnostics(source_map, diagnostics.into_iter())?;
Ok(result)
}

fn ensure_no_fatal_swc_diagnostics<'a>(
#[derive(Debug)]
pub struct SwcFoldDiagnosticsError(Vec<String>);

impl std::error::Error for SwcFoldDiagnosticsError {}

impl std::fmt::Display for SwcFoldDiagnosticsError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
for (i, diagnostic) in self.0.iter().enumerate() {
if i > 0 {
write!(f, "\n\n")?;
}

write!(f, "{}", diagnostic)?
}

Ok(())
}
}

fn ensure_no_fatal_swc_diagnostics(
source_map: &SourceMap,
diagnostics: impl Iterator<Item = &'a SwcDiagnostic>,
) -> Result<()> {
diagnostics: impl Iterator<Item = SwcDiagnostic>,
) -> Result<(), SwcFoldDiagnosticsError> {
let fatal_diagnostics = diagnostics
.filter(|d| is_fatal_swc_diagnostic(d))
.filter(is_fatal_swc_diagnostic)
.collect::<Vec<_>>();
if !fatal_diagnostics.is_empty() {
Err(anyhow!(
"{}",
Err(SwcFoldDiagnosticsError(
fatal_diagnostics
.iter()
.map(|d| format_swc_diagnostic(source_map, d))
.collect::<Vec<_>>()
.join("\n\n")
.collect::<Vec<_>>(),
))
} else {
Ok(())
Expand Down
Loading