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: align module error #4882

Closed
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
4 changes: 2 additions & 2 deletions crates/node_binding/binding.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export class JsCompilation {
getMissingDependencies(): Array<string>
getBuildDependencies(): Array<string>
pushDiagnostic(severity: "error" | "warning", title: string, message: string): void
pushNativeDiagnostics(diagnostics: ExternalObject<'Diagnostic[]'>): void
pushNativeDiagnostics(diagnostics: ExternalObject<'RspackDiagnostic[]'>): void
getStats(): JsStats
getAssetPath(filename: string, data: PathData): string
getAssetPathWithInfo(filename: string, data: PathData): PathWithInfo
Expand Down Expand Up @@ -345,7 +345,7 @@ export interface JsLoaderContext {
* Internal loader diagnostic
* @internal
*/
diagnosticsExternal: ExternalObject<'Diagnostic[]'>
diagnosticsExternal: ExternalObject<'RspackDiagnostic[]'>
}

export interface JsModule {
Expand Down
89 changes: 41 additions & 48 deletions crates/node_binding/src/plugins/mod.rs

Large diffs are not rendered by default.

16 changes: 0 additions & 16 deletions crates/rspack_ast/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
mod ast;

use rspack_error::{internal_error, Result};

pub use crate::ast::css;
use crate::ast::css::Ast as CssAst;
pub use crate::ast::javascript;
Expand All @@ -17,20 +15,6 @@ pub enum RspackAst {
}

impl RspackAst {
pub fn try_into_javascript(self) -> Result<JsAst> {
match self {
RspackAst::JavaScript(program) => Ok(program),
RspackAst::Css(_) => Err(internal_error!("Failed to cast `CSS` AST to `JavaScript`")),
}
}

pub fn try_into_css(self) -> Result<CssAst> {
match self {
RspackAst::Css(stylesheet) => Ok(stylesheet),
RspackAst::JavaScript(_) => Err(internal_error!("Failed to cast `JavaScript` AST to `CSS`")),
}
}

pub fn as_javascript(&self) -> Option<&JsAst> {
match self {
RspackAst::JavaScript(program) => Some(program),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use derivative::Derivative;
use napi::{Either, Env, JsFunction};
use napi_derive::napi;
use rspack_binding_values::JsChunk;
use rspack_error::{internal_error, Result};
use rspack_error::Result;
use rspack_napi_shared::{
threadsafe_function::{ThreadsafeFunction, ThreadsafeFunctionCallMode},
JsRegExp, JsRegExpExt, NapiResultExt, NAPI_ENV,
Expand Down Expand Up @@ -54,7 +54,7 @@ impl TryFrom<RawBannerContentWrapper> for BannerContent {
.call(ctx.into(), ThreadsafeFunctionCallMode::NonBlocking)
.into_rspack_result()?
.await
.map_err(|err| internal_error!("Failed to call rule.use function: {err}"))?
.unwrap_or_else(|err| panic!("Failed to call rule.use function: {err}"))
})
},
)))
Expand Down
3 changes: 1 addition & 2 deletions crates/rspack_binding_options/src/options/raw_external.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ use napi::{Env, JsFunction};
use napi_derive::napi;
use rspack_core::ExternalItemFnCtx;
use rspack_core::{ExternalItem, ExternalItemFnResult, ExternalItemValue};
use rspack_error::internal_error;
use rspack_napi_shared::threadsafe_function::{ThreadsafeFunction, ThreadsafeFunctionCallMode};
use rspack_napi_shared::{JsRegExp, JsRegExpExt, NapiResultExt, NAPI_ENV};

Expand Down Expand Up @@ -106,7 +105,7 @@ impl TryFrom<RawExternalItemWrapper> for ExternalItem {
.call(ctx.into(), ThreadsafeFunctionCallMode::NonBlocking)
.into_rspack_result()?
.await
.map_err(|err| internal_error!("Failed to call external function: {err}"))?
.unwrap_or_else(|err| panic!("Failed to call external function: {err}"))
.map(|r| r.into())
})
})))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use std::{

use napi_derive::napi;
use rspack_core::{rspack_sources::SourceMap, Content, ResourceData};
use rspack_error::Diagnostic;
use rspack_error::RspackDiagnostic;
use rspack_loader_runner::AdditionalData;
use rustc_hash::FxHashSet as HashSet;
use tracing::{span_enabled, Level};
Expand Down Expand Up @@ -140,7 +140,7 @@ impl Loader<LoaderRunnerContext> for JsLoaderAdapter {
.call(js_loader_context, ThreadsafeFunctionCallMode::NonBlocking)
.into_rspack_result()?
.await
.map_err(|err| internal_error!("Failed to call loader: {err}"))??;
.unwrap_or_else(|err| panic!("Failed to call loader: {err}"))?;

if let Some(loader_result) = loader_result {
// This indicate that the JS loaders pitched(return something) successfully
Expand Down Expand Up @@ -170,7 +170,7 @@ impl Loader<LoaderRunnerContext> for JsLoaderAdapter {
.call(js_loader_context, ThreadsafeFunctionCallMode::NonBlocking)
.into_rspack_result()?
.await
.map_err(|err| internal_error!("Failed to call loader: {err}"))??;
.unwrap_or_else(|err| panic!("Failed to call loader: {err}"))?;

if let Some(loader_result) = loader_result {
sync_loader_context(loader_result, loader_context)?;
Expand Down Expand Up @@ -261,8 +261,8 @@ pub struct JsLoaderContext {
pub context_external: External<rspack_core::LoaderRunnerContext>,
/// Internal loader diagnostic
/// @internal
#[napi(ts_type = "ExternalObject<'Diagnostic[]'>")]
pub diagnostics_external: External<Vec<Diagnostic>>,
#[napi(ts_type = "ExternalObject<'RspackDiagnostic[]'>")]
pub diagnostics_external: External<Vec<RspackDiagnostic>>,
}

impl TryFrom<&rspack_core::LoaderContext<'_, rspack_core::LoaderRunnerContext>>
Expand Down
8 changes: 4 additions & 4 deletions crates/rspack_binding_options/src/options/raw_module/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -241,9 +241,9 @@ impl TryFrom<RawRuleSetCondition> for rspack_core::RuleSetCondition {
.call(data, ThreadsafeFunctionCallMode::NonBlocking)
.into_rspack_result()?
.await
.map_err(|err| {
internal_error!("Failed to call RuleSetCondition func_matcher: {err}")
})?
.unwrap_or_else(|err| {
panic!("Failed to call RuleSetCondition func_matcher: {err}")
})
})
}))
}
Expand Down Expand Up @@ -614,7 +614,7 @@ impl RawOptionsApply for RawModuleRule {
.call(ctx.into(), ThreadsafeFunctionCallMode::NonBlocking)
.into_rspack_result()?
.await
.map_err(|err| internal_error!("Failed to call rule.use function: {err}"))?
.unwrap_or_else(|err| panic!("Failed to call rule.use function: {err}"))
.map(|uses| {
uses
.into_iter()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ use napi::bindgen_prelude::Either3;
use napi::{Env, JsFunction};
use napi_derive::napi;
use rspack_binding_values::{JsModule, ToJsModule};
use rspack_error::internal_error;
use rspack_napi_shared::threadsafe_function::{ThreadsafeFunction, ThreadsafeFunctionCallMode};
use rspack_napi_shared::{JsRegExp, JsRegExpExt, NapiResultExt, NAPI_ENV};
use rspack_plugin_split_chunks_new::{CacheGroupTest, CacheGroupTestFnCtx};
Expand Down Expand Up @@ -48,12 +47,7 @@ pub(super) fn normalize_raw_cache_group_test(raw: RawCacheGroupTest) -> CacheGro
.into_rspack_result()
.expect("into rspack result failed")
.await
.unwrap_or_else(|err| {
panic!(
"{}",
internal_error!("Failed to call external function: {err}")
)
})
.unwrap_or_else(|err| panic!("Failed to call external function: {err}"))
.expect("failed")
})
}))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ use napi::bindgen_prelude::Either3;
use napi::{Env, JsFunction};
use napi_derive::napi;
use rspack_binding_values::{JsModule, ToJsModule};
use rspack_error::internal_error;
use rspack_napi_shared::threadsafe_function::{ThreadsafeFunction, ThreadsafeFunctionCallMode};
use rspack_napi_shared::{NapiResultExt, NAPI_ENV};
use rspack_plugin_split_chunks_new::{ChunkNameGetter, ChunkNameGetterFnCtx};
Expand Down Expand Up @@ -53,12 +52,7 @@ pub(super) fn normalize_raw_chunk_name(raw: RawChunkOptionName) -> ChunkNameGett
.into_rspack_result()
.expect("into rspack result failed")
.await
.unwrap_or_else(|err| {
panic!(
"{}",
internal_error!("Failed to call external function: {err}")
)
})
.unwrap_or_else(|err| panic!("Failed to call external function: {err}"))
.expect("failed")
})
}))
Expand Down
10 changes: 5 additions & 5 deletions crates/rspack_binding_values/src/compilation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use rspack_core::rspack_sources::BoxSource;
use rspack_core::AssetInfo;
use rspack_core::ModuleIdentifier;
use rspack_core::{rspack_sources::SourceExt, NormalModuleSource};
use rspack_error::Diagnostic;
use rspack_error::RspackDiagnostic;
use rspack_identifier::Identifier;
use rspack_napi_shared::NapiResultExt;

Expand Down Expand Up @@ -315,14 +315,14 @@ impl JsCompilation {
#[napi(ts_args_type = r#"severity: "error" | "warning", title: string, message: string"#)]
pub fn push_diagnostic(&mut self, severity: String, title: String, message: String) {
let diagnostic = match severity.as_str() {
"warning" => rspack_error::Diagnostic::warn(title, message, 0, 0),
_ => rspack_error::Diagnostic::error(title, message, 0, 0),
"warning" => rspack_error::RspackDiagnostic::warn(title, message, 0, 0),
_ => rspack_error::RspackDiagnostic::error(title, message, 0, 0),
};
self.inner.push_diagnostic(diagnostic);
}

#[napi(ts_args_type = r#"diagnostics: ExternalObject<'Diagnostic[]'>"#)]
pub fn push_native_diagnostics(&mut self, mut diagnostics: External<Vec<Diagnostic>>) {
#[napi(ts_args_type = r#"diagnostics: ExternalObject<'RspackDiagnostic[]'>"#)]
pub fn push_native_diagnostics(&mut self, mut diagnostics: External<Vec<RspackDiagnostic>>) {
while let Some(diagnostic) = diagnostics.pop() {
self.inner.push_diagnostic(diagnostic);
}
Expand Down
31 changes: 11 additions & 20 deletions crates/rspack_core/src/code_generation_results.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ use std::ops::{Deref, DerefMut};
use std::sync::atomic::AtomicU32;

use anymap::CloneAny;
use rspack_error::{internal_error, Result};
use rspack_hash::{HashDigest, HashFunction, HashSalt, RspackHash, RspackHashDigest};
use rspack_identifier::IdentifierMap;
use rspack_sources::BoxSource;
Expand Down Expand Up @@ -182,48 +181,48 @@ impl CodeGenerationResults {
&self,
module_identifier: &ModuleIdentifier,
runtime: Option<&RuntimeSpec>,
) -> Result<&CodeGenerationResult> {
) -> &CodeGenerationResult {
if let Some(entry) = self.map.get(module_identifier) {
if let Some(runtime) = runtime {
entry
.get(runtime)
.and_then(|m| {
self.module_generation_result_map.get(m)
})
.ok_or_else(|| {
internal_error!(
.unwrap_or_else(|| {
panic!(
"Failed to code generation result for {module_identifier} with runtime {runtime:?} \n {entry:?}"
)
})
} else {
if entry.size() > 1 {
let results = entry.get_values();
if results.len() != 1 {
return Err(internal_error!(
panic!(
"No unique code generation entry for unspecified runtime for {module_identifier} ",
));
);
}

return results
.first()
.copied()
.and_then(|m| self.module_generation_result_map.get(m))
.ok_or_else(|| internal_error!("Expected value exists"));
.unwrap_or_else(|| panic!("Expected value exists"));
}

entry
.get_values()
.first()
.copied()
.and_then(|m| self.module_generation_result_map.get(m))
.ok_or_else(|| internal_error!("Expected value exists"))
.unwrap_or_else(|| panic!("Expected value exists"))
}
} else {
Err(internal_error!(
panic!(
"No code generation entry for {} (existing entries: {:?})",
module_identifier,
self.map.keys().collect::<Vec<_>>()
))
)
}
}

Expand All @@ -250,13 +249,7 @@ impl CodeGenerationResults {
module_identifier: &ModuleIdentifier,
runtime: Option<&RuntimeSpec>,
) -> RuntimeGlobals {
match self.get(module_identifier, runtime) {
Ok(result) => result.runtime_requirements,
Err(_) => {
eprintln!("Failed to get runtime requirements for {module_identifier}");
Default::default()
}
}
self.get(module_identifier, runtime).runtime_requirements
}

#[allow(clippy::unwrap_in_result)]
Expand All @@ -265,9 +258,7 @@ impl CodeGenerationResults {
module_identifier: &ModuleIdentifier,
runtime: Option<&RuntimeSpec>,
) -> Option<&RspackHashDigest> {
let code_generation_result = self
.get(module_identifier, runtime)
.expect("should have code generation result");
let code_generation_result = self.get(module_identifier, runtime);

code_generation_result.hash.as_ref()
}
Expand Down
12 changes: 6 additions & 6 deletions crates/rspack_core/src/compiler/compilation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use itertools::Itertools;
use rayon::prelude::{
IntoParallelIterator, IntoParallelRefIterator, ParallelBridge, ParallelIterator,
};
use rspack_error::{internal_error, Diagnostic, Result, Severity, TWithDiagnosticArray};
use rspack_error::{internal_error, Result, RspackDiagnostic, Severity, TWithDiagnosticArray};
use rspack_futures::FuturesResults;
use rspack_hash::{RspackHash, RspackHashDigest};
use rspack_identifier::{Identifiable, IdentifierMap, IdentifierSet};
Expand Down Expand Up @@ -78,7 +78,7 @@ pub struct Compilation {
pub async_entrypoints: Vec<ChunkGroupUkey>,
assets: CompilationAssets,
pub emitted_assets: DashSet<String, BuildHasherDefault<FxHasher>>,
diagnostics: IndexSet<Diagnostic, BuildHasherDefault<FxHasher>>,
diagnostics: IndexSet<RspackDiagnostic, BuildHasherDefault<FxHasher>>,
logging: CompilationLogging,
pub plugin_driver: SharedPluginDriver,
pub resolver_factory: Arc<ResolverFactory>,
Expand Down Expand Up @@ -314,22 +314,22 @@ impl Compilation {
&self.entrypoints
}

pub fn push_diagnostic(&mut self, diagnostic: Diagnostic) {
pub fn push_diagnostic(&mut self, diagnostic: RspackDiagnostic) {
self.diagnostics.insert(diagnostic);
}

pub fn push_batch_diagnostic(&mut self, diagnostics: Vec<Diagnostic>) {
pub fn push_batch_diagnostic(&mut self, diagnostics: Vec<RspackDiagnostic>) {
self.diagnostics.extend(diagnostics);
}

pub fn get_errors(&self) -> impl Iterator<Item = &Diagnostic> {
pub fn get_errors(&self) -> impl Iterator<Item = &RspackDiagnostic> {
self
.diagnostics
.iter()
.filter(|d| matches!(d.severity(), Severity::Error))
}

pub fn get_warnings(&self) -> impl Iterator<Item = &Diagnostic> {
pub fn get_warnings(&self) -> impl Iterator<Item = &RspackDiagnostic> {
self
.diagnostics
.iter()
Expand Down
6 changes: 3 additions & 3 deletions crates/rspack_core/src/compiler/queue.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::sync::Arc;

use rspack_error::{Diagnostic, Result};
use rspack_error::{Result, RspackDiagnostic};

use crate::{
cache::Cache, BoxDependency, BuildContext, BuildResult, Compilation, CompilerContext,
Expand Down Expand Up @@ -56,7 +56,7 @@ pub struct FactorizeTaskResult {
pub factory_result: ModuleFactoryResult,
pub module_graph_module: Box<ModuleGraphModule>,
pub dependencies: Vec<DependencyId>,
pub diagnostics: Vec<Diagnostic>,
pub diagnostics: Vec<RspackDiagnostic>,
pub is_entry: bool,
pub current_profile: Option<Box<ModuleProfile>>,
pub exports_info_related: ExportsInfoRelated,
Expand Down Expand Up @@ -280,7 +280,7 @@ pub struct BuildTask {
pub struct BuildTaskResult {
pub module: Box<dyn Module>,
pub build_result: Box<BuildResult>,
pub diagnostics: Vec<Diagnostic>,
pub diagnostics: Vec<RspackDiagnostic>,
pub current_profile: Option<Box<ModuleProfile>>,
pub from_cache: bool,
}
Expand Down
Loading
Loading