Skip to content

Commit

Permalink
refactor: unexpected should not always rely on
Browse files Browse the repository at this point in the history
  • Loading branch information
h-a-n-a committed Dec 5, 2023
1 parent 3406e7f commit 1aa1c32
Show file tree
Hide file tree
Showing 30 changed files with 128 additions and 192 deletions.
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 @@ -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
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
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
24 changes: 10 additions & 14 deletions crates/rspack_core/src/context_module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use std::{
use itertools::Itertools;
use once_cell::sync::Lazy;
use regex::{Captures, Regex};
use rspack_error::{internal_error, IntoTWithDiagnosticArray, Result, TWithDiagnosticArray};
use rspack_error::{IntoTWithDiagnosticArray, Result, TWithDiagnosticArray};
use rspack_hash::RspackHash;
use rspack_identifier::{Identifiable, Identifier};
use rspack_regex::RspackRegex;
Expand Down Expand Up @@ -358,18 +358,18 @@ impl ContextModule {
}

#[inline]
fn get_source_string(&self, compilation: &Compilation) -> Result<BoxSource> {
fn get_source_string(&self, compilation: &Compilation) -> BoxSource {
match self.options.context_options.mode {
ContextMode::Lazy => Ok(self.get_lazy_source(compilation)),
ContextMode::Lazy => self.get_lazy_source(compilation),
ContextMode::LazyOnce => {
let block = self
.get_blocks()
.first()
.ok_or_else(|| internal_error!("LazyOnce ContextModule should have first block"))?;
.expect("LazyOnce ContextModule should have first block");
let block = compilation
.module_graph
.block_by_id(block)
.ok_or_else(|| internal_error!("should have block"))?;
.expect("should have block");
self.generate_source(block.get_dependencies(), compilation)
}
_ => self.generate_source(self.get_dependencies(), compilation),
Expand Down Expand Up @@ -428,11 +428,7 @@ impl ContextModule {
source.boxed()
}

fn generate_source(
&self,
dependencies: &[DependencyId],
compilation: &Compilation,
) -> Result<BoxSource> {
fn generate_source(&self, dependencies: &[DependencyId], compilation: &Compilation) -> BoxSource {
let map = self.get_user_request_map(dependencies, compilation);
let fake_map = self.get_fake_map(dependencies, compilation);
let mode = &self.options.context_options.mode;
Expand Down Expand Up @@ -520,7 +516,7 @@ impl ContextModule {
source.add(RawSource::from(format!(
"webpackContext.id = '{}';\n",
serde_json::to_string(self.id(&compilation.chunk_graph))
.map_err(|e| internal_error!(e.to_string()))?
.unwrap_or_else(|e| panic!("{}", e.to_string()))
)));
source.add(RawSource::from(
r#"
Expand All @@ -531,7 +527,7 @@ impl ContextModule {
module.exports = webpackContext;
"#,
));
Ok(source.boxed())
source.boxed()
}
}

Expand Down Expand Up @@ -638,7 +634,7 @@ impl Module for ContextModule {
let block = compilation
.module_graph
.block_by_id(block)
.ok_or_else(|| internal_error!("should have block in ContextModule code_generation"))?;
.expect("should have block in ContextModule code_generation");
all_deps.extend(block.get_dependencies());
}
let fake_map = self.get_fake_map(all_deps.iter(), compilation);
Expand All @@ -647,7 +643,7 @@ impl Module for ContextModule {
.runtime_requirements
.insert(RuntimeGlobals::CREATE_FAKE_NAMESPACE_OBJECT);
}
code_generation_result.add(SourceType::JavaScript, self.get_source_string(compilation)?);
code_generation_result.add(SourceType::JavaScript, self.get_source_string(compilation));
code_generation_result.set_hash(
&compilation.options.output.hash_function,
&compilation.options.output.hash_digest,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,10 @@ impl RuntimeModule for ConsumeSharedRuntimeModule {
.clone()
.expect("should have moduleId at <ConsumeSharedRuntimeModule as RuntimeModule>::generate");
ids.push(id.clone());
if let Ok(code_gen) = compilation
if let Some(source) = compilation
.code_generation_results
.get(&module, Some(&chunk.runtime))
&& let Some(source) = code_gen.get(&SourceType::ConsumeShared)
.get(&SourceType::ConsumeShared)
{
module_id_to_source_mapping.insert(id, source.clone());
}
Expand Down
2 changes: 1 addition & 1 deletion crates/rspack_core/src/mf/sharing/share_runtime_module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ impl RuntimeModule for ShareRuntimeModule {
for m in modules {
let code_gen = compilation
.code_generation_results
.get(&m.identifier(), Some(&chunk.runtime)).expect("should have code_generation_result of share-init sourceType module at <ShareRuntimeModule as RuntimeModule>::generate");
.get(&m.identifier(), Some(&chunk.runtime));
let Some(data) = code_gen.data.get::<CodeGenerationDataShareInit>() else {
continue;
};
Expand Down
8 changes: 4 additions & 4 deletions crates/rspack_core/src/module_graph/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::collections::hash_map::Entry;
use std::path::PathBuf;

use dashmap::DashMap;
use rspack_error::{internal_error, Result};
use rspack_error::Result;
use rspack_hash::RspackHashDigest;
use rspack_identifier::{Identifiable, IdentifierMap};
use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet};
Expand Down Expand Up @@ -227,11 +227,11 @@ impl ModuleGraph {
{
let mgm = self
.module_graph_module_by_identifier_mut(&module_identifier)
.ok_or_else(|| {
internal_error!(
.unwrap_or_else(|| {
panic!(
"Failed to set resolved module: Module linked to module identifier {module_identifier} cannot be found"
)
})?;
});

mgm.add_incoming_connection(connection_id);
}
Expand Down
Loading

0 comments on commit 1aa1c32

Please sign in to comment.