Skip to content

Commit

Permalink
refactor(swc/common): use into_inner instead of take
Browse files Browse the repository at this point in the history
  • Loading branch information
kwonoj committed Jul 7, 2022
1 parent 42df149 commit 509e766
Show file tree
Hide file tree
Showing 14 changed files with 30 additions and 97 deletions.
4 changes: 2 additions & 2 deletions crates/swc/src/plugin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ impl RustPlugins {

// Plugin transformation is done. Deserialize transformed bytes back
// into Program
serialized.deserialize().map(|mut v| v.take())
serialized.deserialize().map(|v| v.into_inner())
},
)
}
Expand Down Expand Up @@ -221,7 +221,7 @@ impl RustPlugins {
}
}

serialized.deserialize().map(|mut v| v.take())
serialized.deserialize().map(|v| v.into_inner())
},
)
}
Expand Down
10 changes: 0 additions & 10 deletions crates/swc_common/src/comments.rs
Original file line number Diff line number Diff line change
Expand Up @@ -548,16 +548,6 @@ pub struct Comment {
pub text: String,
}

impl Default for Comment {
fn default() -> Self {
Comment {
kind: CommentKind::Line,
span: DUMMY_SP,
text: Default::default(),
}
}
}

impl Spanned for Comment {
fn span(&self) -> Span {
self.span
Expand Down
13 changes: 0 additions & 13 deletions crates/swc_common/src/errors/diagnostic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,19 +36,6 @@ pub struct Diagnostic {
pub suggestions: Vec<CodeSuggestion>,
}

impl Default for Diagnostic {
fn default() -> Self {
Diagnostic {
level: Level::Bug,
message: vec![],
code: None,
span: MultiSpan::new(),
children: vec![],
suggestions: vec![],
}
}
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(
feature = "diagnostic-serde",
Expand Down
13 changes: 2 additions & 11 deletions crates/swc_common/src/plugin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,6 @@ pub enum PluginError {
Serialize(String),
}

impl Default for PluginError {
fn default() -> Self {
PluginError::Deserialize("Default serialization error".to_string())
}
}

/// Wraps internal representation of serialized data for exchanging data between
/// plugin to the host. Consumers should not rely on specific details of byte
/// format struct contains: it is strict implementation detail which can
Expand Down Expand Up @@ -200,10 +194,7 @@ impl<T> VersionedSerializable<T> {
&self.0 .1
}

pub fn take(&mut self) -> T
where
T: Default,
{
mem::take(&mut self.0 .1)
pub fn into_inner(self) -> T {
self.0 .1
}
}
32 changes: 4 additions & 28 deletions crates/swc_common/src/syntax_pos.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,12 +130,6 @@ pub enum FileName {
Custom(String),
}

impl Default for FileName {
fn default() -> Self {
FileName::Anon
}
}

/// A wrapper that attempts to convert a type to and from UTF-8.
///
/// Types like `OsString` and `PathBuf` aren't guaranteed to be encoded as
Expand Down Expand Up @@ -811,7 +805,7 @@ impl Sub<BytePos> for NonNarrowChar {
derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)
)]
#[cfg_attr(feature = "rkyv", archive_attr(repr(C), derive(bytecheck::CheckBytes)))]
#[derive(Clone, Default)]
#[derive(Clone)]
pub struct SourceFile {
/// The name of the file that the source came from. Source that doesn't
/// originate from files has names between angle brackets by convention,
Expand Down Expand Up @@ -1004,9 +998,7 @@ pub trait Pos {
/// - Values larger than `u32::MAX - 2^16` are reserved for the comments.
///
/// `u32::MAX` is special value used to generate source map entries.
#[derive(
Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug, Serialize, Deserialize, Default,
)]
#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug, Serialize, Deserialize)]
#[serde(transparent)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[cfg_attr(
Expand Down Expand Up @@ -1040,7 +1032,7 @@ impl BytePos {
derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)
)]
#[cfg_attr(feature = "rkyv", archive_attr(repr(C), derive(bytecheck::CheckBytes)))]
#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug, Default)]
#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
pub struct CharPos(pub usize);

// FIXME: Lots of boilerplate in these impls, but so far my attempts to fix
Expand Down Expand Up @@ -1136,7 +1128,7 @@ impl Sub for CharPos {
derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)
)]
#[cfg_attr(feature = "rkyv", archive_attr(repr(C), derive(bytecheck::CheckBytes)))]
#[derive(Debug, Clone, Default)]
#[derive(Debug, Clone)]
pub struct Loc {
/// Information about the original source
pub file: Lrc<SourceFile>,
Expand Down Expand Up @@ -1177,15 +1169,6 @@ pub struct SourceFileAndBytePos {
pub pos: BytePos,
}

impl Default for SourceFileAndBytePos {
fn default() -> Self {
SourceFileAndBytePos {
sf: Lrc::new(SourceFile::default()),
pos: Default::default(),
}
}
}

#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[cfg_attr(
feature = "rkyv",
Expand All @@ -1210,7 +1193,6 @@ pub struct LineCol {
pub col: u32,
}

#[derive(Default)]
#[cfg_attr(
feature = "rkyv",
derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)
Expand Down Expand Up @@ -1242,12 +1224,6 @@ pub enum SpanLinesError {
DistinctSources(DistinctSources),
}

impl Default for SpanLinesError {
fn default() -> Self {
SpanLinesError::IllFormedSpan(DUMMY_SP)
}
}

#[derive(Clone, PartialEq, Eq, Debug)]
pub enum SpanSnippetError {
DummyBytePos,
Expand Down
7 changes: 3 additions & 4 deletions crates/swc_common/src/syntax_pos/hygiene.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,6 @@ struct MarkData {
is_builtin: bool,
}

#[derive(Default)]
#[cfg_attr(
feature = "rkyv",
derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)
Expand Down Expand Up @@ -199,7 +198,7 @@ impl Mark {
len.try_into().expect("Should able to convert ptr length"),
)
.expect("Should able to deserialize")
.take()
.into_inner()
};
self = Mark::from_u32(context.0);

Expand Down Expand Up @@ -238,7 +237,7 @@ impl Mark {
len.try_into().expect("Should able to convert ptr length"),
)
.expect("Should able to deserialize")
.take()
.into_inner()
};
a = Mark::from_u32(context.0);
b = Mark::from_u32(context.1);
Expand Down Expand Up @@ -403,7 +402,7 @@ impl SyntaxContext {
len.try_into().expect("Should able to convert ptr length"),
)
.expect("Should able to deserialize")
.take()
.into_inner()
};

*self = SyntaxContext(context.0);
Expand Down
6 changes: 0 additions & 6 deletions crates/swc_ecma_ast/src/module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,6 @@ pub enum Program {
Script(Script),
}

impl Default for Program {
fn default() -> Self {
Program::Module(Module::dummy())
}
}

#[ast_node("Module")]
#[derive(Eq, Hash, EqIgnoreSpan)]
pub struct Module {
Expand Down
6 changes: 3 additions & 3 deletions crates/swc_plugin_macro/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,14 +62,14 @@ fn handle_func(func: ItemFn) -> TokenStream {
pub fn #process_impl_ident(ast_ptr: *const u8, ast_ptr_len: i32, config_str_ptr: *const u8, config_str_ptr_len: i32, context_str_ptr: *const u8, context_str_ptr_len: i32, should_enable_comments_proxy: i32) -> i32 {
// Reconstruct `Program` & config string from serialized program
// Host (SWC) should allocate memory, copy bytes and pass ptr to plugin.
let program = unsafe { swc_plugin::deserialize_from_ptr(ast_ptr, ast_ptr_len).map(|mut v| v.take()) };
let program = unsafe { swc_plugin::deserialize_from_ptr(ast_ptr, ast_ptr_len).map(|v| v.into_inner()) };
if program.is_err() {
let err = swc_plugin::PluginError::Deserialize("Failed to deserialize program received from host".to_string());
return construct_error_ptr(err);
}
let program: Program = program.expect("Should be a program");

let config = unsafe { swc_plugin::deserialize_from_ptr(config_str_ptr, config_str_ptr_len).map(|mut v| v.take()) };
let config = unsafe { swc_plugin::deserialize_from_ptr(config_str_ptr, config_str_ptr_len).map(|v| v.into_inner()) };
if config.is_err() {
let err = swc_plugin::PluginError::Deserialize(
"Failed to deserialize config string received from host".to_string()
Expand All @@ -78,7 +78,7 @@ fn handle_func(func: ItemFn) -> TokenStream {
}
let config: String = config.expect("Should be a string");

let context = unsafe { swc_plugin::deserialize_from_ptr(context_str_ptr, context_str_ptr_len).map(|mut v| v.take()) };
let context = unsafe { swc_plugin::deserialize_from_ptr(context_str_ptr, context_str_ptr_len).map(|v| v.into_inner()) };
if context.is_err() {
let err = swc_plugin::PluginError::Deserialize("Failed to deserialize context string received from host".to_string());
return construct_error_ptr(err);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use swc_common::plugin::{
};

/// A struct to exchange allocated data between memory spaces.
#[derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Default)]
#[derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
#[archive_attr(repr(C), derive(bytecheck::CheckBytes))]
pub struct AllocatedBytesPtr(pub i32, pub i32);

Expand Down Expand Up @@ -51,7 +51,7 @@ where
.expect("Should able to convert ptr length"),
)
.expect("Should able to deserialize AllocatedBytesPtr")
.take()
.into_inner()
})
}

Expand All @@ -62,7 +62,7 @@ where
pub fn read_returned_result_from_host<F, R>(f: F) -> Option<R>
where
F: FnOnce(i32) -> i32,
R: rkyv::Archive + std::default::Default,
R: rkyv::Archive,
R::Archived: rkyv::Deserialize<R, rkyv::de::deserializers::SharedDeserializeMap>,
{
let allocated_returned_value_ptr = read_returned_result_from_host_inner(f);
Expand All @@ -74,7 +74,7 @@ where
allocated_returned_value_ptr.1,
)
.expect("Returned value should be serializable")
.take()
.into_inner()
})
}

Expand All @@ -88,7 +88,7 @@ where
pub fn read_returned_result_from_host_fallible<F, R>(f: F) -> Option<R>
where
F: FnOnce(i32) -> i32,
R: rkyv::Archive + std::default::Default,
R: rkyv::Archive,
R::Archived: rkyv::Deserialize<R, rkyv::de::deserializers::SharedDeserializeMap>,
{
// Allocate AllocatedBytesPtr to get return value from the host
Expand Down Expand Up @@ -118,7 +118,7 @@ where
serialized_allocated_bytes_raw_ptr_size as i32,
)
.expect("Should able to deserialize AllocatedBytesPtr")
.take()
.into_inner()
};

// Using AllocatedBytesPtr's value, reconstruct actual return value
Expand All @@ -128,6 +128,6 @@ where
allocated_returned_value_ptr.1,
)
.expect("Returned value should be serializable")
.take()
.into_inner()
})
}
Original file line number Diff line number Diff line change
Expand Up @@ -175,15 +175,11 @@ impl SourceMapper for PluginSourceMapProxy {

fn span_to_lines(&self, sp: Span) -> FileLinesResult {
#[cfg(target_arch = "wasm32")]
todo!(
"Need to implement way to take Result<T> from read_returned_result_from_host_fallible"
);
/*
return read_returned_result_from_host_fallible(|serialized_ptr| unsafe {
__span_to_lines_proxy(sp.lo.0, sp.hi.0, sp.ctxt.as_u32(), serialized_ptr)
})
.expect("Host should return FileLinesResult");
*/

#[cfg(not(target_arch = "wasm32"))]
unimplemented!("Sourcemap proxy cannot be called in this context")
}
Expand Down
8 changes: 4 additions & 4 deletions crates/swc_plugin_runner/src/imported_fn/comments.rs
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ pub fn add_leading_comment_proxy(env: &CommentHostEnvironment, byte_pos: u32) {
serialized
.deserialize()
.expect("Should be able to deserialize")
.take(),
.into_inner(),
);
});
}
Expand All @@ -137,7 +137,7 @@ pub fn add_leading_comments_proxy(env: &CommentHostEnvironment, byte_pos: u32) {
serialized
.deserialize()
.expect("Should be able to deserialize")
.take(),
.into_inner(),
);
});
}
Expand Down Expand Up @@ -224,7 +224,7 @@ pub fn add_trailing_comment_proxy(env: &CommentHostEnvironment, byte_pos: u32) {
serialized
.deserialize()
.expect("Should be able to deserialize")
.take(),
.into_inner(),
);
});
}
Expand All @@ -236,7 +236,7 @@ pub fn add_trailing_comments_proxy(env: &CommentHostEnvironment, byte_pos: u32)
serialized
.deserialize()
.expect("Should be able to deserialize")
.take(),
.into_inner(),
);
});
}
Expand Down
2 changes: 1 addition & 1 deletion crates/swc_plugin_runner/src/imported_fn/handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ pub fn emit_diagnostics(env: &BaseHostEnvironment, bytes_ptr: i32, bytes_ptr_len
let serialized = PluginSerializedBytes::from_slice(&diagnostics_bytes[..]);
let diagnostic = PluginSerializedBytes::deserialize::<Diagnostic>(&serialized)
.expect("Should able to be deserialized into diagnostic")
.take();
.into_inner();

let mut builder =
swc_common::errors::DiagnosticBuilder::new_diagnostic(handler, diagnostic);
Expand Down
2 changes: 1 addition & 1 deletion crates/swc_plugin_runner/src/transform_executor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ impl TransformExecutor {
if returned_ptr_result == 0 {
Ok(ret)
} else {
let err: PluginError = ret.deserialize()?.take();
let err: PluginError = ret.deserialize()?.into_inner();
match err {
PluginError::SizeInteropFailure(msg) => Err(anyhow!(
"Failed to convert pointer size to calculate: {}",
Expand Down
4 changes: 2 additions & 2 deletions crates/swc_plugin_runner/tests/integration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ fn internal() -> Result<(), Error> {
let program: Program = program_bytes
.deserialize()
.expect("Should able to deserialize")
.take();
.into_inner();
let mut visitor = TestVisitor {
plugin_transform_found: false,
};
Expand Down Expand Up @@ -226,7 +226,7 @@ fn internal() -> Result<(), Error> {
let program: Program = serialized_program
.deserialize()
.expect("Should able to deserialize")
.take();
.into_inner();
let mut visitor = TestVisitor {
plugin_transform_found: false,
};
Expand Down

0 comments on commit 509e766

Please sign in to comment.