file_path stringlengths 3 280 | file_language stringclasses 66 values | content stringlengths 1 1.04M | repo_name stringlengths 5 92 | repo_stars int64 0 154k | repo_description stringlengths 0 402 | repo_primary_language stringclasses 108 values | developer_username stringlengths 1 25 | developer_name stringlengths 0 30 | developer_company stringlengths 0 82 |
|---|---|---|---|---|---|---|---|---|---|
crates/swc_plugin_proxy/src/comments/plugin_comments_proxy.rs | Rust | #[cfg(feature = "__plugin_mode")]
use swc_common::{
comments::{Comment, Comments},
BytePos,
};
#[cfg(feature = "__plugin_mode")]
use swc_trace_macro::swc_trace;
#[cfg(all(feature = "__rkyv", feature = "__plugin_mode", target_arch = "wasm32"))]
use crate::memory_interop::read_returned_result_from_host;
#[cfg(target_arch = "wasm32")]
extern "C" {
fn __copy_comment_to_host_env(bytes_ptr: u32, bytes_ptr_len: u32);
fn __add_leading_comment_proxy(byte_pos: u32);
fn __add_leading_comments_proxy(byte_pos: u32);
fn __has_leading_comments_proxy(byte_pos: u32) -> u32;
fn __move_leading_comments_proxy(from_byte_pos: u32, to_byte_pos: u32);
fn __take_leading_comments_proxy(byte_pos: u32, allocated_ret_ptr: u32) -> u32;
fn __get_leading_comments_proxy(byte_pos: u32, allocated_ret_ptr: u32) -> u32;
fn __add_trailing_comment_proxy(byte_pos: u32);
fn __add_trailing_comments_proxy(byte_pos: u32);
fn __has_trailing_comments_proxy(byte_pos: u32) -> u32;
fn __move_trailing_comments_proxy(from_byte_pos: u32, to_byte_pos: u32);
fn __take_trailing_comments_proxy(byte_pos: u32, allocated_ret_ptr: u32) -> u32;
fn __get_trailing_comments_proxy(byte_pos: u32, allocated_ret_ptr: u32) -> u32;
fn __add_pure_comment_proxy(byte_pos: u32);
}
/// A struct implements `swc_common::comments::Comments` for the plugin.
/// This is a proxy to the host's comments reference while plugin transform
/// runs, does not contain actual data but lazily requests to the host for each
/// interfaces.
///
/// This _does not_ derives serialization / deserialization for the
/// Serialized::de/serialize interface. Instead, swc_plugin_macro injects an
/// instance in plugin's runtime directly.
#[cfg(feature = "__plugin_mode")]
#[derive(Debug, Copy, Clone)]
pub struct PluginCommentsProxy;
#[cfg(feature = "__plugin_mode")]
#[swc_trace]
impl PluginCommentsProxy {
/// Copy guest memory's struct into host via CommentHostEnvironment's
/// comment_buffer as serialized to pass param from guest to the host for
/// the fn like add_leading*.
#[cfg_attr(not(target_arch = "wasm32"), allow(unused))]
fn allocate_comments_buffer_to_host<T>(&self, value: T)
where
T: for<'a> rkyv::Serialize<
rancor::Strategy<
rkyv::ser::Serializer<
rkyv::util::AlignedVec,
rkyv::ser::allocator::ArenaHandle<'a>,
rkyv::ser::sharing::Share,
>,
rancor::Error,
>,
>,
{
#[cfg(target_arch = "wasm32")]
{
let serialized = swc_common::plugin::serialized::PluginSerializedBytes::try_serialize(
&swc_common::plugin::serialized::VersionedSerializable::new(value),
)
.expect("Should able to serialize value");
let (serialized_comment_ptr, serialized_comment_ptr_len) = serialized.as_ptr();
unsafe {
// We need to copy PluginCommentProxy's param for add_leading (Comment, or
// Vec<Comment>) to the host, before calling proxy to the host. This'll fill in
// CommentHostEnvironment's buffer, subsequent proxy call will read &
// deserialize it.
__copy_comment_to_host_env(
serialized_comment_ptr as u32,
serialized_comment_ptr_len
.try_into()
.expect("Should able to convert ptr length"),
);
}
}
}
}
#[cfg(all(feature = "__plugin_mode", not(target_arch = "wasm32")))]
#[swc_trace]
impl Comments for PluginCommentsProxy {
fn add_leading(&self, pos: BytePos, cmt: Comment) {
swc_common::comments::COMMENTS.with(|c| {
c.add_leading(pos, cmt);
});
}
fn add_leading_comments(&self, pos: BytePos, comments: Vec<Comment>) {
swc_common::comments::COMMENTS.with(|c| {
c.add_leading_comments(pos, comments);
});
}
fn has_leading(&self, pos: BytePos) -> bool {
swc_common::comments::COMMENTS.with(|c| c.has_leading(pos))
}
fn move_leading(&self, from: BytePos, to: BytePos) {
swc_common::comments::COMMENTS.with(|c| {
c.move_leading(from, to);
});
}
fn take_leading(&self, pos: BytePos) -> Option<Vec<Comment>> {
swc_common::comments::COMMENTS.with(|c| c.take_leading(pos))
}
fn get_leading(&self, pos: BytePos) -> Option<Vec<Comment>> {
swc_common::comments::COMMENTS.with(|c| c.get_leading(pos))
}
fn add_trailing(&self, pos: BytePos, cmt: Comment) {
swc_common::comments::COMMENTS.with(|c| {
c.add_trailing(pos, cmt);
});
}
fn add_trailing_comments(&self, pos: BytePos, comments: Vec<Comment>) {
swc_common::comments::COMMENTS.with(|c| {
c.add_trailing_comments(pos, comments);
});
}
fn has_trailing(&self, pos: BytePos) -> bool {
swc_common::comments::COMMENTS.with(|c| c.has_trailing(pos))
}
fn move_trailing(&self, from: BytePos, to: BytePos) {
swc_common::comments::COMMENTS.with(|c| {
c.move_trailing(from, to);
});
}
fn take_trailing(&self, pos: BytePos) -> Option<Vec<Comment>> {
swc_common::comments::COMMENTS.with(|c| c.take_trailing(pos))
}
fn get_trailing(&self, pos: BytePos) -> Option<Vec<Comment>> {
swc_common::comments::COMMENTS.with(|c| c.get_trailing(pos))
}
fn add_pure_comment(&self, pos: BytePos) {
swc_common::comments::COMMENTS.with(|c| {
c.add_pure_comment(pos);
});
}
}
#[cfg(all(feature = "__plugin_mode", target_arch = "wasm32"))]
#[cfg_attr(not(target_arch = "wasm32"), allow(unused))]
#[swc_trace]
impl Comments for PluginCommentsProxy {
fn add_leading(&self, pos: BytePos, cmt: Comment) {
self.allocate_comments_buffer_to_host(cmt);
#[cfg(target_arch = "wasm32")]
unsafe {
__add_leading_comment_proxy(pos.0);
}
}
fn add_leading_comments(&self, pos: BytePos, comments: Vec<Comment>) {
self.allocate_comments_buffer_to_host(comments);
#[cfg(target_arch = "wasm32")]
unsafe {
__add_leading_comments_proxy(pos.0);
}
}
fn has_leading(&self, pos: BytePos) -> bool {
#[cfg(target_arch = "wasm32")]
{
if unsafe { __has_leading_comments_proxy(pos.0) } == 0 {
false
} else {
true
}
}
#[cfg(not(target_arch = "wasm32"))]
false
}
fn move_leading(&self, from: BytePos, to: BytePos) {
#[cfg(target_arch = "wasm32")]
unsafe {
__move_leading_comments_proxy(from.0, to.0)
}
}
fn take_leading(&self, pos: BytePos) -> Option<Vec<Comment>> {
#[cfg(target_arch = "wasm32")]
return read_returned_result_from_host(|serialized_ptr| unsafe {
__take_leading_comments_proxy(pos.0, serialized_ptr)
});
#[cfg(not(target_arch = "wasm32"))]
None
}
fn get_leading(&self, pos: BytePos) -> Option<Vec<Comment>> {
#[cfg(target_arch = "wasm32")]
return read_returned_result_from_host(|serialized_ptr| unsafe {
__get_leading_comments_proxy(pos.0, serialized_ptr)
});
#[cfg(not(target_arch = "wasm32"))]
None
}
fn add_trailing(&self, pos: BytePos, cmt: Comment) {
self.allocate_comments_buffer_to_host(cmt);
#[cfg(target_arch = "wasm32")]
unsafe {
__add_trailing_comment_proxy(pos.0);
}
}
fn add_trailing_comments(&self, pos: BytePos, comments: Vec<Comment>) {
self.allocate_comments_buffer_to_host(comments);
#[cfg(target_arch = "wasm32")]
unsafe {
__add_trailing_comments_proxy(pos.0);
}
}
fn has_trailing(&self, pos: BytePos) -> bool {
#[cfg(target_arch = "wasm32")]
{
if unsafe { __has_trailing_comments_proxy(pos.0) } == 0 {
false
} else {
true
}
}
#[cfg(not(target_arch = "wasm32"))]
false
}
fn move_trailing(&self, from: BytePos, to: BytePos) {
#[cfg(target_arch = "wasm32")]
unsafe {
__move_trailing_comments_proxy(from.0, to.0)
}
}
fn take_trailing(&self, pos: BytePos) -> Option<Vec<Comment>> {
#[cfg(target_arch = "wasm32")]
return read_returned_result_from_host(|serialized_ptr| unsafe {
__take_trailing_comments_proxy(pos.0, serialized_ptr)
});
#[cfg(not(target_arch = "wasm32"))]
None
}
fn get_trailing(&self, pos: BytePos) -> Option<Vec<Comment>> {
#[cfg(target_arch = "wasm32")]
return read_returned_result_from_host(|serialized_ptr| unsafe {
__get_trailing_comments_proxy(pos.0, serialized_ptr)
});
#[cfg(not(target_arch = "wasm32"))]
None
}
fn add_pure_comment(&self, pos: BytePos) {
#[cfg(target_arch = "wasm32")]
{
unsafe {
__add_pure_comment_proxy(pos.0);
}
}
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_plugin_proxy/src/lib.rs | Rust | #![cfg_attr(not(feature = "__rkyv"), allow(warnings))]
mod comments;
mod memory_interop;
mod metadata;
mod source_map;
#[cfg(feature = "__plugin_mode")]
pub use comments::PluginCommentsProxy;
#[cfg(feature = "__plugin_rt")]
pub use comments::{HostCommentsStorage, COMMENTS};
pub use memory_interop::AllocatedBytesPtr;
#[cfg(feature = "__plugin_mode")]
pub use metadata::TransformPluginProgramMetadata;
#[cfg(feature = "__plugin_mode")]
pub use source_map::PluginSourceMapProxy;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_plugin_proxy/src/memory_interop/mod.rs | Rust | mod read_returned_result_from_host;
#[cfg(all(feature = "__rkyv", feature = "__plugin_mode", target_arch = "wasm32"))]
pub(crate) use read_returned_result_from_host::read_returned_result_from_host;
pub use read_returned_result_from_host::AllocatedBytesPtr;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_plugin_proxy/src/memory_interop/read_returned_result_from_host.rs | Rust | #[cfg_attr(not(target_arch = "wasm32"), allow(unused))]
#[cfg(any(feature = "__plugin_rt", feature = "__plugin_mode"))]
use swc_common::plugin::serialized::PluginSerializedBytes;
/// A struct to exchange allocated data between memory spaces.
#[cfg_attr(
feature = "__rkyv",
derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)
)]
#[cfg_attr(feature = "__rkyv", repr(C))]
pub struct AllocatedBytesPtr(pub u32, pub u32);
#[cfg(target_arch = "wasm32")]
extern "C" {
fn __free(ptr: *mut u8, size: i32) -> i32;
}
#[cfg(target_arch = "wasm32")]
impl Drop for AllocatedBytesPtr {
fn drop(&mut self) {
unsafe {
__free(self.0 as _, self.1 as _);
}
}
}
#[cfg(not(feature = "__rkyv"))]
fn read_returned_result_from_host_inner<F>(f: F) -> Option<AllocatedBytesPtr> {
unimplemented!("Plugin proxy does not work without serialization support")
}
/// Performs an interop while calling host fn to get non-determined size return
/// values from the host. This is based on the contract between host's imported
/// fn, by imported fn allocated memory for the guest space then hand over its
/// ptr and length via a struct. Refer plugin_runner/imported_fn/mod.rs for the
/// detail.
///
/// Returns a struct AllocatedBytesPtr to the ptr for actual return value if
/// host fn allocated return value, None otherwise.
#[cfg(all(feature = "__rkyv", feature = "__plugin_mode", target_arch = "wasm32"))]
#[tracing::instrument(level = "info", skip_all)]
fn read_returned_result_from_host_inner<F>(f: F) -> Option<AllocatedBytesPtr>
where
F: FnOnce(u32) -> u32,
{
// Allocate AllocatedBytesPtr to get return value from the host
let allocated_bytes_ptr =
swc_common::plugin::serialized::VersionedSerializable::new(AllocatedBytesPtr(0, 0));
let serialized_allocated_bytes_ptr = PluginSerializedBytes::try_serialize(&allocated_bytes_ptr)
.expect("Should able to serialize AllocatedBytesPtr");
let (serialized_allocated_bytes_raw_ptr, serialized_allocated_bytes_raw_ptr_size) =
serialized_allocated_bytes_ptr.as_ptr();
std::mem::forget(allocated_bytes_ptr); // We should not drop AllocatedBytesPtr(0, 0)
let ret = f(serialized_allocated_bytes_raw_ptr as _);
// Host fn call completes: by contract in host proxy, if return value is 0
// we know there's no value to read. Otherwise, we know host filled in
// AllocatedBytesPtr to the pointer for the actual value for the
// results.
if ret == 0 {
return None;
}
// Return reconstructted AllocatedBytesPtr to reveal ptr to the allocated bytes
Some(
PluginSerializedBytes::from_raw_ptr(
serialized_allocated_bytes_raw_ptr,
serialized_allocated_bytes_raw_ptr_size
.try_into()
.expect("Should able to convert ptr length"),
)
.deserialize()
.expect("Should able to deserialize AllocatedBytesPtr")
.into_inner(),
)
}
#[cfg(not(feature = "__rkyv"))]
pub fn read_returned_result_from_host<F, R>(f: F) -> Option<R> {
unimplemented!("Plugin proxy does not work without serialization support")
}
/// Performs deserialization to the actual return value type from returned ptr.
///
/// This fn is for the Infallible types works for most of the cases.
#[cfg(all(feature = "__rkyv", feature = "__plugin_mode", target_arch = "wasm32"))]
#[cfg_attr(not(target_arch = "wasm32"), allow(unused))]
#[tracing::instrument(level = "info", skip_all)]
pub fn read_returned_result_from_host<F, R>(f: F) -> Option<R>
where
F: FnOnce(u32) -> u32,
R: rkyv::Archive,
R::Archived: rkyv::Deserialize<R, rancor::Strategy<rkyv::de::Pool, rancor::Error>>,
for<'a> R::Archived: bytecheck::CheckBytes<
rancor::Strategy<
rkyv::validation::Validator<
rkyv::validation::archive::ArchiveValidator<'a>,
rkyv::validation::shared::SharedValidator,
>,
rancor::Error,
>,
>,
{
let allocated_returned_value_ptr = read_returned_result_from_host_inner(f);
// Using AllocatedBytesPtr's value, reconstruct actual return value
allocated_returned_value_ptr.map(|allocated_returned_value_ptr| {
PluginSerializedBytes::from_raw_ptr(
allocated_returned_value_ptr.0 as _,
allocated_returned_value_ptr
.1
.try_into()
.expect("Should able to convert ptr length"),
)
.deserialize()
.expect("Returned value should be serializable")
.into_inner()
})
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_plugin_proxy/src/metadata/mod.rs | Rust | mod transform_plugin_metadata;
#[cfg(feature = "__plugin_mode")]
pub use transform_plugin_metadata::TransformPluginProgramMetadata;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_plugin_proxy/src/metadata/transform_plugin_metadata.rs | Rust | #[cfg(feature = "__plugin_mode")]
use swc_common::Mark;
#[cfg(feature = "__plugin_mode")]
use swc_trace_macro::swc_trace;
#[cfg(all(feature = "__rkyv", feature = "__plugin_mode", target_arch = "wasm32"))]
use crate::memory_interop::read_returned_result_from_host;
#[cfg(feature = "__plugin_mode")]
#[cfg_attr(not(target_arch = "wasm32"), allow(unused))]
use crate::{PluginCommentsProxy, PluginSourceMapProxy};
/// An arbitary metadata for given Program to run transform in plugin.
/// These are not directly attached to Program's AST structures
/// but required for certain transforms.
#[cfg(feature = "__plugin_mode")]
#[derive(Debug)]
pub struct TransformPluginProgramMetadata {
/// Proxy to the comments for the Program passed into plugin.
/// This is a proxy to the actual data lives in the host. Only when plugin
/// attempts to read these it'll ask to the host to get values.
pub comments: Option<PluginCommentsProxy>,
/// Proxy to the sourceMap for the Program passed into plugin.
/// This is a proxy to the actual data lives in the host. Only when plugin
/// attempts to read these it'll ask to the host to get values.
pub source_map: PluginSourceMapProxy,
pub unresolved_mark: Mark,
}
#[cfg(target_arch = "wasm32")] // Allow testing
extern "C" {
fn __copy_context_key_to_host_env(bytes_ptr: u32, bytes_ptr_len: u32);
fn __get_transform_plugin_config(allocated_ret_ptr: u32) -> u32;
fn __get_transform_context(key: u32, allocated_ret_ptr: u32) -> i32;
fn __get_experimental_transform_context(allocated_ret_ptr: u32) -> u32;
fn __get_raw_experiemtal_transform_context(allocated_ret_ptr: u32) -> u32;
}
#[cfg(feature = "__plugin_mode")]
#[swc_trace]
impl TransformPluginProgramMetadata {
/// Returns current plugin's configuration as a JSON string.
/// Plugin may need to deserialize this string manually.
pub fn get_transform_plugin_config(&self) -> Option<String> {
#[cfg(target_arch = "wasm32")]
return read_returned_result_from_host(|serialized_ptr| unsafe {
__get_transform_plugin_config(serialized_ptr)
});
#[cfg(not(target_arch = "wasm32"))]
None
}
/// Returns metadata value for given key.
#[cfg_attr(not(target_arch = "wasm32"), allow(unused))]
pub fn get_context(
&self,
key: &swc_common::plugin::metadata::TransformPluginMetadataContextKind,
) -> Option<String> {
#[cfg(target_arch = "wasm32")]
return read_returned_result_from_host(|serialized_ptr| unsafe {
__get_transform_context(*key as u32, serialized_ptr) as u32
});
#[cfg(not(target_arch = "wasm32"))]
None
}
/// Returns an experimental metadata value if exists. Returned value is
/// always a String, but depends on the nature of the metadata it may
/// require additional postprocessing.
///
/// Each time this is called, it'll require a call between host-plugin which
/// involves serialization / deserialization.
///
/// Note these metadata values can be changed anytime. There is no gaurantee
/// values will be available across different @swc/core versions.
#[cfg_attr(not(target_arch = "wasm32"), allow(unused))]
pub fn get_experimental_context(&self, key: &str) -> Option<String> {
#[cfg(target_arch = "wasm32")]
return read_returned_result_from_host(|serialized_ptr| unsafe {
let serialized = swc_common::plugin::serialized::PluginSerializedBytes::try_serialize(
&swc_common::plugin::serialized::VersionedSerializable::new(key.to_string()),
)
.expect("Should be serializable");
let (key_ptr, key_ptr_len) = serialized.as_ptr();
__copy_context_key_to_host_env(key_ptr as u32, key_ptr_len as u32);
__get_experimental_transform_context(serialized_ptr)
});
#[cfg(not(target_arch = "wasm32"))]
None
}
/// Returns experimental metadata context, but returns whole value as a
/// HashMap.
///
/// Each time this is called, it'll require a call between host-plugin which
/// involves serialization / deserialization.
#[allow(unreachable_code)]
pub fn get_raw_experimental_context(&self) -> rustc_hash::FxHashMap<String, String> {
// TODO: There is no clear usecase yet - enable when we have a correct usecase.
unimplemented!("Not supported yet");
#[cfg(target_arch = "wasm32")]
return read_returned_result_from_host(|serialized_ptr| unsafe {
__get_raw_experiemtal_transform_context(serialized_ptr)
})
.expect("Raw experimental metadata should exists, even if it's empty map");
#[cfg(not(target_arch = "wasm32"))]
rustc_hash::FxHashMap::default()
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_plugin_proxy/src/source_map/mod.rs | Rust | mod plugin_source_map_proxy;
#[cfg(feature = "__plugin_mode")]
pub use plugin_source_map_proxy::PluginSourceMapProxy;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_plugin_proxy/src/source_map/plugin_source_map_proxy.rs | Rust | #![allow(unused_imports)]
#![allow(unused_variables)]
#[cfg(feature = "__plugin_mode")]
use swc_common::{
source_map::{
DistinctSources, FileLinesResult, MalformedSourceMapPositions, PartialFileLinesResult,
PartialLoc, SmallPos, SpanSnippetError,
},
sync::Lrc,
BytePos, FileName, Loc, SourceFileAndBytePos, SourceMapper, Span,
};
use swc_common::{sync::OnceCell, CharPos, FileLines, SourceFile};
#[cfg(feature = "__plugin_mode")]
use swc_ecma_ast::SourceMapperExt;
use swc_trace_macro::swc_trace;
#[cfg(all(feature = "__rkyv", feature = "__plugin_mode", target_arch = "wasm32"))]
use crate::memory_interop::read_returned_result_from_host;
#[cfg(target_arch = "wasm32")]
extern "C" {
fn __lookup_char_pos_source_map_proxy(
byte_pos: u32,
should_include_source_file: i32,
allocated_ret_ptr: u32,
) -> u32;
fn __doctest_offset_line_proxy(orig: u32) -> u32;
fn __merge_spans_proxy(
lhs_lo: u32,
lhs_hi: u32,
rhs_lo: u32,
rhs_hi: u32,
allocated_ptr: u32,
) -> u32;
fn __span_to_string_proxy(span_lo: u32, span_hi: u32, allocated_ret_ptr: u32) -> u32;
fn __span_to_filename_proxy(span_lo: u32, span_hi: u32, allocated_ret_ptr: u32) -> u32;
fn __span_to_source_proxy(span_lo: u32, span_hi: u32, allocated_ret_ptr: u32) -> u32;
fn __span_to_lines_proxy(
span_lo: u32,
span_hi: u32,
should_request_source_file: i32,
allocated_ret_ptr: u32,
) -> u32;
fn __lookup_byte_offset_proxy(byte_pos: u32, allocated_ret_ptr: u32) -> u32;
}
#[cfg(feature = "__plugin_mode")]
#[derive(Debug, Clone)]
pub struct PluginSourceMapProxy {
// Sharable instance to `SourceFile` per plugin transform.
// Since each plugin's lifecycle is tied to single `transform`,
// We know this'll be the same across subsequent request for lookup_char_*.
pub source_file: OnceCell<swc_common::sync::Lrc<SourceFile>>,
}
#[cfg(all(feature = "__rkyv", feature = "__plugin_mode", target_arch = "wasm32"))]
#[swc_trace]
impl PluginSourceMapProxy {
pub fn span_to_source<F, Ret>(
&self,
sp: Span,
extract_source: F,
) -> Result<Ret, Box<SpanSnippetError>>
where
F: FnOnce(&str, usize, usize) -> Ret,
{
#[cfg(target_arch = "wasm32")]
{
let src: Result<String, Box<SpanSnippetError>> =
read_returned_result_from_host(|serialized_ptr| unsafe {
__span_to_source_proxy(sp.lo.0, sp.hi.0, serialized_ptr)
})
.expect("Host should return source code");
let src = src?;
return Ok(extract_source(&src, 0, src.len()));
}
#[cfg(not(target_arch = "wasm32"))]
unimplemented!("Sourcemap proxy cannot be called in this context")
}
}
/// Subset of SourceMap interface supported in plugin.
/// Unlike `Comments`, this does not fully implement `SourceMap`.
#[cfg(feature = "__plugin_mode")]
impl SourceMapper for PluginSourceMapProxy {
#[cfg_attr(not(target_arch = "wasm32"), allow(unused))]
fn lookup_char_pos(&self, pos: BytePos) -> Loc {
#[cfg(target_arch = "wasm32")]
{
let should_request_source_file = if self.source_file.get().is_none() {
1
} else {
0
};
let partial_loc: PartialLoc = read_returned_result_from_host(|serialized_ptr| unsafe {
__lookup_char_pos_source_map_proxy(
pos.0,
should_request_source_file,
serialized_ptr,
)
})
.expect("Host should return PartialLoc");
if self.source_file.get().is_none() {
if let Some(source_file) = partial_loc.source_file {
self.source_file
.set(source_file)
.expect("Should able to set source file");
}
}
return Loc {
file: self
.source_file
.get()
.expect("SourceFile should exist")
.clone(),
line: partial_loc.line,
col: CharPos(partial_loc.col),
col_display: partial_loc.col_display,
};
}
#[cfg(not(target_arch = "wasm32"))]
unimplemented!("Sourcemap proxy cannot be called in this context")
}
fn span_to_lines(&self, sp: Span) -> FileLinesResult {
#[cfg(target_arch = "wasm32")]
{
let should_request_source_file = if self.source_file.get().is_none() {
1
} else {
0
};
let partial_files: PartialFileLinesResult =
read_returned_result_from_host(|serialized_ptr| unsafe {
__span_to_lines_proxy(
sp.lo.0,
sp.hi.0,
should_request_source_file,
serialized_ptr,
)
})
.expect("Host should return PartialFileLinesResult");
if self.source_file.get().is_none() {
if let Ok(p) = &partial_files {
if let Some(source_file) = &p.file {
self.source_file
.set(source_file.clone())
.expect("Should able to set source file");
}
}
}
return partial_files.map(|files| FileLines {
file: self
.source_file
.get()
.expect("SourceFile should exist")
.clone(),
lines: files.lines,
});
}
#[cfg(not(target_arch = "wasm32"))]
unimplemented!("Sourcemap proxy cannot be called in this context")
}
fn span_to_string(&self, sp: Span) -> String {
#[cfg(target_arch = "wasm32")]
return read_returned_result_from_host(|serialized_ptr| unsafe {
__span_to_string_proxy(sp.lo.0, sp.hi.0, serialized_ptr)
})
.expect("Host should return String");
#[cfg(not(target_arch = "wasm32"))]
unimplemented!("Sourcemap proxy cannot be called in this context")
}
fn span_to_filename(&self, sp: Span) -> Lrc<FileName> {
#[cfg(target_arch = "wasm32")]
return Lrc::new(
read_returned_result_from_host(|serialized_ptr| unsafe {
__span_to_filename_proxy(sp.lo.0, sp.hi.0, serialized_ptr)
})
.expect("Host should return Filename"),
);
#[cfg(not(target_arch = "wasm32"))]
unimplemented!("Sourcemap proxy cannot be called in this context")
}
fn span_to_snippet(&self, sp: Span) -> Result<String, Box<SpanSnippetError>> {
#[cfg(target_arch = "wasm32")]
return self.span_to_source(sp, |src, start_index, end_index| {
src[start_index..end_index].to_string()
});
#[cfg(not(target_arch = "wasm32"))]
unimplemented!("Sourcemap proxy cannot be called in this context")
}
fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option<Span> {
#[cfg(target_arch = "wasm32")]
unsafe {
// We need to `allocate` memory, force creates empty span instead of DUMMY_SP
let span = Span {
lo: BytePos(0),
hi: BytePos(0),
};
let serialized = swc_common::plugin::serialized::PluginSerializedBytes::try_serialize(
&swc_common::plugin::serialized::VersionedSerializable::new(span),
)
.expect("Should be serializable");
let (ptr, len) = serialized.as_ptr();
let ret =
__merge_spans_proxy(sp_lhs.lo.0, sp_lhs.hi.0, sp_rhs.lo.0, sp_rhs.hi.0, ptr as _);
return if ret == 1 { Some(span) } else { None };
};
#[cfg(not(target_arch = "wasm32"))]
unimplemented!("Sourcemap proxy cannot be called in this context")
}
fn call_span_if_macro(&self, sp: Span) -> Span {
// This mimics host's behavior
// https://github.com/swc-project/swc/blob/f7dc3fff1f03c9b7cee27ef760dc11bc96083f60/crates/swc_common/src/source_map.rs#L1283-L1285=
sp
}
fn doctest_offset_line(&self, line: usize) -> usize {
#[cfg(target_arch = "wasm32")]
unsafe {
return __doctest_offset_line_proxy(line as u32) as usize;
};
#[cfg(not(target_arch = "wasm32"))]
unimplemented!("Sourcemap proxy cannot be called in this context")
}
}
#[cfg(feature = "__plugin_mode")]
impl SourceMapperExt for PluginSourceMapProxy {
fn get_code_map(&self) -> &dyn SourceMapper {
self
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_plugin_runner/benches/ecma_invoke.rs | Rust | #![cfg_attr(not(feature = "__rkyv"), allow(warnings))]
extern crate swc_malloc;
use std::{
env,
path::{Path, PathBuf},
process::Command,
sync::Arc,
};
use codspeed_criterion_compat::{black_box, criterion_group, criterion_main, Bencher, Criterion};
#[cfg(feature = "__rkyv")]
use swc_common::plugin::serialized::{PluginSerializedBytes, VersionedSerializable};
use swc_common::{
plugin::metadata::TransformPluginMetadataContext, FileName, FilePathMapping, Globals, Mark,
SourceMap, GLOBALS,
};
use swc_ecma_ast::EsVersion;
use swc_ecma_parser::parse_file_as_program;
static SOURCE: &str = include_str!("../../swc_ecma_minifier/benches/full/typescript.js");
fn plugin_group(c: &mut Criterion) {
let plugin_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap())
.join("tests")
.join("fixture")
.join("swc_noop_plugin");
{
let mut cmd = Command::new("cargo");
cmd.current_dir(&plugin_dir);
cmd.arg("build")
.arg("--release")
.arg("--target=wasm32-wasi");
let status = cmd.status().unwrap();
assert!(status.success());
}
c.bench_function("es/plugin/invoke/1", |b| bench_transform(b, &plugin_dir));
}
fn bench_transform(b: &mut Bencher, plugin_dir: &Path) {
let path = &plugin_dir
.join("target")
.join("wasm32-wasi")
.join("release")
.join("swc_noop_plugin.wasm");
let raw_module_bytes = std::fs::read(path).expect("Should able to read plugin bytes");
let store = wasmer::Store::default();
let module = wasmer::Module::new(&store, raw_module_bytes).unwrap();
let plugin_module = swc_plugin_runner::plugin_module_bytes::CompiledPluginModuleBytes::new(
path.as_os_str()
.to_str()
.expect("Should able to get path")
.to_string(),
module,
store,
);
#[cfg(feature = "__rkyv")]
b.iter(|| {
GLOBALS.set(&Globals::new(), || {
tokio::runtime::Runtime::new().unwrap().block_on(async {
let cm = Arc::new(SourceMap::new(FilePathMapping::empty()));
let fm = cm.new_source_file(
FileName::Real("src/test.ts".into()).into(),
SOURCE.to_string(),
);
let program = parse_file_as_program(
&fm,
Default::default(),
EsVersion::latest(),
None,
&mut Vec::new(),
)
.unwrap();
let program = VersionedSerializable::new(program);
let program_ser = PluginSerializedBytes::try_serialize(&program).unwrap();
let mut transform_plugin_executor =
swc_plugin_runner::create_plugin_transform_executor(
&cm,
&Mark::new(),
&Arc::new(TransformPluginMetadataContext::new(
None,
"development".to_string(),
None,
)),
Box::new(plugin_module.clone()),
None,
None,
);
let experimental_metadata: VersionedSerializable<FxHashMap<String, String>> =
VersionedSerializable::new(FxHashMap::default());
let _experimental_metadata =
PluginSerializedBytes::try_serialize(&experimental_metadata)
.expect("Should be a hashmap");
let res = transform_plugin_executor
.transform(&program_ser, Some(true))
.unwrap();
let _ = black_box(res);
});
});
})
}
criterion_group!(benches, plugin_group);
criterion_main!(benches);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_plugin_runner/build.rs | Rust | use std::error::Error;
use vergen::{BuildBuilder, CargoBuilder, Emitter};
fn main() -> Result<(), Box<dyn Error>> {
let build = BuildBuilder::all_build()?;
let cargo = CargoBuilder::default()
.dependencies(true)
.name_filter("*_ast")
.build()?;
Emitter::default()
.add_instructions(&build)?
.add_instructions(&cargo)?
.emit()?;
Ok(())
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_plugin_runner/src/cache.rs | Rust | #![allow(unused)]
use std::{
env::current_dir,
path::{Path, PathBuf},
str::FromStr,
};
use anyhow::{Context, Error};
use enumset::EnumSet;
use parking_lot::Mutex;
use rustc_hash::FxHashMap;
use swc_common::sync::{Lazy, OnceCell};
#[cfg(not(target_arch = "wasm32"))]
use wasmer::{sys::BaseTunables, CpuFeature, Engine, Target, Triple};
use wasmer::{Module, Store};
#[cfg(all(not(target_arch = "wasm32"), feature = "filesystem_cache"))]
use wasmer_cache::{Cache as WasmerCache, FileSystemCache, Hash};
use crate::{
plugin_module_bytes::{CompiledPluginModuleBytes, PluginModuleBytes, RawPluginModuleBytes},
wasix_runtime::new_store,
};
/// Version for bytecode cache stored in local filesystem.
///
/// This MUST be updated when bump up wasmer.
///
/// Bytecode cache generated via wasmer is generally portable,
/// however it is not gauranteed to be compatible across wasmer's
/// internal changes.
/// https://github.com/wasmerio/wasmer/issues/2781
const MODULE_SERIALIZATION_VERSION: &str = "v7";
#[derive(Default)]
pub struct PluginModuleCacheInner {
#[cfg(all(not(target_arch = "wasm32"), feature = "filesystem_cache"))]
fs_cache_root: Option<String>,
#[cfg(all(not(target_arch = "wasm32"), feature = "filesystem_cache"))]
fs_cache_store: Option<FileSystemCache>,
// Stores the string representation of the hash of the plugin module to store into
// FileSystemCache. This works since SWC does not revalidates plugin in single process
// lifecycle.
#[cfg(all(not(target_arch = "wasm32"), feature = "filesystem_cache"))]
fs_cache_hash_store: FxHashMap<String, Hash>,
// Generic in-memory cache to the raw bytes, either read by fs or supplied by bindgen.
memory_cache_store: FxHashMap<String, Vec<u8>>,
// A naive hashmap to the compiled plugin modules.
// Current it doesn't have any invalidation or expiration logics like lru,
// having a lot of plugins may create some memory pressure.
compiled_module_bytes: FxHashMap<String, (wasmer::Store, wasmer::Module)>,
}
impl PluginModuleCacheInner {
pub fn get_fs_cache_root(&self) -> Option<String> {
#[cfg(all(not(target_arch = "wasm32"), feature = "filesystem_cache"))]
return self.fs_cache_root.clone();
None
}
/// Check if the cache contains bytes for the corresponding key.
pub fn contains(&self, key: &str) -> bool {
let is_in_cache = self.memory_cache_store.contains_key(key)
|| self.compiled_module_bytes.contains_key(key);
#[cfg(all(not(target_arch = "wasm32"), feature = "filesystem_cache"))]
{
// Instead of accessing FileSystemCache, check if the key have corresponding
// hash since FileSystemCache does not have a way to check if the key
// exists.
return is_in_cache || self.fs_cache_hash_store.contains_key(key);
}
is_in_cache
}
/// Insert raw plugin module bytes into cache does not have compiled
/// wasmer::Module. The bytes stored in this type of cache will return
/// RawPluginModuleBytes. It is strongly recommend to avoid using this
/// type of cache as much as possible, since module compilation time for
/// the wasm is noticeably expensive and caching raw bytes only cuts off
/// the reading time for the plugin module.
pub fn insert_raw_bytes(&mut self, key: String, value: Vec<u8>) {
self.memory_cache_store.insert(key, value);
}
/// Insert already compiled wasmer::Module into cache.
/// The module stored in this cache will return CompiledPluginModuleBytes,
/// which costs near-zero time when calling its `compile_module` method as
/// it clones precompiled module directly.
///
/// In genearl it is recommended to use either using filesystemcache
/// `store_bytes_from_path` which internally calls this or directly call
/// this to store compiled module bytes. CompiledModuleBytes provides way to
/// create it via RawModuleBytes, so there's no practical reason to
/// store raw bytes most cases.
pub fn insert_compiled_module_bytes(
&mut self,
key: String,
value: (wasmer::Store, wasmer::Module),
) {
self.compiled_module_bytes.insert(key, value);
}
/// Store plugin module bytes into the cache, from actual filesystem.
pub fn store_bytes_from_path(&mut self, binary_path: &Path, key: &str) -> Result<(), Error> {
#[cfg(all(not(target_arch = "wasm32"), feature = "filesystem_cache"))]
{
let raw_module_bytes =
std::fs::read(binary_path).context("Cannot read plugin from specified path")?;
// If FilesystemCache is available, store serialized bytes into fs.
if let Some(fs_cache_store) = &mut self.fs_cache_store {
let module_bytes_hash = Hash::generate(&raw_module_bytes);
let store = new_store();
let module =
if let Ok(module) = unsafe { fs_cache_store.load(&store, module_bytes_hash) } {
tracing::debug!("Build WASM from cache: {key}");
module
} else {
let module = Module::new(&store, raw_module_bytes.clone())
.context("Cannot compile plugin binary")?;
fs_cache_store.store(module_bytes_hash, &module)?;
module
};
// Store hash to load from fs_cache_store later.
self.fs_cache_hash_store
.insert(key.to_string(), module_bytes_hash);
// Also store in memory for the in-process cache.
self.insert_compiled_module_bytes(key.to_string(), (store, module));
}
// Store raw bytes into memory cache.
self.insert_raw_bytes(key.to_string(), raw_module_bytes);
return Ok(());
}
anyhow::bail!("Filesystem cache is not enabled, cannot read plugin from phsyical path");
}
/// Returns a PluingModuleBytes can be compiled into a wasmer::Module.
/// Depends on the cache availability, it may return a raw bytes or a
/// serialized bytes.
pub fn get(&self, key: &str) -> Option<Box<dyn PluginModuleBytes>> {
// Look for compiled module bytes first, it is the cheapest way to get compile
// wasmer::Module.
if let Some(compiled_module) = self.compiled_module_bytes.get(key) {
return Some(Box::new(CompiledPluginModuleBytes::new(
key.to_string(),
compiled_module.1.clone(),
Store::new(compiled_module.0.engine().clone()),
)));
}
// Next, read serialzied bytes from filesystem cache.
#[cfg(all(not(target_arch = "wasm32"), feature = "filesystem_cache"))]
if let Some(fs_cache_store) = &self.fs_cache_store {
let hash = self.fs_cache_hash_store.get(key)?;
let store = new_store();
let module = unsafe { fs_cache_store.load(&store, *hash) };
if let Ok(module) = module {
return Some(Box::new(CompiledPluginModuleBytes::new(
key.to_string(),
module,
store,
)));
}
}
// Lastly, look for if there's a raw bytes in memory. This requires compilation
// still, but doesn't go through filesystem access.
if let Some(memory_cache_bytes) = self.memory_cache_store.get(key) {
return Some(Box::new(RawPluginModuleBytes::new(
key.to_string(),
memory_cache_bytes.clone(),
)));
}
None
}
}
#[derive(Default)]
pub struct PluginModuleCache {
pub inner: OnceCell<Mutex<PluginModuleCacheInner>>,
/// To prevent concurrent access to `WasmerInstance::new`.
/// This is a precaution only yet, for the preparation of wasm thread
/// support in the future.
instantiation_lock: Mutex<()>,
}
impl PluginModuleCache {
pub fn create_inner(
enable_fs_cache_store: bool,
fs_cache_store_root: &Option<String>,
) -> PluginModuleCacheInner {
PluginModuleCacheInner {
#[cfg(all(not(target_arch = "wasm32"), feature = "filesystem_cache"))]
fs_cache_root: fs_cache_store_root.clone(),
#[cfg(all(not(target_arch = "wasm32"), feature = "filesystem_cache"))]
fs_cache_store: if enable_fs_cache_store {
create_filesystem_cache(fs_cache_store_root)
} else {
None
},
#[cfg(all(not(target_arch = "wasm32"), feature = "filesystem_cache"))]
fs_cache_hash_store: Default::default(),
memory_cache_store: Default::default(),
compiled_module_bytes: Default::default(),
}
}
}
#[cfg(all(not(target_arch = "wasm32"), feature = "filesystem_cache"))]
#[tracing::instrument(level = "info", skip_all)]
fn create_filesystem_cache(filesystem_cache_root: &Option<String>) -> Option<FileSystemCache> {
let mut root_path = if let Some(root) = filesystem_cache_root {
Some(PathBuf::from(root))
} else if let Ok(cwd) = current_dir() {
Some(cwd.join(".swc"))
} else {
None
};
if let Some(root_path) = &mut root_path {
root_path.push("plugins");
root_path.push(format!(
"{}_{}_{}_{}",
MODULE_SERIALIZATION_VERSION,
std::env::consts::OS,
std::env::consts::ARCH,
option_env!("CARGO_PKG_VERSION").unwrap_or("plugin_runner_unknown")
));
return FileSystemCache::new(&root_path).ok();
}
None
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_plugin_runner/src/host_environment.rs | Rust | use wasmer::Memory;
/// An external environment state imported (declared in host, injected into
/// guest) fn can access. This'll allow host to read from updated state from
/// guest.
///
/// This is `base` environment exposes nothing. For other
/// calls requires additional data to be set in the host, separate
/// hostenvironments are declared. Refer `CommentsHostEnvironment` for an
/// example.
///
/// ref: https://docs.wasmer.io/integrations/examples/host-functions#declaring-the-data
#[derive(Clone)]
pub struct BaseHostEnvironment {
pub memory: Option<Memory>,
}
impl BaseHostEnvironment {
pub fn new() -> BaseHostEnvironment {
BaseHostEnvironment { memory: None }
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_plugin_runner/src/imported_fn/comments.rs | Rust | use std::sync::Arc;
use parking_lot::Mutex;
use swc_common::{
comments::{Comments, SingleThreadedComments},
plugin::serialized::{PluginSerializedBytes, VersionedSerializable},
BytePos,
};
use swc_plugin_proxy::COMMENTS;
use wasmer::{AsStoreMut, FunctionEnvMut, Memory, TypedFunction};
use crate::memory_interop::{allocate_return_values_into_guest, copy_bytes_into_host};
/// External environment state for imported (declared in host, injected into
/// guest) fn for comments proxy.
#[derive(Clone)]
pub struct CommentHostEnvironment {
pub memory: Option<Memory>,
/// Attached imported fn `__alloc` to the hostenvironment to allow any other
/// imported fn can allocate guest's memory space from host runtime.
pub alloc_guest_memory: Option<TypedFunction<u32, u32>>,
/// A buffer to `Comment`, or `Vec<Comment>` plugin need to pass to the host
/// to perform mutable comment operations like `add_leading, or
/// add_leading_comments`. This is vec to serialized bytes, doesn't
/// distinguish if it's Vec<Comment> or not. Host should perform
/// typed deserialization accordingly.
pub mutable_comment_buffer: Arc<Mutex<Vec<u8>>>,
}
impl CommentHostEnvironment {
pub fn new(mutable_comment_buffer: &Arc<Mutex<Vec<u8>>>) -> CommentHostEnvironment {
CommentHostEnvironment {
memory: None,
alloc_guest_memory: None,
mutable_comment_buffer: mutable_comment_buffer.clone(),
}
}
}
/// Copy given serialized byte into host's comment buffer, subsequent proxy call
/// in the host can read it.
#[tracing::instrument(level = "info", skip_all)]
pub fn copy_comment_to_host_env(
mut env: FunctionEnvMut<CommentHostEnvironment>,
bytes_ptr: i32,
bytes_ptr_len: i32,
) {
let memory = env
.data()
.memory
.as_ref()
.expect("Memory instance should be available, check initialization");
(*env.data_mut().mutable_comment_buffer.lock()) =
copy_bytes_into_host(&memory.view(&env), bytes_ptr, bytes_ptr_len);
}
/// Utility fn to unwrap necessary values for the comments fn operation when fn
/// needs to return values.
#[tracing::instrument(level = "info", skip_all)]
fn unwrap_comments_storage_or_default<F, R>(f: F, default: R) -> R
where
F: FnOnce(&SingleThreadedComments) -> R,
{
if !COMMENTS.is_set() {
return default;
}
COMMENTS.with(|storage| {
if let Some(comments) = &storage.inner {
f(comments)
} else {
default
}
})
}
/// Utility fn to unwrap necessary values for the comments fn operation when fn
/// does not need to return values.
#[tracing::instrument(level = "info", skip_all)]
fn unwrap_comments_storage<F>(f: F)
where
F: FnOnce(&SingleThreadedComments),
{
unwrap_comments_storage_or_default(
|comments| {
f(comments);
None
},
None as Option<i32>,
);
}
/// Utility fn to unwrap necessary values for the comments, as well as host
/// environment's state.
#[tracing::instrument(level = "info", skip_all)]
fn unwrap_comments_storage_with_env<F, R>(
env: &FunctionEnvMut<CommentHostEnvironment>,
f: F,
default: R,
) -> R
where
F: FnOnce(&SingleThreadedComments, &Memory, &TypedFunction<u32, u32>) -> R,
{
let memory = env
.data()
.memory
.as_ref()
.expect("Memory instance should be available, check initialization");
let alloc_guest_memory = env
.data()
.alloc_guest_memory
.as_ref()
.expect("Alloc guest memory fn should be available, check initialization");
unwrap_comments_storage_or_default(|comments| f(comments, memory, alloc_guest_memory), default)
}
/// Common logics for add_*_comment/comments.
#[tracing::instrument(level = "info", skip_all)]
fn add_comments_inner<F>(mut env: FunctionEnvMut<CommentHostEnvironment>, byte_pos: u32, f: F)
where
F: FnOnce(&SingleThreadedComments, BytePos, PluginSerializedBytes),
{
unwrap_comments_storage(|comments| {
let byte_pos = BytePos(byte_pos);
// PluginCommentProxy in the guest should've copied buffer already
let comment_byte = &mut (*env.data_mut().mutable_comment_buffer.lock());
let serialized = PluginSerializedBytes::from_slice(comment_byte);
f(comments, byte_pos, serialized);
// This is not strictly required, but will help to ensure to access previous
// call's buffer when we make some mistakes for the execution order.
comment_byte.clear();
});
}
pub fn add_leading_comment_proxy(env: FunctionEnvMut<CommentHostEnvironment>, byte_pos: u32) {
add_comments_inner(env, byte_pos, |comments, byte_pos, serialized| {
comments.add_leading(
byte_pos,
serialized
.deserialize()
.expect("Should be able to deserialize")
.into_inner(),
);
});
}
#[tracing::instrument(level = "info", skip_all)]
pub fn add_leading_comments_proxy(env: FunctionEnvMut<CommentHostEnvironment>, byte_pos: u32) {
add_comments_inner(env, byte_pos, |comments, byte_pos, serialized| {
comments.add_leading_comments(
byte_pos,
serialized
.deserialize()
.expect("Should be able to deserialize")
.into_inner(),
);
});
}
#[tracing::instrument(level = "info", skip_all)]
pub fn has_leading_comments_proxy(byte_pos: u32) -> i32 {
unwrap_comments_storage_or_default(|comments| comments.has_leading(BytePos(byte_pos)) as i32, 0)
}
#[tracing::instrument(level = "info", skip_all)]
pub fn move_leading_comments_proxy(from_byte_pos: u32, to_byte_pos: u32) {
unwrap_comments_storage(|comments| {
comments.move_leading(BytePos(from_byte_pos), BytePos(to_byte_pos))
});
}
#[tracing::instrument(level = "info", skip_all)]
pub fn take_leading_comments_proxy(
mut env: FunctionEnvMut<CommentHostEnvironment>,
byte_pos: u32,
allocated_ret_ptr: u32,
) -> i32 {
let memory = env.data().memory.clone();
let memory = memory
.as_ref()
.expect("Memory instance should be available, check initialization");
let alloc_guest_memory = env.data().alloc_guest_memory.clone();
let alloc_guest_memory = alloc_guest_memory
.as_ref()
.expect("Alloc guest memory fn should be available, check initialization");
unwrap_comments_storage_or_default(
|comments| {
let leading_comments = comments.take_leading(BytePos(byte_pos));
if let Some(leading_comments) = leading_comments {
let serialized_leading_comments_vec_bytes = PluginSerializedBytes::try_serialize(
&VersionedSerializable::new(leading_comments),
)
.expect("Should be serializable");
allocate_return_values_into_guest(
memory,
&mut env.as_store_mut(),
alloc_guest_memory,
allocated_ret_ptr,
&serialized_leading_comments_vec_bytes,
);
1
} else {
0
}
},
0,
)
}
/// Ask to get leading_comments from currently scoped comments held by
/// HostCommentsStorage.
///
/// Returns 1 if operation success with Some(Vec<Comments>), 0 otherwise.
/// Allocated results should be read through CommentsPtr.
#[tracing::instrument(level = "info", skip_all)]
pub fn get_leading_comments_proxy(
mut env: FunctionEnvMut<CommentHostEnvironment>,
byte_pos: u32,
allocated_ret_ptr: u32,
) -> i32 {
let memory = env.data().memory.clone();
let memory = memory
.as_ref()
.expect("Memory instance should be available, check initialization");
let alloc_guest_memory = env.data().alloc_guest_memory.clone();
let alloc_guest_memory = alloc_guest_memory
.as_ref()
.expect("Alloc guest memory fn should be available, check initialization");
unwrap_comments_storage_or_default(
|comments| {
let leading_comments = comments.get_leading(BytePos(byte_pos));
if let Some(leading_comments) = leading_comments {
let serialized_leading_comments_vec_bytes = PluginSerializedBytes::try_serialize(
&VersionedSerializable::new(leading_comments),
)
.expect("Should be serializable");
allocate_return_values_into_guest(
memory,
&mut env.as_store_mut(),
alloc_guest_memory,
allocated_ret_ptr,
&serialized_leading_comments_vec_bytes,
);
1
} else {
0
}
},
0,
)
}
#[tracing::instrument(level = "info", skip_all)]
pub fn add_trailing_comment_proxy(env: FunctionEnvMut<CommentHostEnvironment>, byte_pos: u32) {
add_comments_inner(env, byte_pos, |comments, byte_pos, serialized| {
comments.add_trailing(
byte_pos,
serialized
.deserialize()
.expect("Should be able to deserialize")
.into_inner(),
);
});
}
#[tracing::instrument(level = "info", skip_all)]
pub fn add_trailing_comments_proxy(env: FunctionEnvMut<CommentHostEnvironment>, byte_pos: u32) {
add_comments_inner(env, byte_pos, |comments, byte_pos, serialized| {
comments.add_trailing_comments(
byte_pos,
serialized
.deserialize()
.expect("Should be able to deserialize")
.into_inner(),
);
});
}
#[tracing::instrument(level = "info", skip_all)]
pub fn has_trailing_comments_proxy(byte_pos: u32) -> i32 {
unwrap_comments_storage_or_default(
|comments| comments.has_trailing(BytePos(byte_pos)) as i32,
0,
)
}
#[tracing::instrument(level = "info", skip_all)]
pub fn move_trailing_comments_proxy(from_byte_pos: u32, to_byte_pos: u32) {
unwrap_comments_storage(|comments| {
comments.move_trailing(BytePos(from_byte_pos), BytePos(to_byte_pos))
});
}
#[tracing::instrument(level = "info", skip_all)]
pub fn take_trailing_comments_proxy(
mut env: FunctionEnvMut<CommentHostEnvironment>,
byte_pos: u32,
allocated_ret_ptr: u32,
) -> i32 {
let memory = env.data().memory.clone();
let memory = memory
.as_ref()
.expect("Memory instance should be available, check initialization");
let alloc_guest_memory = env.data().alloc_guest_memory.clone();
let alloc_guest_memory = alloc_guest_memory
.as_ref()
.expect("Alloc guest memory fn should be available, check initialization");
unwrap_comments_storage_or_default(
|comments| {
let trailing_comments = comments.take_trailing(BytePos(byte_pos));
if let Some(leading_comments) = trailing_comments {
let serialized_leading_comments_vec_bytes = PluginSerializedBytes::try_serialize(
&VersionedSerializable::new(leading_comments),
)
.expect("Should be serializable");
allocate_return_values_into_guest(
memory,
&mut env.as_store_mut(),
alloc_guest_memory,
allocated_ret_ptr,
&serialized_leading_comments_vec_bytes,
);
1
} else {
0
}
},
0,
)
}
#[tracing::instrument(level = "info", skip_all)]
pub fn get_trailing_comments_proxy(
mut env: FunctionEnvMut<CommentHostEnvironment>,
byte_pos: u32,
allocated_ret_ptr: u32,
) -> i32 {
let memory = env.data().memory.clone();
let memory = memory
.as_ref()
.expect("Memory instance should be available, check initialization");
let alloc_guest_memory = env.data().alloc_guest_memory.clone();
let alloc_guest_memory = alloc_guest_memory
.as_ref()
.expect("Alloc guest memory fn should be available, check initialization");
unwrap_comments_storage_or_default(
|comments| {
let trailing_comments = comments.get_trailing(BytePos(byte_pos));
if let Some(leading_comments) = trailing_comments {
let serialized_leading_comments_vec_bytes = PluginSerializedBytes::try_serialize(
&VersionedSerializable::new(leading_comments),
)
.expect("Should be serializable");
allocate_return_values_into_guest(
memory,
&mut env.as_store_mut(),
alloc_guest_memory,
allocated_ret_ptr,
&serialized_leading_comments_vec_bytes,
);
1
} else {
0
}
},
0,
)
}
#[tracing::instrument(level = "info", skip_all)]
pub fn add_pure_comment_proxy(byte_pos: u32) {
unwrap_comments_storage(|comments| comments.add_pure_comment(BytePos(byte_pos)));
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_plugin_runner/src/imported_fn/diagnostics.rs | Rust | use std::sync::Arc;
use parking_lot::Mutex;
use wasmer::{FunctionEnvMut, Memory};
use crate::memory_interop::copy_bytes_into_host;
/// External environment to read swc_core diagnostics from the host.
#[derive(Clone)]
pub struct DiagnosticContextHostEnvironment {
pub memory: Option<Memory>,
/// A buffer to store diagnostics data strings.
pub core_diag_buffer: Arc<Mutex<Vec<u8>>>,
}
impl DiagnosticContextHostEnvironment {
pub fn new(core_diag_buffer: &Arc<Mutex<Vec<u8>>>) -> Self {
DiagnosticContextHostEnvironment {
memory: None,
core_diag_buffer: core_diag_buffer.clone(),
}
}
}
#[tracing::instrument(level = "info", skip_all)]
pub fn set_plugin_core_pkg_diagnostics(
mut env: FunctionEnvMut<DiagnosticContextHostEnvironment>,
bytes_ptr: i32,
bytes_ptr_len: i32,
) {
let memory = env
.data()
.memory
.as_ref()
.expect("Memory instance should be available, check initialization");
(*env.data_mut().core_diag_buffer.lock()) =
copy_bytes_into_host(&memory.view(&env), bytes_ptr, bytes_ptr_len);
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_plugin_runner/src/imported_fn/handler.rs | Rust | use swc_common::{
errors::{Diagnostic, HANDLER},
plugin::serialized::PluginSerializedBytes,
};
use wasmer::FunctionEnvMut;
use crate::{host_environment::BaseHostEnvironment, memory_interop::copy_bytes_into_host};
#[tracing::instrument(level = "info", skip_all)]
pub fn emit_diagnostics(
env: FunctionEnvMut<BaseHostEnvironment>,
bytes_ptr: i32,
bytes_ptr_len: i32,
) {
let memory = env
.data()
.memory
.as_ref()
.expect("Memory instance should be available, check initialization");
if HANDLER.is_set() {
HANDLER.with(|handler| {
let diagnostics_bytes =
copy_bytes_into_host(&memory.view(&env), bytes_ptr, bytes_ptr_len);
let serialized = PluginSerializedBytes::from_slice(&diagnostics_bytes[..]);
let diagnostic = PluginSerializedBytes::deserialize::<Diagnostic>(&serialized)
.expect("Should able to be deserialized into diagnostic");
let mut builder = swc_common::errors::DiagnosticBuilder::new_diagnostic(
handler,
diagnostic.into_inner(),
);
builder.emit();
})
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_plugin_runner/src/imported_fn/hygiene.rs | Rust | use swc_common::{
hygiene::MutableMarkContext,
plugin::serialized::{PluginSerializedBytes, VersionedSerializable},
Mark, SyntaxContext,
};
use wasmer::{AsStoreMut, FunctionEnvMut};
use crate::{host_environment::BaseHostEnvironment, memory_interop::write_into_memory_view};
/// A proxy to Mark::fresh() that can be used in plugin.
/// This it not directly called by plugin, instead `impl Mark` will selectively
/// call this depends on the running context.
pub fn mark_fresh_proxy(parent: u32) -> u32 {
Mark::fresh(Mark::from_u32(parent)).as_u32()
}
pub fn mark_parent_proxy(self_mark: u32) -> u32 {
Mark::from_u32(self_mark).parent().as_u32()
}
/// A proxy to Mark::is_descendant_of_() that can be used in plugin.
/// Original call site have mutable param, which we'll pass over as return value
/// via serialized MutableMarkContext.
/// Inside of guest context, once this host function returns it'll assign params
/// with return value accordingly.
#[tracing::instrument(level = "info", skip_all)]
pub fn mark_is_descendant_of_proxy(
mut env: FunctionEnvMut<BaseHostEnvironment>,
self_mark: u32,
ancestor: u32,
allocated_ptr: u32,
) {
let memory = env.data().memory.clone();
let memory = memory
.as_ref()
.expect("Memory instance should be available, check initialization");
let self_mark = Mark::from_u32(self_mark);
let ancestor = Mark::from_u32(ancestor);
let return_value = self_mark.is_descendant_of(ancestor);
let context = VersionedSerializable::new(MutableMarkContext(
self_mark.as_u32(),
0,
return_value as u32,
));
let serialized_bytes =
PluginSerializedBytes::try_serialize(&context).expect("Should be serializable");
write_into_memory_view(
memory,
&mut env.as_store_mut(),
&serialized_bytes,
|_, _| allocated_ptr,
);
}
#[tracing::instrument(level = "info", skip_all)]
pub fn mark_least_ancestor_proxy(
mut env: FunctionEnvMut<BaseHostEnvironment>,
a: u32,
b: u32,
allocated_ptr: u32,
) {
let memory = env.data().memory.clone();
let memory = memory
.as_ref()
.expect("Memory instance should be available, check initialization");
let a = Mark::from_u32(a);
let b = Mark::from_u32(b);
let return_value = Mark::least_ancestor(a, b).as_u32();
let context =
VersionedSerializable::new(MutableMarkContext(a.as_u32(), b.as_u32(), return_value));
let serialized_bytes =
PluginSerializedBytes::try_serialize(&context).expect("Should be serializable");
write_into_memory_view(
memory,
&mut env.as_store_mut(),
&serialized_bytes,
|_, _| allocated_ptr,
);
}
#[tracing::instrument(level = "info", skip_all)]
pub fn syntax_context_apply_mark_proxy(self_syntax_context: u32, mark: u32) -> u32 {
SyntaxContext::from_u32(self_syntax_context)
.apply_mark(Mark::from_u32(mark))
.as_u32()
}
#[tracing::instrument(level = "info", skip_all)]
pub fn syntax_context_remove_mark_proxy(
mut env: FunctionEnvMut<BaseHostEnvironment>,
self_mark: u32,
allocated_ptr: u32,
) {
let memory = env.data().memory.clone();
let memory = memory
.as_ref()
.expect("Memory instance should be available, check initialization");
let mut self_mark = SyntaxContext::from_u32(self_mark);
let return_value = self_mark.remove_mark();
let context = VersionedSerializable::new(MutableMarkContext(
self_mark.as_u32(),
0,
return_value.as_u32(),
));
let serialized_bytes =
PluginSerializedBytes::try_serialize(&context).expect("Should be serializable");
write_into_memory_view(
memory,
&mut env.as_store_mut(),
&serialized_bytes,
|_, _| allocated_ptr,
);
}
#[tracing::instrument(level = "info", skip_all)]
pub fn syntax_context_outer_proxy(self_mark: u32) -> u32 {
SyntaxContext::from_u32(self_mark).outer().as_u32()
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_plugin_runner/src/imported_fn/metadata_context.rs | Rust | use std::sync::Arc;
use parking_lot::Mutex;
use swc_common::plugin::{
metadata::{TransformPluginMetadataContext, TransformPluginMetadataContextKind},
serialized::{PluginSerializedBytes, VersionedSerializable},
};
use wasmer::{AsStoreMut, FunctionEnvMut, Memory, TypedFunction};
use crate::memory_interop::{allocate_return_values_into_guest, copy_bytes_into_host};
#[derive(Clone)]
pub struct MetadataContextHostEnvironment {
pub memory: Option<Memory>,
/// Attached imported fn `__alloc` to the hostenvironment to allow any other
/// imported fn can allocate guest's memory space from host runtime.
pub alloc_guest_memory: Option<TypedFunction<u32, u32>>,
pub metadata_context: Arc<TransformPluginMetadataContext>,
pub transform_plugin_config: Option<serde_json::Value>,
/// A buffer to string key to the context plugin need to pass to the host.
pub mutable_context_key_buffer: Arc<Mutex<Vec<u8>>>,
}
impl MetadataContextHostEnvironment {
pub fn new(
metadata_context: &Arc<TransformPluginMetadataContext>,
plugin_config: &Option<serde_json::Value>,
mutable_context_key_buffer: &Arc<Mutex<Vec<u8>>>,
) -> Self {
MetadataContextHostEnvironment {
memory: None,
alloc_guest_memory: None,
metadata_context: metadata_context.clone(),
transform_plugin_config: plugin_config.clone(),
mutable_context_key_buffer: mutable_context_key_buffer.clone(),
}
}
}
/// Copy given serialized byte into host's comment buffer, subsequent proxy call
/// in the host can read it.
#[tracing::instrument(level = "info", skip_all)]
pub fn copy_context_key_to_host_env(
mut env: FunctionEnvMut<MetadataContextHostEnvironment>,
bytes_ptr: i32,
bytes_ptr_len: i32,
) {
let memory = env
.data()
.memory
.as_ref()
.expect("Memory instance should be available, check initialization");
(*env.data_mut().mutable_context_key_buffer.lock()) =
copy_bytes_into_host(&memory.view(&env), bytes_ptr, bytes_ptr_len);
}
#[tracing::instrument(level = "info", skip_all)]
pub fn get_transform_plugin_config(
mut env: FunctionEnvMut<MetadataContextHostEnvironment>,
allocated_ret_ptr: u32,
) -> i32 {
let memory = env.data().memory.clone();
let memory = memory
.as_ref()
.expect("Memory instance should be available, check initialization");
let alloc_guest_memory = env.data().alloc_guest_memory.clone();
let alloc_guest_memory = alloc_guest_memory
.as_ref()
.expect("Alloc guest memory fn should be available, check initialization");
let config_value = &env.data().transform_plugin_config;
if let Some(config_value) = config_value {
// Lazy as possible as we can - only deserialize json value if transform plugin
// actually needs it.
let config = serde_json::to_string(config_value).ok();
if let Some(config) = config {
let serialized =
PluginSerializedBytes::try_serialize(&VersionedSerializable::new(config))
.expect("Should be serializable");
allocate_return_values_into_guest(
memory,
&mut env.as_store_mut(),
alloc_guest_memory,
allocated_ret_ptr,
&serialized,
);
return 1;
}
}
0
}
#[tracing::instrument(level = "info", skip_all)]
pub fn get_transform_context(
mut env: FunctionEnvMut<MetadataContextHostEnvironment>,
key: u32,
allocated_ret_ptr: u32,
) -> i32 {
let memory = env.data().memory.clone();
let memory = memory
.as_ref()
.expect("Memory instance should be available, check initialization");
let alloc_guest_memory = env.data().alloc_guest_memory.clone();
let alloc_guest_memory = alloc_guest_memory
.as_ref()
.expect("Alloc guest memory fn should be available, check initialization");
let value = VersionedSerializable::new(
env.data()
.metadata_context
.get(&TransformPluginMetadataContextKind::from(key)),
);
let serialized = PluginSerializedBytes::try_serialize(&value).expect("Should be serializable");
allocate_return_values_into_guest(
memory,
&mut env.as_store_mut(),
alloc_guest_memory,
allocated_ret_ptr,
&serialized,
);
1
}
#[tracing::instrument(level = "info", skip_all)]
pub fn get_experimental_transform_context(
mut env: FunctionEnvMut<MetadataContextHostEnvironment>,
allocated_ret_ptr: u32,
) -> i32 {
let memory = env.data().memory.clone();
let memory = memory
.as_ref()
.expect("Memory instance should be available, check initialization");
let alloc_guest_memory = env.data().alloc_guest_memory.clone();
let alloc_guest_memory = alloc_guest_memory
.as_ref()
.expect("Alloc guest memory fn should be available, check initialization");
let context_key_buffer = env.data().mutable_context_key_buffer.lock().clone();
let key: String = PluginSerializedBytes::from_slice(&context_key_buffer[..])
.deserialize()
.expect("Should able to deserialize")
.into_inner();
let value = env
.data()
.metadata_context
.experimental
.get(&key)
.map(|v| v.to_string());
if let Some(value) = value {
let serialized = PluginSerializedBytes::try_serialize(&VersionedSerializable::new(value))
.expect("Should be serializable");
allocate_return_values_into_guest(
memory,
&mut env.as_store_mut(),
alloc_guest_memory,
allocated_ret_ptr,
&serialized,
);
return 1;
}
0
}
#[tracing::instrument(level = "info", skip_all)]
pub fn get_raw_experiemtal_transform_context(
mut env: FunctionEnvMut<MetadataContextHostEnvironment>,
allocated_ret_ptr: u32,
) -> i32 {
let memory = env.data().memory.clone();
let memory = memory
.as_ref()
.expect("Memory instance should be available, check initialization");
let alloc_guest_memory = env.data().alloc_guest_memory.clone();
let alloc_guest_memory = alloc_guest_memory
.as_ref()
.expect("Alloc guest memory fn should be available, check initialization");
let experimental_context =
VersionedSerializable::new(env.data().metadata_context.experimental.clone());
let serialized_experimental_context_bytes =
PluginSerializedBytes::try_serialize(&experimental_context)
.expect("Should be serializable");
allocate_return_values_into_guest(
memory,
&mut env.as_store_mut(),
alloc_guest_memory,
allocated_ret_ptr,
&serialized_experimental_context_bytes,
);
1
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_plugin_runner/src/imported_fn/mod.rs | Rust | //! Functions for syntax_pos::hygiene imported into the guests (plugin) runtime
//! allows interop between host's state to plugin. When guest calls these fn,
//! it'll be executed in host's memory space.
/*
* Below diagram shows one reference example how guest does trampoline between
* host's memory space.
*┌───────────────────────────────────────┐ ┌─────────────────────────────────────────────┐
*│Host (SWC/core) │ │Plugin (wasm) │
*│ ┌────────────────────────────────┐ │ │ │
*│ │COMMENTS.with() │ │ │ ┌──────────────────────────────────────┐ │
*│ │ │ │ │ │PluginCommentsProxy │ │
*│ │ │ │ │ │ │ │
*│ │ ┌────────────────────────────┐ │ │ │ │ ┌────────────────────────────────┐ │ │
*│ │ │get_leading_comments_proxy()│◀┼───┼────┼──┼─┤get_leading() │ │ │
*│ │ │ │ │ │ │ │ │ │ │ │
*│ │ │ │ │ │ │ │ │ ┌──────────────────────────┐ │ │ │
*│ │ │ │─┼───┼──┬─┼──┼─┼─▶AllocatedBytesPtr(p,len) │ │ │ │
*│ │ └────────────────────────────┘ │ │ │ │ │ │ │ │ │ │ │
*│ │ │ │ │ │ │ │ └─────────────┬────────────┘ │ │ │
*│ │ │ │ │ │ │ │ │ │ │ │
*│ │ │ │ │ │ │ │ ┌─────────────▼────────────┐ │ │ │
*│ └────────────────────────────────┘ │ │ │ │ │ │Vec<Comments> │ │ │ │
*│ │ └─┼──┼─┼─▶ │ │ │ │
*│ │ │ │ │ └──────────────────────────┘ │ │ │
*│ │ │ │ └────────────────────────────────┘ │ │
*│ │ │ └──────────────────────────────────────┘ │
*└───────────────────────────────────────┘ └─────────────────────────────────────────────┘
* 1. Plugin calls `PluginCommentsProxy::get_leading()`. PluginCommentsProxy is
* a struct constructed in plugin's memory space.
* 2. `get_leading()` internally calls `__get_leading_comments_proxy`, which is
* imported fn `get_leading_comments_proxy` exists in the host.
* 3. Host access necessary values in its memory space (COMMENTS)
* 4. Host copies value to be returned into plugin's memory space. Memory
* allocation for the value should be manually performed.
* 5. Host completes imported fn, `PluginCommentsProxy::get_leading()` now can
* read, deserialize memory host wrote.
* - In case of `get_leading`, returned value is non-deterministic vec
* (`Vec<Comments>`) guest cannot preallocate with specific length. Instead,
* guest passes a fixed size struct (AllocatedBytesPtr), once host allocates
* actual vec into guest it'll write pointer to the vec into the struct.
*/
use wasmer::{imports, Function, FunctionEnv, Imports, Store};
use crate::{
host_environment::BaseHostEnvironment,
imported_fn::{
comments::{
add_leading_comment_proxy, add_leading_comments_proxy, add_pure_comment_proxy,
add_trailing_comment_proxy, add_trailing_comments_proxy, copy_comment_to_host_env,
get_leading_comments_proxy, get_trailing_comments_proxy, has_leading_comments_proxy,
has_trailing_comments_proxy, move_leading_comments_proxy, move_trailing_comments_proxy,
take_leading_comments_proxy, take_trailing_comments_proxy, CommentHostEnvironment,
},
diagnostics::{set_plugin_core_pkg_diagnostics, DiagnosticContextHostEnvironment},
metadata_context::get_raw_experiemtal_transform_context,
set_transform_result::{set_transform_result, TransformResultHostEnvironment},
source_map::span_to_source_proxy,
span::span_dummy_with_cmt_proxy,
},
};
pub(crate) mod comments;
pub(crate) mod diagnostics;
pub(crate) mod handler;
pub(crate) mod hygiene;
pub(crate) mod metadata_context;
pub(crate) mod set_transform_result;
pub(crate) mod source_map;
pub(crate) mod span;
use handler::*;
use hygiene::*;
use self::{
metadata_context::{
copy_context_key_to_host_env, get_experimental_transform_context, get_transform_context,
get_transform_plugin_config, MetadataContextHostEnvironment,
},
source_map::{
doctest_offset_line_proxy, lookup_byte_offset_proxy, lookup_char_pos_proxy,
merge_spans_proxy, span_to_filename_proxy, span_to_lines_proxy, span_to_string_proxy,
SourceMapHostEnvironment,
},
};
/// Create an ImportObject includes functions to be imported from host to the
/// plugins.
pub(crate) fn build_import_object(
wasmer_store: &mut Store,
metadata_env: &FunctionEnv<MetadataContextHostEnvironment>,
transform_env: &FunctionEnv<TransformResultHostEnvironment>,
base_env: &FunctionEnv<BaseHostEnvironment>,
comments_env: &FunctionEnv<CommentHostEnvironment>,
source_map_host_env: &FunctionEnv<SourceMapHostEnvironment>,
diagnostics_env: &FunctionEnv<DiagnosticContextHostEnvironment>,
) -> Imports {
// core_diagnostics
let set_transform_plugin_core_pkg_diagnostics_fn_decl = Function::new_typed_with_env(
wasmer_store,
diagnostics_env,
set_plugin_core_pkg_diagnostics,
);
// metadata
let copy_context_key_to_host_env_fn_decl =
Function::new_typed_with_env(wasmer_store, metadata_env, copy_context_key_to_host_env);
let get_transform_plugin_config_fn_decl =
Function::new_typed_with_env(wasmer_store, metadata_env, get_transform_plugin_config);
let get_transform_context_fn_decl =
Function::new_typed_with_env(wasmer_store, metadata_env, get_transform_context);
let get_experimental_transform_context_fn_decl = Function::new_typed_with_env(
wasmer_store,
metadata_env,
get_experimental_transform_context,
);
let get_raw_experiemtal_transform_context_fn_decl = Function::new_typed_with_env(
wasmer_store,
metadata_env,
get_raw_experiemtal_transform_context,
);
// transform_result
let set_transform_result_fn_decl =
Function::new_typed_with_env(wasmer_store, transform_env, set_transform_result);
// handler
let emit_diagnostics_fn_decl =
Function::new_typed_with_env(wasmer_store, base_env, emit_diagnostics);
// hygiene
let mark_fresh_fn_decl = Function::new_typed(wasmer_store, mark_fresh_proxy);
let mark_parent_fn_decl = Function::new_typed(wasmer_store, mark_parent_proxy);
let mark_is_descendant_of_fn_decl =
Function::new_typed_with_env(wasmer_store, base_env, mark_is_descendant_of_proxy);
let mark_least_ancestor_fn_decl =
Function::new_typed_with_env(wasmer_store, base_env, mark_least_ancestor_proxy);
let syntax_context_apply_mark_fn_decl =
Function::new_typed(wasmer_store, syntax_context_apply_mark_proxy);
let syntax_context_remove_mark_fn_decl =
Function::new_typed_with_env(wasmer_store, base_env, syntax_context_remove_mark_proxy);
let syntax_context_outer_fn_decl =
Function::new_typed(wasmer_store, syntax_context_outer_proxy);
// Span
let span_dummy_with_cmt_fn_decl = Function::new_typed(wasmer_store, span_dummy_with_cmt_proxy);
// comments
let copy_comment_to_host_env_fn_decl =
Function::new_typed_with_env(wasmer_store, comments_env, copy_comment_to_host_env);
let add_leading_comment_fn_decl =
Function::new_typed_with_env(wasmer_store, comments_env, add_leading_comment_proxy);
let add_leading_comments_fn_decl =
Function::new_typed_with_env(wasmer_store, comments_env, add_leading_comments_proxy);
let has_leading_comments_fn_decl =
Function::new_typed(wasmer_store, has_leading_comments_proxy);
let move_leading_comments_fn_decl =
Function::new_typed(wasmer_store, move_leading_comments_proxy);
let take_leading_comments_fn_decl = Function::new_typed_with_env(
wasmer_store,
// take_* doesn't need to share buffer to pass values from plugin to the host - do not
// clone buffer here.
comments_env,
take_leading_comments_proxy,
);
let get_leading_comments_fn_decl = Function::new_typed_with_env(
wasmer_store,
// get_* doesn't need to share buffer to pass values from plugin to the host - do not clone
// buffer here.
comments_env,
get_leading_comments_proxy,
);
let add_trailing_comment_fn_decl =
Function::new_typed_with_env(wasmer_store, comments_env, add_trailing_comment_proxy);
let add_trailing_comments_fn_decl =
Function::new_typed_with_env(wasmer_store, comments_env, add_trailing_comments_proxy);
let has_trailing_comments_fn_decl =
Function::new_typed(wasmer_store, has_trailing_comments_proxy);
let move_trailing_comments_fn_decl =
Function::new_typed(wasmer_store, move_trailing_comments_proxy);
let take_trailing_comments_fn_decl = Function::new_typed_with_env(
wasmer_store,
// take_* doesn't need to share buffer to pass values from plugin to the host - do not
// clone buffer here.
comments_env,
take_trailing_comments_proxy,
);
let get_trailing_comments_fn_decl = Function::new_typed_with_env(
wasmer_store,
// get_* doesn't need to share buffer to pass values from plugin to the host - do not clone
// buffer here.
comments_env,
get_trailing_comments_proxy,
);
let add_pure_comment_fn_decl = Function::new_typed(wasmer_store, add_pure_comment_proxy);
// source_map
let lookup_char_pos_source_map_fn_decl =
Function::new_typed_with_env(wasmer_store, source_map_host_env, lookup_char_pos_proxy);
let doctest_offset_line_fn_decl =
Function::new_typed_with_env(wasmer_store, source_map_host_env, doctest_offset_line_proxy);
let merge_spans_fn_decl =
Function::new_typed_with_env(wasmer_store, source_map_host_env, merge_spans_proxy);
let span_to_string_fn_decl =
Function::new_typed_with_env(wasmer_store, source_map_host_env, span_to_string_proxy);
let span_to_filename_fn_decl =
Function::new_typed_with_env(wasmer_store, source_map_host_env, span_to_filename_proxy);
let span_to_source_fn_decl =
Function::new_typed_with_env(wasmer_store, source_map_host_env, span_to_source_proxy);
let span_to_lines_fn_decl =
Function::new_typed_with_env(wasmer_store, source_map_host_env, span_to_lines_proxy);
let lookup_byte_offset_fn_decl =
Function::new_typed_with_env(wasmer_store, source_map_host_env, lookup_byte_offset_proxy);
imports! {
"env" => {
"__set_transform_plugin_core_pkg_diagnostics" => set_transform_plugin_core_pkg_diagnostics_fn_decl,
// metadata
"__copy_context_key_to_host_env" => copy_context_key_to_host_env_fn_decl,
"__get_transform_plugin_config" => get_transform_plugin_config_fn_decl,
"__get_transform_context" => get_transform_context_fn_decl,
"__get_experimental_transform_context" => get_experimental_transform_context_fn_decl,
"__get_raw_experiemtal_transform_context" => get_raw_experiemtal_transform_context_fn_decl,
// transform
"__set_transform_result" => set_transform_result_fn_decl,
// handler
"__emit_diagnostics" => emit_diagnostics_fn_decl,
// hygiene
"__mark_fresh_proxy" => mark_fresh_fn_decl,
"__mark_parent_proxy" => mark_parent_fn_decl,
"__mark_is_descendant_of_proxy" => mark_is_descendant_of_fn_decl,
"__mark_least_ancestor" => mark_least_ancestor_fn_decl,
"__syntax_context_apply_mark_proxy" => syntax_context_apply_mark_fn_decl,
"__syntax_context_remove_mark_proxy" => syntax_context_remove_mark_fn_decl,
"__syntax_context_outer_proxy" => syntax_context_outer_fn_decl,
// span
"__span_dummy_with_cmt_proxy" => span_dummy_with_cmt_fn_decl,
// comments
"__copy_comment_to_host_env" => copy_comment_to_host_env_fn_decl,
"__add_leading_comment_proxy" => add_leading_comment_fn_decl,
"__add_leading_comments_proxy" => add_leading_comments_fn_decl,
"__has_leading_comments_proxy" => has_leading_comments_fn_decl,
"__move_leading_comments_proxy" => move_leading_comments_fn_decl,
"__take_leading_comments_proxy" => take_leading_comments_fn_decl,
"__get_leading_comments_proxy" => get_leading_comments_fn_decl,
"__add_trailing_comment_proxy" => add_trailing_comment_fn_decl,
"__add_trailing_comments_proxy" => add_trailing_comments_fn_decl,
"__has_trailing_comments_proxy" => has_trailing_comments_fn_decl,
"__move_trailing_comments_proxy" => move_trailing_comments_fn_decl,
"__take_trailing_comments_proxy" => take_trailing_comments_fn_decl,
"__get_trailing_comments_proxy" => get_trailing_comments_fn_decl,
"__add_pure_comment_proxy" => add_pure_comment_fn_decl,
// source_map
"__lookup_char_pos_source_map_proxy" => lookup_char_pos_source_map_fn_decl,
"__doctest_offset_line_proxy" => doctest_offset_line_fn_decl,
"__merge_spans_proxy" => merge_spans_fn_decl,
"__span_to_string_proxy" => span_to_string_fn_decl,
"__span_to_filename_proxy" => span_to_filename_fn_decl,
"__span_to_source_proxy" => span_to_source_fn_decl,
"__span_to_lines_proxy" => span_to_lines_fn_decl,
"__lookup_byte_offset_proxy" => lookup_byte_offset_fn_decl
}
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_plugin_runner/src/imported_fn/set_transform_result.rs | Rust | use std::sync::Arc;
use parking_lot::Mutex;
use wasmer::{FunctionEnvMut, Memory};
use crate::memory_interop::copy_bytes_into_host;
/// Environment states allow to return guest's transform result back to the
/// host, using a buffer `transform_result` attached to the environment.
///
/// When plugin performs its transform it'll fill in `transform_result` with
/// serialized result. Host will reconstruct AST from those value.
#[derive(Clone)]
pub struct TransformResultHostEnvironment {
pub memory: Option<Memory>,
pub transform_result: Arc<Mutex<Vec<u8>>>,
}
impl TransformResultHostEnvironment {
pub fn new(transform_result: &Arc<Mutex<Vec<u8>>>) -> TransformResultHostEnvironment {
TransformResultHostEnvironment {
memory: None,
transform_result: transform_result.clone(),
}
}
}
/// Set plugin's transformed result into host's environment.
/// This is an `imported` fn - when we instantiate plugin module, we inject this
/// fn into plugin's export space. Once transform completes, plugin will call
/// this to set its result back to host.
#[tracing::instrument(level = "info", skip_all)]
pub fn set_transform_result(
mut env: FunctionEnvMut<TransformResultHostEnvironment>,
bytes_ptr: i32,
bytes_ptr_len: i32,
) {
let memory = env
.data()
.memory
.as_ref()
.expect("Memory instance should be available, check initialization");
(*env.data_mut().transform_result.lock()) =
copy_bytes_into_host(&memory.view(&env), bytes_ptr, bytes_ptr_len);
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_plugin_runner/src/imported_fn/source_map.rs | Rust | #![allow(dead_code)]
use std::sync::Arc;
use parking_lot::Mutex;
use swc_common::{
plugin::serialized::{PluginSerializedBytes, VersionedSerializable},
source_map::{PartialFileLines, PartialLoc},
BytePos, SourceMap, SourceMapper, Span,
};
use wasmer::{AsStoreMut, FunctionEnvMut, Memory, TypedFunction};
use crate::memory_interop::{allocate_return_values_into_guest, write_into_memory_view};
/// External environment state for imported (declared in host, injected into
/// guest) fn for source map proxy.
#[derive(Clone)]
pub struct SourceMapHostEnvironment {
pub memory: Option<Memory>,
/// Attached imported fn `__alloc` to the hostenvironment to allow any other
/// imported fn can allocate guest's memory space from host runtime.
pub alloc_guest_memory: Option<TypedFunction<u32, u32>>,
pub source_map: Arc<Mutex<Arc<SourceMap>>>,
/// A buffer to non-determined size of return value from the host.
pub mutable_source_map_buffer: Arc<Mutex<Vec<u8>>>,
}
impl SourceMapHostEnvironment {
pub fn new(
source_map: &Arc<Mutex<Arc<SourceMap>>>,
mutable_source_map_buffer: &Arc<Mutex<Vec<u8>>>,
) -> SourceMapHostEnvironment {
SourceMapHostEnvironment {
memory: None,
alloc_guest_memory: None,
source_map: source_map.clone(),
mutable_source_map_buffer: mutable_source_map_buffer.clone(),
}
}
}
/// Returns `Loc` form given bytepos to the guest.
/// Returned `Loc` is partial, which excludes `SourceFile` from original struct
/// to avoid unnecessary data copying.
#[tracing::instrument(level = "info", skip_all)]
pub fn lookup_char_pos_proxy(
mut env: FunctionEnvMut<SourceMapHostEnvironment>,
byte_pos: u32,
should_include_source_file: i32,
allocated_ret_ptr: u32,
) -> u32 {
let memory = env.data().memory.clone();
let memory = memory
.as_ref()
.expect("Memory instance should be available, check initialization");
let alloc_guest_memory = env.data().alloc_guest_memory.clone();
let alloc_guest_memory = alloc_guest_memory
.as_ref()
.expect("Alloc guest memory fn should be available, check initialization");
let original_loc = (env.data().source_map.lock()).lookup_char_pos(BytePos(byte_pos));
let ret = VersionedSerializable::new(PartialLoc {
source_file: if should_include_source_file == 0 {
None
} else {
Some(original_loc.file)
},
line: original_loc.line,
col: original_loc.col.0,
col_display: original_loc.col_display,
});
let serialized_loc_bytes =
PluginSerializedBytes::try_serialize(&ret).expect("Should be serializable");
allocate_return_values_into_guest(
memory,
&mut env.as_store_mut(),
alloc_guest_memory,
allocated_ret_ptr,
&serialized_loc_bytes,
);
1
}
#[tracing::instrument(level = "info", skip_all)]
pub fn doctest_offset_line_proxy(env: FunctionEnvMut<SourceMapHostEnvironment>, orig: u32) -> u32 {
(env.data().source_map.lock()).doctest_offset_line(orig as usize) as u32
}
#[allow(clippy::too_many_arguments)]
#[tracing::instrument(level = "info", skip_all)]
pub fn merge_spans_proxy(
mut env: FunctionEnvMut<SourceMapHostEnvironment>,
lhs_lo: u32,
lhs_hi: u32,
rhs_lo: u32,
rhs_hi: u32,
allocated_ptr: u32,
) -> i32 {
let memory = env.data().memory.clone();
let memory = memory
.as_ref()
.expect("Memory instance should be available, check initialization");
let sp_lhs = Span {
lo: BytePos(lhs_lo),
hi: BytePos(lhs_hi),
};
let sp_rhs = Span {
lo: BytePos(rhs_lo),
hi: BytePos(rhs_hi),
};
let ret = (env.data().source_map.lock()).merge_spans(sp_lhs, sp_rhs);
if let Some(span) = ret {
let span = VersionedSerializable::new(span);
let serialized_bytes =
PluginSerializedBytes::try_serialize(&span).expect("Should be serializable");
write_into_memory_view(
memory,
&mut env.as_store_mut(),
&serialized_bytes,
|_, _| allocated_ptr,
);
1
} else {
0
}
}
#[tracing::instrument(level = "info", skip_all)]
pub fn span_to_lines_proxy(
mut env: FunctionEnvMut<SourceMapHostEnvironment>,
span_lo: u32,
span_hi: u32,
should_request_source_file: i32,
allocated_ret_ptr: u32,
) -> i32 {
let memory = env.data().memory.clone();
let memory = memory
.as_ref()
.expect("Memory instance should be available, check initialization");
let alloc_guest_memory = env.data().alloc_guest_memory.clone();
let alloc_guest_memory = alloc_guest_memory
.as_ref()
.expect("Alloc guest memory fn should be available, check initialization");
let span = Span {
lo: BytePos(span_lo),
hi: BytePos(span_hi),
};
let ret = (env.data().source_map.lock())
.span_to_lines(span)
.map(|lines| PartialFileLines {
file: if should_request_source_file == 0 {
None
} else {
Some(lines.file)
},
lines: lines.lines,
});
let serialized_loc_bytes =
PluginSerializedBytes::try_serialize(&VersionedSerializable::new(ret))
.expect("Should be serializable");
allocate_return_values_into_guest(
memory,
&mut env.as_store_mut(),
alloc_guest_memory,
allocated_ret_ptr,
&serialized_loc_bytes,
);
1
}
#[tracing::instrument(level = "info", skip_all)]
pub fn lookup_byte_offset_proxy(
mut env: FunctionEnvMut<SourceMapHostEnvironment>,
byte_pos: u32,
allocated_ret_ptr: u32,
) -> i32 {
let memory = env.data().memory.clone();
let memory = memory
.as_ref()
.expect("Memory instance should be available, check initialization");
let alloc_guest_memory = env.data().alloc_guest_memory.clone();
let alloc_guest_memory = alloc_guest_memory
.as_ref()
.expect("Alloc guest memory fn should be available, check initialization");
let byte_pos = BytePos(byte_pos);
let ret = (env.data().source_map.lock()).lookup_byte_offset(byte_pos);
let serialized_loc_bytes =
PluginSerializedBytes::try_serialize(&VersionedSerializable::new(ret))
.expect("Should be serializable");
allocate_return_values_into_guest(
memory,
&mut env.as_store_mut(),
alloc_guest_memory,
allocated_ret_ptr,
&serialized_loc_bytes,
);
1
}
#[tracing::instrument(level = "info", skip_all)]
pub fn span_to_string_proxy(
mut env: FunctionEnvMut<SourceMapHostEnvironment>,
span_lo: u32,
span_hi: u32,
allocated_ret_ptr: u32,
) -> i32 {
let memory = env.data().memory.clone();
let memory = memory
.as_ref()
.expect("Memory instance should be available, check initialization");
let alloc_guest_memory = env.data().alloc_guest_memory.clone();
let alloc_guest_memory = alloc_guest_memory
.as_ref()
.expect("Alloc guest memory fn should be available, check initialization");
let span = Span {
lo: BytePos(span_lo),
hi: BytePos(span_hi),
};
let ret = (env.data().source_map.lock()).span_to_string(span);
let serialized_loc_bytes =
PluginSerializedBytes::try_serialize(&VersionedSerializable::new(ret))
.expect("Should be serializable");
allocate_return_values_into_guest(
memory,
&mut env.as_store_mut(),
alloc_guest_memory,
allocated_ret_ptr,
&serialized_loc_bytes,
);
1
}
#[tracing::instrument(level = "info", skip_all)]
pub fn span_to_filename_proxy(
mut env: FunctionEnvMut<SourceMapHostEnvironment>,
span_lo: u32,
span_hi: u32,
allocated_ret_ptr: u32,
) -> i32 {
let memory = env.data().memory.clone();
let memory = memory
.as_ref()
.expect("Memory instance should be available, check initialization");
let alloc_guest_memory = env.data().alloc_guest_memory.clone();
let alloc_guest_memory = alloc_guest_memory
.as_ref()
.expect("Alloc guest memory fn should be available, check initialization");
let span = Span {
lo: BytePos(span_lo),
hi: BytePos(span_hi),
};
let ret = (env.data().source_map.lock()).span_to_filename(span);
let serialized_loc_bytes =
PluginSerializedBytes::try_serialize(&VersionedSerializable::new(ret))
.expect("Should be serializable");
allocate_return_values_into_guest(
memory,
&mut env.as_store_mut(),
alloc_guest_memory,
allocated_ret_ptr,
&serialized_loc_bytes,
);
1
}
#[tracing::instrument(level = "info", skip_all)]
pub fn span_to_source_proxy(
mut env: FunctionEnvMut<SourceMapHostEnvironment>,
span_lo: u32,
span_hi: u32,
allocated_ret_ptr: u32,
) -> i32 {
let memory = env.data().memory.clone();
let memory = memory
.as_ref()
.expect("Memory instance should be available, check initialization");
let alloc_guest_memory = env.data().alloc_guest_memory.clone();
let alloc_guest_memory = alloc_guest_memory
.as_ref()
.expect("Alloc guest memory fn should be available, check initialization");
let span = Span {
lo: BytePos(span_lo),
hi: BytePos(span_hi),
};
let ret = (*env.data().source_map.lock()).span_to_snippet(span);
let serialized_loc_bytes =
PluginSerializedBytes::try_serialize(&VersionedSerializable::new(ret))
.expect("Should be serializable");
allocate_return_values_into_guest(
memory,
&mut env.as_store_mut(),
alloc_guest_memory,
allocated_ret_ptr,
&serialized_loc_bytes,
);
1
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_plugin_runner/src/imported_fn/span.rs | Rust | pub fn span_dummy_with_cmt_proxy() -> u32 {
// Instead of trying to serialize whole span, send bytepos only
swc_common::Span::dummy_with_cmt().lo.0
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_plugin_runner/src/lib.rs | Rust | #![cfg_attr(not(feature = "__rkyv"), allow(warnings))]
use std::sync::Arc;
use swc_common::{plugin::metadata::TransformPluginMetadataContext, SourceMap};
use transform_executor::TransformExecutor;
pub mod cache;
mod host_environment;
#[cfg(feature = "__rkyv")]
mod imported_fn;
#[cfg(feature = "__rkyv")]
mod memory_interop;
pub mod plugin_module_bytes;
mod transform_executor;
pub mod wasix_runtime;
use plugin_module_bytes::PluginModuleBytes;
/**
* Creates an executor to run plugin binaries.
*/
#[cfg(feature = "__rkyv")]
pub fn create_plugin_transform_executor(
source_map: &Arc<SourceMap>,
unresolved_mark: &swc_common::Mark,
metadata_context: &Arc<TransformPluginMetadataContext>,
plugin_module: Box<dyn PluginModuleBytes>,
plugin_config: Option<serde_json::Value>,
runtime: Option<Arc<dyn wasmer_wasix::Runtime + Send + Sync>>,
) -> TransformExecutor {
TransformExecutor::new(
plugin_module,
source_map,
unresolved_mark,
metadata_context,
plugin_config,
runtime,
)
}
#[cfg(not(feature = "__rkyv"))]
pub fn create_plugin_transform_executor(
source_map: &Arc<SourceMap>,
unresolved_mark: &swc_common::Mark,
metadata_context: &Arc<TransformPluginMetadataContext>,
plugin_module: Box<dyn PluginModuleBytes>,
plugin_config: Option<serde_json::Value>,
runtime: Option<()>,
) -> TransformExecutor {
unimplemented!("Transform plugin cannot be used without serialization support")
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_plugin_runner/src/memory_interop.rs | Rust | use swc_common::plugin::serialized::{PluginSerializedBytes, VersionedSerializable};
use swc_plugin_proxy::AllocatedBytesPtr;
use wasmer::{Memory, MemoryView, StoreMut, TypedFunction, WasmPtr};
#[tracing::instrument(level = "info", skip_all)]
pub fn copy_bytes_into_host(memory: &MemoryView, bytes_ptr: i32, bytes_ptr_len: i32) -> Vec<u8> {
let ptr: WasmPtr<u8> = WasmPtr::new(bytes_ptr as _);
let values = ptr
.slice(memory, bytes_ptr_len as u32)
.expect("Should able to get a slice from memory view");
values
.read_to_vec()
.expect("Should able to read memory from given ptr")
}
/// Locate a view from given memory, write serialized bytes into.
#[tracing::instrument(level = "info", skip_all)]
pub fn write_into_memory_view<F>(
memory: &Memory,
store: &mut StoreMut,
serialized_bytes: &PluginSerializedBytes,
get_allocated_ptr: F,
) -> (u32, u32)
where
F: Fn(&mut StoreMut, usize) -> u32,
{
let serialized_len = serialized_bytes.as_ptr().1;
let ptr_start = get_allocated_ptr(store, serialized_len);
let ptr_start_size: u64 = ptr_start as u64;
// Note: it's important to get a view from memory _after_ alloc completes
let view = memory.view(store);
// [TODO]: we need wasmer@3 compatible optimization like before
// https://github.com/swc-project/swc/blob/f73f96dd94639f8b7edcdb6290653e16bf848db6/crates/swc_plugin_runner/src/memory_interop.rs#L54
view.write(ptr_start_size, serialized_bytes.as_slice())
.expect("Should able to write into memory view");
(
ptr_start,
serialized_len
.try_into()
.expect("Should be able to convert to i32"),
)
}
/// Set `return` value to pass into guest from functions returning values with
/// non-deterministic size like `Vec<Comment>`. Guest pre-allocates a struct to
/// contain ptr to the value, host in here allocates guest memory for the actual
/// value then returns its ptr with length to the preallocated struct.
#[tracing::instrument(level = "info", skip_all)]
pub fn allocate_return_values_into_guest(
memory: &Memory,
store: &mut StoreMut,
alloc_guest_memory: &TypedFunction<u32, u32>,
allocated_ret_ptr: u32,
serialized_bytes: &PluginSerializedBytes,
) {
let serialized_bytes_len: usize = serialized_bytes.as_ptr().1;
// In most cases our host-plugin trampoline works in a way that
// plugin pre-allocates
// memory before calling host imported fn. But in case of
// comments return value is Vec<Comments> which
// guest cannot predetermine size to allocate, instead
// let host allocate by calling guest's alloc via attached
// hostenvironment.
let guest_memory_ptr = alloc_guest_memory
.call(
store,
serialized_bytes_len
.try_into()
.expect("Should be able to convert size"),
)
.expect("Should able to allocate memory in the plugin");
let (allocated_ptr, allocated_ptr_len) =
write_into_memory_view(memory, store, serialized_bytes, |_, _| guest_memory_ptr);
let allocated_bytes =
VersionedSerializable::new(AllocatedBytesPtr(allocated_ptr, allocated_ptr_len));
// Retuning (allocated_ptr, len) into caller (plugin)
let comment_ptr_serialized =
PluginSerializedBytes::try_serialize(&allocated_bytes).expect("Should be serializable");
write_into_memory_view(memory, store, &comment_ptr_serialized, |_, _| {
allocated_ret_ptr
});
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_plugin_runner/src/plugin_module_bytes.rs | Rust | use anyhow::Error;
use serde::{Deserialize, Serialize};
use wasmer::{Module, Store};
use crate::wasix_runtime::new_store;
// A trait abstracts plugin's wasm compilation and instantiation.
// Depends on the caller, this could be a simple clone from existing module, or
// load from file system cache.
pub trait PluginModuleBytes {
// Returns a name to the module, typically either path to the plugin or its
// package name.
fn get_module_name(&self) -> &str;
// Returns a compiled wasmer::Module for the plugin module.
fn compile_module(&self) -> Result<(Store, Module), Error>;
}
/// A struct for the plugin contains raw bytes can be compiled into Wasm Module.
#[derive(Debug, Clone, Eq, Serialize, Deserialize, PartialEq)]
pub struct RawPluginModuleBytes {
plugin_name: String,
bytes: Vec<u8>,
}
impl PluginModuleBytes for RawPluginModuleBytes {
fn get_module_name(&self) -> &str {
&self.plugin_name
}
fn compile_module(&self) -> Result<(Store, Module), Error> {
let store = new_store();
let module = Module::new(&store, &self.bytes)?;
Ok((store, module))
}
}
impl RawPluginModuleBytes {
pub fn new(identifier: String, bytes: Vec<u8>) -> Self {
Self {
plugin_name: identifier,
bytes,
}
}
}
/// A struct for the plugin contains pre-compiled binary.
/// This is for the cases would like to reuse the compiled module, or either
/// load from FileSystemCache.
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct CompiledPluginModuleBytes {
plugin_name: String,
#[serde(skip)]
bytes: Option<wasmer::Module>,
#[serde(skip)]
store: Option<wasmer::Store>,
}
impl Eq for CompiledPluginModuleBytes {}
impl Clone for CompiledPluginModuleBytes {
fn clone(&self) -> Self {
Self {
plugin_name: self.plugin_name.clone(),
bytes: self.bytes.clone(),
store: Some(Store::new(
self.store
.as_ref()
.expect("Store should be available")
.engine()
.clone(),
)),
}
}
}
impl CompiledPluginModuleBytes {
pub fn new(identifier: String, bytes: wasmer::Module, store: wasmer::Store) -> Self {
Self {
plugin_name: identifier,
bytes: Some(bytes),
store: Some(store),
}
}
}
// Allow to `pre` compile wasm module when there is a raw bytes, want to avoid
// to skip the compilation step per each trasform.
impl From<RawPluginModuleBytes> for CompiledPluginModuleBytes {
fn from(raw: RawPluginModuleBytes) -> Self {
let (store, module) = raw.compile_module().unwrap();
Self::new(raw.plugin_name, module, store)
}
}
impl PluginModuleBytes for CompiledPluginModuleBytes {
fn get_module_name(&self) -> &str {
&self.plugin_name
}
fn compile_module(&self) -> Result<(Store, Module), Error> {
Ok((
Store::new(
self.store
.as_ref()
.expect("Store should be available")
.engine()
.clone(),
),
self.bytes
.as_ref()
.expect("Module should be available")
.clone(),
))
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_plugin_runner/src/transform_executor.rs | Rust | use std::{env, sync::Arc};
use anyhow::{anyhow, Context, Error};
use parking_lot::Mutex;
#[cfg(feature = "__rkyv")]
use swc_common::plugin::serialized::{PluginError, PluginSerializedBytes};
#[cfg(any(
feature = "plugin_transform_schema_v1",
feature = "plugin_transform_schema_vtest"
))]
use swc_common::plugin::PLUGIN_TRANSFORM_AST_SCHEMA_VERSION;
use swc_common::{
plugin::{diagnostics::PluginCorePkgDiagnostics, metadata::TransformPluginMetadataContext},
SourceMap,
};
use wasmer::{AsStoreMut, FunctionEnv, Instance, Store, TypedFunction};
use wasmer_wasix::{default_fs_backing, is_wasi_module, Runtime, WasiEnv, WasiFunctionEnv};
#[cfg(feature = "__rkyv")]
use crate::{
host_environment::BaseHostEnvironment,
imported_fn::{
build_import_object, comments::CommentHostEnvironment,
diagnostics::DiagnosticContextHostEnvironment,
metadata_context::MetadataContextHostEnvironment,
set_transform_result::TransformResultHostEnvironment, source_map::SourceMapHostEnvironment,
},
memory_interop::write_into_memory_view,
};
use crate::{plugin_module_bytes::PluginModuleBytes, wasix_runtime::build_wasi_runtime};
/// An internal state to the plugin transform.
struct PluginTransformState {
// Main transform interface plugin exports
exported_plugin_transform: TypedFunction<(u32, u32, u32, u32), u32>,
// `__free` function automatically exported via swc_plugin sdk to allow deallocation in guest
// memory space
exported_plugin_free: TypedFunction<(u32, u32), u32>,
// `__alloc` function automatically exported via swc_plugin sdk to allow allocation in guest
// memory space
exported_plugin_alloc: TypedFunction<u32, u32>,
wasi_env: Option<WasiFunctionEnv>,
instance: Instance,
store: Store,
transform_result: Arc<Mutex<Vec<u8>>>,
#[allow(unused)]
plugin_core_diag: PluginCorePkgDiagnostics,
}
#[cfg(feature = "__rkyv")]
impl PluginTransformState {
fn run(
&mut self,
program: &PluginSerializedBytes,
unresolved_mark: swc_common::Mark,
should_enable_comments_proxy: Option<bool>,
) -> Result<PluginSerializedBytes, Error> {
let memory = self.instance.exports.get_memory("memory")?;
let should_enable_comments_proxy =
u32::from(should_enable_comments_proxy.unwrap_or_default());
// Copy host's serialized bytes into guest (plugin)'s allocated memory.
let guest_program_ptr = write_into_memory_view(
memory,
&mut self.store.as_store_mut(),
program,
|s, serialized_len| {
self.exported_plugin_alloc
.call(
s,
serialized_len
.try_into()
.expect("Should able to convert size"),
)
.unwrap_or_else(|_| {
panic!(
"Should able to allocate memory for the size of {}",
serialized_len
)
})
},
);
let returned_ptr_result = self.exported_plugin_transform.call(
&mut self.store,
guest_program_ptr.0,
guest_program_ptr.1,
unresolved_mark.as_u32(),
should_enable_comments_proxy,
)?;
// Copy guest's memory into host, construct serialized struct from raw
// bytes.
let transformed_result = &(*self.transform_result.lock());
let ret = PluginSerializedBytes::from_slice(&transformed_result[..]);
let ret = if returned_ptr_result == 0 {
Ok(ret)
} else {
let err: PluginError = ret.deserialize()?.into_inner();
match err {
PluginError::SizeInteropFailure(msg) => Err(anyhow!(
"Failed to convert pointer size to calculate: {}",
msg
)),
PluginError::Deserialize(msg) | PluginError::Serialize(msg) => {
Err(anyhow!("{}", msg))
}
_ => Err(anyhow!(
"Unexpected error occurred while running plugin transform"
)),
}
};
self.exported_plugin_free.call(
&mut self.store,
guest_program_ptr.0,
guest_program_ptr.1,
)?;
// [TODO]: disabled for now as it always panic if it is being called
// inside of tokio runtime
// https://github.com/wasmerio/wasmer/discussions/3966
// [NOTE]: this is not a critical as plugin does not have things to clean up
// in most cases
if let Some(_wasi_env) = &self.wasi_env {
//wasi_env.cleanup(&mut self.store, None);
}
ret
}
/**
* Check compile-time version of AST schema between the plugin and
* the host. Returns true if it's compatible, false otherwise.
*
* Host should appropriately handle if plugin is not compatible to the
* current runtime.
*/
#[allow(unreachable_code)]
pub fn is_transform_schema_compatible(&mut self) -> Result<(), Error> {
#[cfg(any(
feature = "plugin_transform_schema_v1",
feature = "plugin_transform_schema_vtest"
))]
return {
let host_schema_version = PLUGIN_TRANSFORM_AST_SCHEMA_VERSION;
// TODO: this is incomplete
if host_schema_version >= self.plugin_core_diag.ast_schema_version {
Ok(())
} else {
anyhow::bail!(
"Plugin's AST schema version is not compatible with host's. Host: {}, Plugin: \
{}",
host_schema_version,
self.plugin_core_diag.ast_schema_version
)
}
};
#[cfg(not(all(
feature = "plugin_transform_schema_v1",
feature = "plugin_transform_schema_vtest"
)))]
anyhow::bail!(
"Plugin runner cannot detect plugin's schema version. Ensure host is compiled with \
proper versions"
)
}
}
/// A struct encapsule executing a plugin's transform.
pub struct TransformExecutor {
source_map: Arc<SourceMap>,
unresolved_mark: swc_common::Mark,
metadata_context: Arc<TransformPluginMetadataContext>,
plugin_config: Option<serde_json::Value>,
module_bytes: Box<dyn PluginModuleBytes>,
runtime: Option<Arc<dyn Runtime + Send + Sync>>,
}
#[cfg(feature = "__rkyv")]
impl TransformExecutor {
#[tracing::instrument(
level = "info",
skip(source_map, metadata_context, plugin_config, module_bytes)
)]
pub fn new(
module_bytes: Box<dyn PluginModuleBytes>,
source_map: &Arc<SourceMap>,
unresolved_mark: &swc_common::Mark,
metadata_context: &Arc<TransformPluginMetadataContext>,
plugin_config: Option<serde_json::Value>,
runtime: Option<Arc<dyn Runtime + Send + Sync>>,
) -> Self {
let runtime = if runtime.is_some() {
runtime
} else {
// https://github.com/wasmerio/wasmer/issues/4029
// prevent to wasienvbuilder invoke default PluggableRuntime::new which causes
// unexpected failure
build_wasi_runtime(None)
};
Self {
source_map: source_map.clone(),
unresolved_mark: *unresolved_mark,
metadata_context: metadata_context.clone(),
plugin_config,
module_bytes,
runtime,
}
}
// Import, export, and create memory for the plugin to communicate between host
// and guest then acquire necessary exports from the plugin.
fn setup_plugin_env_exports(&mut self) -> Result<PluginTransformState, Error> {
// First, compile plugin module bytes into wasmer::Module and get the
// corresponding store
let (mut store, module) = self.module_bytes.compile_module()?;
let context_key_buffer = Arc::new(Mutex::new(Vec::new()));
let metadata_env = FunctionEnv::new(
&mut store,
MetadataContextHostEnvironment::new(
&self.metadata_context,
&self.plugin_config,
&context_key_buffer,
),
);
let transform_result: Arc<Mutex<Vec<u8>>> = Arc::new(Mutex::new(Vec::new()));
let transform_env = FunctionEnv::new(
&mut store,
TransformResultHostEnvironment::new(&transform_result),
);
let base_env = FunctionEnv::new(&mut store, BaseHostEnvironment::new());
let comment_buffer = Arc::new(Mutex::new(Vec::new()));
let comments_env =
FunctionEnv::new(&mut store, CommentHostEnvironment::new(&comment_buffer));
let source_map_buffer = Arc::new(Mutex::new(Vec::new()));
let source_map = Arc::new(Mutex::new(self.source_map.clone()));
let source_map_host_env = FunctionEnv::new(
&mut store,
SourceMapHostEnvironment::new(&source_map, &source_map_buffer),
);
let diagnostics_buffer: Arc<Mutex<Vec<u8>>> = Arc::new(Mutex::new(Vec::new()));
let diagnostics_env = FunctionEnv::new(
&mut store,
DiagnosticContextHostEnvironment::new(&diagnostics_buffer),
);
let mut import_object = build_import_object(
&mut store,
&metadata_env,
&transform_env,
&base_env,
&comments_env,
&source_map_host_env,
&diagnostics_env,
);
// Plugin binary can be either wasm32-wasi or wasm32-unknown-unknown.
// Wasi specific env need to be initialized if given module targets wasm32-wasi.
// TODO: wasm host native runtime throws 'Memory should be set on `WasiEnv`
// first'
let (instance, wasi_env) = if is_wasi_module(&module) {
let builder = WasiEnv::builder(self.module_bytes.get_module_name());
let builder = if let Some(runtime) = &self.runtime {
builder.runtime(runtime.clone())
} else {
builder
};
// Implicitly enable filesystem access for the wasi plugin to cwd.
//
// This allows wasi plugin can read arbitary data (i.e node_modules) or produce
// output for post process (i.e .lcov coverage data) directly.
//
// TODO: this is not finalized decision
// - should we support this?
// - can we limit to allowlisted input / output only?
// - should there be a top-level config from .swcrc to manually override this?
let wasi_env_builder = if let Ok(cwd) = env::current_dir() {
builder
.fs(default_fs_backing())
.map_dirs(vec![("/cwd".to_string(), cwd)].drain(..))?
} else {
builder
};
//create the `WasiEnv`
let mut wasi_env = wasi_env_builder.finalize(&mut store)?;
// Then, we get the import object related to our WASI,
// overwrite into imported_object
// and attach it to the Wasm instance.
let wasi_env_import_object = wasi_env.import_object(&mut store, &module)?;
import_object.extend(&wasi_env_import_object);
let instance = Instance::new(&mut store, &module, &import_object)?;
wasi_env.initialize(&mut store, instance.clone())?;
(instance, Some(wasi_env))
} else {
(Instance::new(&mut store, &module, &import_object)?, None)
};
// Attach the memory export
let memory = instance.exports.get_memory("memory")?;
import_object.define("env", "memory", memory.clone());
let alloc = instance.exports.get_typed_function(&store, "__alloc")?;
// Unlike wasmer@2, have to manually `import` memory / necessary functions from
// the guest into env.
metadata_env.as_mut(&mut store).memory = Some(memory.clone());
metadata_env.as_mut(&mut store).alloc_guest_memory = Some(alloc.clone());
transform_env.as_mut(&mut store).memory = Some(memory.clone());
base_env.as_mut(&mut store).memory = Some(memory.clone());
comments_env.as_mut(&mut store).memory = Some(memory.clone());
comments_env.as_mut(&mut store).alloc_guest_memory = Some(alloc.clone());
source_map_host_env.as_mut(&mut store).memory = Some(memory.clone());
source_map_host_env.as_mut(&mut store).alloc_guest_memory = Some(alloc);
diagnostics_env.as_mut(&mut store).memory = Some(memory.clone());
// As soon as instance is ready, host calls a fn to read plugin's swc_core pkg
// diagnostics as `handshake`. Once read those values will be available across
// whole plugin transform execution.
// IMPORTANT NOTE
// Note this is `handshake`, which we expect to success ALL TIME. Do not try to
// expand `PluginCorePkgDiagnostics` as it'll cause deserialization failure
// until we have forward-compat schema changes.
instance
.exports
.get_typed_function::<(), u32>(&store, "__get_transform_plugin_core_pkg_diag")?
.call(&mut store)?;
let diag_result: PluginCorePkgDiagnostics =
PluginSerializedBytes::from_slice(&(&(*diagnostics_buffer.lock()))[..])
.deserialize()?
.into_inner();
// Main transform interface plugin exports
let exported_plugin_transform: TypedFunction<(u32, u32, u32, u32), u32> = instance
.exports
.get_typed_function(&store, "__transform_plugin_process_impl")?;
// `__free` function automatically exported via swc_plugin sdk to allow
// deallocation in guest memory space
let exported_plugin_free: TypedFunction<(u32, u32), u32> =
instance.exports.get_typed_function(&store, "__free")?;
// `__alloc` function automatically exported via swc_plugin sdk to allow
// allocation in guest memory space
let exported_plugin_alloc: TypedFunction<u32, u32> =
instance.exports.get_typed_function(&store, "__alloc")?;
Ok(PluginTransformState {
exported_plugin_transform,
exported_plugin_free,
exported_plugin_alloc,
instance,
store,
wasi_env,
transform_result,
plugin_core_diag: diag_result,
})
}
#[tracing::instrument(level = "info", skip_all)]
pub fn transform(
&mut self,
program: &PluginSerializedBytes,
should_enable_comments_proxy: Option<bool>,
) -> Result<PluginSerializedBytes, Error> {
let mut transform_state = self.setup_plugin_env_exports()?;
transform_state.is_transform_schema_compatible()?;
transform_state
.run(program, self.unresolved_mark, should_enable_comments_proxy)
.with_context(|| {
format!(
"failed to run Wasm plugin transform. Please ensure the version of `swc_core` \
used by the plugin is compatible with the host runtime. See the \
documentation for compatibility information. If you are an author of the \
plugin, please update `swc_core` to the compatible version.
Note that if you want to use the os features like filesystem, you need to use \
`wasi`. Wasm itself does not have concept of filesystem.
https://swc.rs/docs/plugin/selecting-swc-core
See https://plugins.swc.rs/versions/from-plugin-runner/{PKG_VERSION} for the list of the compatible versions.
Build info:
Date: {BUILD_DATE}
Timestamp: {BUILD_TIMESTAMP}
Version info:
swc_plugin_runner: {PKG_VERSION}
Dependencies: {PKG_DEPS}
"
)
})
}
}
const BUILD_DATE: &str = env!("VERGEN_BUILD_DATE");
const BUILD_TIMESTAMP: &str = env!("VERGEN_BUILD_TIMESTAMP");
const PKG_VERSION: &str = env!("CARGO_PKG_VERSION");
const PKG_DEPS: &str = env!("VERGEN_CARGO_DEPENDENCIES");
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_plugin_runner/src/wasix_runtime.rs | Rust | #![allow(unused)]
use std::{path::PathBuf, sync::Arc};
use parking_lot::Mutex;
use swc_common::sync::Lazy;
use wasmer::Store;
use wasmer_wasix::Runtime;
/// A shared instance to plugin runtime engine.
/// ref: https://github.com/wasmerio/wasmer/issues/3793#issuecomment-1607117480
static ENGINE: Lazy<Mutex<wasmer::Engine>> = Lazy::new(|| {
// Use empty enumset to disable simd.
use enumset::EnumSet;
use wasmer::{
sys::{BaseTunables, EngineBuilder},
CompilerConfig, Target, Triple,
};
let mut set = EnumSet::new();
// [TODO]: Should we use is_x86_feature_detected! macro instead?
#[cfg(target_arch = "x86_64")]
set.insert(wasmer::CpuFeature::SSE2);
let target = Target::new(Triple::host(), set);
let config = wasmer_compiler_cranelift::Cranelift::default();
let mut engine = EngineBuilder::new(Box::new(config) as Box<dyn CompilerConfig>)
.set_target(Some(target))
.engine();
let tunables = BaseTunables::for_target(engine.target());
engine.set_tunables(tunables);
parking_lot::Mutex::new(wasmer::Engine::from(engine))
});
/// Dummy http client for wasix runtime to avoid instantiation failure for the
/// default pluggable runtime. We don't support network in the host runtime
/// anyway (we init vnet instead), and for the default runtime mostly it's for
/// the wapm registry which is redundant for the plugin.
#[derive(Debug)]
struct StubHttpClient;
impl wasmer_wasix::http::HttpClient for StubHttpClient {
fn request(
&self,
_request: wasmer_wasix::http::HttpRequest,
) -> futures::future::BoxFuture<'_, Result<wasmer_wasix::http::HttpResponse, anyhow::Error>>
{
unimplemented!()
}
}
/// Construct a runtime for the wasix engine depends on the compilation
/// features.
///
/// This is mainly for the case if a host already sets up its runtime, which
/// makes wasix initialization fails due to conflicting runtime. When specified,
/// instead of using default runtime it'll try to use shared one.
pub fn build_wasi_runtime(
_fs_cache_path: Option<PathBuf>,
) -> Option<Arc<dyn Runtime + Send + Sync>> {
use wasmer_wasix::{
runtime::{
module_cache::{ModuleCache, SharedCache},
package_loader::UnsupportedPackageLoader,
resolver::MultiSource,
task_manager::tokio::TokioTaskManager,
},
virtual_net, PluggableRuntime,
};
let cache =
SharedCache::default().with_fallback(wasmer_wasix::runtime::module_cache::in_memory());
let dummy_loader = UnsupportedPackageLoader;
let rt = PluggableRuntime {
rt: Arc::new(TokioTaskManager::default()),
networking: Arc::new(virtual_net::UnsupportedVirtualNetworking::default()),
engine: Some(ENGINE.lock().clone()),
tty: None,
source: Arc::new(MultiSource::new()),
module_cache: Arc::new(cache),
http_client: None,
package_loader: Arc::new(dummy_loader),
};
Some(Arc::new(rt))
}
/// Creates an instnace of [Store] with custom engine instead of default one to
/// disable simd for certain platform targets
#[cfg(not(target_arch = "wasm32"))]
#[allow(unused_mut)]
pub(crate) fn new_store() -> Store {
let engine = ENGINE.lock().clone();
Store::new(engine)
}
#[cfg(target_arch = "wasm32")]
pub(crate) fn new_store() -> Store {
Store::default()
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_plugin_runner/tests/css-plugins/swc_noop_plugin/src/lib.rs | Rust | use swc_core::{
css::ast::Stylesheet,
plugin::{css_plugin_transform, metadata::TransformPluginProgramMetadata},
};
#[css_plugin_transform]
pub fn process(program: Stylesheet, metadata: TransformPluginProgramMetadata) -> Stylesheet {
program
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_plugin_runner/tests/css_rkyv.rs | Rust | #![cfg_attr(not(feature = "__rkyv"), allow(warnings))]
use std::{
env, fs,
path::{Path, PathBuf},
process::{Command, Stdio},
sync::Arc,
};
use anyhow::{anyhow, Error};
use rustc_hash::FxHashMap;
use serde_json::json;
#[cfg(feature = "__rkyv")]
use swc_common::plugin::serialized::PluginSerializedBytes;
use swc_common::{plugin::metadata::TransformPluginMetadataContext, sync::Lazy, FileName, Mark};
use testing::CARGO_TARGET_DIR;
use tracing::info;
/// Returns the path to the built plugin
fn build_plugin(dir: &Path) -> Result<PathBuf, Error> {
{
let mut cmd = Command::new("cargo");
cmd.env("CARGO_TARGET_DIR", &*CARGO_TARGET_DIR);
cmd.current_dir(dir);
cmd.args(["build", "--target=wasm32-wasi", "--release"])
.stderr(Stdio::inherit());
cmd.output()?;
if !cmd
.status()
.expect("Exit code should be available")
.success()
{
return Err(anyhow!("Failed to build plugin"));
}
}
for entry in fs::read_dir(CARGO_TARGET_DIR.join("wasm32-wasi").join("release"))? {
let entry = entry?;
let s = entry.file_name().to_string_lossy().into_owned();
if s.eq_ignore_ascii_case("swc_noop_plugin.wasm") {
return Ok(entry.path());
}
}
Err(anyhow!("Could not find built plugin"))
}
#[cfg(feature = "__rkyv")]
static PLUGIN_BYTES: Lazy<swc_plugin_runner::plugin_module_bytes::CompiledPluginModuleBytes> =
Lazy::new(|| {
let path = build_plugin(
&PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap())
.join("tests")
.join("css-plugins")
.join("swc_noop_plugin"),
)
.unwrap();
let raw_module_bytes = std::fs::read(&path).expect("Should able to read plugin bytes");
let store = wasmer::Store::default();
let module = wasmer::Module::new(&store, raw_module_bytes).unwrap();
swc_plugin_runner::plugin_module_bytes::CompiledPluginModuleBytes::new(
path.as_os_str()
.to_str()
.expect("Should able to get path")
.to_string(),
module,
store,
)
});
#[cfg(feature = "__rkyv")]
#[testing::fixture("../swc_css_parser/tests/fixture/**/input.css")]
fn invoke(input: PathBuf) {
use swc_css_ast::Stylesheet;
tokio::runtime::Runtime::new().unwrap().block_on(async {
// run single plugin
testing::run_test(false, |cm, _handler| {
let fm = cm.new_source_file(FileName::Anon.into(), "console.log(foo)".into());
let parsed: Stylesheet =
swc_css_parser::parse_file(&fm, None, Default::default(), &mut Vec::new()).unwrap();
let program = PluginSerializedBytes::try_serialize(
&swc_common::plugin::serialized::VersionedSerializable::new(parsed.clone()),
)
.expect("Should serializable");
let experimental_metadata: FxHashMap<String, String> = [
(
"TestExperimental".to_string(),
"ExperimentalValue".to_string(),
),
("OtherTest".to_string(), "OtherVal".to_string()),
]
.into_iter()
.collect();
let mut plugin_transform_executor = swc_plugin_runner::create_plugin_transform_executor(
&cm,
&Mark::new(),
&Arc::new(TransformPluginMetadataContext::new(
None,
"development".to_string(),
Some(experimental_metadata),
)),
Box::new(PLUGIN_BYTES.clone()),
Some(json!({ "pluginConfig": "testValue" })),
None,
);
info!("Created transform executor");
let program_bytes = plugin_transform_executor
.transform(&program, Some(false))
.expect("Plugin should apply transform");
let program: Stylesheet = program_bytes
.deserialize()
.expect("Should able to deserialize")
.into_inner();
assert_eq!(parsed, program);
Ok(())
})
.expect("Should able to run single plugin transform");
// Run multiple plugins.
testing::run_test(false, |cm, _handler| {
let fm = cm.new_source_file(FileName::Anon.into(), "console.log(foo)".into());
let parsed: Stylesheet =
swc_css_parser::parse_file(&fm, None, Default::default(), &mut Vec::new()).unwrap();
let mut serialized_program = PluginSerializedBytes::try_serialize(
&swc_common::plugin::serialized::VersionedSerializable::new(parsed.clone()),
)
.expect("Should serializable");
let experimental_metadata: FxHashMap<String, String> = [
(
"TestExperimental".to_string(),
"ExperimentalValue".to_string(),
),
("OtherTest".to_string(), "OtherVal".to_string()),
]
.into_iter()
.collect();
let mut plugin_transform_executor = swc_plugin_runner::create_plugin_transform_executor(
&cm,
&Mark::new(),
&Arc::new(TransformPluginMetadataContext::new(
None,
"development".to_string(),
Some(experimental_metadata.clone()),
)),
Box::new(PLUGIN_BYTES.clone()),
Some(json!({ "pluginConfig": "testValue" })),
None,
);
serialized_program = plugin_transform_executor
.transform(&serialized_program, Some(false))
.expect("Plugin should apply transform");
// TODO: we'll need to apply 2 different plugins
let mut plugin_transform_executor = swc_plugin_runner::create_plugin_transform_executor(
&cm,
&Mark::new(),
&Arc::new(TransformPluginMetadataContext::new(
None,
"development".to_string(),
Some(experimental_metadata),
)),
Box::new(PLUGIN_BYTES.clone()),
Some(json!({ "pluginConfig": "testValue" })),
None,
);
serialized_program = plugin_transform_executor
.transform(&serialized_program, Some(false))
.expect("Plugin should apply transform");
let program: Stylesheet = serialized_program
.deserialize()
.expect("Should able to deserialize")
.into_inner();
assert_eq!(parsed, program);
Ok(())
})
.expect("Should able to run multiple plugins transform");
});
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_plugin_runner/tests/ecma_integration.rs | Rust | #![cfg_attr(not(feature = "__rkyv"), allow(warnings))]
use std::{
env, fs,
path::{Path, PathBuf},
process::{Command, Stdio},
sync::Arc,
};
use anyhow::{anyhow, Error};
use rustc_hash::FxHashMap;
use serde_json::json;
#[cfg(feature = "__rkyv")]
use swc_common::plugin::serialized::PluginSerializedBytes;
use swc_common::{
errors::HANDLER, plugin::metadata::TransformPluginMetadataContext, sync::Lazy, FileName, Mark,
};
use swc_ecma_ast::{CallExpr, Callee, EsVersion, Expr, Lit, MemberExpr, Program, Str};
use swc_ecma_parser::{parse_file_as_program, Syntax};
use swc_ecma_visit::{Visit, VisitWith};
use testing::CARGO_TARGET_DIR;
/// Returns the path to the built plugin
fn build_plugin(dir: &Path) -> Result<PathBuf, Error> {
{
let mut cmd = Command::new("cargo");
cmd.env("CARGO_TARGET_DIR", &*CARGO_TARGET_DIR);
cmd.current_dir(dir);
cmd.args(["build", "--target=wasm32-wasi"])
.stderr(Stdio::inherit());
cmd.output()?;
if !cmd
.status()
.expect("Exit code should be available")
.success()
{
return Err(anyhow!("Failed to build plugin"));
}
}
for entry in fs::read_dir(CARGO_TARGET_DIR.join("wasm32-wasi").join("debug"))? {
let entry = entry?;
let s = entry.file_name().to_string_lossy().into_owned();
if s.eq_ignore_ascii_case("swc_internal_plugin.wasm") {
return Ok(entry.path());
}
}
Err(anyhow!("Could not find built plugin"))
}
struct TestVisitor {
pub plugin_transform_found: bool,
}
impl Visit for TestVisitor {
fn visit_call_expr(&mut self, call: &CallExpr) {
if let Callee::Expr(expr) = &call.callee {
if let Expr::Member(MemberExpr { obj, .. }) = &**expr {
if let Expr::Ident(ident) = &**obj {
if ident.sym == *"console" {
let args = &*(call.args[0].expr);
if let Expr::Lit(Lit::Str(Str { value, .. })) = args {
self.plugin_transform_found = value == "changed_via_plugin";
}
}
}
}
}
}
}
#[cfg(feature = "__rkyv")]
static PLUGIN_BYTES: Lazy<swc_plugin_runner::plugin_module_bytes::CompiledPluginModuleBytes> =
Lazy::new(|| {
let path = build_plugin(
&PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap())
.join("tests")
.join("fixture")
.join("swc_internal_plugin"),
)
.unwrap();
let raw_module_bytes = std::fs::read(&path).expect("Should able to read plugin bytes");
let store = wasmer::Store::default();
let module = wasmer::Module::new(&store, raw_module_bytes).unwrap();
swc_plugin_runner::plugin_module_bytes::CompiledPluginModuleBytes::new(
path.as_os_str()
.to_str()
.expect("Should able to get path")
.to_string(),
module,
store,
)
});
#[cfg(feature = "__rkyv")]
#[test]
fn internal() {
use swc_common::plugin::serialized::VersionedSerializable;
tokio::runtime::Runtime::new().unwrap().block_on(async {
// run single plugin
testing::run_test(false, |cm, _handler| {
eprint!("First run start");
let fm = cm.new_source_file(FileName::Anon.into(), "console.log(foo)".into());
let program = parse_file_as_program(
&fm,
Syntax::Es(Default::default()),
EsVersion::latest(),
None,
&mut Vec::new(),
)
.unwrap();
let program =
PluginSerializedBytes::try_serialize(&VersionedSerializable::new(program))
.expect("Should serializable");
let experimental_metadata: FxHashMap<String, String> = [
(
"TestExperimental".to_string(),
"ExperimentalValue".to_string(),
),
("OtherTest".to_string(), "OtherVal".to_string()),
]
.into_iter()
.collect();
let mut plugin_transform_executor = swc_plugin_runner::create_plugin_transform_executor(
&cm,
&Mark::new(),
&Arc::new(TransformPluginMetadataContext::new(
None,
"development".to_string(),
Some(experimental_metadata),
)),
Box::new(PLUGIN_BYTES.clone()),
Some(json!({ "pluginConfig": "testValue" })),
None,
);
/* [TODO]: reenable this later
assert!(!plugin_transform_executor
.plugin_core_diag
.pkg_version
.is_empty());
*/
let program_bytes = plugin_transform_executor
.transform(&program, Some(false))
.expect("Plugin should apply transform");
let program: Program = program_bytes
.deserialize()
.expect("Should able to deserialize")
.into_inner();
eprintln!("First run retured");
let mut visitor = TestVisitor {
plugin_transform_found: false,
};
program.visit_with(&mut visitor);
visitor
.plugin_transform_found
.then_some(visitor.plugin_transform_found)
.ok_or(())
})
.expect("Should able to run single plugin transform");
// run single plugin with handler
testing::run_test2(false, |cm, handler| {
eprintln!("Second run start");
let fm = cm.new_source_file(FileName::Anon.into(), "console.log(foo)".into());
let program = parse_file_as_program(
&fm,
Syntax::Es(Default::default()),
EsVersion::latest(),
None,
&mut Vec::new(),
)
.unwrap();
let program =
PluginSerializedBytes::try_serialize(&VersionedSerializable::new(program))
.expect("Should serializable");
let experimental_metadata: FxHashMap<String, String> = [
(
"TestExperimental".to_string(),
"ExperimentalValue".to_string(),
),
("OtherTest".to_string(), "OtherVal".to_string()),
]
.into_iter()
.collect();
let _res = HANDLER.set(&handler, || {
let mut plugin_transform_executor =
swc_plugin_runner::create_plugin_transform_executor(
&cm,
&Mark::new(),
&Arc::new(TransformPluginMetadataContext::new(
None,
"development".to_string(),
Some(experimental_metadata),
)),
Box::new(PLUGIN_BYTES.clone()),
Some(json!({ "pluginConfig": "testValue" })),
None,
);
plugin_transform_executor
.transform(&program, Some(false))
.expect("Plugin should apply transform")
});
eprintln!("Second run retured");
Ok(())
})
.expect("Should able to run single plugin transform with handler");
});
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_plugin_runner/tests/ecma_rkyv.rs | Rust | #![cfg_attr(not(feature = "__rkyv"), allow(warnings))]
use std::{
env, fs,
path::{Path, PathBuf},
process::{Command, Stdio},
sync::Arc,
};
use anyhow::{anyhow, Error};
use rustc_hash::FxHashMap;
use serde_json::json;
#[cfg(feature = "__rkyv")]
use swc_common::plugin::serialized::PluginSerializedBytes;
use swc_common::{plugin::metadata::TransformPluginMetadataContext, sync::Lazy, FileName, Mark};
use swc_ecma_ast::{EsVersion, Program};
use swc_ecma_parser::{parse_file_as_program, Syntax, TsSyntax};
use testing::CARGO_TARGET_DIR;
use tracing::info;
/// Returns the path to the built plugin
fn build_plugin(dir: &Path) -> Result<PathBuf, Error> {
{
let mut cmd = Command::new("cargo");
cmd.env("CARGO_TARGET_DIR", &*CARGO_TARGET_DIR);
cmd.current_dir(dir);
cmd.args(["build", "--target=wasm32-wasi", "--release"])
.stderr(Stdio::inherit());
cmd.output()?;
if !cmd
.status()
.expect("Exit code should be available")
.success()
{
return Err(anyhow!("Failed to build plugin"));
}
}
for entry in fs::read_dir(CARGO_TARGET_DIR.join("wasm32-wasi").join("release"))? {
let entry = entry?;
let s = entry.file_name().to_string_lossy().into_owned();
if s.eq_ignore_ascii_case("swc_noop_plugin.wasm") {
return Ok(entry.path());
}
}
Err(anyhow!("Could not find built plugin"))
}
#[cfg(feature = "__rkyv")]
static PLUGIN_BYTES: Lazy<swc_plugin_runner::plugin_module_bytes::CompiledPluginModuleBytes> =
Lazy::new(|| {
let path = build_plugin(
&PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap())
.join("tests")
.join("fixture")
.join("swc_noop_plugin"),
)
.unwrap();
let raw_module_bytes = std::fs::read(&path).expect("Should able to read plugin bytes");
let store = wasmer::Store::default();
let module = wasmer::Module::new(&store, raw_module_bytes).unwrap();
swc_plugin_runner::plugin_module_bytes::CompiledPluginModuleBytes::new(
path.as_os_str()
.to_str()
.expect("Should able to get path")
.to_string(),
module,
store,
)
});
#[cfg(feature = "__rkyv")]
#[testing::fixture("../swc_ecma_parser/tests/tsc/*.ts")]
#[testing::fixture("../swc_ecma_parser/tests/tsc/*.tsx")]
fn internal(input: PathBuf) {
// run single plugin
tokio::runtime::Runtime::new().unwrap().block_on(async {
testing::run_test(false, |cm, _handler| {
let fm = cm.new_source_file(FileName::Anon.into(), "console.log(foo)".into());
let parsed = parse_file_as_program(
&fm,
Syntax::Typescript(TsSyntax {
tsx: input.to_string_lossy().ends_with(".tsx"),
..Default::default()
}),
EsVersion::latest(),
None,
&mut Vec::new(),
)
.unwrap();
let program = PluginSerializedBytes::try_serialize(
&swc_common::plugin::serialized::VersionedSerializable::new(parsed.clone()),
)
.expect("Should serializable");
let experimental_metadata: FxHashMap<String, String> = [
(
"TestExperimental".to_string(),
"ExperimentalValue".to_string(),
),
("OtherTest".to_string(), "OtherVal".to_string()),
]
.into_iter()
.collect();
let mut plugin_transform_executor = swc_plugin_runner::create_plugin_transform_executor(
&cm,
&Mark::new(),
&Arc::new(TransformPluginMetadataContext::new(
None,
"development".to_string(),
Some(experimental_metadata),
)),
Box::new(PLUGIN_BYTES.clone()),
Some(json!({ "pluginConfig": "testValue" })),
None,
);
info!("Created transform executor");
let program_bytes = plugin_transform_executor
.transform(&program, Some(false))
.expect("Plugin should apply transform");
let program: Program = program_bytes
.deserialize()
.expect("Should able to deserialize")
.into_inner();
assert_eq!(parsed, program);
Ok(())
})
.expect("Should able to run single plugin transform");
// Run multiple plugins.
testing::run_test(false, |cm, _handler| {
let fm = cm.new_source_file(FileName::Anon.into(), "console.log(foo)".into());
let parsed = parse_file_as_program(
&fm,
Syntax::Es(Default::default()),
EsVersion::latest(),
None,
&mut Vec::new(),
)
.unwrap();
let mut serialized_program = PluginSerializedBytes::try_serialize(
&swc_common::plugin::serialized::VersionedSerializable::new(parsed.clone()),
)
.expect("Should serializable");
let experimental_metadata: FxHashMap<String, String> = [
(
"TestExperimental".to_string(),
"ExperimentalValue".to_string(),
),
("OtherTest".to_string(), "OtherVal".to_string()),
]
.into_iter()
.collect();
let mut plugin_transform_executor = swc_plugin_runner::create_plugin_transform_executor(
&cm,
&Mark::new(),
&Arc::new(TransformPluginMetadataContext::new(
None,
"development".to_string(),
Some(experimental_metadata.clone()),
)),
Box::new(PLUGIN_BYTES.clone()),
Some(json!({ "pluginConfig": "testValue" })),
None,
);
serialized_program = plugin_transform_executor
.transform(&serialized_program, Some(false))
.expect("Plugin should apply transform");
// TODO: we'll need to apply 2 different plugins
let mut plugin_transform_executor = swc_plugin_runner::create_plugin_transform_executor(
&cm,
&Mark::new(),
&Arc::new(TransformPluginMetadataContext::new(
None,
"development".to_string(),
Some(experimental_metadata),
)),
Box::new(PLUGIN_BYTES.clone()),
Some(json!({ "pluginConfig": "testValue" })),
None,
);
serialized_program = plugin_transform_executor
.transform(&serialized_program, Some(false))
.expect("Plugin should apply transform");
let program: Program = serialized_program
.deserialize()
.expect("Should able to deserialize")
.into_inner();
assert_eq!(parsed, program);
Ok(())
})
.expect("Should able to run multiple plugins transform");
});
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_plugin_runner/tests/fixture/issue_6404/src/lib.rs | Rust | use swc_core::{
common::{BytePos, SourceMapper, Span, SyntaxContext},
ecma::ast::*,
plugin::{metadata::TransformPluginProgramMetadata, plugin_transform},
};
#[plugin_transform]
pub fn process_transform(program: Program, metadata: TransformPluginProgramMetadata) -> Program {
for i in 1..5 {
let j: u32 = i;
// println!("i {} j {}", i, j);
let res = metadata.source_map.span_to_snippet(Span::new(BytePos(j), BytePos(j + 10000000)));
// let _ = dbg!(res);
}
program
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_plugin_runner/tests/fixture/swc_internal_plugin/src/lib.rs | Rust | use swc_core::{
common::{SourceMapper, DUMMY_SP},
ecma::{ast::*, atoms::*, visit::*},
plugin::{
errors::HANDLER,
metadata::{TransformPluginMetadataContextKind, TransformPluginProgramMetadata},
plugin_transform,
},
quote,
};
struct ConsoleOutputReplacer {
metadata: TransformPluginProgramMetadata,
}
/// An example plugin replaces any `console.log(${text})` into
/// `console.log('changed_via_plugin')`.
impl VisitMut for ConsoleOutputReplacer {
fn visit_mut_call_expr(&mut self, call: &mut CallExpr) {
if let Callee::Expr(expr) = &call.callee {
if let Expr::Member(MemberExpr { obj, .. }) = &**expr {
if let Expr::Ident(ident) = &**obj {
println!(
"lookup_char_pos {:#?}",
self.metadata.source_map.lookup_char_pos(ident.span.lo)
);
if ident.sym == *"console" {
call.args[0].expr = Lit::Str(Str {
span: DUMMY_SP,
value: Atom::from("changed_via_plugin"),
raw: Some(Atom::from("\"changed_via_plugin\"")),
})
.into();
}
}
}
}
}
}
/// An example plugin function with macro support.
/// `plugin_transform` macro interop pointers into deserialized structs, as well
/// as returning ptr back to host.
///
/// It is possible to opt out from macro by writing transform fn manually via
/// `__transform_plugin_process_impl(
/// 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: i32) ->
/// i32 /* 0 for success, fail otherwise.
/// Note this is only for internal pointer interop result,
/// not actual transform result */
///
/// if plugin need to handle low-level ptr directly. However, there are
/// important steps manually need to be performed like sending transformed
/// results back to host. Refer swc_plugin_macro how does it work internally.
#[plugin_transform]
pub fn process(mut program: Program, metadata: TransformPluginProgramMetadata) -> Program {
dbg!();
HANDLER.with(|handler| {
handler
.struct_span_err(DUMMY_SP, "Test diagnostics from plugin")
.emit();
});
dbg!();
let _stmt = quote!(
"const $name = 4;" as Stmt,
name = Ident::new_no_ctxt("ref".into(), DUMMY_SP)
);
dbg!();
let filename = metadata
.get_context(&TransformPluginMetadataContextKind::Filename)
.expect("Filename should exists");
dbg!();
let env = metadata
.get_context(&TransformPluginMetadataContextKind::Env)
.expect("Metadata should exists");
dbg!();
if env != "development" {
panic!("Env should be development");
}
dbg!();
let experimental_value = metadata
.get_experimental_context("TestExperimental")
.expect("Experimental metadata should exist");
// Let test fail if metadata is not correctly passed
if &experimental_value != "ExperimentalValue" {
panic!("Experimental metadata should be `ExperimentalValue`");
}
dbg!();
let experimental_value = metadata
.get_experimental_context("OtherTest")
.expect("Experimental metadata 'othertest' should exist");
dbg!();
if &experimental_value != "OtherVal" {
panic!("Experimental metadata 'othertest' should be `OtherVal`");
}
dbg!();
let nonexistent_value = metadata.get_experimental_context("Nonexistent");
dbg!();
if nonexistent_value.is_some() {
panic!("Experimental metadata 'nonexistent' should not exist");
}
dbg!();
let plugin_config = metadata
.get_transform_plugin_config()
.expect("Plugin config should exist");
if plugin_config != "{\"pluginConfig\":\"testValue\"}" {
panic!("Plugin config should be testValue");
}
dbg!();
program.visit_mut_with(&mut ConsoleOutputReplacer { metadata });
program
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_plugin_runner/tests/fixture/swc_noop_plugin/src/lib.rs | Rust | use swc_core::{
ecma::ast::*,
plugin::{metadata::TransformPluginProgramMetadata, plugin_transform},
};
#[plugin_transform]
pub fn process(program: Program, _metadata: TransformPluginProgramMetadata) -> Program {
program
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_plugin_runner/tests/issues.rs | Rust | #![cfg_attr(not(feature = "__rkyv"), allow(warnings))]
use std::{
env, fs,
path::{Path, PathBuf},
process::{Command, Stdio},
sync::Arc,
};
use anyhow::{anyhow, Error};
use rustc_hash::FxHashMap;
use serde_json::json;
#[cfg(feature = "__rkyv")]
use swc_common::plugin::serialized::PluginSerializedBytes;
use swc_common::{plugin::metadata::TransformPluginMetadataContext, Mark};
use swc_ecma_ast::{EsVersion, Program};
use swc_ecma_parser::{parse_file_as_program, Syntax};
use testing::CARGO_TARGET_DIR;
/// Returns the path to the built plugin
fn build_plugin(dir: &Path, crate_name: &str) -> Result<PathBuf, Error> {
{
let mut cmd = Command::new("cargo");
cmd.env("CARGO_TARGET_DIR", &*CARGO_TARGET_DIR);
cmd.current_dir(dir);
cmd.args(["build", "--release", "--target=wasm32-wasi"])
.stderr(Stdio::inherit());
cmd.output()?;
if !cmd
.status()
.expect("Exit code should be available")
.success()
{
return Err(anyhow!("Failed to build plugin"));
}
}
for entry in fs::read_dir(CARGO_TARGET_DIR.join("wasm32-wasi").join("release"))? {
let entry = entry?;
let s = entry.file_name().to_string_lossy().into_owned();
if s.eq_ignore_ascii_case(&format!("{}.wasm", crate_name)) {
return Ok(entry.path());
}
}
Err(anyhow!("Could not find built plugin"))
}
#[cfg(feature = "__rkyv")]
#[test]
fn issue_6404() -> Result<(), Error> {
use swc_common::plugin::serialized::VersionedSerializable;
let plugin_path = build_plugin(
&PathBuf::from(env::var("CARGO_MANIFEST_DIR")?)
.join("tests")
.join("fixture")
.join("issue_6404"),
"swc_issue_6404",
)?;
tokio::runtime::Runtime::new().unwrap().block_on(async {
dbg!("Built!");
// run single plugin
testing::run_test(false, |cm, _handler| {
let fm = cm
.load_file("../swc_ecma_minifier/benches/full/typescript.js".as_ref())
.unwrap();
let program = parse_file_as_program(
&fm,
Syntax::Es(Default::default()),
EsVersion::latest(),
None,
&mut Vec::new(),
)
.unwrap();
let program =
PluginSerializedBytes::try_serialize(&VersionedSerializable::new(program))
.expect("Should serializable");
let experimental_metadata: FxHashMap<String, String> = [
(
"TestExperimental".to_string(),
"ExperimentalValue".to_string(),
),
("OtherTest".to_string(), "OtherVal".to_string()),
]
.into_iter()
.collect();
let raw_module_bytes =
std::fs::read(&plugin_path).expect("Should able to read plugin bytes");
let store = wasmer::Store::default();
let module = wasmer::Module::new(&store, raw_module_bytes).unwrap();
let plugin_module =
swc_plugin_runner::plugin_module_bytes::CompiledPluginModuleBytes::new(
plugin_path
.as_os_str()
.to_str()
.expect("Should able to get path")
.to_string(),
module,
store,
);
let mut plugin_transform_executor = swc_plugin_runner::create_plugin_transform_executor(
&cm,
&Mark::new(),
&Arc::new(TransformPluginMetadataContext::new(
None,
"development".to_string(),
Some(experimental_metadata),
)),
Box::new(plugin_module),
Some(json!({ "pluginConfig": "testValue" })),
None,
);
/* [TODO]: reenable this test
assert!(!plugin_transform_executor
.plugin_core_diag
.pkg_version
.is_empty());
*/
let program_bytes = plugin_transform_executor
.transform(&program, Some(false))
.expect("Plugin should apply transform");
let _: Program = program_bytes
.deserialize()
.expect("Should able to deserialize")
.into_inner();
Ok(())
})
.expect("Should able to run single plugin transform");
});
Ok(())
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_plugin_testing/src/lib.rs | Rust | willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | ||
crates/swc_timer/src/lib.rs | Rust | #[doc(hidden)]
pub extern crate tracing;
use tracing::{info, span::EnteredSpan};
/// Prints time elapsed since `start` when dropped.
///
/// See [timer] for usages.
pub struct Timer {
#[cfg(not(target_arch = "wasm32"))]
_span: EnteredSpan,
#[cfg(not(target_arch = "wasm32"))]
start: std::time::Instant,
}
impl Timer {
/// Don't use this directly. Use [timer] instead.
pub fn new(_span: EnteredSpan) -> Self {
Self {
#[cfg(not(target_arch = "wasm32"))]
_span,
#[cfg(not(target_arch = "wasm32"))]
start: std::time::Instant::now(),
}
}
}
#[cfg(not(target_arch = "wasm32"))]
impl Drop for Timer {
fn drop(&mut self) {
let dur = self.start.elapsed();
info!(kind = "perf", "Done in {:?}", dur);
}
}
/// Creates a timer. For input arguments, see [tracing::span].
///
/// # Convention
///
/// The string passed to `timer!` should start with a verb.
///
/// # Example usage
///
/// ```
/// use swc_timer::timer;
/// # let _logger = testing::init();
/// let _timer = timer!("");
/// ```
///
/// ## With arguments
/// ```
/// use swc_timer::timer;
/// # let _logger = testing::init();
/// let arg = "path";
/// let _timer = timer!("bundle", path = arg);
/// ```
#[macro_export]
macro_rules! timer {
($($args:tt)*) => {{
#[cfg(not(target_arch = "wasm32"))]
let span = $crate::tracing::span!($crate::tracing::Level::INFO, $($args)*).entered();
#[cfg(not(target_arch = "wasm32"))]
$crate::Timer::new(span)
}};
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_timer/tests/timer.rs | Rust | use swc_timer::timer;
#[test]
fn logging() {
testing::run_test(false, |_, _| {
let _timer = timer!("operation");
Ok(())
})
.unwrap();
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_trace_macro/src/lib.rs | Rust | extern crate proc_macro;
use quote::ToTokens;
use syn::{parse_quote, AttrStyle, Attribute, ImplItem, ItemImpl};
/// Utility proc macro to add `#[tracing::instrument(level = "info",
/// skip_all)]` to all methods in an impl block.
///
/// This attribute macro is typically applied on an `VisitMut` impl block.
/// If this is applied, all implemented methods will annotated with the
/// instrument annotation from `tracing`.
#[proc_macro_attribute]
pub fn swc_trace(
_args: proc_macro::TokenStream,
input: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
let mut item = syn::parse::<ItemImpl>(input).expect("#[swc_trace] expects an impl block");
item.items.iter_mut().for_each(|item| {
// We only handle methods
if let ImplItem::Fn(m) = item {
// #[tracing::instrument(level = "info", skip_all)]
let attr = Attribute {
pound_token: Default::default(),
style: AttrStyle::Outer,
bracket_token: Default::default(),
meta: parse_quote!(tracing::instrument(level = "info", skip_all)),
};
m.attrs.push(attr);
}
});
item.to_token_stream().into()
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_transform_common/src/lib.rs | Rust | pub mod output;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_transform_common/src/output.rs | Rust | //! (Experimental) Output capturing.
//!
//! This module provides a way to emit metadata to the JS caller.
use std::cell::RefCell;
use better_scoped_tls::scoped_tls;
use rustc_hash::FxHashMap;
use serde_json::Value;
scoped_tls!(static OUTPUT: RefCell<FxHashMap<String, serde_json::Value>>);
/// (Experimental) Captures output.
///
/// This is not stable and may be removed in the future.
pub fn capture<Ret>(f: impl FnOnce() -> Ret) -> (Ret, FxHashMap<String, serde_json::Value>) {
let output = RefCell::new(Default::default());
let ret = OUTPUT.set(&output, f);
(ret, output.into_inner())
}
/// (Experimental) Emits a value to the JS caller.
///
/// This is not stable and may be removed in the future.
pub fn emit(key: String, value: Value) {
OUTPUT.with(|output| {
let previous = output.borrow_mut().insert(key, value);
if let Some(previous) = previous {
panic!("Key already set. Previous value: {previous:?}");
}
});
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/examples/isolated_declarations.rs | Rust | use std::{env, path::Path};
use swc_common::{comments::SingleThreadedComments, Mark};
use swc_ecma_codegen::to_code_with_comments;
use swc_ecma_parser::{parse_file_as_program, Syntax, TsSyntax};
use swc_ecma_transforms_base::{fixer::paren_remover, resolver};
use swc_typescript::fast_dts::{FastDts, FastDtsOptions};
pub fn main() {
let mut dts_code = String::new();
let res = testing::run_test2(false, |cm, handler| {
let name = env::args().nth(1).unwrap_or_else(|| "index.ts".to_string());
let input = Path::new(&name);
let fm = cm.load_file(input).expect("failed to load test case");
let unresolved_mark = Mark::new();
let top_level_mark = Mark::new();
let comments = SingleThreadedComments::default();
let mut program = parse_file_as_program(
&fm,
Syntax::Typescript(TsSyntax {
tsx: true,
..Default::default()
}),
Default::default(),
Some(&comments),
&mut Vec::new(),
)
.map_err(|err| err.into_diagnostic(&handler).emit())
.map(|program| program.apply(resolver(unresolved_mark, top_level_mark, true)))
.map(|program| program.apply(paren_remover(None)))
.unwrap();
let internal_annotations = FastDts::get_internal_annotations(&comments);
let mut checker = FastDts::new(
fm.name.clone(),
unresolved_mark,
FastDtsOptions {
internal_annotations: Some(internal_annotations),
},
);
let issues = checker.transform(&mut program);
dts_code = to_code_with_comments(Some(&comments), &program);
for issue in issues {
handler
.struct_span_err(issue.range.span, &issue.message)
.emit();
}
if handler.has_errors() {
Err(())
} else {
Ok(())
}
});
let mut output =
format!("```==================== .D.TS ====================\n\n{dts_code}\n\n");
if let Err(issues) = res {
output.push_str(&format!(
"==================== Errors ====================\n{issues}\n\n```"
));
}
println!("{}", output);
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/src/diagnostic.rs | Rust | //! References
//! * <https://github.com/oxc-project/oxc/blob/main/crates/oxc_isolated_declarations/src/diagnostics.rs>
use std::{borrow::Cow, sync::Arc};
use swc_common::{FileName, Span};
use crate::fast_dts::FastDts;
#[derive(Debug, Clone)]
pub struct SourceRange {
pub filename: Arc<FileName>,
pub span: Span,
}
#[derive(Debug, Clone)]
pub struct DtsIssue {
pub range: SourceRange,
pub message: Cow<'static, str>,
}
impl FastDts {
pub fn function_must_have_explicit_return_type(&mut self, span: Span) {
self.mark_diagnostic(
"TS9007: Function must have an explicit return type annotation with \
--isolatedDeclarations.",
span,
);
}
pub fn method_must_have_explicit_return_type(&mut self, span: Span) {
self.mark_diagnostic(
"TS9008: Method must have an explicit return type annotation with \
--isolatedDeclarations.",
span,
);
}
pub fn accessor_must_have_explicit_return_type(&mut self, span: Span) {
self.mark_diagnostic(
"TS9009: At least one accessor must have an explicit return type annotation with \
--isolatedDeclarations.",
span,
);
}
pub fn variable_must_have_explicit_type(&mut self, span: Span) {
self.mark_diagnostic(
"TS9010: Variable must have an explicit type annotation with --isolatedDeclarations.",
span,
);
}
pub fn parameter_must_have_explicit_type(&mut self, span: Span) {
self.mark_diagnostic(
"TS9011: Parameter must have an explicit type annotation with --isolatedDeclarations.",
span,
);
}
pub fn property_must_have_explicit_type(&mut self, span: Span) {
self.mark_diagnostic(
"TS9012: Property must have an explicit type annotation with --isolatedDeclarations.",
span,
);
}
pub fn inferred_type_of_expression(&mut self, span: Span) {
self.mark_diagnostic(
"TS9013: Expression type can't be inferred with --isolatedDeclarations.",
span,
);
}
pub fn signature_computed_property_name(&mut self, span: Span) {
self.mark_diagnostic(
"TS9014: Computed properties must be number or string literals, variables or dotted \
expressions with --isolatedDeclarations.",
span,
);
}
pub fn object_with_spread_assignments(&mut self, span: Span) {
self.mark_diagnostic(
"TS9015: Objects that contain spread assignments can't be inferred with \
--isolatedDeclarations.",
span,
);
}
pub fn shorthand_property(&mut self, span: Span) {
self.mark_diagnostic(
"TS9016: Objects that contain shorthand properties can't be inferred with \
--isolatedDeclarations.",
span,
);
}
pub fn array_inferred(&mut self, span: Span) {
self.mark_diagnostic(
"TS9017: Only const arrays can be inferred with --isolatedDeclarations.",
span,
);
}
pub fn arrays_with_spread_elements(&mut self, span: Span) {
self.mark_diagnostic(
"TS9018: Arrays with spread elements can't inferred with --isolatedDeclarations.",
span,
);
}
pub fn binding_element_export(&mut self, span: Span) {
self.mark_diagnostic(
"TS9019: Binding elements can't be exported directly with --isolatedDeclarations.",
span,
);
}
pub fn enum_member_initializers(&mut self, span: Span) {
self.mark_diagnostic(
"TS9020: Enum member initializers must be computable without references to external \
symbols with --isolatedDeclarations.",
span,
);
}
pub fn extends_clause_expression(&mut self, span: Span) {
self.mark_diagnostic(
"TS9021: Extends clause can't contain an expression with --isolatedDeclarations.",
span,
);
}
pub fn inferred_type_of_class_expression(&mut self, span: Span) {
self.mark_diagnostic(
"TS9022: Inference from class expressions is not supported with \
--isolatedDeclarations.",
span,
);
}
pub fn implicitly_adding_undefined_to_type(&mut self, span: Span) {
self.mark_diagnostic(
"TS9025: Declaration emit for this parameter requires implicitly adding undefined to \
it's type. This is not supported with --isolatedDeclarations.",
span,
);
}
pub fn function_with_assigning_properties(&mut self, span: Span) {
self.mark_diagnostic(
"TS9023: Assigning properties to functions without declaring them is not supported \
with --isolatedDeclarations. Add an explicit declaration for the properties assigned \
to this function.",
span,
);
}
pub fn default_export_inferred(&mut self, span: Span) {
self.mark_diagnostic(
"TS9037: Default exports can't be inferred with --isolatedDeclarations.",
span,
);
}
pub fn computed_property_name(&mut self, span: Span) {
self.mark_diagnostic(
"TS9038: Computed property names on class or object literals cannot be inferred with \
--isolatedDeclarations.",
span,
);
}
pub fn type_containing_private_name(&mut self, name: &str, span: Span) {
self.mark_diagnostic(
format!(
"TS9039: Type containing private name '{name}' can't be used with \
--isolatedDeclarations."
),
span,
);
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/src/fast_dts/class.rs | Rust | use rustc_hash::FxHashMap;
use swc_common::{util::take::Take, Spanned, SyntaxContext, DUMMY_SP};
use swc_ecma_ast::{
Accessibility, BindingIdent, Class, ClassMember, ClassProp, Expr, Key, Lit, MethodKind, Param,
ParamOrTsParamProp, Pat, PrivateName, PrivateProp, PropName, TsParamProp, TsParamPropParam,
TsTypeAnn,
};
use super::{
type_ann,
util::ast_ext::{ExprExit, PatExt, PropNameExit},
FastDts,
};
impl FastDts {
pub(crate) fn transform_class(&mut self, class: &mut Class) {
if let Some(super_class) = &class.super_class {
let is_not_allowed = super_class.get_root_ident().is_none();
if is_not_allowed {
self.extends_clause_expression(super_class.span());
}
}
let setter_getter_annotations = self.collect_getter_or_setter_annotations(class);
let mut is_function_overloads = false;
let mut has_private_key = false;
let body = class.body.take();
for mut member in body {
match &mut member {
ClassMember::Constructor(constructor) => {
if self.has_internal_annotation(constructor.span_lo()) {
continue;
}
if !(constructor.is_optional) && constructor.body.is_none() {
is_function_overloads = true;
} else if is_function_overloads {
is_function_overloads = false;
continue;
}
if self.report_property_key(&constructor.key) {
continue;
}
// Transform parameters
class.body.splice(
0..0,
self.transform_constructor_params(&mut constructor.params),
);
if constructor
.accessibility
.is_some_and(|accessibility| accessibility == Accessibility::Private)
{
constructor.params.clear();
}
constructor.body = None;
constructor.accessibility =
self.transform_accessibility(constructor.accessibility);
class.body.push(member);
}
ClassMember::Method(method) => {
if self.has_internal_annotation(method.span_lo()) {
continue;
}
if !(method.is_abstract || method.is_optional) && method.function.body.is_none()
{
is_function_overloads = true;
} else if is_function_overloads {
is_function_overloads = false;
continue;
}
if self.report_property_key(&method.key) {
continue;
}
// Transform parameters
match method.kind {
MethodKind::Method => {
if method.accessibility.is_some_and(|accessibility| {
accessibility == Accessibility::Private
}) {
class.body.push(ClassMember::ClassProp(ClassProp {
span: method.span,
key: method.key.clone(),
value: None,
type_ann: None,
is_static: method.is_static,
decorators: Vec::new(),
accessibility: self
.transform_accessibility(method.accessibility),
is_abstract: method.is_abstract,
is_optional: method.is_optional,
is_override: false,
readonly: false,
declare: false,
definite: false,
}));
continue;
}
self.transform_fn_params(&mut method.function.params);
}
MethodKind::Getter => {
if method.accessibility.is_some_and(|accessibility| {
accessibility == Accessibility::Private
}) {
method.function.params.clear();
method.function.return_type = None;
method.function.decorators.clear();
method.function.body = None;
method.function.is_generator = false;
method.function.is_async = false;
method.accessibility =
self.transform_accessibility(method.accessibility);
class.body.push(member);
continue;
}
self.transform_fn_params(&mut method.function.params);
}
MethodKind::Setter => {
if method.accessibility.is_some_and(|accessibility| {
accessibility == Accessibility::Private
}) {
method.function.params = vec![Param {
span: DUMMY_SP,
decorators: Vec::new(),
pat: Pat::Ident(BindingIdent {
id: "value".into(),
type_ann: None,
}),
}];
method.function.decorators.clear();
method.function.body = None;
method.function.is_generator = false;
method.function.is_async = false;
method.function.return_type = None;
method.accessibility =
self.transform_accessibility(method.accessibility);
class.body.push(member);
continue;
}
if method.function.params.is_empty() {
method.function.params.push(Param {
span: DUMMY_SP,
decorators: Vec::new(),
pat: Pat::Ident(BindingIdent {
id: "value".into(),
type_ann: None,
}),
});
} else {
method.function.params.truncate(1);
let param = method.function.params.first_mut().unwrap();
let static_name = method.key.static_name();
if let Some(type_ann) = static_name
.and_then(|name| setter_getter_annotations.get(name.as_ref()))
{
param.pat.set_type_ann(Some(type_ann.clone()));
}
}
}
}
// Transform return
match method.kind {
MethodKind::Method => {
self.transform_fn_return_type(&mut method.function);
if method.function.return_type.is_none() {
self.method_must_have_explicit_return_type(method.key.span());
}
}
MethodKind::Getter => {
self.transform_fn_return_type(&mut method.function);
if method.function.return_type.is_none() {
method.function.return_type = method
.key
.static_name()
.and_then(|name| setter_getter_annotations.get(name.as_ref()))
.cloned();
}
if method.function.return_type.is_none() {
self.accessor_must_have_explicit_return_type(method.key.span());
}
}
MethodKind::Setter => method.function.return_type = None,
}
method.function.body = None;
method.function.is_async = false;
method.function.is_generator = false;
method.accessibility = self.transform_accessibility(method.accessibility);
class.body.push(member);
}
ClassMember::ClassProp(prop) => {
if self.has_internal_annotation(prop.span_lo()) {
continue;
}
if self.report_property_key(&prop.key) {
continue;
}
self.transform_class_property(prop);
class.body.push(member);
}
ClassMember::PrivateMethod(_) | ClassMember::PrivateProp(_) => {
has_private_key = true;
}
ClassMember::TsIndexSignature(ts_index_signature) => {
if self.has_internal_annotation(ts_index_signature.span_lo()) {
continue;
}
class.body.push(member);
}
ClassMember::AutoAccessor(auto_accessor) => {
if self.has_internal_annotation(auto_accessor.span_lo()) {
continue;
}
let Key::Public(prop_name) = &auto_accessor.key else {
has_private_key = true;
continue;
};
if self.report_property_key(prop_name) {
continue;
}
if auto_accessor
.accessibility
.is_some_and(|accessibility| accessibility == Accessibility::Private)
{
auto_accessor.decorators.clear();
auto_accessor.definite = false;
auto_accessor.type_ann = None;
auto_accessor.accessibility =
self.transform_accessibility(auto_accessor.accessibility);
}
auto_accessor.is_override = false;
auto_accessor.value = None;
class.body.push(member);
}
ClassMember::Empty(_) | ClassMember::StaticBlock(_) => {}
}
}
if has_private_key {
class.body.insert(
0,
ClassMember::PrivateProp(PrivateProp {
span: DUMMY_SP,
ctxt: SyntaxContext::empty(),
key: PrivateName {
span: DUMMY_SP,
name: "private".into(),
},
value: None,
type_ann: None,
is_static: false,
decorators: Vec::new(),
accessibility: None,
is_optional: false,
is_override: false,
readonly: false,
definite: false,
}),
);
}
}
pub(crate) fn transform_constructor_params(
&mut self,
params: &mut [ParamOrTsParamProp],
) -> Vec<ClassMember> {
let mut is_required = false;
let mut private_properties = Vec::new();
for param in params.iter_mut().rev() {
match param {
ParamOrTsParamProp::TsParamProp(ts_param_prop) => {
is_required |= match &ts_param_prop.param {
TsParamPropParam::Ident(binding_ident) => !binding_ident.optional,
TsParamPropParam::Assign(_) => false,
};
if let Some(private_prop) =
self.transform_constructor_ts_param(ts_param_prop, is_required)
{
private_properties.push(private_prop);
}
ts_param_prop.readonly = false;
ts_param_prop.accessibility = None;
}
ParamOrTsParamProp::Param(param) => {
self.transform_fn_param(param, is_required);
is_required |= match ¶m.pat {
Pat::Ident(binding_ident) => !binding_ident.optional,
Pat::Array(array_pat) => !array_pat.optional,
Pat::Object(object_pat) => !object_pat.optional,
Pat::Assign(_) | Pat::Invalid(_) | Pat::Expr(_) | Pat::Rest(_) => false,
}
}
}
}
private_properties.reverse();
private_properties
}
pub(crate) fn transform_constructor_ts_param(
&mut self,
ts_param_prop: &mut TsParamProp,
is_required: bool,
) -> Option<ClassMember> {
// We do almost same thing as self::transform_fn_param
// 1. Check assign pat type
if let TsParamPropParam::Assign(assign_pat) = &mut ts_param_prop.param {
if self.check_assign_pat_param(assign_pat) {
self.parameter_must_have_explicit_type(ts_param_prop.span);
return None;
}
}
// 2. Infer type annotation
let (type_ann, should_add_undefined) = match &mut ts_param_prop.param {
TsParamPropParam::Ident(binding_ident) => {
if binding_ident.type_ann.is_none() {
self.parameter_must_have_explicit_type(ts_param_prop.span);
}
let is_none = binding_ident.type_ann.is_none();
(&mut binding_ident.type_ann, is_none)
}
TsParamPropParam::Assign(assign_pat) => {
if !self.transform_assign_pat(assign_pat, is_required) {
self.parameter_must_have_explicit_type(ts_param_prop.span);
}
(
match assign_pat.left.as_mut() {
Pat::Ident(ident) => &mut ident.type_ann,
Pat::Array(array_pat) => &mut array_pat.type_ann,
Pat::Object(object_pat) => &mut object_pat.type_ann,
Pat::Assign(_) | Pat::Rest(_) | Pat::Invalid(_) | Pat::Expr(_) => {
return None
}
},
true,
)
}
};
// 3. Add undefined type if needed
if let Some(type_ann) = type_ann {
if is_required && should_add_undefined && self.add_undefined_type_for_param(type_ann) {
self.implicitly_adding_undefined_to_type(ts_param_prop.span);
}
}
// 4. Flat param pat
if let Some(assign_pat) = ts_param_prop.param.as_assign() {
// A parameter property may not be declared using a binding pattern.
if let Some(ident) = assign_pat.left.as_ident() {
ts_param_prop.param = TsParamPropParam::Ident(ident.clone());
}
}
// Create private property
let ident = (match &ts_param_prop.param {
TsParamPropParam::Ident(binding_ident) => Some(binding_ident.id.clone()),
TsParamPropParam::Assign(assign_pat) => assign_pat
.left
.as_ident()
.map(|binding_ident| binding_ident.id.clone()),
})?;
let type_ann = if ts_param_prop
.accessibility
.is_some_and(|accessibility| accessibility == Accessibility::Private)
{
None
} else {
match &ts_param_prop.param {
TsParamPropParam::Ident(binding_ident) => binding_ident.type_ann.clone(),
TsParamPropParam::Assign(assign_pat) => match assign_pat.left.as_ref() {
Pat::Ident(binding_ident) => binding_ident.type_ann.clone(),
Pat::Array(array_pat) => array_pat.type_ann.clone(),
Pat::Object(object_pat) => object_pat.type_ann.clone(),
Pat::Assign(_) | Pat::Rest(_) | Pat::Invalid(_) | Pat::Expr(_) => None,
},
}
};
Some(ClassMember::ClassProp(ClassProp {
span: DUMMY_SP,
key: PropName::Ident(ident.into()),
value: None,
type_ann,
is_static: false,
decorators: Vec::new(),
accessibility: self.transform_accessibility(ts_param_prop.accessibility),
is_abstract: false,
is_optional: false,
is_override: ts_param_prop.is_override,
readonly: ts_param_prop.readonly,
declare: false,
definite: false,
}))
}
pub(crate) fn transform_class_property(&mut self, prop: &mut ClassProp) {
if prop.accessibility.map_or(true, |accessibility| {
accessibility != Accessibility::Private
}) {
if prop.type_ann.is_none() {
if let Some(value) = prop.value.as_ref() {
if prop.readonly {
if Self::need_to_infer_type_from_expression(value) {
prop.type_ann = self.transform_expr_to_ts_type(value).map(type_ann);
prop.value = None;
} else if let Some(tpl) = value.as_tpl() {
prop.value = self
.tpl_to_string(tpl)
.map(|s| Box::new(Expr::Lit(Lit::Str(s))));
}
} else {
prop.type_ann = self.infer_type_from_expr(value).map(type_ann);
prop.value = None;
}
}
} else {
prop.value = None;
}
if prop.type_ann.is_none() && prop.value.is_none() {
self.property_must_have_explicit_type(prop.key.span());
}
} else {
prop.type_ann = None;
prop.value = None;
}
prop.declare = false;
prop.decorators.clear();
prop.accessibility = self.transform_accessibility(prop.accessibility);
}
pub(crate) fn transform_accessibility(
&mut self,
accessibility: Option<Accessibility>,
) -> Option<Accessibility> {
if accessibility.is_none()
|| accessibility.is_some_and(|accessibility| accessibility == Accessibility::Public)
{
None
} else {
accessibility
}
}
pub(crate) fn collect_getter_or_setter_annotations(
&mut self,
class: &Class,
) -> FxHashMap<String, Box<TsTypeAnn>> {
let mut annotations = FxHashMap::default();
for member in &class.body {
let ClassMember::Method(method) = member else {
continue;
};
if method
.accessibility
.is_some_and(|accessibility| accessibility == Accessibility::Private)
|| (method
.key
.as_computed()
.map_or(false, |computed| Self::is_literal(&computed.expr)))
{
continue;
}
let Some(static_name) = method.key.static_name().map(|name| name.to_string()) else {
continue;
};
match method.kind {
MethodKind::Getter => {
if let Some(type_ann) = method
.function
.return_type
.clone()
.or_else(|| self.infer_function_return_type(&method.function))
{
annotations.insert(static_name, type_ann);
}
}
MethodKind::Setter => {
let Some(first_param) = method.function.params.first() else {
continue;
};
if let Some(type_ann) = first_param.pat.get_type_ann() {
annotations.insert(static_name, type_ann.clone());
}
}
_ => continue,
}
}
annotations
}
pub(crate) fn report_property_key(&mut self, key: &PropName) -> bool {
if let Some(computed) = key.as_computed() {
let is_symbol = self.is_global_symbol_object(&computed.expr);
let is_literal = Self::is_literal(&computed.expr);
if !is_symbol && !is_literal {
self.computed_property_name(key.span());
}
return !is_symbol && !is_literal;
}
false
}
pub(crate) fn is_global_symbol_object(&self, expr: &Expr) -> bool {
let Some(obj) = (match expr {
Expr::Member(member) => Some(&member.obj),
Expr::OptChain(opt_chain) => opt_chain.base.as_member().map(|member| &member.obj),
_ => None,
}) else {
return false;
};
// https://github.com/microsoft/TypeScript/blob/cbac1ddfc73ca3b9d8741c1b51b74663a0f24695/src/compiler/transformers/declarations.ts#L1011
if let Some(ident) = obj.as_ident() {
// Exactly `Symbol.something` and `Symbol` either does not resolve
// or definitely resolves to the global Symbol
return ident.sym.as_str() == "Symbol" && ident.ctxt.has_mark(self.unresolved_mark);
}
if let Some(member_expr) = obj.as_member() {
// Exactly `globalThis.Symbol.something` and `globalThis` resolves
// to the global `globalThis`
if let Some(ident) = member_expr.obj.as_ident() {
return ident.sym.as_str() == "globalThis"
&& ident.ctxt.has_mark(self.unresolved_mark)
&& member_expr.prop.is_ident_with("Symbol");
}
}
false
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/src/fast_dts/decl.rs | Rust | use swc_common::Spanned;
use swc_ecma_ast::{
Decl, DefaultDecl, Expr, Lit, Pat, TsNamespaceBody, VarDeclKind, VarDeclarator,
};
use swc_ecma_visit::VisitMutWith;
use super::{
type_ann,
util::{ast_ext::PatExt, types::any_type_ann},
visitors::internal_annotation::InternalAnnotationTransformer,
FastDts,
};
impl FastDts {
pub(crate) fn transform_decl(&mut self, decl: &mut Decl, check_binding: bool) {
let is_declare = self.is_top_level;
match decl {
Decl::Class(class_decl) => {
if class_decl.declare {
return;
}
if check_binding && !self.used_refs.contains(&class_decl.ident.to_id()) {
return;
}
class_decl.declare = is_declare;
self.transform_class(&mut class_decl.class);
}
Decl::Fn(fn_decl) => {
if fn_decl.declare {
return;
}
if check_binding && !self.used_refs.contains(&fn_decl.ident.to_id()) {
return;
}
fn_decl.declare = is_declare;
self.transform_fn(&mut fn_decl.function, Some(fn_decl.ident.span));
}
Decl::Var(var) => {
if var.declare {
return;
}
var.declare = is_declare;
for decl in var.decls.iter_mut() {
if check_binding
&& decl
.name
.as_ident()
.map_or(false, |ident| !self.used_refs.contains(&ident.to_id()))
{
return;
}
self.transform_variables_declarator(var.kind, decl, check_binding);
}
}
Decl::Using(using) => {
for decl in using.decls.iter_mut() {
if check_binding
&& decl
.name
.as_ident()
.map_or(false, |ident| !self.used_refs.contains(&ident.to_id()))
{
return;
}
self.transform_variables_declarator(VarDeclKind::Const, decl, check_binding);
}
}
Decl::TsEnum(ts_enum) => {
ts_enum.declare = is_declare;
if check_binding && !self.used_refs.contains(&ts_enum.id.to_id()) {
return;
}
self.transform_enum(ts_enum.as_mut());
}
Decl::TsModule(ts_module) => {
if ts_module.declare {
return;
}
if !ts_module.global
&& !ts_module.id.is_str()
&& check_binding
&& ts_module
.id
.as_ident()
.map_or(false, |ident| !self.used_refs.contains(&ident.to_id()))
{
return;
}
ts_module.declare = is_declare;
if let Some(body) = ts_module.body.as_mut() {
self.transform_ts_namespace_decl(
body,
ts_module.global || ts_module.id.is_str(),
);
}
}
Decl::TsInterface(ts_interface) => {
if let Some(internal_annotations) = self.internal_annotations.as_ref() {
ts_interface.visit_mut_children_with(&mut InternalAnnotationTransformer::new(
internal_annotations,
))
}
for type_element in ts_interface.body.body.iter() {
self.check_ts_signature(type_element);
}
}
Decl::TsTypeAlias(ts_type_alias) => {
if let Some(internal_annotations) = self.internal_annotations.as_ref() {
ts_type_alias.visit_mut_children_with(&mut InternalAnnotationTransformer::new(
internal_annotations,
))
}
if let Some(ts_lit) = ts_type_alias.type_ann.as_ts_type_lit() {
for type_element in ts_lit.members.iter() {
self.check_ts_signature(type_element);
}
}
}
}
}
pub(crate) fn transform_variables_declarator(
&mut self,
kind: VarDeclKind,
decl: &mut VarDeclarator,
check_binding: bool,
) {
let pat = match &decl.name {
Pat::Assign(assign_pat) => &assign_pat.left,
_ => &decl.name,
};
if matches!(pat, Pat::Array(_) | Pat::Object(_)) {
pat.bound_names(&mut |ident| {
if !check_binding || self.used_refs.contains(&ident.to_id()) {
self.binding_element_export(ident.span);
}
});
return;
}
let mut binding_type = None;
let mut init = None;
if pat.get_type_ann().is_none() {
if let Some(init_expr) = &decl.init {
if kind == VarDeclKind::Const
&& !Self::need_to_infer_type_from_expression(init_expr)
{
if let Some(tpl) = init_expr.as_tpl() {
init = self
.tpl_to_string(tpl)
.map(|s| Box::new(Expr::Lit(Lit::Str(s))));
} else {
init = Some(init_expr.clone());
}
} else if kind != VarDeclKind::Const || !init_expr.is_tpl() {
binding_type = self.infer_type_from_expr(init_expr).map(type_ann);
}
}
if init.is_none() && binding_type.is_none() {
binding_type = Some(any_type_ann());
if !decl
.init
.as_ref()
.is_some_and(|init| init.is_fn_expr() || init.is_arrow())
{
self.variable_must_have_explicit_type(decl.name.span());
}
}
}
decl.init = init;
if binding_type.is_some() {
decl.name.set_type_ann(binding_type);
}
}
pub(crate) fn transform_default_decl(&mut self, decl: &mut DefaultDecl) {
match decl {
DefaultDecl::Class(class_expr) => {
self.transform_class(&mut class_expr.class);
}
DefaultDecl::Fn(fn_expr) => {
self.transform_fn(
&mut fn_expr.function,
fn_expr.ident.as_ref().map(|ident| ident.span),
);
}
DefaultDecl::TsInterfaceDecl(_) => {}
};
}
pub(crate) fn transform_ts_namespace_decl(
&mut self,
body: &mut TsNamespaceBody,
in_global_or_lit_module: bool,
) {
let original_is_top_level = self.is_top_level;
self.is_top_level = false;
match body {
TsNamespaceBody::TsModuleBlock(ts_module_block) => {
self.transform_module_body(&mut ts_module_block.body, in_global_or_lit_module);
}
TsNamespaceBody::TsNamespaceDecl(ts_ns) => {
self.transform_ts_namespace_decl(&mut ts_ns.body, ts_ns.global)
}
};
self.is_top_level = original_is_top_level;
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/src/fast_dts/enum.rs | Rust | use core::f64;
use rustc_hash::FxHashMap;
use swc_atoms::Atom;
use swc_common::{Spanned, SyntaxContext, DUMMY_SP};
use swc_ecma_ast::{
BinExpr, BinaryOp, Expr, Ident, Lit, Number, Str, TsEnumDecl, TsEnumMemberId, UnaryExpr,
UnaryOp,
};
use swc_ecma_utils::number::JsNumber;
use super::{util::ast_ext::MemberPropExt, FastDts};
#[derive(Debug, Clone)]
enum ConstantValue {
Number(f64),
String(String),
}
impl FastDts {
pub(crate) fn transform_enum(&mut self, decl: &mut TsEnumDecl) {
let mut prev_init_value = Some(ConstantValue::Number(-1.0));
let mut prev_members = FxHashMap::default();
for member in &mut decl.members {
let value = if let Some(init_expr) = &member.init {
let computed_value = self.evaluate(init_expr, &decl.id.sym, &prev_members);
if computed_value.is_none() {
self.enum_member_initializers(member.id.span());
}
computed_value
} else if let Some(ConstantValue::Number(v)) = prev_init_value {
Some(ConstantValue::Number(v + 1.0))
} else {
None
};
prev_init_value = value.clone();
if let Some(value) = &value {
let member_name = match &member.id {
TsEnumMemberId::Ident(ident) => &ident.sym,
TsEnumMemberId::Str(s) => &s.value,
};
prev_members.insert(member_name.clone(), value.clone());
}
member.init = value.map(|value| {
Box::new(match value {
ConstantValue::Number(v) => {
let is_neg = v < 0.0;
let expr = if v.is_infinite() {
Expr::Ident(Ident {
span: DUMMY_SP,
sym: "Infinity".into(),
ctxt: SyntaxContext::empty(),
optional: false,
})
} else {
Expr::Lit(Lit::Num(Number {
span: DUMMY_SP,
value: v,
raw: Some(v.to_string().into()),
}))
};
if is_neg {
Expr::Unary(UnaryExpr {
span: DUMMY_SP,
arg: Box::new(expr),
op: UnaryOp::Minus,
})
} else {
expr
}
}
ConstantValue::String(s) => Expr::Lit(Lit::Str(Str {
span: DUMMY_SP,
value: s.clone().into(),
raw: None,
})),
})
});
}
}
fn evaluate(
&self,
expr: &Expr,
enum_name: &Atom,
prev_members: &FxHashMap<Atom, ConstantValue>,
) -> Option<ConstantValue> {
match expr {
Expr::Lit(lit) => match lit {
Lit::Str(s) => Some(ConstantValue::String(s.value.to_string())),
Lit::Num(number) => Some(ConstantValue::Number(number.value)),
Lit::Null(_) | Lit::BigInt(_) | Lit::Bool(_) | Lit::Regex(_) | Lit::JSXText(_) => {
None
}
},
Expr::Tpl(tpl) => {
let mut value = String::new();
for part in &tpl.quasis {
value.push_str(&part.raw);
}
Some(ConstantValue::String(value))
}
Expr::Paren(expr) => self.evaluate(&expr.expr, enum_name, prev_members),
Expr::Bin(bin_expr) => self.evaluate_binary_expr(bin_expr, enum_name, prev_members),
Expr::Unary(unary_expr) => {
self.evaluate_unary_expr(unary_expr, enum_name, prev_members)
}
Expr::Ident(ident) => {
if ident.sym == "Infinity" {
Some(ConstantValue::Number(f64::INFINITY))
} else if ident.sym == "NaN" {
Some(ConstantValue::Number(f64::NAN))
} else {
prev_members.get(&ident.sym).cloned()
}
}
Expr::Member(member) => {
let ident = member.obj.as_ident()?;
if &ident.sym == enum_name {
let name = member.prop.static_name()?;
prev_members.get(name).cloned()
} else {
None
}
}
Expr::OptChain(opt_chain) => {
let member = opt_chain.base.as_member()?;
let ident = member.obj.as_ident()?;
if &ident.sym == enum_name {
let name = member.prop.static_name()?;
prev_members.get(name).cloned()
} else {
None
}
}
_ => None,
}
}
fn evaluate_unary_expr(
&self,
expr: &UnaryExpr,
enum_name: &Atom,
prev_members: &FxHashMap<Atom, ConstantValue>,
) -> Option<ConstantValue> {
let value = self.evaluate(&expr.arg, enum_name, prev_members)?;
let value = match value {
ConstantValue::Number(n) => n,
ConstantValue::String(_) => {
let value = if expr.op == UnaryOp::Minus {
ConstantValue::Number(f64::NAN)
} else if expr.op == UnaryOp::Tilde {
ConstantValue::Number(-1.0)
} else {
value
};
return Some(value);
}
};
match expr.op {
UnaryOp::Minus => Some(ConstantValue::Number(-value)),
UnaryOp::Plus => Some(ConstantValue::Number(value)),
UnaryOp::Tilde => Some(ConstantValue::Number((!JsNumber::from(value)).into())),
_ => None,
}
}
fn evaluate_binary_expr(
&self,
expr: &BinExpr,
enum_name: &Atom,
prev_members: &FxHashMap<Atom, ConstantValue>,
) -> Option<ConstantValue> {
let left = self.evaluate(&expr.left, enum_name, prev_members)?;
let right = self.evaluate(&expr.right, enum_name, prev_members)?;
if expr.op == BinaryOp::Add
&& (matches!(left, ConstantValue::String(_))
|| matches!(right, ConstantValue::String(_)))
{
let left_string = match left {
ConstantValue::Number(number) => number.to_string(),
ConstantValue::String(s) => s,
};
let right_string = match right {
ConstantValue::Number(number) => number.to_string(),
ConstantValue::String(s) => s,
};
return Some(ConstantValue::String(format!(
"{left_string}{right_string}"
)));
}
let left = JsNumber::from(match left {
ConstantValue::Number(n) => n,
ConstantValue::String(_) => return None,
});
let right = JsNumber::from(match right {
ConstantValue::Number(n) => n,
ConstantValue::String(_) => return None,
});
match expr.op {
BinaryOp::LShift => Some(left << right),
BinaryOp::RShift => Some(left >> right),
BinaryOp::ZeroFillRShift => Some(left.unsigned_shr(right)),
BinaryOp::Add => Some(left + right),
BinaryOp::Sub => Some(left - right),
BinaryOp::Mul => Some(left * right),
BinaryOp::Div => Some(left / right),
BinaryOp::Mod => Some(left & right),
BinaryOp::BitOr => Some(left | right),
BinaryOp::BitXor => Some(left ^ right),
BinaryOp::BitAnd => Some(left & right),
BinaryOp::Exp => Some(left.pow(right)),
_ => None,
}
.map(|number| ConstantValue::Number(number.into()))
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/src/fast_dts/function.rs | Rust | use std::mem;
use swc_atoms::Atom;
use swc_common::{Span, Spanned, DUMMY_SP};
use swc_ecma_ast::{
AssignPat, Decl, ExportDecl, Function, ModuleDecl, ModuleItem, Param, Pat, Script, Stmt,
TsKeywordTypeKind, TsType, TsTypeAnn, TsUnionOrIntersectionType, TsUnionType,
};
use super::{
type_ann,
util::types::{any_type_ann, ts_keyword_type},
FastDts,
};
impl FastDts {
pub(crate) fn transform_fn(&mut self, func: &mut Function, ident_span: Option<Span>) {
self.transform_fn_return_type(func);
if func.return_type.is_none() {
self.function_must_have_explicit_return_type(
ident_span.unwrap_or_else(|| Span::new(func.span_lo(), func.body.span_lo())),
);
}
self.transform_fn_params(&mut func.params);
func.is_async = false;
func.is_generator = false;
func.body = None
}
pub(crate) fn transform_fn_return_type(&mut self, func: &mut Function) {
if func.return_type.is_none() && !func.is_async && !func.is_generator {
func.return_type = self.infer_function_return_type(func);
}
}
pub(crate) fn transform_fn_params(&mut self, params: &mut [Param]) {
// If there is required param after current param.
let mut is_required = false;
for param in params.iter_mut().rev() {
is_required |= match ¶m.pat {
Pat::Ident(binding_ident) => !binding_ident.optional,
Pat::Array(array_pat) => !array_pat.optional,
Pat::Object(object_pat) => !object_pat.optional,
Pat::Assign(_) | Pat::Invalid(_) | Pat::Expr(_) | Pat::Rest(_) => false,
};
self.transform_fn_param(param, is_required);
}
}
pub(crate) fn transform_fn_param(&mut self, param: &mut Param, is_required: bool) {
// 1. Check assign pat type
if let Pat::Assign(assign_pat) = &mut param.pat {
if self.check_assign_pat_param(assign_pat) {
self.parameter_must_have_explicit_type(param.span);
return;
}
}
// 2. Infer type annotation
let (type_ann, should_add_undefined) = match &mut param.pat {
Pat::Ident(ident) => {
if ident.type_ann.is_none() {
self.parameter_must_have_explicit_type(param.span);
}
let is_none = ident.type_ann.is_none();
(ident.type_ann.as_mut(), is_none)
}
Pat::Array(arr_pat) => {
if arr_pat.type_ann.is_none() {
self.parameter_must_have_explicit_type(param.span);
}
let is_none = arr_pat.type_ann.is_none();
(arr_pat.type_ann.as_mut(), is_none)
}
Pat::Object(obj_pat) => {
if obj_pat.type_ann.is_none() {
self.parameter_must_have_explicit_type(param.span);
}
let is_none = obj_pat.type_ann.is_none();
(obj_pat.type_ann.as_mut(), is_none)
}
Pat::Assign(assign_pat) => {
if !self.transform_assign_pat(assign_pat, is_required) {
self.parameter_must_have_explicit_type(param.span);
}
(
match assign_pat.left.as_mut() {
Pat::Ident(ident) => ident.type_ann.as_mut(),
Pat::Array(array_pat) => array_pat.type_ann.as_mut(),
Pat::Object(object_pat) => object_pat.type_ann.as_mut(),
Pat::Assign(_) | Pat::Rest(_) | Pat::Invalid(_) | Pat::Expr(_) => return,
},
true,
)
}
Pat::Rest(_) | Pat::Expr(_) | Pat::Invalid(_) => (None, false),
};
// 3. Add undefined type if needed
if let Some(type_ann) = type_ann {
if is_required && should_add_undefined && self.add_undefined_type_for_param(type_ann) {
self.implicitly_adding_undefined_to_type(param.span);
}
}
// 4. Flat param pat
let pat = mem::take(&mut param.pat);
param.pat = match pat {
Pat::Assign(assign_pat) => *assign_pat.left,
_ => pat,
};
}
pub(crate) fn transform_assign_pat(
&mut self,
assign_pat: &mut AssignPat,
is_required: bool,
) -> bool {
// We can only infer types from the right expr of assign pat
let left_type_ann = match assign_pat.left.as_mut() {
Pat::Ident(ident) => {
ident.optional |= !is_required;
&mut ident.type_ann
}
Pat::Array(array_pat) => {
array_pat.optional |= !is_required;
&mut array_pat.type_ann
}
Pat::Object(object_pat) => {
object_pat.optional |= !is_required;
&mut object_pat.type_ann
}
// These are illegal
Pat::Assign(_) | Pat::Rest(_) | Pat::Invalid(_) | Pat::Expr(_) => return true,
};
let mut has_expclicit_type = true;
if left_type_ann.is_none() {
*left_type_ann = self
.infer_type_from_expr(&assign_pat.right)
.map(type_ann)
.or_else(|| {
has_expclicit_type = false;
Some(any_type_ann())
});
}
has_expclicit_type
}
pub(crate) fn check_assign_pat_param(&mut self, assign_pat: &AssignPat) -> bool {
assign_pat
.left
.as_array()
.map(|array_pat| array_pat.type_ann.is_none())
.unwrap_or(false)
|| assign_pat
.left
.as_object()
.map(|object_pat| object_pat.type_ann.is_none())
.unwrap_or(false)
}
pub(crate) fn add_undefined_type_for_param(&mut self, type_ann: &mut TsTypeAnn) -> bool {
if type_ann.type_ann.is_ts_type_ref() {
return true;
}
if !is_maybe_undefined(&type_ann.type_ann) {
type_ann.type_ann = Box::new(TsType::TsUnionOrIntersectionType(
TsUnionOrIntersectionType::TsUnionType(TsUnionType {
span: DUMMY_SP,
types: vec![
type_ann.type_ann.clone(),
ts_keyword_type(TsKeywordTypeKind::TsUndefinedKeyword),
],
}),
))
}
false
}
pub(crate) fn remove_function_overloads_in_module(items: &mut Vec<ModuleItem>) {
let mut last_function_name: Option<Atom> = None;
let mut is_export_default_function_overloads = false;
items.retain(|item| match item {
ModuleItem::Stmt(Stmt::Decl(Decl::Fn(fn_decl)))
| ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(ExportDecl {
decl: Decl::Fn(fn_decl),
..
})) => {
if fn_decl.function.body.is_some() {
if last_function_name
.as_ref()
.is_some_and(|last_name| last_name == &fn_decl.ident.sym)
{
return false;
}
} else {
last_function_name = Some(fn_decl.ident.sym.clone());
}
true
}
ModuleItem::ModuleDecl(ModuleDecl::ExportDefaultDecl(export)) => {
if let Some(fn_expr) = export.decl.as_fn_expr() {
if is_export_default_function_overloads && fn_expr.function.body.is_some() {
is_export_default_function_overloads = false;
false
} else {
is_export_default_function_overloads = true;
true
}
} else {
is_export_default_function_overloads = false;
true
}
}
_ => true,
});
}
pub(crate) fn remove_function_overloads_in_script(script: &mut Script) {
let mut last_function_name: Option<Atom> = None;
script.body.retain(|stmt| {
if let Some(fn_decl) = stmt.as_decl().and_then(|decl| decl.as_fn_decl()) {
if fn_decl.function.body.is_some() {
if last_function_name
.as_ref()
.is_some_and(|last_name| last_name == &fn_decl.ident.sym)
{
return false;
}
} else {
last_function_name = Some(fn_decl.ident.sym.clone());
}
}
true
});
}
}
fn is_maybe_undefined(ts_type: &TsType) -> bool {
match ts_type {
TsType::TsKeywordType(keyword_type) => matches!(
keyword_type.kind,
TsKeywordTypeKind::TsAnyKeyword
| TsKeywordTypeKind::TsUndefinedKeyword
| TsKeywordTypeKind::TsUnknownKeyword
),
TsType::TsUnionOrIntersectionType(TsUnionOrIntersectionType::TsUnionType(union_type)) => {
union_type.types.iter().any(|ty| is_maybe_undefined(ty))
}
_ => false,
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/src/fast_dts/inferrer.rs | Rust | use swc_common::{Spanned, DUMMY_SP};
use swc_ecma_ast::{
ArrowExpr, BindingIdent, BlockStmtOrExpr, Class, Expr, Function, Ident, Lit, ReturnStmt, Stmt,
TsKeywordTypeKind, TsParenthesizedType, TsType, TsTypeAliasDecl, TsTypeAnn,
TsUnionOrIntersectionType, TsUnionType, UnaryExpr, UnaryOp,
};
use swc_ecma_visit::{Visit, VisitWith};
use super::{
util::types::{ts_keyword_type, type_ann},
FastDts,
};
impl FastDts {
pub(crate) fn infer_type_from_expr(&mut self, e: &Expr) -> Option<Box<TsType>> {
match e {
Expr::Ident(ident) if ident.sym.as_str() == "undefined" => {
Some(ts_keyword_type(TsKeywordTypeKind::TsUndefinedKeyword))
}
Expr::Lit(lit) => match lit {
Lit::Str(_) => Some(ts_keyword_type(TsKeywordTypeKind::TsStringKeyword)),
Lit::Bool(_) => Some(ts_keyword_type(TsKeywordTypeKind::TsBooleanKeyword)),
Lit::Num(_) => Some(ts_keyword_type(TsKeywordTypeKind::TsNumberKeyword)),
Lit::BigInt(_) => Some(ts_keyword_type(TsKeywordTypeKind::TsBigIntKeyword)),
Lit::Null(_) => Some(ts_keyword_type(TsKeywordTypeKind::TsNullKeyword)),
Lit::Regex(_) | Lit::JSXText(_) => None,
},
Expr::Tpl(_) => Some(ts_keyword_type(TsKeywordTypeKind::TsStringKeyword)),
Expr::Fn(fn_expr) => self.transform_fn_to_ts_type(
&fn_expr.function,
fn_expr.ident.as_ref().map(|ident| ident.span),
),
Expr::Arrow(arrow_expr) => self.transform_arrow_expr_to_ts_type(arrow_expr),
Expr::Array(arr) => {
self.array_inferred(arr.span);
Some(ts_keyword_type(TsKeywordTypeKind::TsUnknownKeyword))
}
Expr::Object(obj) => self.transform_object_to_ts_type(obj, false),
Expr::Class(class) => {
self.inferred_type_of_class_expression(class.span());
Some(ts_keyword_type(TsKeywordTypeKind::TsUnknownKeyword))
}
Expr::Paren(expr) => self.infer_type_from_expr(&expr.expr),
Expr::TsNonNull(non_null) => self.infer_type_from_expr(&non_null.expr),
Expr::TsSatisfies(satisifies) => self.infer_type_from_expr(&satisifies.expr),
Expr::TsConstAssertion(assertion) => self.transform_expr_to_ts_type(&assertion.expr),
Expr::TsAs(ts_as) => Some(ts_as.type_ann.clone()),
Expr::TsTypeAssertion(type_assertion) => Some(type_assertion.type_ann.clone()),
Expr::Unary(unary) if Self::can_infer_unary_expr(unary) => {
self.infer_type_from_expr(&unary.arg)
}
_ => None,
}
}
pub(crate) fn infer_function_return_type(
&mut self,
function: &Function,
) -> Option<Box<TsTypeAnn>> {
if function.return_type.is_some() {
return function.return_type.clone();
}
if function.is_async || function.is_generator {
return None;
}
function
.body
.as_ref()
.and_then(|body| ReturnTypeInferrer::infer(self, &body.stmts))
.map(type_ann)
}
pub(crate) fn infer_arrow_return_type(&mut self, arrow: &ArrowExpr) -> Option<Box<TsTypeAnn>> {
if arrow.return_type.is_some() {
return arrow.return_type.clone();
}
if arrow.is_async || arrow.is_generator {
return None;
}
match arrow.body.as_ref() {
BlockStmtOrExpr::BlockStmt(block_stmt) => {
ReturnTypeInferrer::infer(self, &block_stmt.stmts)
}
BlockStmtOrExpr::Expr(expr) => self.infer_type_from_expr(expr),
}
.map(type_ann)
}
pub(crate) fn need_to_infer_type_from_expression(expr: &Expr) -> bool {
match expr {
Expr::Lit(lit) => !(lit.is_str() || lit.is_num() || lit.is_big_int() || lit.is_bool()),
Expr::Tpl(tpl) => !tpl.exprs.is_empty(),
Expr::Unary(unary) => !Self::can_infer_unary_expr(unary),
_ => true,
}
}
pub(crate) fn can_infer_unary_expr(unary: &UnaryExpr) -> bool {
let is_arithmetic = matches!(unary.op, UnaryOp::Plus | UnaryOp::Minus);
let is_number_lit = match unary.arg.as_ref() {
Expr::Lit(lit) => lit.is_num() || lit.is_big_int(),
_ => false,
};
is_arithmetic && is_number_lit
}
}
#[derive(Default)]
pub struct ReturnTypeInferrer {
value_bindings: Vec<Ident>,
type_bindings: Vec<Ident>,
return_expr: Option<Option<Box<Expr>>>,
return_expr_count: u8,
}
impl ReturnTypeInferrer {
pub fn infer(transformer: &mut FastDts, stmts: &[Stmt]) -> Option<Box<TsType>> {
let mut visitor = ReturnTypeInferrer::default();
stmts.visit_children_with(&mut visitor);
let expr = visitor.return_expr??;
let Some(mut expr_type) = transformer.infer_type_from_expr(&expr) else {
return if expr.is_fn_expr() || expr.is_arrow() {
Some(ts_keyword_type(TsKeywordTypeKind::TsUnknownKeyword))
} else {
None
};
};
if let Some((ref_name, is_value)) = match expr_type.as_ref() {
TsType::TsTypeRef(type_ref) => Some((type_ref.type_name.as_ident()?, false)),
TsType::TsTypeQuery(type_query) => {
Some((type_query.expr_name.as_ts_entity_name()?.as_ident()?, true))
}
_ => None,
} {
let is_defined = if is_value {
visitor.value_bindings.contains(ref_name)
} else {
visitor.type_bindings.contains(ref_name)
};
if is_defined {
transformer.type_containing_private_name(ref_name.sym.as_str(), ref_name.span);
}
}
if visitor.return_expr_count > 1 {
if expr_type.is_ts_fn_or_constructor_type() {
expr_type = Box::new(TsType::TsParenthesizedType(TsParenthesizedType {
span: DUMMY_SP,
type_ann: expr_type,
}));
}
expr_type = Box::new(TsType::TsUnionOrIntersectionType(
TsUnionOrIntersectionType::TsUnionType(TsUnionType {
span: DUMMY_SP,
types: vec![
expr_type,
ts_keyword_type(TsKeywordTypeKind::TsUndefinedKeyword),
],
}),
))
}
Some(expr_type)
}
}
impl Visit for ReturnTypeInferrer {
fn visit_arrow_expr(&mut self, _node: &ArrowExpr) {}
fn visit_function(&mut self, _node: &Function) {}
fn visit_class(&mut self, _node: &Class) {}
fn visit_binding_ident(&mut self, node: &BindingIdent) {
self.value_bindings.push(node.id.clone());
}
fn visit_ts_type_alias_decl(&mut self, node: &TsTypeAliasDecl) {
self.type_bindings.push(node.id.clone());
}
fn visit_return_stmt(&mut self, node: &ReturnStmt) {
self.return_expr_count += 1;
if self.return_expr_count > 1 {
if let Some(return_expr) = &self.return_expr {
if return_expr.is_some() {
self.return_expr = None;
return;
}
} else {
return;
}
}
self.return_expr = Some(node.arg.clone());
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/src/fast_dts/mod.rs | Rust | use std::{borrow::Cow, mem::take, sync::Arc};
use rustc_hash::{FxHashMap, FxHashSet};
use swc_atoms::Atom;
use swc_common::{
comments::SingleThreadedComments, util::take::Take, BytePos, FileName, Mark, Span, Spanned,
DUMMY_SP,
};
use swc_ecma_ast::{
BindingIdent, Decl, DefaultDecl, ExportDefaultExpr, Id, Ident, ImportSpecifier, ModuleDecl,
ModuleItem, NamedExport, Pat, Program, Script, Stmt, TsExportAssignment, VarDecl, VarDeclKind,
VarDeclarator,
};
use type_usage::TypeUsageAnalyzer;
use util::{
ast_ext::MemberPropExt, expando_function_collector::ExpandoFunctionCollector, types::type_ann,
};
use visitors::type_usage;
use crate::diagnostic::{DtsIssue, SourceRange};
mod class;
mod decl;
mod r#enum;
mod function;
mod inferrer;
mod types;
mod util;
mod visitors;
/// TypeScript Isolated Declaration support.
///
/// ---
///
/// # License
///
/// Mostly translated from <https://github.com/oxc-project/oxc/tree/main/crates/oxc_isolated_declarations>
///
/// The original code is MIT licensed.
pub struct FastDts {
filename: Arc<FileName>,
unresolved_mark: Mark,
diagnostics: Vec<DtsIssue>,
// states
id_counter: u32,
is_top_level: bool,
used_refs: FxHashSet<Id>,
internal_annotations: Option<FxHashSet<BytePos>>,
}
#[derive(Debug, Default)]
pub struct FastDtsOptions {
pub internal_annotations: Option<FxHashSet<BytePos>>,
}
/// Diagnostics
impl FastDts {
pub fn new(filename: Arc<FileName>, unresolved_mark: Mark, options: FastDtsOptions) -> Self {
let internal_annotations = options.internal_annotations;
Self {
filename,
unresolved_mark,
diagnostics: Vec::new(),
id_counter: 0,
is_top_level: true,
used_refs: FxHashSet::default(),
internal_annotations,
}
}
pub fn mark_diagnostic<T: Into<Cow<'static, str>>>(&mut self, message: T, range: Span) {
self.diagnostics.push(DtsIssue {
message: message.into(),
range: SourceRange {
filename: self.filename.clone(),
span: range,
},
})
}
}
impl FastDts {
pub fn transform(&mut self, program: &mut Program) -> Vec<DtsIssue> {
match program {
Program::Module(module) => self.transform_module_body(&mut module.body, false),
Program::Script(script) => self.transform_script(script),
}
take(&mut self.diagnostics)
}
fn transform_module_body(
&mut self,
items: &mut Vec<ModuleItem>,
in_global_or_lit_module: bool,
) {
// 1. Analyze usage
self.used_refs.extend(TypeUsageAnalyzer::analyze(
items,
self.internal_annotations.as_ref(),
));
// 2. Transform.
Self::remove_function_overloads_in_module(items);
self.transform_module_items(items);
// 3. Strip export keywords in ts module blocks
for item in items.iter_mut() {
if let Some(Stmt::Decl(Decl::TsModule(ts_module))) = item.as_mut_stmt() {
if ts_module.global || !ts_module.id.is_str() {
continue;
}
if let Some(body) = ts_module
.body
.as_mut()
.and_then(|body| body.as_mut_ts_module_block())
{
self.strip_export(&mut body.body);
}
}
}
// 4. Report error for expando function and remove statements.
self.report_error_for_expando_function_in_module(items);
items.retain(|item| {
item.as_stmt()
.map(|stmt| stmt.is_decl() && !self.has_internal_annotation(stmt.span_lo()))
.unwrap_or(true)
});
// 5. Remove unused imports and decls
self.remove_ununsed(items, in_global_or_lit_module);
// 6. Add empty export mark if there's any declaration that is used but not
// exported to keep its privacy.
let mut has_non_exported_stmt = false;
let mut has_export = false;
for item in items.iter_mut() {
match item {
ModuleItem::Stmt(stmt) => {
if stmt.as_decl().map_or(true, |decl| !decl.is_ts_module()) {
has_non_exported_stmt = true;
}
}
ModuleItem::ModuleDecl(
ModuleDecl::ExportDefaultDecl(_)
| ModuleDecl::ExportDefaultExpr(_)
| ModuleDecl::ExportNamed(_)
| ModuleDecl::TsExportAssignment(_),
) => has_export = true,
_ => {}
}
}
if items.is_empty() || (has_non_exported_stmt && !has_export) {
items.push(ModuleItem::ModuleDecl(ModuleDecl::ExportNamed(
NamedExport {
span: DUMMY_SP,
specifiers: Vec::new(),
src: None,
type_only: false,
with: None,
},
)));
} else if !self.is_top_level {
self.strip_export(items);
}
}
fn transform_script(&mut self, script: &mut Script) {
// 1. Transform.
Self::remove_function_overloads_in_script(script);
let body = script.body.take();
for mut stmt in body {
if self.has_internal_annotation(stmt.span_lo()) {
continue;
}
if let Some(decl) = stmt.as_mut_decl() {
self.transform_decl(decl, false);
}
script.body.push(stmt);
}
// 2. Report error for expando function and remove statements.
self.report_error_for_expando_function_in_script(&script.body);
script
.body
.retain(|stmt| stmt.is_decl() && !self.has_internal_annotation(stmt.span_lo()));
}
fn transform_module_items(&mut self, items: &mut Vec<ModuleItem>) {
let orig_items = take(items);
for mut item in orig_items {
match &mut item {
ModuleItem::ModuleDecl(
ModuleDecl::Import(..)
| ModuleDecl::TsImportEquals(_)
| ModuleDecl::TsNamespaceExport(_),
) => items.push(item),
ModuleItem::ModuleDecl(ModuleDecl::ExportNamed(_) | ModuleDecl::ExportAll(_)) => {
items.push(item);
}
ModuleItem::Stmt(stmt) => {
if self.has_internal_annotation(stmt.span_lo()) {
continue;
}
if let Some(decl) = stmt.as_mut_decl() {
self.transform_decl(decl, true);
}
items.push(item);
}
ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(expor_decl)) => {
if self.has_internal_annotation(expor_decl.span_lo()) {
continue;
}
self.transform_decl(&mut expor_decl.decl, false);
items.push(item);
}
ModuleItem::ModuleDecl(ModuleDecl::ExportDefaultDecl(export)) => {
self.transform_default_decl(&mut export.decl);
items.push(item);
}
ModuleItem::ModuleDecl(
ModuleDecl::ExportDefaultExpr(_) | ModuleDecl::TsExportAssignment(_),
) => {
let expr = match &item {
ModuleItem::ModuleDecl(ModuleDecl::ExportDefaultExpr(export)) => {
&export.expr
}
ModuleItem::ModuleDecl(ModuleDecl::TsExportAssignment(export)) => {
&export.expr
}
_ => unreachable!(),
};
if expr.is_ident() {
items.push(item);
continue;
}
let name_ident = Ident::new_no_ctxt(self.gen_unique_name("_default"), DUMMY_SP);
let type_ann = self.infer_type_from_expr(expr).map(type_ann);
self.used_refs.insert(name_ident.to_id());
if type_ann.is_none() {
self.default_export_inferred(expr.span());
}
items.push(
VarDecl {
span: DUMMY_SP,
kind: VarDeclKind::Const,
declare: true,
decls: vec![VarDeclarator {
span: DUMMY_SP,
name: Pat::Ident(BindingIdent {
id: name_ident.clone(),
type_ann,
}),
init: None,
definite: false,
}],
..Default::default()
}
.into(),
);
match &item {
ModuleItem::ModuleDecl(ModuleDecl::ExportDefaultExpr(export)) => items
.push(
ExportDefaultExpr {
span: export.span,
expr: name_ident.into(),
}
.into(),
),
ModuleItem::ModuleDecl(ModuleDecl::TsExportAssignment(export)) => items
.push(
TsExportAssignment {
span: export.span,
expr: name_ident.into(),
}
.into(),
),
_ => unreachable!(),
};
}
}
}
}
fn report_error_for_expando_function_in_module(&mut self, items: &[ModuleItem]) {
let used_refs = self.used_refs.clone();
let mut assignable_properties_for_namespace = FxHashMap::<&str, FxHashSet<Atom>>::default();
let mut collector = ExpandoFunctionCollector::new(&used_refs);
for item in items {
let decl = match item {
ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(export_decl)) => {
if let Some(ts_module) = export_decl.decl.as_ts_module() {
ts_module
} else {
continue;
}
}
ModuleItem::Stmt(Stmt::Decl(Decl::TsModule(ts_module))) => ts_module,
_ => continue,
};
let (Some(name), Some(block)) = (
decl.id.as_ident(),
decl.body
.as_ref()
.and_then(|body| body.as_ts_module_block()),
) else {
continue;
};
for item in &block.body {
// Note that all the module blocks have been transformed
let Some(decl) = item.as_stmt().and_then(|stmt| stmt.as_decl()) else {
continue;
};
match &decl {
Decl::Class(class_decl) => {
assignable_properties_for_namespace
.entry(name.sym.as_str())
.or_default()
.insert(class_decl.ident.sym.clone());
}
Decl::Fn(fn_decl) => {
assignable_properties_for_namespace
.entry(name.sym.as_str())
.or_default()
.insert(fn_decl.ident.sym.clone());
}
Decl::Var(var_decl) => {
for decl in &var_decl.decls {
if let Some(ident) = decl.name.as_ident() {
assignable_properties_for_namespace
.entry(name.sym.as_str())
.or_default()
.insert(ident.sym.clone());
}
}
}
Decl::Using(using_decl) => {
for decl in &using_decl.decls {
if let Some(ident) = decl.name.as_ident() {
assignable_properties_for_namespace
.entry(name.sym.as_str())
.or_default()
.insert(ident.sym.clone());
}
}
}
_ => {}
}
}
}
for item in items {
match item {
ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(export_decl)) => {
match &export_decl.decl {
Decl::Fn(fn_decl) => collector.add_fn_decl(fn_decl, false),
Decl::Var(var_decl) => collector.add_var_decl(var_decl, false),
_ => (),
}
}
ModuleItem::ModuleDecl(ModuleDecl::ExportDefaultDecl(export_decl)) => {
if let DefaultDecl::Fn(fn_expr) = &export_decl.decl {
collector.add_fn_expr(fn_expr)
}
}
ModuleItem::ModuleDecl(ModuleDecl::ExportNamed(_export_named)) => {
// TODO: may be function
}
ModuleItem::Stmt(Stmt::Decl(decl)) => match decl {
Decl::Fn(fn_decl) => collector.add_fn_decl(fn_decl, true),
Decl::Var(var_decl) => collector.add_var_decl(var_decl, true),
_ => (),
},
ModuleItem::Stmt(Stmt::Expr(expr_stmt)) => {
let Some(assign_expr) = expr_stmt.expr.as_assign() else {
continue;
};
let Some(member_expr) = assign_expr
.left
.as_simple()
.and_then(|simple| simple.as_member())
else {
continue;
};
if let Some(ident) = member_expr.obj.as_ident() {
if collector.contains(&ident.sym)
&& !assignable_properties_for_namespace
.get(ident.sym.as_str())
.map_or(false, |properties| {
member_expr
.prop
.static_name()
.map_or(false, |name| properties.contains(name))
})
{
self.function_with_assigning_properties(member_expr.span);
}
}
}
_ => (),
}
}
}
fn report_error_for_expando_function_in_script(&mut self, stmts: &[Stmt]) {
let used_refs = self.used_refs.clone();
let mut collector = ExpandoFunctionCollector::new(&used_refs);
for stmt in stmts {
match stmt {
Stmt::Decl(decl) => match decl {
Decl::Fn(fn_decl) => collector.add_fn_decl(fn_decl, false),
Decl::Var(var_decl) => collector.add_var_decl(var_decl, false),
_ => (),
},
Stmt::Expr(expr_stmt) => {
let Some(assign_expr) = expr_stmt.expr.as_assign() else {
continue;
};
let Some(member_expr) = assign_expr
.left
.as_simple()
.and_then(|simple| simple.as_member())
else {
continue;
};
if let Some(ident) = member_expr.obj.as_ident() {
if collector.contains(&ident.sym) {
self.function_with_assigning_properties(member_expr.span);
}
}
}
_ => (),
}
}
}
fn strip_export(&self, items: &mut Vec<ModuleItem>) {
for item in items {
if let ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(export_decl)) = item {
*item = ModuleItem::Stmt(Stmt::Decl(export_decl.decl.clone()));
}
}
}
fn remove_ununsed(&self, items: &mut Vec<ModuleItem>, in_global_or_lit_module: bool) {
let used_refs = &self.used_refs;
items.retain_mut(|node| match node {
ModuleItem::Stmt(Stmt::Decl(decl)) if !in_global_or_lit_module => match decl {
Decl::Class(class_decl) => used_refs.contains(&class_decl.ident.to_id()),
Decl::Fn(fn_decl) => used_refs.contains(&fn_decl.ident.to_id()),
Decl::Var(var_decl) => {
var_decl.decls.retain(|decl| {
if let Some(ident) = decl.name.as_ident() {
used_refs.contains(&ident.to_id())
} else {
false
}
});
!var_decl.decls.is_empty()
}
Decl::Using(using_decl) => {
using_decl.decls.retain(|decl| {
if let Some(ident) = decl.name.as_ident() {
used_refs.contains(&ident.to_id())
} else {
false
}
});
!using_decl.decls.is_empty()
}
Decl::TsInterface(ts_interface_decl) => {
used_refs.contains(&ts_interface_decl.id.to_id())
}
Decl::TsTypeAlias(ts_type_alias_decl) => {
used_refs.contains(&ts_type_alias_decl.id.to_id())
}
Decl::TsEnum(ts_enum) => used_refs.contains(&ts_enum.id.to_id()),
Decl::TsModule(ts_module_decl) => {
ts_module_decl.global
|| ts_module_decl.id.is_str()
|| ts_module_decl
.id
.as_ident()
.map_or(true, |ident| used_refs.contains(&ident.to_id()))
}
},
ModuleItem::ModuleDecl(ModuleDecl::Import(import_decl)) => {
if import_decl.specifiers.is_empty() {
return true;
}
import_decl.specifiers.retain(|specifier| match specifier {
ImportSpecifier::Named(specifier) => {
used_refs.contains(&specifier.local.to_id())
}
ImportSpecifier::Default(specifier) => {
used_refs.contains(&specifier.local.to_id())
}
ImportSpecifier::Namespace(specifier) => {
used_refs.contains(&specifier.local.to_id())
}
});
!import_decl.specifiers.is_empty()
}
ModuleItem::ModuleDecl(ModuleDecl::TsImportEquals(ts_import_equals)) => {
used_refs.contains(&ts_import_equals.id.to_id())
}
_ => true,
});
}
pub fn has_internal_annotation(&self, pos: BytePos) -> bool {
if let Some(internal_annotations) = &self.internal_annotations {
return internal_annotations.contains(&pos);
}
false
}
pub fn get_internal_annotations(comments: &SingleThreadedComments) -> FxHashSet<BytePos> {
let mut internal_annotations = FxHashSet::default();
let (leading, _) = comments.borrow_all();
for (pos, comment) in leading.iter() {
let has_internal_annotation = comment
.iter()
.any(|comment| comment.text.contains("@internal"));
if has_internal_annotation {
internal_annotations.insert(*pos);
}
}
internal_annotations
}
fn gen_unique_name(&mut self, name: &str) -> Atom {
self.id_counter += 1;
format!("{name}_{}", self.id_counter).into()
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/src/fast_dts/types.rs | Rust | use swc_common::{BytePos, Span, Spanned, DUMMY_SP};
use swc_ecma_ast::{
ArrayLit, ArrowExpr, Expr, Function, Lit, ObjectLit, Param, Pat, Prop, PropName, PropOrSpread,
Str, Tpl, TsFnOrConstructorType, TsFnParam, TsFnType, TsKeywordTypeKind, TsLit,
TsMethodSignature, TsPropertySignature, TsTupleElement, TsTupleType, TsType, TsTypeElement,
TsTypeLit, TsTypeOperator, TsTypeOperatorOp, UnaryOp,
};
use super::{
inferrer::ReturnTypeInferrer,
type_ann,
util::{
ast_ext::{ExprExit, PatExt},
types::{ts_keyword_type, ts_lit_type},
},
FastDts,
};
impl FastDts {
pub(crate) fn transform_expr_to_ts_type(&mut self, expr: &Expr) -> Option<Box<TsType>> {
match expr {
Expr::Ident(ident) if ident.sym == "undefined" => {
Some(ts_keyword_type(TsKeywordTypeKind::TsUndefinedKeyword))
}
Expr::Lit(lit) => match lit {
Lit::Str(string) => Some(ts_lit_type(TsLit::Str(string.clone()))),
Lit::Bool(b) => Some(ts_lit_type(TsLit::Bool(*b))),
Lit::Null(_) => Some(ts_keyword_type(TsKeywordTypeKind::TsNullKeyword)),
Lit::Num(number) => Some(ts_lit_type(TsLit::Number(number.clone()))),
Lit::BigInt(big_int) => Some(ts_lit_type(TsLit::BigInt(big_int.clone()))),
Lit::Regex(_) | Lit::JSXText(_) => None,
},
Expr::Tpl(tpl) => self
.tpl_to_string(tpl)
.map(|string| ts_lit_type(TsLit::Str(string))),
Expr::Unary(unary) if Self::can_infer_unary_expr(unary) => {
let mut expr = self.transform_expr_to_ts_type(&unary.arg)?;
if unary.op == UnaryOp::Minus {
match &mut expr.as_mut_ts_lit_type()?.lit {
TsLit::Number(number) => {
number.value = -number.value;
number.raw = None;
}
TsLit::BigInt(big_int) => {
*big_int.value = -*big_int.value.clone();
big_int.raw = None;
}
_ => {}
}
};
Some(expr)
}
Expr::Array(array) => self.transform_array_to_ts_type(array),
Expr::Object(obj) => self.transform_object_to_ts_type(obj, true),
Expr::Fn(fn_expr) => self.transform_fn_to_ts_type(
&fn_expr.function,
fn_expr.ident.as_ref().map(|ident| ident.span),
),
Expr::Arrow(arrow) => self.transform_arrow_expr_to_ts_type(arrow),
Expr::TsConstAssertion(assertion) => self.transform_expr_to_ts_type(&assertion.expr),
Expr::TsAs(ts_as) => Some(ts_as.type_ann.clone()),
_ => None,
}
}
pub(crate) fn transform_fn_to_ts_type(
&mut self,
function: &Function,
ident_span: Option<Span>,
) -> Option<Box<TsType>> {
let return_type = self.infer_function_return_type(function);
if return_type.is_none() {
self.function_must_have_explicit_return_type(
ident_span
.unwrap_or_else(|| Span::new(function.span_lo(), function.body.span_lo())),
);
}
return_type.map(|return_type| {
Box::new(TsType::TsFnOrConstructorType(
TsFnOrConstructorType::TsFnType(TsFnType {
span: DUMMY_SP,
params: self.transform_fn_params_to_ts_type(&function.params),
type_params: function.type_params.clone(),
type_ann: return_type,
}),
))
})
}
pub(crate) fn transform_arrow_expr_to_ts_type(
&mut self,
arrow: &ArrowExpr,
) -> Option<Box<TsType>> {
let return_type = self.infer_arrow_return_type(arrow);
if return_type.is_none() {
self.function_must_have_explicit_return_type(Span::new(
arrow.span_lo(),
arrow.body.span_lo() + BytePos(1),
));
}
return_type.map(|return_type| {
Box::new(TsType::TsFnOrConstructorType(
TsFnOrConstructorType::TsFnType(TsFnType {
span: DUMMY_SP,
params: self.transform_fn_params_to_ts_type(
&arrow
.params
.iter()
.map(|pat| Param {
span: pat.span(),
decorators: Vec::new(),
pat: pat.clone(),
})
.collect::<Vec<_>>(),
),
type_params: arrow.type_params.clone(),
type_ann: return_type,
}),
))
})
}
pub(crate) fn transform_fn_params_to_ts_type(&mut self, params: &[Param]) -> Vec<TsFnParam> {
let mut params = params.to_owned().clone();
self.transform_fn_params(&mut params);
params
.into_iter()
.filter_map(|param| match param.pat {
Pat::Ident(binding_ident) => Some(TsFnParam::Ident(binding_ident)),
Pat::Array(array_pat) => Some(TsFnParam::Array(array_pat)),
Pat::Rest(rest_pat) => Some(TsFnParam::Rest(rest_pat)),
Pat::Object(object_pat) => Some(TsFnParam::Object(object_pat)),
Pat::Assign(_) | Pat::Invalid(_) | Pat::Expr(_) => None,
})
.collect()
}
pub(crate) fn transform_object_to_ts_type(
&mut self,
object: &ObjectLit,
is_const: bool,
) -> Option<Box<TsType>> {
let mut members = Vec::new();
for prop in &object.props {
match prop {
PropOrSpread::Prop(prop) => match prop.as_ref() {
Prop::Shorthand(_) => {
self.shorthand_property(object.span);
continue;
}
Prop::KeyValue(kv) => {
if self.report_property_key(&kv.key) {
continue;
}
let type_ann = if is_const {
self.transform_expr_to_ts_type(&kv.value)
} else {
self.infer_type_from_expr(&kv.value)
}
.map(type_ann);
if type_ann.is_none() {
self.inferred_type_of_expression(kv.value.span());
}
let (key, computed) = self.transform_property_name_to_expr(&kv.key);
members.push(TsTypeElement::TsPropertySignature(TsPropertySignature {
span: DUMMY_SP,
readonly: is_const,
key: Box::new(key),
computed,
optional: false,
type_ann,
}));
}
Prop::Getter(getter) => {
if self.report_property_key(&getter.key) {
continue;
}
let type_ann = getter.type_ann.clone().or_else(|| {
getter
.body
.as_ref()
.and_then(|body| ReturnTypeInferrer::infer(self, &body.stmts))
.map(type_ann)
});
if type_ann.is_none() {
self.accessor_must_have_explicit_return_type(getter.span);
}
let (key, computed) = self.transform_property_name_to_expr(&getter.key);
members.push(TsTypeElement::TsPropertySignature(TsPropertySignature {
span: DUMMY_SP,
readonly: is_const,
key: Box::new(key),
computed,
optional: false,
type_ann,
}));
}
Prop::Setter(setter) => {
if self.report_property_key(&setter.key) {
continue;
}
let (key, computed) = self.transform_property_name_to_expr(&setter.key);
members.push(TsTypeElement::TsPropertySignature(TsPropertySignature {
span: DUMMY_SP,
readonly: is_const,
key: Box::new(key),
computed,
optional: false,
type_ann: setter.param.get_type_ann().clone(),
}));
}
Prop::Method(method) => {
if self.report_property_key(&method.key) {
continue;
}
if is_const {
let (key, computed) = self.transform_property_name_to_expr(&method.key);
members.push(TsTypeElement::TsPropertySignature(TsPropertySignature {
span: DUMMY_SP,
readonly: is_const,
key: Box::new(key),
computed,
optional: false,
type_ann: self
.transform_fn_to_ts_type(
&method.function,
Some(method.key.span()),
)
.map(type_ann),
}));
} else {
let return_type = self.infer_function_return_type(&method.function);
let (key, computed) = self.transform_property_name_to_expr(&method.key);
members.push(TsTypeElement::TsMethodSignature(TsMethodSignature {
span: DUMMY_SP,
key: Box::new(key),
computed,
optional: false,
params: self
.transform_fn_params_to_ts_type(&method.function.params),
type_ann: return_type,
type_params: method.function.type_params.clone(),
}));
}
}
Prop::Assign(_) => {}
},
PropOrSpread::Spread(spread_element) => {
self.object_with_spread_assignments(spread_element.span());
}
}
}
Some(Box::new(TsType::TsTypeLit(TsTypeLit {
span: DUMMY_SP,
members,
})))
}
pub(crate) fn transform_array_to_ts_type(&mut self, array: &ArrayLit) -> Option<Box<TsType>> {
let mut elements = Vec::new();
for elem in &array.elems {
let Some(elem) = elem else {
elements.push(TsTupleElement {
span: DUMMY_SP,
label: None,
ty: ts_keyword_type(TsKeywordTypeKind::TsUndefinedKeyword),
});
continue;
};
if let Some(spread_span) = elem.spread {
self.arrays_with_spread_elements(spread_span);
continue;
}
if let Some(type_ann) = self.transform_expr_to_ts_type(&elem.expr) {
elements.push(TsTupleElement {
span: DUMMY_SP,
label: None,
ty: type_ann,
});
} else {
self.inferred_type_of_expression(elem.span());
}
}
Some(Box::new(TsType::TsTypeOperator(TsTypeOperator {
span: DUMMY_SP,
op: TsTypeOperatorOp::ReadOnly,
type_ann: Box::new(TsType::TsTupleType(TsTupleType {
span: DUMMY_SP,
elem_types: elements,
})),
})))
}
pub(crate) fn transform_property_name_to_expr(&mut self, name: &PropName) -> (Expr, bool) {
match name {
PropName::Ident(ident) => (Expr::Ident(ident.clone().into()), false),
PropName::Str(str_prop) => (Lit::Str(str_prop.clone()).into(), false),
PropName::Num(num) => (Lit::Num(num.clone()).into(), true),
PropName::Computed(computed) => (*computed.expr.clone(), true),
PropName::BigInt(big_int) => (Lit::BigInt(big_int.clone()).into(), true),
}
}
pub(crate) fn check_ts_signature(&mut self, signature: &TsTypeElement) {
match signature {
TsTypeElement::TsPropertySignature(ts_property_signature) => {
self.report_signature_property_key(
&ts_property_signature.key,
ts_property_signature.computed,
);
}
TsTypeElement::TsGetterSignature(ts_getter_signature) => {
self.report_signature_property_key(
&ts_getter_signature.key,
ts_getter_signature.computed,
);
}
TsTypeElement::TsSetterSignature(ts_setter_signature) => {
self.report_signature_property_key(
&ts_setter_signature.key,
ts_setter_signature.computed,
);
}
TsTypeElement::TsMethodSignature(ts_method_signature) => {
self.report_signature_property_key(
&ts_method_signature.key,
ts_method_signature.computed,
);
}
_ => {}
}
}
pub(crate) fn report_signature_property_key(&mut self, key: &Expr, computed: bool) {
if !computed {
return;
}
let is_not_allowed = match key {
Expr::Ident(_) | Expr::Member(_) | Expr::OptChain(_) => key.get_root_ident().is_none(),
_ => !Self::is_literal(key),
};
if is_not_allowed {
self.signature_computed_property_name(key.span());
}
}
pub(crate) fn tpl_to_string(&mut self, tpl: &Tpl) -> Option<Str> {
if !tpl.exprs.is_empty() {
return None;
}
tpl.quasis.first().map(|element| Str {
span: DUMMY_SP,
value: element.cooked.as_ref().unwrap_or(&element.raw).clone(),
raw: None,
})
}
pub(crate) fn is_literal(expr: &Expr) -> bool {
match expr {
Expr::Lit(_) => true,
Expr::Unary(unary) => Self::can_infer_unary_expr(unary),
_ => false,
}
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/src/fast_dts/util/ast_ext.rs | Rust | use std::borrow::Cow;
use swc_atoms::Atom;
use swc_ecma_ast::{
BindingIdent, Expr, Ident, Lit, MemberProp, ObjectPatProp, Pat, PropName, TsTypeAnn,
};
pub trait ExprExit {
fn get_root_ident(&self) -> Option<&Ident>;
}
impl ExprExit for Expr {
fn get_root_ident(&self) -> Option<&Ident> {
match self {
Expr::Member(member_expr) => member_expr.obj.get_root_ident(),
Expr::Ident(ident) => Some(ident),
Expr::OptChain(opt_chain_expr) => opt_chain_expr
.base
.as_member()
.and_then(|member_expr| member_expr.obj.get_root_ident()),
_ => None,
}
}
}
pub trait PatExt {
fn get_type_ann(&self) -> &Option<Box<TsTypeAnn>>;
fn set_type_ann(&mut self, type_anno: Option<Box<TsTypeAnn>>);
fn bound_names<F: FnMut(&BindingIdent)>(&self, f: &mut F);
}
impl PatExt for Pat {
fn get_type_ann(&self) -> &Option<Box<TsTypeAnn>> {
let pat = match self {
Pat::Assign(assign_pat) => &assign_pat.left,
_ => self,
};
match pat {
Pat::Ident(binding_ident) => &binding_ident.type_ann,
Pat::Array(array_pat) => &array_pat.type_ann,
Pat::Rest(rest_pat) => &rest_pat.type_ann,
Pat::Object(object_pat) => &object_pat.type_ann,
Pat::Assign(_) | Pat::Invalid(_) | Pat::Expr(_) => &None,
}
}
fn set_type_ann(&mut self, type_anno: Option<Box<TsTypeAnn>>) {
let pat = match self {
Pat::Assign(assign_pat) => &mut assign_pat.left,
_ => self,
};
match pat {
Pat::Ident(binding_ident) => binding_ident.type_ann = type_anno,
Pat::Array(array_pat) => array_pat.type_ann = type_anno,
Pat::Rest(rest_pat) => rest_pat.type_ann = type_anno,
Pat::Object(object_pat) => object_pat.type_ann = type_anno,
Pat::Assign(_) | Pat::Invalid(_) | Pat::Expr(_) => {}
}
}
fn bound_names<F: FnMut(&BindingIdent)>(&self, f: &mut F) {
match self {
Pat::Ident(binding_ident) => f(binding_ident),
Pat::Array(array_pat) => {
for pat in array_pat.elems.iter().flatten() {
pat.bound_names(f);
}
}
Pat::Rest(rest_pat) => rest_pat.arg.bound_names(f),
Pat::Object(object_pat) => {
for pat in &object_pat.props {
match pat {
ObjectPatProp::KeyValue(key_value_pat_prop) => {
key_value_pat_prop.value.bound_names(f)
}
ObjectPatProp::Assign(assign_pat_prop) => f(&assign_pat_prop.key),
ObjectPatProp::Rest(rest_pat) => rest_pat.arg.bound_names(f),
}
}
}
Pat::Assign(assign_pat) => assign_pat.left.bound_names(f),
Pat::Invalid(_) | Pat::Expr(_) => todo!(),
}
}
}
pub trait PropNameExit {
fn static_name(&self) -> Option<Cow<str>>;
}
impl PropNameExit for PropName {
fn static_name(&self) -> Option<Cow<str>> {
match self {
PropName::Ident(ident_name) => Some(Cow::Borrowed(ident_name.sym.as_str())),
PropName::Str(string) => Some(Cow::Borrowed(string.value.as_str())),
PropName::Num(number) => Some(Cow::Owned(number.value.to_string())),
PropName::BigInt(big_int) => Some(Cow::Owned(big_int.value.to_string())),
PropName::Computed(computed_prop_name) => match computed_prop_name.expr.as_ref() {
Expr::Lit(lit) => match lit {
Lit::Str(string) => Some(Cow::Borrowed(string.value.as_str())),
Lit::Bool(b) => Some(Cow::Owned(b.value.to_string())),
Lit::Null(_) => Some(Cow::Borrowed("null")),
Lit::Num(number) => Some(Cow::Owned(number.value.to_string())),
Lit::BigInt(big_int) => Some(Cow::Owned(big_int.value.to_string())),
Lit::Regex(regex) => Some(Cow::Owned(regex.exp.to_string())),
Lit::JSXText(_) => None,
},
Expr::Tpl(tpl) if tpl.exprs.is_empty() => tpl
.quasis
.first()
.and_then(|e| e.cooked.as_ref())
.map(|atom| Cow::Borrowed(atom.as_str())),
_ => None,
},
}
}
}
pub trait MemberPropExt {
fn static_name(&self) -> Option<&Atom>;
}
impl MemberPropExt for MemberProp {
fn static_name(&self) -> Option<&Atom> {
match self {
MemberProp::Ident(ident_name) => Some(&ident_name.sym),
MemberProp::Computed(computed_prop_name) => match computed_prop_name.expr.as_ref() {
Expr::Lit(Lit::Str(s)) => Some(&s.value),
Expr::Tpl(tpl) if tpl.quasis.len() == 1 && tpl.exprs.is_empty() => {
Some(&tpl.quasis[0].raw)
}
_ => None,
},
MemberProp::PrivateName(_) => None,
}
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/src/fast_dts/util/expando_function_collector.rs | Rust | use rustc_hash::FxHashSet;
use swc_atoms::Atom;
use swc_ecma_ast::{FnDecl, FnExpr, Id, VarDecl};
use super::ast_ext::PatExt;
pub(crate) struct ExpandoFunctionCollector<'a> {
declared_function_names: FxHashSet<Atom>,
used_refs: &'a FxHashSet<Id>,
}
impl<'a> ExpandoFunctionCollector<'a> {
pub(crate) fn new(used_refs: &'a FxHashSet<Id>) -> Self {
Self {
declared_function_names: FxHashSet::default(),
used_refs,
}
}
pub(crate) fn add_fn_expr(&mut self, fn_expr: &FnExpr) {
if let Some(ident) = fn_expr.ident.as_ref() {
self.declared_function_names.insert(ident.sym.clone());
}
}
pub(crate) fn add_fn_decl(&mut self, fn_decl: &FnDecl, check_binding: bool) {
if !check_binding || self.used_refs.contains(&fn_decl.ident.to_id()) {
self.declared_function_names
.insert(fn_decl.ident.sym.clone());
}
}
pub(crate) fn add_var_decl(&mut self, var_decl: &VarDecl, check_binding: bool) {
for decl in &var_decl.decls {
if decl
.name
.get_type_ann()
.as_ref()
.is_some_and(|type_ann| type_ann.type_ann.is_ts_fn_or_constructor_type())
{
if let Some(name) = decl.name.as_ident() {
if !check_binding || self.used_refs.contains(&name.to_id()) {
self.declared_function_names.insert(name.sym.clone());
}
}
}
}
}
pub(crate) fn contains(&self, name: &Atom) -> bool {
self.declared_function_names.contains(name)
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/src/fast_dts/util/mod.rs | Rust | pub mod ast_ext;
pub mod expando_function_collector;
pub mod types;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/src/fast_dts/util/types.rs | Rust | use swc_common::DUMMY_SP;
use swc_ecma_ast::{TsKeywordType, TsKeywordTypeKind, TsLit, TsLitType, TsType, TsTypeAnn};
pub fn any_type_ann() -> Box<TsTypeAnn> {
type_ann(ts_keyword_type(TsKeywordTypeKind::TsAnyKeyword))
}
pub fn type_ann(ts_type: Box<TsType>) -> Box<TsTypeAnn> {
Box::new(TsTypeAnn {
span: DUMMY_SP,
type_ann: ts_type,
})
}
pub fn ts_keyword_type(kind: TsKeywordTypeKind) -> Box<TsType> {
Box::new(TsType::TsKeywordType(TsKeywordType {
span: DUMMY_SP,
kind,
}))
}
pub fn ts_lit_type(lit: TsLit) -> Box<TsType> {
Box::new(TsType::TsLitType(TsLitType {
span: DUMMY_SP,
lit,
}))
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/src/fast_dts/visitors/internal_annotation.rs | Rust | use rustc_hash::FxHashSet;
use swc_common::{BytePos, Spanned};
use swc_ecma_ast::TsTypeElement;
use swc_ecma_visit::VisitMut;
pub struct InternalAnnotationTransformer<'a> {
internal_annotations: &'a FxHashSet<BytePos>,
}
impl<'a> InternalAnnotationTransformer<'a> {
pub fn new(internal_annotations: &'a FxHashSet<BytePos>) -> Self {
Self {
internal_annotations,
}
}
}
impl VisitMut for InternalAnnotationTransformer<'_> {
fn visit_mut_ts_type_elements(&mut self, node: &mut Vec<TsTypeElement>) {
node.retain(|elem| !self.internal_annotations.contains(&elem.span_lo()));
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/src/fast_dts/visitors/mod.rs | Rust | pub(crate) mod internal_annotation;
pub(crate) mod type_usage;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/src/fast_dts/visitors/type_usage.rs | Rust | use petgraph::{
graph::{DiGraph, NodeIndex},
visit::Bfs,
Graph,
};
use rustc_hash::{FxHashMap, FxHashSet};
use swc_common::{BytePos, Spanned, SyntaxContext};
use swc_ecma_ast::{
Accessibility, Class, ClassMember, Decl, ExportDecl, ExportDefaultDecl, ExportDefaultExpr,
Function, Id, Ident, ModuleExportName, ModuleItem, NamedExport, TsEntityName,
TsExportAssignment, TsExprWithTypeArgs, TsPropertySignature, TsTypeElement,
};
use swc_ecma_visit::{Visit, VisitWith};
use crate::fast_dts::util::ast_ext::ExprExit;
pub struct TypeUsageAnalyzer<'a> {
graph: DiGraph<Id, ()>,
nodes: FxHashMap<Id, NodeIndex>,
// Global scope + nested ts module block scope
scope_entries: Vec<NodeIndex>,
// We will only consider referred nodes and ignore binding nodes
references: FxHashSet<NodeIndex>,
source: Option<NodeIndex>,
internal_annotations: Option<&'a FxHashSet<BytePos>>,
}
impl TypeUsageAnalyzer<'_> {
pub fn analyze(
module_items: &Vec<ModuleItem>,
internal_annotations: Option<&FxHashSet<BytePos>>,
) -> FxHashSet<Id> {
// Create a fake entry
let mut graph = Graph::default();
let entry = graph.add_node(("".into(), SyntaxContext::empty()));
let mut analyzer = TypeUsageAnalyzer {
graph,
nodes: FxHashMap::default(),
scope_entries: vec![entry],
references: FxHashSet::default(),
source: None,
internal_annotations,
};
module_items.visit_with(&mut analyzer);
// Reachability
let mut used_refs = FxHashSet::default();
let mut bfs = Bfs::new(&analyzer.graph, entry);
bfs.next(&analyzer.graph);
while let Some(node_id) = bfs.next(&analyzer.graph) {
if analyzer.references.contains(&node_id) {
used_refs.insert(analyzer.graph[node_id].clone());
}
}
used_refs
}
pub fn with_source<F: FnMut(&mut TypeUsageAnalyzer)>(
&mut self,
id: Option<NodeIndex>,
mut f: F,
) {
// If id is None, we use the nearest scope
let old_source = self
.source
.replace(id.unwrap_or(*self.scope_entries.last().expect("No scope")));
f(self);
self.source = old_source;
}
pub fn with_source_ident<F: FnMut(&mut TypeUsageAnalyzer)>(&mut self, ident: &Ident, f: F) {
self.add_edge(ident.to_id(), false);
let id = *self
.nodes
.entry(ident.to_id())
.or_insert_with(|| self.graph.add_node(ident.to_id()));
self.with_source(Some(id), f);
}
pub fn add_edge(&mut self, reference: Id, is_ref: bool) {
if let Some(source) = self.source {
let target_id = *self
.nodes
.entry(reference.clone())
.or_insert_with(|| self.graph.add_node(reference));
self.graph.add_edge(source, target_id, ());
if is_ref {
self.references.insert(target_id);
}
}
}
fn has_internal_annotation(&self, pos: BytePos) -> bool {
if let Some(internal_annotations) = &self.internal_annotations {
return internal_annotations.contains(&pos);
}
false
}
}
impl Visit for TypeUsageAnalyzer<'_> {
fn visit_ts_property_signature(&mut self, node: &TsPropertySignature) {
if let Some(ident) = node.key.get_root_ident() {
self.add_edge(ident.to_id(), true);
}
node.visit_children_with(self);
}
fn visit_ts_expr_with_type_args(&mut self, node: &TsExprWithTypeArgs) {
if let Some(ident) = node.expr.get_root_ident() {
self.add_edge(ident.to_id(), true);
}
node.visit_children_with(self);
}
fn visit_ts_entity_name(&mut self, node: &TsEntityName) {
match node {
TsEntityName::TsQualifiedName(ts_qualified_name) => {
ts_qualified_name.left.visit_with(self);
}
TsEntityName::Ident(ident) => {
self.add_edge(ident.to_id(), true);
}
};
}
fn visit_decl(&mut self, node: &Decl) {
match node {
Decl::Class(class_decl) => {
self.with_source_ident(&class_decl.ident, |this| class_decl.class.visit_with(this));
}
Decl::Fn(fn_decl) => {
self.with_source_ident(&fn_decl.ident, |this| fn_decl.function.visit_with(this));
}
Decl::Var(var_decl) => {
for decl in &var_decl.decls {
decl.name.visit_with(self);
if let Some(name) = decl.name.as_ident() {
self.with_source_ident(&name.id, |this| decl.init.visit_with(this));
}
}
}
Decl::Using(using_decl) => {
for decl in &using_decl.decls {
decl.name.visit_with(self);
if let Some(name) = decl.name.as_ident() {
self.with_source_ident(&name.id, |this| decl.init.visit_with(this));
}
}
}
Decl::TsInterface(ts_interface_decl) => {
self.with_source_ident(&ts_interface_decl.id, |this| {
ts_interface_decl.body.visit_with(this);
ts_interface_decl.extends.visit_with(this);
ts_interface_decl.type_params.visit_with(this);
});
}
Decl::TsTypeAlias(ts_type_alias_decl) => {
self.with_source_ident(&ts_type_alias_decl.id, |this| {
ts_type_alias_decl.type_ann.visit_with(this);
ts_type_alias_decl.type_params.visit_with(this);
});
}
Decl::TsEnum(ts_enum_decl) => {
self.with_source_ident(&ts_enum_decl.id, |this| {
ts_enum_decl.members.visit_with(this);
});
}
Decl::TsModule(ts_module_decl) => {
if ts_module_decl.global || ts_module_decl.id.is_str() {
// Here we enter global scope
self.with_source(Some(self.scope_entries[0]), |this| {
ts_module_decl.body.visit_with(this)
});
} else if let Some(ident) = ts_module_decl.id.as_ident() {
// Push a new scope and set current scope to None, which indicates that
// non-exported elements in ts module block are unreachable
self.add_edge(ident.to_id(), false);
let id = *self
.nodes
.entry(ident.to_id())
.or_insert_with(|| self.graph.add_node(ident.to_id()));
self.scope_entries.push(id);
let old_source = self.source.take();
ts_module_decl.body.visit_with(self);
self.source = old_source;
self.scope_entries.pop();
}
}
}
}
fn visit_export_decl(&mut self, node: &ExportDecl) {
self.with_source(self.source, |this| {
node.visit_children_with(this);
});
}
fn visit_named_export(&mut self, node: &NamedExport) {
self.with_source(self.source, |this| {
for specifier in &node.specifiers {
if let Some(name) = specifier.as_named() {
if let ModuleExportName::Ident(ident) = &name.orig {
this.add_edge(ident.to_id(), true);
}
}
}
});
}
fn visit_export_default_decl(&mut self, node: &ExportDefaultDecl) {
self.with_source(self.source, |this| {
node.visit_children_with(this);
});
}
fn visit_export_default_expr(&mut self, node: &ExportDefaultExpr) {
self.with_source(self.source, |this| {
if let Some(ident) = node.expr.as_ident() {
this.add_edge(ident.to_id(), true);
}
node.visit_children_with(this);
});
}
fn visit_ts_export_assignment(&mut self, node: &TsExportAssignment) {
self.with_source(self.source, |this| {
node.visit_children_with(this);
});
}
fn visit_function(&mut self, node: &Function) {
// Skip body
node.params.visit_with(self);
node.decorators.visit_with(self);
node.type_params.visit_with(self);
node.return_type.visit_with(self);
}
fn visit_class(&mut self, node: &Class) {
if let Some(super_class) = &node.super_class {
if let Some(ident) = super_class.get_root_ident() {
self.add_edge(ident.to_id(), true);
}
}
node.visit_children_with(self);
}
fn visit_class_member(&mut self, node: &ClassMember) {
if self.has_internal_annotation(node.span_lo()) {
return;
}
let is_private = match node {
ClassMember::Constructor(constructor) => constructor
.accessibility
.is_some_and(|accessibility| accessibility == Accessibility::Private),
ClassMember::Method(class_method) => class_method
.accessibility
.is_some_and(|accessibility| accessibility == Accessibility::Private),
ClassMember::PrivateMethod(_) => true,
ClassMember::ClassProp(class_prop) => class_prop
.accessibility
.is_some_and(|accessibility| accessibility == Accessibility::Private),
ClassMember::PrivateProp(_) => true,
ClassMember::TsIndexSignature(_) => false,
ClassMember::Empty(_) => false,
ClassMember::StaticBlock(_) => false,
ClassMember::AutoAccessor(auto_accessor) => {
auto_accessor
.accessibility
.is_some_and(|accessibility| accessibility == Accessibility::Private)
|| auto_accessor.key.is_private()
}
};
if is_private {
return;
}
node.visit_children_with(self);
}
fn visit_ts_type_element(&mut self, node: &TsTypeElement) {
if self.has_internal_annotation(node.span_lo()) {
return;
}
node.visit_children_with(self);
}
fn visit_module_items(&mut self, node: &[ModuleItem]) {
for item in node {
// Skip statements and internals
if item.as_stmt().map_or(false, |stmt| !stmt.is_decl())
|| self.has_internal_annotation(item.span_lo())
{
continue;
}
item.visit_children_with(self);
}
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/src/lib.rs | Rust | #![allow(clippy::boxed_local)]
pub mod diagnostic;
pub mod fast_dts;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/tests/deno_test.rs | Rust | //! Tests copied from deno
//! Make some changes to align with tsc
use swc_common::Mark;
use swc_ecma_ast::EsVersion;
use swc_ecma_codegen::to_code;
use swc_ecma_parser::{parse_file_as_program, Syntax, TsSyntax};
use swc_ecma_transforms_base::resolver;
use swc_typescript::fast_dts::FastDts;
#[track_caller]
fn transform_dts_test(source: &str, expected: &str) {
testing::run_test(false, |cm, _| {
let fm = cm.new_source_file(
swc_common::FileName::Real("test.ts".into()).into(),
source.to_string(),
);
let unresolved_mark = Mark::new();
let top_level_mark = Mark::new();
let mut program = parse_file_as_program(
&fm,
Syntax::Typescript(TsSyntax {
..Default::default()
}),
EsVersion::latest(),
None,
&mut Vec::new(),
)
.map(|program| program.apply(resolver(unresolved_mark, top_level_mark, true)))
.unwrap();
let mut checker = FastDts::new(fm.name.clone(), unresolved_mark, Default::default());
let _issues = checker.transform(&mut program);
let code = to_code(&program);
assert_eq!(
code.trim(),
expected.trim(),
"Actual:\n{code}\nExpected:\n{expected}"
);
Ok(())
})
.unwrap();
}
#[test]
fn dts_function_test() {
transform_dts_test(
r#"export function foo(a: number): number {
return {};
}"#,
"export declare function foo(a: number): number;",
);
transform_dts_test(
r#"export function foo(a: string): number;
export function foo(a: any): number {
return {};
}"#,
r#"export declare function foo(a: string): number;"#,
);
transform_dts_test(
r#"export function foo(a = 2): number {
return 2;
}"#,
r#"export declare function foo(a?: number): number;"#,
);
transform_dts_test(
r#"export function foo(a: string = 2): number {
return 2;
}"#,
r#"export declare function foo(a?: string): number;"#,
);
}
#[test]
fn dts_class_decl_test() {
transform_dts_test(
r#"export class Foo {
a: number = 2;
static b: number = 1;
#b: number = 3;
constructor(value: string) {
return 42;
}
foo(): string {
return "abc";
}
#bar(): number {
return 2
}
get asdf(): number {
}
set asdf(value: number) {
}
static {
}
}"#,
r#"export declare class Foo {
#private;
a: number;
static b: number;
constructor(value: string);
foo(): string;
get asdf(): number;
set asdf(value: number);
}"#,
);
}
#[test]
fn dts_class_decl_rest_test() {
transform_dts_test(
r#"export class Foo {
constructor(...args: string[]) {}
}"#,
r#"export declare class Foo {
constructor(...args: string[]);
}"#,
);
}
#[test]
fn dts_class_decl_overloads_test() {
transform_dts_test(
r#"export class Foo {
constructor(arg: string);
constructor(arg: number);
constructor(arg: any) {}
}"#,
r#"export declare class Foo {
constructor(arg: string);
constructor(arg: number);
}"#,
);
transform_dts_test(
r#"export class Foo {
foo(arg: string);
foo(arg: number);
foo(arg: any) {}
}"#,
r#"export declare class Foo {
foo(arg: string);
foo(arg: number);
}"#,
);
transform_dts_test(
r#"export class Foo {
constructor(arg: string);
constructor(arg: number);
constructor(arg: any) {}
bar(arg: number): number {
return 2
}
foo(arg: string);
foo(arg: number);
foo(arg: any) {}
}"#,
r#"export declare class Foo {
constructor(arg: string);
constructor(arg: number);
bar(arg: number): number;
foo(arg: string);
foo(arg: number);
}"#,
);
}
#[test]
fn dts_class_decl_prop_test() {
transform_dts_test(
r#"export class Foo { private a!: string }"#,
r#"export declare class Foo {
private a;
}"#,
);
transform_dts_test(
r#"export class Foo { declare a: string }"#,
r#"export declare class Foo {
a: string;
}"#,
);
}
#[test]
fn dts_class_decl_prop_infer_test() {
transform_dts_test(
r#"export class Foo { foo = (a: string): string => ({} as any) }"#,
r#"export declare class Foo {
foo: (a: string) => string;
}"#,
);
transform_dts_test(
r#"export class Foo { foo = function(a: string): void {} }"#,
r#"export declare class Foo {
foo: (a: string) => void;
}"#,
);
}
#[test]
fn dts_var_decl_test() {
transform_dts_test(
r#"export const foo: number = 42;"#,
"export declare const foo: number;",
);
transform_dts_test(
r#"export var foo: number = 42;"#,
"export declare var foo: number;",
);
transform_dts_test(
r#"export let foo: number = 42;"#,
"export declare let foo: number;",
);
// Default to any if it cannot be determined
transform_dts_test(
r#"export const foo = adsf.b;"#,
"export declare const foo: any;",
);
transform_dts_test(r#"export let foo;"#, "export declare let foo: any;");
}
#[test]
fn dts_global_declare() {
transform_dts_test(
r#"declare global {
interface String {
fancyFormat(opts: StringFormatOptions): string;
}
}"#,
r#"declare global {
interface String {
fancyFormat(opts: StringFormatOptions): string;
}
}"#,
);
}
#[test]
fn dts_inference() {
transform_dts_test(
r#"export const foo = null as string as number;"#,
"export declare const foo: number;",
);
}
#[test]
fn dts_as_const() {
transform_dts_test(
r#"export const foo = [1, 2] as const;"#,
"export declare const foo: readonly [1, 2];",
);
transform_dts_test(
r#"export const foo = [1, ,2] as const;"#,
"export declare const foo: readonly [1, undefined, 2];",
);
transform_dts_test(
r#"export const foo = { str: "bar", bool: true, bool2: false, num: 42, nullish: null } as const;"#,
r#"export declare const foo: {
readonly str: "bar";
readonly bool: true;
readonly bool2: false;
readonly num: 42;
readonly nullish: null;
};"#,
);
transform_dts_test(
r#"export const foo = { str: [1, 2] as const } as const;"#,
r#"export declare const foo: {
readonly str: readonly [1, 2];
};"#,
);
transform_dts_test(
r#"export const foo = { bar } as const;"#,
r#"export declare const foo: {
};"#,
);
}
#[test]
fn dts_literal_inference_ann() {
transform_dts_test(
r#"export const foo: number = "abc";"#,
"export declare const foo: number;",
);
transform_dts_test(
r#"export let foo: number = "abc";"#,
"export declare let foo: number;",
);
transform_dts_test(
r#"export var foo: number = "abc";"#,
"export declare var foo: number;",
);
}
#[test]
fn dts_literal_inference() {
transform_dts_test(
r#"export const foo = 42;"#,
"export declare const foo = 42;",
);
transform_dts_test(
r#"export const foo = "foo";"#,
"export declare const foo = \"foo\";",
);
transform_dts_test(
r#"export const foo = true;"#,
"export declare const foo = true;",
);
transform_dts_test(
r#"export const foo = false;"#,
"export declare const foo = false;",
);
transform_dts_test(
r#"export const foo = null;"#,
"export declare const foo: null;",
);
transform_dts_test(
r#"export let foo = undefined;"#,
"export declare let foo: undefined;",
);
transform_dts_test(
r#"export let foo = 10n;"#,
"export declare let foo: bigint;",
);
}
#[test]
fn dts_fn_expr() {
transform_dts_test(
r#"export let foo = function add(a: number, b: number): number {
return a + b;
}"#,
"export declare let foo: (a: number, b: number) => number;",
);
transform_dts_test(
r#"export let foo = function add<T>([a, b]: T): void {}"#,
"export declare let foo: <T>([a, b]: T) => void;",
);
transform_dts_test(
r#"export let foo = function add<T>({a, b}: T): void {}"#,
"export declare let foo: <T>({ a, b }: T) => void;",
);
transform_dts_test(
r#"export let foo = function add(a = 2): void {}"#,
"export declare let foo: (a?: number) => void;",
);
transform_dts_test(
r#"export let foo = function add(...params: any[]): void {}"#,
"export declare let foo: (...params: any[]) => void;",
);
}
#[test]
fn dts_fn_arrow_expr() {
transform_dts_test(
r#"export let foo = (a: number, b: number): number => {
return a + b;
}"#,
"export declare let foo: (a: number, b: number) => number;",
);
transform_dts_test(
r#"export let foo = <T>([a, b]: T): void => {}"#,
"export declare let foo: <T>([a, b]: T) => void;",
);
transform_dts_test(
r#"export let foo = <T>({a, b}: T): void => {}"#,
"export declare let foo: <T>({ a, b }: T) => void;",
);
transform_dts_test(
r#"export let foo = (a = 2): void => {}"#,
"export declare let foo: (a?: number) => void;",
);
transform_dts_test(
r#"export let foo = (...params: any[]): void => {}"#,
"export declare let foo: (...params: any[]) => void;",
);
}
#[test]
fn dts_type_export() {
transform_dts_test(r#"interface Foo {}"#, "interface Foo {\n}");
transform_dts_test(r#"type Foo = number;"#, "type Foo = number;");
transform_dts_test(r#"export interface Foo {}"#, "export interface Foo {\n}");
transform_dts_test(r#"export type Foo = number;"#, "export type Foo = number;");
}
#[test]
fn dts_enum_export() {
transform_dts_test(
r#"export enum Foo { A, B }"#,
"export declare enum Foo {\n A = 0,\n B = 1\n}",
);
transform_dts_test(
r#"export const enum Foo { A, B }"#,
"export declare const enum Foo {\n A = 0,\n B = 1\n}",
);
transform_dts_test(
r#"export enum Foo { A = "foo", B = "bar" }"#,
r#"export declare enum Foo {
A = "foo",
B = "bar"
}"#,
);
}
#[test]
fn dts_default_export() {
transform_dts_test(
r#"export default function(a: number, b: number): number {};"#,
"export default function(a: number, b: number): number;",
);
transform_dts_test(
r#"export default function(a: number, b: number): number;
export default function(a: number, b: number): any {
return foo
};"#,
"export default function(a: number, b: number): number;",
);
transform_dts_test(
r#"export default class {foo = 2};"#,
r#"export default class {
foo: number;
}"#,
);
transform_dts_test(
r#"export default 42;"#,
r#"declare const _default_1: number;
export default _default_1;"#,
);
transform_dts_test(
r#"const a: number = 42; export default a;"#,
r#"declare const a: number;
export default a;"#,
);
}
#[test]
fn dts_default_export_named() {
transform_dts_test(
r#"export { foo, bar } from "foo";"#,
r#"export { foo, bar } from "foo";"#,
);
}
#[test]
fn dts_default_export_all() {
transform_dts_test(
r#"export * as foo from "foo";"#,
r#"export * as foo from "foo";"#,
);
}
#[test]
fn dts_imports() {
transform_dts_test(
r#"import { foo } from "bar";export const foobar = foo;"#,
r#"export declare const foobar: any;"#,
);
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/tests/fixture/abstract-overloads.ts | TypeScript | export abstract class Value {
protected body?(): string | undefined | Promise<string | undefined>;
protected footer(): string | undefined {
return "";
}
}
function overloadsNonExportDecl(args: string): void;
function overloadsNonExportDecl(args: number): void;
function overloadsNonExportDecl(args: any): void {}
export { overloadsNonExportDecl };
export default function defaultExport(args: string): void;
export default function defaultExport(args: number): void;
export default function defaultExport(args: any): void {}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/tests/fixture/binding-ref.ts | TypeScript | export const ssrUtils = { createComponentInstance: 1 };
const { createComponentInstance } = ssrUtils;
export function createComponentInstance(): void {}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/tests/fixture/class-abstract-method.ts | TypeScript | export abstract class Manager {
protected abstract A(): void;
protected B(): void {
console.log("B");
}
protected C(): void {
console.log("B");
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/tests/fixture/class-params-initializers.ts | TypeScript | export class Object {
constructor(
values: {},
{
a,
b,
}: {
a?: A;
b?: B;
} = {}
) {}
method(
values: {},
{
a,
b,
}: {
a?: A;
b?: B;
} = {},
value = 1
) {}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/tests/fixture/class-properties-computed.ts | TypeScript | export class Test {
[Symbol.for("nodejs.util.inspect.custom")]() {}
["string"]: string;
["string2" as string]: string;
[1 as number]: string;
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/tests/fixture/issues/10034.ts | TypeScript | const A_SYMBOL = Symbol("A_SYMBOL");
const func = () => null;
export class SomeClass {
private func(
queryFingerprint: string,
onStale: () => void
): null | typeof A_SYMBOL {
return null;
}
private func2(
queryFingerprint: string,
onStale: () => void
): null | typeof func {
return null;
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/tests/fixture/issues/9550.ts | TypeScript | /**
* Sample JSDoc that I wish was in the swc.transform output
* @param a - string param
* @param b - number param
* @returns - object with a and b
*/
function sampleFunc(a: string, b: number): void {}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/tests/fixture/issues/9817.tsx | TypeScript (TSX) | import React from "react";
export class Component<T> extends React.PureComponent<{}, {}> {
render(): React.ReactNode {
return <div>Hello world</div>;
}
} | willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/tests/fixture/issues/9859.ts | TypeScript | export class NumberRange implements Iterable<number> {
private start: number;
private end: number;
constructor(start: number, end: number) {
this.start = start;
this.end = end;
}
[Symbol.iterator](): Iterator<number> {
let current = this.start;
const end = this.end;
return {
next(): IteratorResult<number> {
if (current <= end) {
return { value: current++, done: false };
} else {
return { value: undefined, done: true };
}
},
};
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/tests/fixture/private-accessibility.ts | TypeScript | const A_SYMBOL = Symbol("A_SYMBOL");
export class A {
private p1: typeof A_SYMBOL;
private constructor(a: typeof A_SYMBOL) {}
private accessor myProperty: typeof A_SYMBOL;
private func1(a: typeof A_SYMBOL): typeof A_SYMBOL | null {
return null;
}
}
export class B {
private constructor(private a: typeof A_SYMBOL) {}
}
export class C {
#p1: typeof A_SYMBOL;
accessor #myProperty: typeof A_SYMBOL;
#f(a: typeof A_SYMBOL) {}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/tests/fixture/signature-computed-property-name.ts | TypeScript | export interface A {
["foo" as string]: number;
["bar" as string](a: number): string;
}
export type B = {
["foo" as string]: number;
["bar" as string](a: number): string;
};
export type C = {
[D?.b]: number;
};
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/tests/fixture/simple-constants.ts | TypeScript | export const foo1 = 1;
export var foo2: number = "abc";
export enum Foo3 {
A = "foo",
B = "bar",
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/tests/fixture/symbol-properties.ts | TypeScript | // Correct
export const foo = {
[Symbol.iterator]: (): void => {},
[Symbol.asyncIterator]: async (): Promise<void> => {},
[globalThis.Symbol.iterator]: (): void => {},
get [Symbol.toStringTag]() {
return "foo";
},
};
export abstract class Foo {
[Symbol.iterator](): void {}
async [Symbol.asyncIterator](): Promise<void> {}
[globalThis.Symbol.iterator](): void {}
get [Symbol.toStringTag]() {
return "Foo";
}
}
// OK because these are not exported
namespace Foo {
const Symbol = {};
const globalThis = {};
export const foo = {
[Symbol.iterator]: (): void => {},
[globalThis.Symbol.iterator]: (): void => {},
};
}
function bar(Symbol: {}, globalThis: {}) {
return {
[Symbol.iterator]: (): void => {},
[globalThis.Symbol.iterator]: (): void => {},
};
}
// Incorrect
export namespace Foo {
const Symbol = {};
const globalThis = {};
export const foo = {
[Symbol.iterator]: (): void => {},
[globalThis.Symbol.iterator]: (): void => {},
};
}
export function bar(Symbol: {}, globalThis: {}) {
return {
[Symbol.iterator]: (): void => {},
[globalThis.Symbol.iterator]: (): void => {},
};
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/tests/fixture/transitive-references.ts | TypeScript | type A = number;
type B = A | string;
export function exp1(): void {}
var a = 1;
var b: typeof a = 2;
export function exp2(): void {}
export {};
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/tests/fixture/ts-property.ts | TypeScript | const A = "123";
const B = "456";
export interface I {
[A]: "123";
[B]: "456";
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/tests/fixture/type-usage.ts | TypeScript | import type * as Member from "some-path/my_module";
export interface IMember extends Member.C<"SimpleEntity"> {}
import type * as Ident from "some-path/my_module";
export interface IIdent extends Ident {}
import * as Paren from "some-path/my_module";
export class CParen extends Paren {}
import * as OptChain from "some-path/my_module";
export class COptChain extends OptChain?.C<"SimpleEntity"> {}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/tests/oxc_fixture/arrow-function-return-type.ts | TypeScript | function A() {
return () => {
return C;
}
}
const B = () => { return B };
const C = function () {}
const D = () => `${''}`;
const E = (): (() => void) | undefined => {
return () => {};
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/tests/oxc_fixture/as-const.ts | TypeScript | const F = {
string: `string`,
templateLiteral: `templateLiteral`,
number: 1.23,
bigint: -1_2_3n,
boolean: true,
null: null,
undefined: undefined,
function(a: string): void {},
arrow: (a: string): void => {},
object: {
a: `a`,
b: `b`
},
array: [`a`, , { b: `\n` }],
} as const
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/tests/oxc_fixture/async-function.ts | TypeScript | // Correct
async function asyncFunctionGood(): Promise<number> {}
const asyncFunctionGoo2 = async (): Promise<number> => {
return Promise.resolve(0);
}
class AsyncClassGood {
async method(): number {
return 42;
}
}
// Need to explicit return type for async functions
// Incorrect
async function asyncFunction() {
return 42;
}
const asyncFunction2 = async () => {
return "Hello, World!";
}
class AsyncClassBad {
async method() {
return 42;
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/tests/oxc_fixture/class.ts | TypeScript | export class Foo {
private constructor(a: number = 0) {}
}
export class Bar {
public constructor(a: number = 0) {}
}
export class Zoo {
foo<F>(f: F): F {
return f;
}
}
export abstract class Qux {
abstract foo(): void;
protected foo2?(): void;
bar(): void {}
baz(): void {}
}
export class Baz {
/** Just a comment */
readonly prop1 = "some string";
/** Just a comment */
prop2 = "another string";
/** Just a comment */
private prop3 = "yet another string";
/** Just a comment */
private prop4(): void {}
/** Just a comment */
private static prop5 = "yet another string";
/** Just a comment */
private static prop6(): void {}
}
export class Boo {
constructor(
public readonly prop: number = 0,
private readonly prop2: number = 1,
readonly prop3: number = 1,
) {}
}
export class Bux {
private constructor(
public readonly prop: number = 0,
private readonly prop2: number = 1,
readonly prop3: number = 1,
) {}
}
export class PrivateFieldsWithConstructorAssignments {
private second = 0;
constructor(public first: number) {}
}
export class PrivateMethodClass {
private good(a): void {}
private get goodGetter() {
return {[('x')]: 1};
}
}
export class PublicMethodClass {
public bad(a): void {}
public get badGetter() {
return {[('x')]: 1};
}
} | willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/tests/oxc_fixture/declare-global.ts | TypeScript | function MyFunction() {
return 'here is my function'
}
declare global {
interface Window {
MyFunction: typeof MyFunction
}
}
export {}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/tests/oxc_fixture/eliminate-imports.ts | TypeScript | import { AExtend, BExtend, Type, CImplements1, CImplements2, CType, ThisType1, ThisType2, Unused } from 'mod';
export interface A extends AExtend<Type> {}
export class B extends BExtend<Type> {}
export class C implements CImplements1<CType>, CImplements2<CType> {}
export function foo(this: ThisType1): void {}
export const bar: (this: ThisType2) => void = function() {}
import { type InferType1, type InferType2 } from 'infer';
export type F<X extends InferType1> = X extends infer U extends InferType2 ? U : never
export { Unused } from './unused'; | willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/tests/oxc_fixture/empty-export.ts | TypeScript | type A = string;
export function a(): A {
return ""
}
export declare const ShallowReactiveMarker: unique symbol
export type ShallowReactive<T> = T & { [ShallowReactiveMarker]?: true }
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/tests/oxc_fixture/empty-export2.ts | TypeScript | import * as a from "mod";
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/tests/oxc_fixture/expando-function.ts | TypeScript | export function foo(): void {}
foo.apply = () => {}
export const bar = (): void => {}
bar.call = () => {}
export namespace NS {
export const goo = (): void => {}
goo.length = 10
}
export namespace foo {
// declaration must be exported
let bar = 42;
export let baz = 100;
}
foo.bar = 42;
foo.baz = 100;
// unexported
const zoo = (): void => {}
zoo.toString = () => {}
function qux(): void {}
namespace qux {
export let woo = 42;
}
qux.woo = 42;
export default qux;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/tests/oxc_fixture/export-default.ts | TypeScript | const defaultDelimitersClose = new Uint8Array([125, 125])
export default class Tokenizer {
public delimiterClose: Uint8Array = defaultDelimitersClose
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/tests/oxc_fixture/function-overloads.ts | TypeScript | function a(a: number): number;
function a(a: string): string;
function a(a: any): any {}
function b(a: number): number {};
function b(a: string): string {};
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/tests/oxc_fixture/function-parameters.ts | TypeScript | // Correct
export function fnDeclGood(p: T = [], rParam = ""): void { };
export function fnDeclGood2(p: T = [], rParam?: number): void { };
export function fooGood([a, b]: any[] = [1, 2]): number {
return 2;
}
export const fooGood2 = ({a, b}: object = { a: 1, b: 2 }): number => {
return 2;
}
const x = 42;
const y = '';
export function fooGood3({a = x, b: [{c = y}]}: object): void {}
// Incorrect
export function fnDeclBad<T>(p: T = [], rParam: T = "", r2: T): void { }
export function fnDeclBad2<T>(p: T = [], r2: T): void { }
export function fnDeclBad3<T>(p: T = [], rParam?: T, r2: T): void { }
export function fooBad([a, b] = [1, 2]): number {
return 2;
}
export const fooBad2 = ({a, b} = { a: 1, b: 2 }): number => {
return 2;
}
export function withAny(a: any = 1, b: string): void { }
export function withUnknown(a: unknown = 1, b: string): void { }
export function withTypeAssertion(a = /regular-repression-cannot-infer/ as any): void { } | willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/tests/oxc_fixture/function-signatures.ts | TypeScript | // All of these are valid function signatures under isolatedDeclarations
export function A(): void {
return;
}
export function B(): (() => void) | undefined {
return () => {};
}
// There should be no declaration for the implementation signature, just the
// two overloads.
export function C(x: string): void
export function C(x: number): void
export function C(x: string | number): void {
return;
}
// private, not emitted
function D(a, b): void {
return;
}
function E(a: number, b: string) {
return `${a} ${b}`;
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/tests/oxc_fixture/generator.ts | TypeScript | // Correct
function *generatorGood(): Generator<number> {}
class GeneratorClassGood {
*method(): Generator<number> {
yield 50;
return 42;
}
}
// Need to explicit return type for async functions
// Incorrect
function *generatorBad() {
yield 50;
return 42;
}
class GeneratorClassBad {
*method() {
yield 50;
return 42;
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/tests/oxc_fixture/infer-expression.ts | TypeScript | // Correct
// ParenthesizedExpression
const n = (0);
const s = ("");
const t = (``);
const b = (true);
// UnaryExpression
let unaryA = +12;
const unaryB = -1_2n;
// Incorrect
// UnaryExpression
const unaryC = +"str"
const unaryD = typeof "str"
const unaryE = {E: -"str"} as const
const unaryF = [+"str"] as const
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/tests/oxc_fixture/infer-return-type.ts | TypeScript | function foo() {
return 1;
}
// inferred type is number
function bar() {
if (a) {
return;
}
return 1;
}
// inferred type is number | undefined
function baz() {
if (a) {
return null;
}
return 1;
}
// We can't infer return type if there are multiple return statements with different types
function qux() {
const a = (() => {
return 1;
})();
return `Hello, world!`;
}
function quux() {
return `${''}`
}
// Inferred type is string
function returnFunctionOrNothing() {
if (process.env.NODE_ENV === 'development') {
return
}
return () => 0;
} | willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/tests/oxc_fixture/infer-template-literal.ts | TypeScript | export const CSS_VARS_HELPER = `useCssVars`
export function g(func = `useCssVar`) : void {}
export const F = {
a: `a`,
b: [`b`]
} as const
export let GOOD = `useCssV${v}ars`
export const BAD = `useCssV${v}ars`
export let BAD2 = `useCssV${v}ars` as const
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/tests/oxc_fixture/mapped-types.ts | TypeScript | import {K} from 'foo'
import {T} from 'bar'
export interface I {
prop: {[key in K]: T}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/tests/oxc_fixture/module-declaration-with-export.ts | TypeScript | export namespace OnlyOneExport {
export const a = 0;
}
export namespace TwoExports {
export const c = 0;
export const a: typeof c = 0;
}
export namespace OneExportReferencedANonExported {
const c = 0;
export const a: typeof c = c;
}
declare module "OnlyOneExport" {
export const a = 0;
}
declare module "TwoExports" {
export const c = 0;
export const a: typeof c;
}
declare module "OneExportReferencedANonExported" {
const c = 0;
export const a: typeof c;
}
declare global {
const c = 0;
export const a: typeof c;
} | willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/tests/oxc_fixture/module-declaration.ts | TypeScript | import "foo";
declare module "foo" {
interface Foo {}
const foo = 42;
}
declare global {
interface Bar {}
const bar = 42;
}
import { type X } from "./x";
type Y = 1;
declare module "foo" {
interface Foo {
x: X;
y: Y;
}
}
// should not be emitted
module baz {
interface Baz {}
const baz = 42;
}
declare module x {
interface Qux {}
const qux = 42;
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/tests/oxc_fixture/non-exported-binding-elements.ts | TypeScript | // Correct
const [A, B] = [1, 2, 3];
export function foo(): number {
return A;
}
// Incorrect
const { c, d } = { c: 1, d: 2 };
const [ e ] = [4];
export { c, d, e }
export const { f, g } = { f: 5, g: 6 };
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/tests/oxc_fixture/readonly.ts | TypeScript | export const EMPTY_OBJ: { readonly [key: string]: any } = __DEV__
? Object.freeze({})
: {}
export const EMPTY_ARR: readonly never[] = __DEV__ ? Object.freeze([]) : []
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/tests/oxc_fixture/set-get-accessor.ts | TypeScript | // Correct
class Cls {
get a() {
return 1;
}
set a() {
return;
}
get b(): string {
}
set b(v) {
}
private get c() {}
private set c() {}
}
// Incorrect
class ClsBad {
get a() {
return;
}
set a(v) {
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/tests/oxc_fixture/signatures.ts | TypeScript | export interface X {
set value(_: string);
}
export type A = {
set value({ a, b, c }: { a: string; b: string; c: string });
get value();
};
export interface I {
set value(_);
get value(): string;
}
// Do nothing
export interface Ref<T = any, S = T> {
get value(): T
set value(_: S)
}
export interface MultipleSetterAndGetter {
get ok(): string
set ok(_: string)
get bad() // infer return type
set bad(_: string)
} | willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/tests/oxc_fixture/strip-internal.ts | TypeScript | /*
@internal
*/
class StripInternalClass {
public test() {
console.log("test");
}
}
class StripInternalClassFields {
/**
* @internal
*/
internalProperty: string = "internal";
// @internal
internalMethod(): void {}
}
/**
@internal
*/
function stripInternalFunction() {
console.log("test");
}
export { stripInternalFunction, StripInternalClass, StripInternalClassFields };
/**
@internal
*/
export function stripInternalExportedFunction() {
console.log("test");
}
/**
@internal*/
export const stripInternalExportedConst = "test";
/**
@internal*/
export interface StripInternalExportedInterface {}
export interface StripInternalInterfaceSignatures {
/**
* @internal
*/
internalMethod(): void;
/**
* @internal
*/
internalProperty: number;
/**@internal */
new (): any;
}
export type StripInternalTypeSignatures = {
/**
* @internal
*/
internalMethod(): void;
/**
* @internal
*/
internalProperty: number;
/**@internal */
new (): any;
};
export namespace StripInternalNamespaceInner {
/**
* @internal
*/
export function internalFunction() {
console.log("test");
}
}
/**
* @internal
*/
export namespace StripInternalNamespace {} | willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_typescript/tests/oxc_fixture/ts-export-assignment.ts | TypeScript | const Res = 0;
export = function Foo(): typeof Res {
return Res;
} | willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.