Skip to content
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
22 changes: 22 additions & 0 deletions Cargo.lock

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

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ scopes = ["view", "utils", "visit"]
sourcemap = ["dprint-swc-ext/sourcemap", "swc_sourcemap"]
transforms = ["swc_ecma_loader", "swc_ecma_transforms_base"]
emit = ["base64", "codegen", "sourcemap"]
type_strip = [ "swc_ts_fast_strip" ]
transpiling = ["emit", "proposal", "react", "transforms", "typescript", "utils", "visit"]
typescript = ["transforms", "swc_ecma_transforms_typescript"]
utils = ["swc_ecma_utils"]
Expand Down Expand Up @@ -74,6 +75,7 @@ swc_bundler = { version = "=32.0.0", optional = true }
swc_graph_analyzer = { version = "=14.0.1", optional = true }
swc_macros_common = { version = "=1.0.1", optional = true }
swc_sourcemap = { version = "=9.3.4", optional = true }
swc_ts_fast_strip = { version = "=33.0.0", optional = true }
swc_trace_macro = { version = "=2.0.2", optional = true }
swc_visit = { version = "=2.0.1", optional = true }
thiserror = "2.0.12"
Expand Down
109 changes: 109 additions & 0 deletions src/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use std::fmt::Display;
use std::fmt::Write as _;
use std::path::PathBuf;

use deno_error::JsError;
use deno_terminal::colors;
use unicode_width::UnicodeWidthStr;

Expand All @@ -16,6 +17,8 @@ use crate::SourceRange;
use crate::SourceRanged;
use crate::SourceTextInfo;

use crate::swc::common::errors::Diagnostic as SwcDiagnostic;

pub enum DiagnosticLevel {
Error,
Warning,
Expand Down Expand Up @@ -560,6 +563,112 @@ fn specifier_to_file_path(specifier: &ModuleSpecifier) -> Option<PathBuf> {
}
}

pub(crate) type DiagnosticsCell = crate::swc::common::sync::Lrc<
crate::swc::common::sync::Lock<Vec<SwcDiagnostic>>,
>;

#[derive(Default, Clone)]
pub(crate) struct DiagnosticCollector {
diagnostics: DiagnosticsCell,
}

impl DiagnosticCollector {
pub fn into_handler_and_cell(
self,
) -> (crate::swc::common::errors::Handler, DiagnosticsCell) {
let cell = self.diagnostics.clone();
(
crate::swc::common::errors::Handler::with_emitter(
true,
false,
Box::new(self),
),
cell,
)
}
}

impl crate::swc::common::errors::Emitter for DiagnosticCollector {
fn emit(
&mut self,
db: &mut crate::swc::common::errors::DiagnosticBuilder<'_>,
) {
let mut diagnostics = self.diagnostics.lock();
diagnostics.push(db.take());
}
}

#[derive(Debug, JsError)]
#[class(syntax)]
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(())
}
}

pub(crate) fn ensure_no_fatal_swc_diagnostics(
source_map: &swc_common::SourceMap,
diagnostics: impl Iterator<Item = SwcDiagnostic>,
) -> Result<(), SwcFoldDiagnosticsError> {
let fatal_diagnostics = diagnostics
.filter(is_fatal_swc_diagnostic)
.collect::<Vec<_>>();
if !fatal_diagnostics.is_empty() {
Err(SwcFoldDiagnosticsError(
fatal_diagnostics
.iter()
.map(|d| format_swc_diagnostic(source_map, d))
.collect::<Vec<_>>(),
))
} else {
Ok(())
}
}

fn is_fatal_swc_diagnostic(diagnostic: &SwcDiagnostic) -> bool {
use crate::swc::common::errors::Level;
match diagnostic.level {
Level::Bug
| Level::Cancelled
| Level::FailureNote
| Level::Fatal
| Level::PhaseFatal
| Level::Error => true,
Level::Help | Level::Note | Level::Warning => false,
}
}

fn format_swc_diagnostic(
source_map: &swc_common::SourceMap,
diagnostic: &SwcDiagnostic,
) -> String {
if let Some(span) = &diagnostic.span.primary_span() {
let file_name = source_map.span_to_filename(*span);
let loc = source_map.lookup_char_pos(span.lo);
format!(
"{} at {}:{}:{}",
diagnostic.message(),
file_name,
loc.line,
loc.col_display + 1,
)
} else {
diagnostic.message()
}
}

#[cfg(test)]
mod tests {
use std::borrow::Cow;
Expand Down
4 changes: 4 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ mod source_map;
mod text_changes;
#[cfg(feature = "transpiling")]
mod transpiling;
#[cfg(feature = "type_strip")]
mod type_strip;
mod types;

#[cfg(feature = "view")]
Expand All @@ -50,6 +52,8 @@ pub use source_map::*;
pub use text_changes::*;
#[cfg(feature = "transpiling")]
pub use transpiling::*;
#[cfg(feature = "type_strip")]
pub use type_strip::*;
pub use types::*;

pub type ModuleSpecifier = url::Url;
Expand Down
108 changes: 5 additions & 103 deletions src/transpiling/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,12 @@ use crate::ParseDiagnosticsError;
use crate::ParsedSource;
use crate::ProgramRef;
use crate::SourceMap;
use crate::diagnostics::DiagnosticCollector;
use crate::diagnostics::SwcFoldDiagnosticsError;
use crate::diagnostics::ensure_no_fatal_swc_diagnostics;
use crate::emit;
use crate::swc::ast::Program;
use crate::swc::common::comments::SingleThreadedComments;
use crate::swc::common::errors::Diagnostic as SwcDiagnostic;
use crate::swc::common::sync::Lock;
use crate::swc::common::sync::Lrc;
use crate::swc::ecma_visit::visit_mut_pass;
use crate::swc::parser::error::SyntaxError;
use crate::swc::transforms::fixer;
Expand Down Expand Up @@ -667,31 +667,6 @@ fn convert_script_module_to_swc_script(
})
}

#[derive(Default, Clone)]
struct DiagnosticCollector {
diagnostics: Lrc<Lock<Vec<SwcDiagnostic>>>,
}

impl DiagnosticCollector {
pub fn into_handler(self) -> crate::swc::common::errors::Handler {
crate::swc::common::errors::Handler::with_emitter(
true,
false,
Box::new(self),
)
}
}

impl crate::swc::common::errors::Emitter for DiagnosticCollector {
fn emit(
&mut self,
db: &mut crate::swc::common::errors::DiagnosticBuilder<'_>,
) {
let mut diagnostics = self.diagnostics.lock();
diagnostics.push(db.take());
}
}

#[derive(Debug, Error, JsError)]
pub enum FoldProgramError {
#[class(inherit)]
Expand Down Expand Up @@ -849,91 +824,18 @@ pub fn fold_program<'a>(
);

let emitter = DiagnosticCollector::default();
let diagnostics_cell = emitter.diagnostics.clone();
let handler = emitter.into_handler();
let (handler, diagnostics_cell) = emitter.into_handler_and_cell();
let result = crate::swc::common::errors::HANDLER.set(&handler, || {
helpers::HELPERS
.set(&helpers::Helpers::new(false), || program.apply(passes))
});

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

#[derive(Debug, JsError)]
#[class(syntax)]
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 = SwcDiagnostic>,
) -> Result<(), SwcFoldDiagnosticsError> {
let fatal_diagnostics = diagnostics
.filter(is_fatal_swc_diagnostic)
.collect::<Vec<_>>();
if !fatal_diagnostics.is_empty() {
Err(SwcFoldDiagnosticsError(
fatal_diagnostics
.iter()
.map(|d| format_swc_diagnostic(source_map, d))
.collect::<Vec<_>>(),
))
} else {
Ok(())
}
}

fn is_fatal_swc_diagnostic(diagnostic: &SwcDiagnostic) -> bool {
use crate::swc::common::errors::Level;
match diagnostic.level {
Level::Bug
| Level::Cancelled
| Level::FailureNote
| Level::Fatal
| Level::PhaseFatal
| Level::Error => true,
Level::Help | Level::Note | Level::Warning => false,
}
}

fn format_swc_diagnostic(
source_map: &SourceMap,
diagnostic: &SwcDiagnostic,
) -> String {
if let Some(span) = &diagnostic.span.primary_span() {
let source_map = source_map.inner();
let file_name = source_map.span_to_filename(*span);
let loc = source_map.lookup_char_pos(span.lo);
format!(
"{} at {}:{}:{}",
diagnostic.message(),
file_name,
loc.line,
loc.col_display + 1,
)
} else {
diagnostic.message()
}
}

fn ensure_no_fatal_diagnostics<'a>(
diagnostics: Box<dyn Iterator<Item = &'a ParseDiagnostic> + 'a>,
) -> Result<(), ParseDiagnosticsError> {
Expand Down
Loading
Loading