Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(allocator): Add maybe types #9278

Merged
merged 19 commits into from
Jul 19, 2024
4 changes: 4 additions & 0 deletions Cargo.lock

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

2 changes: 1 addition & 1 deletion bindings/binding_core_node/src/bundle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ impl Task for BundleTask {
.map(JsWord::from)
.collect::<Vec<_>>()
} else {
vec![]
Vec::new()
};

// Defaults to es3
Expand Down
4 changes: 2 additions & 2 deletions crates/ast_node/src/ast_node_macro.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ impl Parse for Args {
}

pub fn expand_struct(args: Args, i: DeriveInput) -> Vec<ItemImpl> {
let mut items = vec![];
let mut items = Vec::new();
let generics = i.generics.clone();
// let item_ident = Ident::new("Item", i.ident.span());

Expand Down Expand Up @@ -128,7 +128,7 @@ pub fn expand_struct(args: Args, i: DeriveInput) -> Vec<ItemImpl> {
// let item = DeriveInput {
// vis: Visibility::Inherited,
// ident: item_ident,
// attrs: vec![],
// attrs: Vec::new(),
// data: item_data,
// ..cloned
// };
Expand Down
4 changes: 2 additions & 2 deletions crates/ast_node/src/enum_deserialize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,8 +113,8 @@ pub fn expand(
.collect::<Vec<Arm>>();

let tag_expr: Expr = {
let mut visit_str_arms = vec![];
let mut visit_bytes_arms = vec![];
let mut visit_str_arms = Vec::new();
let mut visit_bytes_arms = Vec::new();

for variant in &data.variants {
let tags = variant
Expand Down
8 changes: 4 additions & 4 deletions crates/dbg-swc/src/util/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ pub fn parse_js(fm: Arc<SourceFile>) -> Result<ModuleRecord> {
let unresolved_mark = Mark::new();
let top_level_mark = Mark::new();

let mut errors = vec![];
let mut errors = Vec::new();
let comments = SingleThreadedComments::default();
let res = parse_file_as_module(
&fm,
Expand Down Expand Up @@ -80,7 +80,7 @@ pub fn parse_js(fm: Arc<SourceFile>) -> Result<ModuleRecord> {
}

pub fn print_js(cm: Arc<SourceMap>, m: &Module, minify: bool) -> Result<String> {
let mut buf = vec![];
let mut buf = Vec::new();

{
let mut wr = Box::new(JsWriter::new(cm.clone(), "\n", &mut buf, None)) as Box<dyn WriteJs>;
Expand Down Expand Up @@ -112,7 +112,7 @@ pub struct ModuleRecord {
pub fn all_js_files(path: &Path) -> Result<Vec<PathBuf>> {
wrap_task(|| {
if path.is_dir() {
let mut files = vec![];
let mut files = Vec::new();
for entry in path.read_dir().context("failed to read dir")? {
let entry = entry.context("read_dir returned an error")?;
let path = entry.path();
Expand All @@ -122,7 +122,7 @@ pub fn all_js_files(path: &Path) -> Result<Vec<PathBuf>> {
} else if path.extension() == Some("js".as_ref()) {
Ok(vec![path.to_path_buf()])
} else {
Ok(vec![])
Ok(Vec::new())
}
})
.with_context(|| format!("failed to get list of `.js` files in {}", path.display()))
Expand Down
2 changes: 1 addition & 1 deletion crates/from_variant/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ fn derive(
_ => panic!("#[derive(FromVariant)] only works for an enum."),
};

let mut from_impls: Vec<ItemImpl> = vec![];
let mut from_impls: Vec<ItemImpl> = Vec::new();

for v in variants {
let variant_name = v.ident;
Expand Down
4 changes: 2 additions & 2 deletions crates/jsdoc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ mod input;
pub fn parse(i: Input) -> IResult<Input, JsDoc> {
let i = skip(i);

let mut tags = vec![];
let mut tags = Vec::new();
let lo = i.span().lo;
let (description, mut i) = take_while(|c| c != '@')(i)?;
let description = trim(description).into();
Expand Down Expand Up @@ -546,7 +546,7 @@ fn parse_one_of<'i>(i: Input<'i>, list: &[&str]) -> IResult<Input<'i>, Text> {

fn parse_name_path(mut i: Input) -> IResult<Input, NamePath> {
let lo = i.span().lo;
let mut components = vec![];
let mut components = Vec::new();

loop {
let (input, component) = parse_word(i)?;
Expand Down
4 changes: 2 additions & 2 deletions crates/jsdoc/tests/fixture.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ fn fixture(path: PathBuf) {

let fm = cm.load_file(&path).expect("failed to load fixture file");

let mut errors = vec![];
let mut errors = Vec::new();

if let Err(err) = parse_file_as_module(
&fm,
Expand All @@ -35,7 +35,7 @@ fn fixture(path: PathBuf) {
if handler.has_errors() {
return Err(());
}
let mut res = vec![];
let mut res = Vec::new();
let mut comments: Vec<_> = comments.leading.into_iter().collect();
comments.sort_by_key(|v| v.0);

Expand Down
2 changes: 1 addition & 1 deletion crates/swc/src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1548,7 +1548,7 @@ impl GlobalPassOption {
fn expr(cm: &SourceMap, handler: &Handler, src: String) -> Box<Expr> {
let fm = cm.new_source_file(FileName::Anon.into(), src);

let mut errors = vec![];
let mut errors = Vec::new();
let expr = parse_file_as_expr(
&fm,
Syntax::Es(Default::default()),
Expand Down
6 changes: 3 additions & 3 deletions crates/swc/tests/tsc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ fn matrix(input: &Path) -> Vec<TestUnitData> {

let mut sub_filename = filename;

let mut files = vec![];
let mut files = Vec::new();

let mut buffer = String::default();
for line in fm.src.lines() {
Expand Down Expand Up @@ -344,7 +344,7 @@ fn matrix(input: &Path) -> Vec<TestUnitData> {
"#,
);

let mut test_unit_data_list = vec![];
let mut test_unit_data_list = Vec::new();

let is_jsx = input
.extension()
Expand All @@ -357,7 +357,7 @@ fn matrix(input: &Path) -> Vec<TestUnitData> {
for minify in [None, Some(default_minify)] {
for target in targets.clone() {
for module in modules.clone() {
let mut vary_name = vec![];
let mut vary_name = Vec::new();

if modules.len() > 1 {
vary_name.push(format!("module={}", &module));
Expand Down
9 changes: 9 additions & 0 deletions crates/swc_allocator/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,15 @@ pub mod boxed;
#[cfg(feature = "nightly")]
pub mod vec;

/// Box<T> and Vec<T> depeding on the feature.
pub mod maybe {
#[cfg(not(feature = "nightly"))]
pub use std::{boxed, vec};

#[cfg(feature = "nightly")]
pub use crate::{boxed, vec};
}

/// Fast allocator, effectively working as a cache.
///
/// This type implements [Default] and [Copy]. This type is intended to stored
Expand Down
6 changes: 6 additions & 0 deletions crates/swc_allocator/src/vec/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -381,3 +381,9 @@ impl io::Write for Vec<u8> {
self
}
}

impl<T> AsRef<[T]> for Vec<T> {
fn as_ref(&self) -> &[T] {
self.0.as_ref()
}
}
4 changes: 2 additions & 2 deletions crates/swc_bundler/examples/bundle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ use swc_ecma_visit::VisitMutWith;
fn print_bundles(cm: Lrc<SourceMap>, modules: Vec<Bundle>, minify: bool) {
for bundled in modules {
let code = {
let mut buf = vec![];
let mut buf = Vec::new();

{
let wr = JsWriter::new(cm.clone(), "\n", &mut buf, None);
Expand Down Expand Up @@ -232,7 +232,7 @@ impl Load for Loader {
Syntax::Es(Default::default()),
EsVersion::Es2020,
None,
&mut vec![],
&mut Vec::new(),
)
.unwrap_or_else(|err| {
let handler =
Expand Down
4 changes: 2 additions & 2 deletions crates/swc_bundler/examples/path.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ fn main() {
let globals = Globals::new();
let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
// This example does not use core modules.
let external_modules = vec![];
let external_modules = Vec::new();
let mut bundler = Bundler::new(
&globals,
cm.clone(),
Expand Down Expand Up @@ -74,7 +74,7 @@ impl Load for PathLoader {
Syntax::Es(Default::default()),
Default::default(),
None,
&mut vec![],
&mut Vec::new(),
)
.expect("This should not happen");

Expand Down
12 changes: 6 additions & 6 deletions crates/swc_bundler/src/bundler/chunk/cjs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ fn wrap_module(
pat: Pat::Ident(Ident::new("exports".into(), DUMMY_SP, local_ctxt).into()),
},
],
decorators: vec![],
decorators: Vec::new(),
span: DUMMY_SP,
body: Some(BlockStmt {
span: dep.span,
Expand Down Expand Up @@ -205,7 +205,7 @@ where
let load = CallExpr {
span: node.span,
callee: Ident::new("load".into(), i.span, i.ctxt).as_callee(),
args: vec![],
args: Vec::new(),
..Default::default()
};
self.replaced = true;
Expand Down Expand Up @@ -253,7 +253,7 @@ where
*node = CallExpr {
span: DUMMY_SP,
callee: load_var.as_callee(),
args: vec![],
args: Vec::new(),

..Default::default()
}
Expand All @@ -262,7 +262,7 @@ where
return;
}

let mut props = vec![];
let mut props = Vec::new();
// TODO
for spec in i.specifiers.clone() {
match spec {
Expand Down Expand Up @@ -303,7 +303,7 @@ where
CallExpr {
span: DUMMY_SP,
callee: load_var.as_callee(),
args: vec![],
args: Vec::new(),

..Default::default()
}
Expand Down Expand Up @@ -335,7 +335,7 @@ where
init: Some(Box::new(Expr::Call(CallExpr {
span: DUMMY_SP,
callee: load_var.as_callee(),
args: vec![],
args: Vec::new(),
..Default::default()
}))),
definite: false,
Expand Down
2 changes: 1 addition & 1 deletion crates/swc_bundler/src/bundler/chunk/computed_key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ where

let is_async = module.iter().any(|m| contains_top_level_await(m.1));

let mut additional_items = vec![];
let mut additional_items = Vec::new();

module.iter().for_each(|(module_id, item)| {
match item {
Expand Down
8 changes: 4 additions & 4 deletions crates/swc_bundler/src/bundler/chunk/merge.rs
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ where
{
// Handle `export *` for non-wrapped modules.

let mut vars = vec![];
let mut vars = Vec::new();
/// We recurse if `export *` is nested.
fn add_var(
injected_ctxt: SyntaxContext,
Expand Down Expand Up @@ -568,7 +568,7 @@ where
return;
}

let mut extra = vec![];
let mut extra = Vec::new();

module.map_any_items(|_, items| {
let mut new = Vec::with_capacity(items.len() * 11 / 10);
Expand Down Expand Up @@ -977,7 +977,7 @@ where
if !dep.is_es6 {
dep.helpers.require.store(true, Ordering::SeqCst);

let mut vars = vec![];
let mut vars = Vec::new();
let mod_var = private_ident!("_cjs_module_");

vars.push(VarDeclarator {
Expand Down Expand Up @@ -1234,7 +1234,7 @@ where
pub(super) fn replace_import_specifiers(&self, info: &TransformedModule, module: &mut Modules) {
let injected_ctxt = self.injected_ctxt;

let mut vars = vec![];
let mut vars = Vec::new();
module.map_any_items(|module_id, stmts| {
let mut new = Vec::with_capacity(stmts.len() + 32);

Expand Down
2 changes: 1 addition & 1 deletion crates/swc_bundler/src/bundler/finalize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ where
let is_async = contains_top_level_await(&module);

// Properties of returned object
let mut props = vec![];
let mut props = Vec::new();

let mut body = BlockStmt {
span: module.span,
Expand Down
4 changes: 2 additions & 2 deletions crates/swc_bundler/src/bundler/helpers/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ fn parse(code: &'static str, name: &'static str) -> Vec<ModuleItem> {
Default::default(),
Default::default(),
None,
&mut vec![],
&mut Vec::new(),
)
.map(|script| drop_span(script.body))
.map_err(|_| {})
Expand Down Expand Up @@ -59,7 +59,7 @@ impl Helpers {
}

pub fn add_to(&self, to: &mut Vec<ModuleItem>) {
let mut buf = vec![];
let mut buf = Vec::new();

if self.require.load(SeqCst) {
build_swcpack_require(&mut buf);
Expand Down
4 changes: 2 additions & 2 deletions crates/swc_bundler/src/bundler/import/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@ where

let decl = ImportDecl {
span,
specifiers: vec![],
specifiers: Vec::new(),
src: Box::new(src.clone()),
type_only: false,
with: None,
Expand Down Expand Up @@ -544,7 +544,7 @@ where
});

if self.deglob_phase {
let mut wrapping_required = vec![];
let mut wrapping_required = Vec::new();
for import in self.info.imports.iter_mut() {
let use_ns = self.info.forced_ns.contains(&import.src.value)
|| self
Expand Down
Loading
Loading