feat(allocator): Add maybe types (#9278)

This commit is contained in:
Donny/강동윤 2024-07-19 13:22:34 +09:00 committed by GitHub
parent 201f58dc7b
commit a417ff4d86
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
226 changed files with 821 additions and 778 deletions

4
Cargo.lock generated
View File

@ -3866,6 +3866,7 @@ dependencies = [
"serde", "serde",
"serde_json", "serde_json",
"sourcemap", "sourcemap",
"swc_allocator",
"swc_atoms", "swc_atoms",
"swc_common", "swc_common",
"swc_config", "swc_config",
@ -4176,6 +4177,7 @@ dependencies = [
"serde", "serde",
"serde_json", "serde_json",
"sourcemap", "sourcemap",
"swc_allocator",
"swc_atoms", "swc_atoms",
"swc_common", "swc_common",
"swc_ecma_ast", "swc_ecma_ast",
@ -4788,6 +4790,7 @@ dependencies = [
"serde", "serde",
"sha1", "sha1",
"string_enum", "string_enum",
"swc_allocator",
"swc_atoms", "swc_atoms",
"swc_common", "swc_common",
"swc_config", "swc_config",
@ -4991,6 +4994,7 @@ dependencies = [
"codspeed-criterion-compat", "codspeed-criterion-compat",
"criterion", "criterion",
"serde", "serde",
"swc_allocator",
"swc_common", "swc_common",
"swc_ecma_ast", "swc_ecma_ast",
"swc_ecma_codegen", "swc_ecma_codegen",

View File

@ -63,7 +63,7 @@ impl Task for BundleTask {
.map(JsWord::from) .map(JsWord::from)
.collect::<Vec<_>>() .collect::<Vec<_>>()
} else { } else {
vec![] Vec::new()
}; };
// Defaults to es3 // Defaults to es3

View File

@ -16,7 +16,7 @@ impl Parse for Args {
} }
pub fn expand_struct(args: Args, i: DeriveInput) -> Vec<ItemImpl> { 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 generics = i.generics.clone();
// let item_ident = Ident::new("Item", i.ident.span()); // let item_ident = Ident::new("Item", i.ident.span());
@ -128,7 +128,7 @@ pub fn expand_struct(args: Args, i: DeriveInput) -> Vec<ItemImpl> {
// let item = DeriveInput { // let item = DeriveInput {
// vis: Visibility::Inherited, // vis: Visibility::Inherited,
// ident: item_ident, // ident: item_ident,
// attrs: vec![], // attrs: Vec::new(),
// data: item_data, // data: item_data,
// ..cloned // ..cloned
// }; // };

View File

@ -113,8 +113,8 @@ pub fn expand(
.collect::<Vec<Arm>>(); .collect::<Vec<Arm>>();
let tag_expr: Expr = { let tag_expr: Expr = {
let mut visit_str_arms = vec![]; let mut visit_str_arms = Vec::new();
let mut visit_bytes_arms = vec![]; let mut visit_bytes_arms = Vec::new();
for variant in &data.variants { for variant in &data.variants {
let tags = variant let tags = variant

View File

@ -49,7 +49,7 @@ pub fn parse_js(fm: Arc<SourceFile>) -> Result<ModuleRecord> {
let unresolved_mark = Mark::new(); let unresolved_mark = Mark::new();
let top_level_mark = Mark::new(); let top_level_mark = Mark::new();
let mut errors = vec![]; let mut errors = Vec::new();
let comments = SingleThreadedComments::default(); let comments = SingleThreadedComments::default();
let res = parse_file_as_module( let res = parse_file_as_module(
&fm, &fm,
@ -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> { 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>; let mut wr = Box::new(JsWriter::new(cm.clone(), "\n", &mut buf, None)) as Box<dyn WriteJs>;
@ -112,7 +112,7 @@ pub struct ModuleRecord {
pub fn all_js_files(path: &Path) -> Result<Vec<PathBuf>> { pub fn all_js_files(path: &Path) -> Result<Vec<PathBuf>> {
wrap_task(|| { wrap_task(|| {
if path.is_dir() { if path.is_dir() {
let mut files = vec![]; let mut files = Vec::new();
for entry in path.read_dir().context("failed to read dir")? { for entry in path.read_dir().context("failed to read dir")? {
let entry = entry.context("read_dir returned an error")?; let entry = entry.context("read_dir returned an error")?;
let path = entry.path(); let path = entry.path();
@ -122,7 +122,7 @@ pub fn all_js_files(path: &Path) -> Result<Vec<PathBuf>> {
} else if path.extension() == Some("js".as_ref()) { } else if path.extension() == Some("js".as_ref()) {
Ok(vec![path.to_path_buf()]) Ok(vec![path.to_path_buf()])
} else { } else {
Ok(vec![]) Ok(Vec::new())
} }
}) })
.with_context(|| format!("failed to get list of `.js` files in {}", path.display())) .with_context(|| format!("failed to get list of `.js` files in {}", path.display()))

View File

@ -32,7 +32,7 @@ fn derive(
_ => panic!("#[derive(FromVariant)] only works for an enum."), _ => 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 { for v in variants {
let variant_name = v.ident; let variant_name = v.ident;

View File

@ -14,7 +14,7 @@ mod input;
pub fn parse(i: Input) -> IResult<Input, JsDoc> { pub fn parse(i: Input) -> IResult<Input, JsDoc> {
let i = skip(i); let i = skip(i);
let mut tags = vec![]; let mut tags = Vec::new();
let lo = i.span().lo; let lo = i.span().lo;
let (description, mut i) = take_while(|c| c != '@')(i)?; let (description, mut i) = take_while(|c| c != '@')(i)?;
let description = trim(description).into(); let description = trim(description).into();
@ -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> { fn parse_name_path(mut i: Input) -> IResult<Input, NamePath> {
let lo = i.span().lo; let lo = i.span().lo;
let mut components = vec![]; let mut components = Vec::new();
loop { loop {
let (input, component) = parse_word(i)?; let (input, component) = parse_word(i)?;

View File

@ -15,7 +15,7 @@ fn fixture(path: PathBuf) {
let fm = cm.load_file(&path).expect("failed to load fixture file"); 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( if let Err(err) = parse_file_as_module(
&fm, &fm,
@ -35,7 +35,7 @@ fn fixture(path: PathBuf) {
if handler.has_errors() { if handler.has_errors() {
return Err(()); return Err(());
} }
let mut res = vec![]; let mut res = Vec::new();
let mut comments: Vec<_> = comments.leading.into_iter().collect(); let mut comments: Vec<_> = comments.leading.into_iter().collect();
comments.sort_by_key(|v| v.0); comments.sort_by_key(|v| v.0);

View File

@ -1548,7 +1548,7 @@ impl GlobalPassOption {
fn expr(cm: &SourceMap, handler: &Handler, src: String) -> Box<Expr> { fn expr(cm: &SourceMap, handler: &Handler, src: String) -> Box<Expr> {
let fm = cm.new_source_file(FileName::Anon.into(), src); 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( let expr = parse_file_as_expr(
&fm, &fm,
Syntax::Es(Default::default()), Syntax::Es(Default::default()),

View File

@ -113,7 +113,7 @@ fn matrix(input: &Path) -> Vec<TestUnitData> {
let mut sub_filename = filename; let mut sub_filename = filename;
let mut files = vec![]; let mut files = Vec::new();
let mut buffer = String::default(); let mut buffer = String::default();
for line in fm.src.lines() { for line in fm.src.lines() {
@ -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 let is_jsx = input
.extension() .extension()
@ -357,7 +357,7 @@ fn matrix(input: &Path) -> Vec<TestUnitData> {
for minify in [None, Some(default_minify)] { for minify in [None, Some(default_minify)] {
for target in targets.clone() { for target in targets.clone() {
for module in modules.clone() { for module in modules.clone() {
let mut vary_name = vec![]; let mut vary_name = Vec::new();
if modules.len() > 1 { if modules.len() > 1 {
vary_name.push(format!("module={}", &module)); vary_name.push(format!("module={}", &module));

View File

@ -42,6 +42,15 @@ pub mod boxed;
#[cfg(feature = "nightly")] #[cfg(feature = "nightly")]
pub mod vec; 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. /// Fast allocator, effectively working as a cache.
/// ///
/// This type implements [Default] and [Copy]. This type is intended to stored /// This type implements [Default] and [Copy]. This type is intended to stored

View File

@ -381,3 +381,9 @@ impl io::Write for Vec<u8> {
self self
} }
} }
impl<T> AsRef<[T]> for Vec<T> {
fn as_ref(&self) -> &[T] {
self.0.as_ref()
}
}

View File

@ -36,7 +36,7 @@ use swc_ecma_visit::VisitMutWith;
fn print_bundles(cm: Lrc<SourceMap>, modules: Vec<Bundle>, minify: bool) { fn print_bundles(cm: Lrc<SourceMap>, modules: Vec<Bundle>, minify: bool) {
for bundled in modules { for bundled in modules {
let code = { let code = {
let mut buf = vec![]; let mut buf = Vec::new();
{ {
let wr = JsWriter::new(cm.clone(), "\n", &mut buf, None); let wr = JsWriter::new(cm.clone(), "\n", &mut buf, None);
@ -232,7 +232,7 @@ impl Load for Loader {
Syntax::Es(Default::default()), Syntax::Es(Default::default()),
EsVersion::Es2020, EsVersion::Es2020,
None, None,
&mut vec![], &mut Vec::new(),
) )
.unwrap_or_else(|err| { .unwrap_or_else(|err| {
let handler = let handler =

View File

@ -14,7 +14,7 @@ fn main() {
let globals = Globals::new(); let globals = Globals::new();
let cm = Lrc::new(SourceMap::new(FilePathMapping::empty())); let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
// This example does not use core modules. // This example does not use core modules.
let external_modules = vec![]; let external_modules = Vec::new();
let mut bundler = Bundler::new( let mut bundler = Bundler::new(
&globals, &globals,
cm.clone(), cm.clone(),
@ -74,7 +74,7 @@ impl Load for PathLoader {
Syntax::Es(Default::default()), Syntax::Es(Default::default()),
Default::default(), Default::default(),
None, None,
&mut vec![], &mut Vec::new(),
) )
.expect("This should not happen"); .expect("This should not happen");

View File

@ -126,7 +126,7 @@ fn wrap_module(
pat: Pat::Ident(Ident::new("exports".into(), DUMMY_SP, local_ctxt).into()), pat: Pat::Ident(Ident::new("exports".into(), DUMMY_SP, local_ctxt).into()),
}, },
], ],
decorators: vec![], decorators: Vec::new(),
span: DUMMY_SP, span: DUMMY_SP,
body: Some(BlockStmt { body: Some(BlockStmt {
span: dep.span, span: dep.span,
@ -205,7 +205,7 @@ where
let load = CallExpr { let load = CallExpr {
span: node.span, span: node.span,
callee: Ident::new("load".into(), i.span, i.ctxt).as_callee(), callee: Ident::new("load".into(), i.span, i.ctxt).as_callee(),
args: vec![], args: Vec::new(),
..Default::default() ..Default::default()
}; };
self.replaced = true; self.replaced = true;
@ -253,7 +253,7 @@ where
*node = CallExpr { *node = CallExpr {
span: DUMMY_SP, span: DUMMY_SP,
callee: load_var.as_callee(), callee: load_var.as_callee(),
args: vec![], args: Vec::new(),
..Default::default() ..Default::default()
} }
@ -262,7 +262,7 @@ where
return; return;
} }
let mut props = vec![]; let mut props = Vec::new();
// TODO // TODO
for spec in i.specifiers.clone() { for spec in i.specifiers.clone() {
match spec { match spec {
@ -303,7 +303,7 @@ where
CallExpr { CallExpr {
span: DUMMY_SP, span: DUMMY_SP,
callee: load_var.as_callee(), callee: load_var.as_callee(),
args: vec![], args: Vec::new(),
..Default::default() ..Default::default()
} }
@ -335,7 +335,7 @@ where
init: Some(Box::new(Expr::Call(CallExpr { init: Some(Box::new(Expr::Call(CallExpr {
span: DUMMY_SP, span: DUMMY_SP,
callee: load_var.as_callee(), callee: load_var.as_callee(),
args: vec![], args: Vec::new(),
..Default::default() ..Default::default()
}))), }))),
definite: false, definite: false,

View File

@ -48,7 +48,7 @@ where
let is_async = module.iter().any(|m| contains_top_level_await(m.1)); 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)| { module.iter().for_each(|(module_id, item)| {
match item { match item {

View File

@ -183,7 +183,7 @@ where
{ {
// Handle `export *` for non-wrapped modules. // Handle `export *` for non-wrapped modules.
let mut vars = vec![]; let mut vars = Vec::new();
/// We recurse if `export *` is nested. /// We recurse if `export *` is nested.
fn add_var( fn add_var(
injected_ctxt: SyntaxContext, injected_ctxt: SyntaxContext,
@ -568,7 +568,7 @@ where
return; return;
} }
let mut extra = vec![]; let mut extra = Vec::new();
module.map_any_items(|_, items| { module.map_any_items(|_, items| {
let mut new = Vec::with_capacity(items.len() * 11 / 10); let mut new = Vec::with_capacity(items.len() * 11 / 10);
@ -977,7 +977,7 @@ where
if !dep.is_es6 { if !dep.is_es6 {
dep.helpers.require.store(true, Ordering::SeqCst); dep.helpers.require.store(true, Ordering::SeqCst);
let mut vars = vec![]; let mut vars = Vec::new();
let mod_var = private_ident!("_cjs_module_"); let mod_var = private_ident!("_cjs_module_");
vars.push(VarDeclarator { vars.push(VarDeclarator {
@ -1234,7 +1234,7 @@ where
pub(super) fn replace_import_specifiers(&self, info: &TransformedModule, module: &mut Modules) { pub(super) fn replace_import_specifiers(&self, info: &TransformedModule, module: &mut Modules) {
let injected_ctxt = self.injected_ctxt; let injected_ctxt = self.injected_ctxt;
let mut vars = vec![]; let mut vars = Vec::new();
module.map_any_items(|module_id, stmts| { module.map_any_items(|module_id, stmts| {
let mut new = Vec::with_capacity(stmts.len() + 32); let mut new = Vec::with_capacity(stmts.len() + 32);

View File

@ -150,7 +150,7 @@ where
let is_async = contains_top_level_await(&module); let is_async = contains_top_level_await(&module);
// Properties of returned object // Properties of returned object
let mut props = vec![]; let mut props = Vec::new();
let mut body = BlockStmt { let mut body = BlockStmt {
span: module.span, span: module.span,

View File

@ -20,7 +20,7 @@ fn parse(code: &'static str, name: &'static str) -> Vec<ModuleItem> {
Default::default(), Default::default(),
Default::default(), Default::default(),
None, None,
&mut vec![], &mut Vec::new(),
) )
.map(|script| drop_span(script.body)) .map(|script| drop_span(script.body))
.map_err(|_| {}) .map_err(|_| {})
@ -59,7 +59,7 @@ impl Helpers {
} }
pub fn add_to(&self, to: &mut Vec<ModuleItem>) { pub fn add_to(&self, to: &mut Vec<ModuleItem>) {
let mut buf = vec![]; let mut buf = Vec::new();
if self.require.load(SeqCst) { if self.require.load(SeqCst) {
build_swcpack_require(&mut buf); build_swcpack_require(&mut buf);

View File

@ -239,7 +239,7 @@ where
let decl = ImportDecl { let decl = ImportDecl {
span, span,
specifiers: vec![], specifiers: Vec::new(),
src: Box::new(src.clone()), src: Box::new(src.clone()),
type_only: false, type_only: false,
with: None, with: None,
@ -544,7 +544,7 @@ where
}); });
if self.deglob_phase { if self.deglob_phase {
let mut wrapping_required = vec![]; let mut wrapping_required = Vec::new();
for import in self.info.imports.iter_mut() { for import in self.info.imports.iter_mut() {
let use_ns = self.info.forced_ns.contains(&import.src.value) let use_ns = self.info.forced_ns.contains(&import.src.value)
|| self || self

View File

@ -225,7 +225,7 @@ where
) -> Result<(Exports, Vec<(Source, Lrc<FileName>)>), Error> { ) -> Result<(Exports, Vec<(Source, Lrc<FileName>)>), Error> {
self.run(|| { self.run(|| {
tracing::trace!("resolve_exports({})", base); tracing::trace!("resolve_exports({})", base);
let mut files = vec![]; let mut files = Vec::new();
let mut exports = Exports::default(); let mut exports = Exports::default();
@ -282,7 +282,7 @@ where
) -> Result<(Imports, Vec<(Source, Lrc<FileName>)>), Error> { ) -> Result<(Imports, Vec<(Source, Lrc<FileName>)>), Error> {
self.run(|| { self.run(|| {
tracing::trace!("resolve_imports({})", base); tracing::trace!("resolve_imports({})", base);
let mut files = vec![]; let mut files = Vec::new();
let mut merged = Imports::default(); let mut merged = Imports::default();
let RawImports { let RawImports {
@ -300,7 +300,7 @@ where
( (
ImportDecl { ImportDecl {
span: src.span, span: src.span,
specifiers: vec![], specifiers: Vec::new(),
src: Box::new(src), src: Box::new(src),
type_only: false, type_only: false,
with: None, with: None,
@ -346,7 +346,7 @@ where
files.push((src.clone(), file_name)); files.push((src.clone(), file_name));
// TODO: Handle rename // TODO: Handle rename
let mut specifiers = vec![]; let mut specifiers = Vec::new();
for s in decl.specifiers { for s in decl.specifiers {
match s { match s {
ImportSpecifier::Named(s) => { ImportSpecifier::Named(s) => {

View File

@ -141,7 +141,7 @@ impl TestBuilder {
disable_hygiene: false, disable_hygiene: false,
disable_fixer: false, disable_fixer: false,
disable_dce: false, disable_dce: false,
external_modules: vec![], external_modules: Vec::new(),
module: Default::default(), module: Default::default(),
}, },
Box::new(Hook), Box::new(Hook),

View File

@ -266,7 +266,7 @@ impl Modules {
}) })
.collect::<String>(); .collect::<String>();
let mut cloned = self.clone(); let mut cloned = self.clone();
let mut stmts = vec![]; let mut stmts = Vec::new();
for (id, mut module) in cloned.modules { for (id, mut module) in cloned.modules {
swc_ecma_utils::prepend_stmts( swc_ecma_utils::prepend_stmts(

View File

@ -30,7 +30,7 @@ impl Modules {
cm: &Lrc<SourceMap>, cm: &Lrc<SourceMap>,
) -> Vec<Chunk> { ) -> Vec<Chunk> {
let injected_ctxt = self.injected_ctxt; let injected_ctxt = self.injected_ctxt;
let mut chunks = vec![]; let mut chunks = Vec::new();
let mut modules = take(&mut self.modules); let mut modules = take(&mut self.modules);
@ -69,7 +69,7 @@ fn toposort_real_modules<'a>(
let mut queue = modules.iter().map(|v| v.0).collect::<VecDeque<_>>(); let mut queue = modules.iter().map(|v| v.0).collect::<VecDeque<_>>();
queue.push_front(entry); queue.push_front(entry);
let mut chunks = vec![]; let mut chunks = Vec::new();
tracing::debug!( tracing::debug!(
"Topologically sorting modules based on the dependency graph: ({} items)", "Topologically sorting modules based on the dependency graph: ({} items)",
@ -88,7 +88,7 @@ fn toposort_real_modules<'a>(
continue; continue;
} }
let mut stmts = vec![]; let mut stmts = Vec::new();
for id in ids.iter().copied().rev() { for id in ids.iter().copied().rev() {
if let Some((_, module)) = modules.iter_mut().find(|(module_id, _)| *module_id == id) { if let Some((_, module)) = modules.iter_mut().find(|(module_id, _)| *module_id == id) {

View File

@ -22,10 +22,10 @@ pub(super) fn sort_stmts(
) -> Vec<ModuleItem> { ) -> Vec<ModuleItem> {
let total_len: usize = modules.iter().map(|v| v.len()).sum(); let total_len: usize = modules.iter().map(|v| v.len()).sum();
let mut stmts = vec![]; let mut stmts = Vec::new();
let mut free = vec![]; let mut free = Vec::new();
let mut same_module_ranges = vec![]; let mut same_module_ranges = Vec::new();
let mut module_starts = vec![]; let mut module_starts = Vec::new();
for module in modules { for module in modules {
let start = stmts.len(); let start = stmts.len();
@ -226,7 +226,7 @@ fn iter<'a>(
// dbg!(&deps); // dbg!(&deps);
if !deps.is_empty() { if !deps.is_empty() {
let mut deps_to_push = vec![]; let mut deps_to_push = Vec::new();
for dep in deps.iter().rev().copied() { for dep in deps.iter().rev().copied() {
if deps_to_push.contains(&dep) { if deps_to_push.contains(&dep) {
continue; continue;

View File

@ -16,7 +16,7 @@ fn assert_sorted_with_free(src: &[&str], free: &str, res: &str) {
s = s.file(&format!("{}.js", i), src); s = s.file(&format!("{}.js", i), src);
} }
s.run(|t| { s.run(|t| {
let mut modules = vec![]; let mut modules = Vec::new();
let mut entry = None; let mut entry = None;
let mut free: Module = drop_span(t.parse(free)); let mut free: Module = drop_span(t.parse(free));

View File

@ -204,7 +204,7 @@ impl ExportMetadata {
pub fn into_with(self) -> Box<ObjectLit> { pub fn into_with(self) -> Box<ObjectLit> {
let mut obj = Some(Box::new(ObjectLit { let mut obj = Some(Box::new(ObjectLit {
span: DUMMY_SP, span: DUMMY_SP,
props: vec![], props: Vec::new(),
})); }));
self.encode(&mut obj); self.encode(&mut obj);
@ -213,7 +213,7 @@ impl ExportMetadata {
} }
pub fn encode(&self, to: &mut Option<Box<ObjectLit>>) { pub fn encode(&self, to: &mut Option<Box<ObjectLit>>) {
let mut props = vec![]; let mut props = Vec::new();
if self.injected { if self.injected {
props.push(metadata("__swc_bundler__injected__", "1")); props.push(metadata("__swc_bundler__injected__", "1"));

View File

@ -78,7 +78,7 @@ fn load_url(url: Url) -> Result<String, Error> {
.bytes() .bytes()
.with_context(|| format!("failed to read data from `{}`", url))?; .with_context(|| format!("failed to read data from `{}`", url))?;
let mut content = vec![]; let mut content = Vec::new();
write!(content, "// Loaded from {}\n\n\n", url).unwrap(); write!(content, "// Loaded from {}\n\n\n", url).unwrap();
content.extend_from_slice(&bytes); content.extend_from_slice(&bytes);
@ -124,7 +124,7 @@ impl Load for Loader {
}), }),
EsVersion::Es2020, EsVersion::Es2020,
None, None,
&mut vec![], &mut Vec::new(),
) )
.unwrap_or_else(|err| { .unwrap_or_else(|err| {
let handler = let handler =

View File

@ -1074,7 +1074,7 @@ fn bundle(url: &str, minify: bool) -> String {
module.visit_mut_with(&mut fixer(None)); module.visit_mut_with(&mut fixer(None));
} }
let mut buf = vec![]; let mut buf = Vec::new();
{ {
let mut wr: Box<dyn WriteJs> = let mut wr: Box<dyn WriteJs> =
Box::new(JsWriter::new(cm.clone(), "\n", &mut buf, None)); Box::new(JsWriter::new(cm.clone(), "\n", &mut buf, None));

View File

@ -51,7 +51,7 @@ fn do_test(entry: &Path, entries: HashMap<String, FileName>, inline: bool) {
for bundled in modules { for bundled in modules {
let code = { let code = {
let mut buf = vec![]; let mut buf = Vec::new();
{ {
let mut emitter = Emitter { let mut emitter = Emitter {

View File

@ -136,8 +136,8 @@ impl Diagnostic {
message: vec![Message(message.to_owned(), Style::NoStyle)], message: vec![Message(message.to_owned(), Style::NoStyle)],
code, code,
span: MultiSpan::new(), span: MultiSpan::new(),
children: vec![], children: Vec::new(),
suggestions: vec![], suggestions: Vec::new(),
} }
} }

View File

@ -241,8 +241,8 @@ impl EmitterWriter {
}); });
} }
let mut output = vec![]; let mut output = Vec::new();
let mut multiline_annotations = vec![]; let mut multiline_annotations = Vec::new();
if let Some(ref sm) = self.sm { if let Some(ref sm) = self.sm {
for span_label in msp.span_labels() { for span_label in msp.span_labels() {
@ -496,7 +496,7 @@ impl EmitterWriter {
// | x_span // | x_span
// <EMPTY LINE> // <EMPTY LINE>
// //
let mut annotations_position = vec![]; let mut annotations_position = Vec::new();
let mut line_len = 0; let mut line_len = 0;
let mut p = 0; let mut p = 0;
for (i, annotation) in annotations.iter().enumerate() { for (i, annotation) in annotations.iter().enumerate() {
@ -562,7 +562,7 @@ impl EmitterWriter {
// If there are no annotations or the only annotations on this line are // If there are no annotations or the only annotations on this line are
// MultilineLine, then there's only code being shown, stop processing. // MultilineLine, then there's only code being shown, stop processing.
if line.annotations.iter().all(|a| a.is_line()) { if line.annotations.iter().all(|a| a.is_line()) {
return vec![]; return Vec::new();
} }
// Write the column separator. // Write the column separator.
@ -792,8 +792,8 @@ impl EmitterWriter {
let mut spans_updated = false; let mut spans_updated = false;
if let Some(ref sm) = self.sm { if let Some(ref sm) = self.sm {
let mut before_after: Vec<(Span, Span)> = vec![]; let mut before_after: Vec<(Span, Span)> = Vec::new();
let new_labels: Vec<(Span, String)> = vec![]; let new_labels: Vec<(Span, String)> = Vec::new();
// First, find all the spans in <*macros> and point instead at their use site // First, find all the spans in <*macros> and point instead at their use site
for sp in span.primary_spans() { for sp in span.primary_spans() {

View File

@ -21,14 +21,14 @@ pub struct StyledBuffer {
impl StyledBuffer { impl StyledBuffer {
pub fn new() -> StyledBuffer { pub fn new() -> StyledBuffer {
StyledBuffer { StyledBuffer {
text: vec![], text: Vec::new(),
styles: vec![], styles: Vec::new(),
} }
} }
fn replace_tabs(&mut self) { fn replace_tabs(&mut self) {
for (line_pos, line) in self.text.iter_mut().enumerate() { for (line_pos, line) in self.text.iter_mut().enumerate() {
let mut tab_pos = vec![]; let mut tab_pos = Vec::new();
for (pos, c) in line.iter().enumerate() { for (pos, c) in line.iter().enumerate() {
if *c == '\t' { if *c == '\t' {
tab_pos.push(pos); tab_pos.push(pos);
@ -48,8 +48,8 @@ impl StyledBuffer {
} }
pub fn render(&mut self) -> Vec<Vec<StyledString>> { pub fn render(&mut self) -> Vec<Vec<StyledString>> {
let mut output: Vec<Vec<StyledString>> = vec![]; let mut output: Vec<Vec<StyledString>> = Vec::new();
let mut styled_vec: Vec<StyledString> = vec![]; let mut styled_vec: Vec<StyledString> = Vec::new();
// before we render, replace tabs with spaces // before we render, replace tabs with spaces
self.replace_tabs(); self.replace_tabs();
@ -81,7 +81,7 @@ impl StyledBuffer {
// We're done with the row, push and keep going // We're done with the row, push and keep going
output.push(styled_vec); output.push(styled_vec);
styled_vec = vec![]; styled_vec = Vec::new();
} }
output output
@ -89,8 +89,8 @@ impl StyledBuffer {
fn ensure_lines(&mut self, line: usize) { fn ensure_lines(&mut self, line: usize) {
while line >= self.text.len() { while line >= self.text.len() {
self.text.push(vec![]); self.text.push(Vec::new());
self.styles.push(vec![]); self.styles.push(Vec::new());
} }
} }

View File

@ -516,7 +516,7 @@ impl SourceMap {
if lo.file.src.is_empty() { if lo.file.src.is_empty() {
return Ok(FileLines { return Ok(FileLines {
file: lo.file, file: lo.file,
lines: vec![], lines: Vec::new(),
}); });
} }
@ -1434,7 +1434,9 @@ pub struct FilePathMapping {
impl FilePathMapping { impl FilePathMapping {
pub fn empty() -> FilePathMapping { pub fn empty() -> FilePathMapping {
FilePathMapping { mapping: vec![] } FilePathMapping {
mapping: Vec::new(),
}
} }
pub fn new(mapping: Vec<(PathBuf, PathBuf)>) -> FilePathMapping { pub fn new(mapping: Vec<(PathBuf, PathBuf)>) -> FilePathMapping {

View File

@ -535,14 +535,14 @@ impl MultiSpan {
pub fn from_span(primary_span: Span) -> MultiSpan { pub fn from_span(primary_span: Span) -> MultiSpan {
MultiSpan { MultiSpan {
primary_spans: vec![primary_span], primary_spans: vec![primary_span],
span_labels: vec![], span_labels: Vec::new(),
} }
} }
pub fn from_spans(vec: Vec<Span>) -> MultiSpan { pub fn from_spans(vec: Vec<Span>) -> MultiSpan {
MultiSpan { MultiSpan {
primary_spans: vec, primary_spans: vec,
span_labels: vec![], span_labels: Vec::new(),
} }
} }

View File

@ -21,8 +21,8 @@ pub fn analyze_source_file(
source_file_start_pos: BytePos, source_file_start_pos: BytePos,
) -> (Vec<BytePos>, Vec<MultiByteChar>, Vec<NonNarrowChar>) { ) -> (Vec<BytePos>, Vec<MultiByteChar>, Vec<NonNarrowChar>) {
let mut lines = vec![source_file_start_pos]; let mut lines = vec![source_file_start_pos];
let mut multi_byte_chars = vec![]; let mut multi_byte_chars = Vec::new();
let mut non_narrow_chars = vec![]; let mut non_narrow_chars = Vec::new();
// Calls the right implementation, depending on hardware support available. // Calls the right implementation, depending on hardware support available.
analyze_source_file_generic( analyze_source_file_generic(
@ -178,9 +178,9 @@ mod tests {
case: empty_text, case: empty_text,
text: "", text: "",
source_file_start_pos: 0, source_file_start_pos: 0,
lines: vec![], lines: Vec::new(),
multi_byte_chars: vec![], multi_byte_chars: Vec::new(),
non_narrow_chars: vec![], non_narrow_chars: Vec::new(),
); );
test!( test!(
@ -188,8 +188,8 @@ mod tests {
text: "a\nc", text: "a\nc",
source_file_start_pos: 0, source_file_start_pos: 0,
lines: vec![0, 2], lines: vec![0, 2],
multi_byte_chars: vec![], multi_byte_chars: Vec::new(),
non_narrow_chars: vec![], non_narrow_chars: Vec::new(),
); );
test!( test!(
@ -197,8 +197,8 @@ mod tests {
text: "012345678\nabcdef012345678\na", text: "012345678\nabcdef012345678\na",
source_file_start_pos: 0, source_file_start_pos: 0,
lines: vec![0, 10, 26], lines: vec![0, 10, 26],
multi_byte_chars: vec![], multi_byte_chars: Vec::new(),
non_narrow_chars: vec![], non_narrow_chars: Vec::new(),
); );
test!( test!(
@ -207,7 +207,7 @@ mod tests {
source_file_start_pos: 0, source_file_start_pos: 0,
lines: vec![0, 11], lines: vec![0, 11],
multi_byte_chars: vec![(5, 2)], multi_byte_chars: vec![(5, 2)],
non_narrow_chars: vec![], non_narrow_chars: Vec::new(),
); );
test!( test!(
@ -215,7 +215,7 @@ mod tests {
text: "01234\u{07}6789\nbcdef0123456789abcdef", text: "01234\u{07}6789\nbcdef0123456789abcdef",
source_file_start_pos: 0, source_file_start_pos: 0,
lines: vec![0, 11], lines: vec![0, 11],
multi_byte_chars: vec![], multi_byte_chars: Vec::new(),
non_narrow_chars: vec![(5, 0)], non_narrow_chars: vec![(5, 0)],
); );
@ -225,7 +225,7 @@ mod tests {
source_file_start_pos: 0, source_file_start_pos: 0,
lines: vec![0], lines: vec![0],
multi_byte_chars: vec![(1, 2)], multi_byte_chars: vec![(1, 2)],
non_narrow_chars: vec![], non_narrow_chars: Vec::new(),
); );
test!( test!(
@ -234,7 +234,7 @@ mod tests {
source_file_start_pos: 0, source_file_start_pos: 0,
lines: vec![0], lines: vec![0],
multi_byte_chars: vec![(13, 2), (22, 2)], multi_byte_chars: vec![(13, 2), (22, 2)],
non_narrow_chars: vec![], non_narrow_chars: Vec::new(),
); );
test!( test!(
@ -243,7 +243,7 @@ mod tests {
source_file_start_pos: 0, source_file_start_pos: 0,
lines: vec![0], lines: vec![0],
multi_byte_chars: vec![(15, 2)], multi_byte_chars: vec![(15, 2)],
non_narrow_chars: vec![], non_narrow_chars: Vec::new(),
); );
test!( test!(
@ -252,7 +252,7 @@ mod tests {
source_file_start_pos: 0, source_file_start_pos: 0,
lines: vec![0], lines: vec![0],
multi_byte_chars: vec![(15, 2)], multi_byte_chars: vec![(15, 2)],
non_narrow_chars: vec![], non_narrow_chars: Vec::new(),
); );
test!( test!(
@ -260,7 +260,7 @@ mod tests {
text: "0\t2", text: "0\t2",
source_file_start_pos: 0, source_file_start_pos: 0,
lines: vec![0], lines: vec![0],
multi_byte_chars: vec![], multi_byte_chars: Vec::new(),
non_narrow_chars: vec![(1, 4)], non_narrow_chars: vec![(1, 4)],
); );
@ -269,7 +269,7 @@ mod tests {
text: "01\t3456789abcdef01234567\u{07}9", text: "01\t3456789abcdef01234567\u{07}9",
source_file_start_pos: 0, source_file_start_pos: 0,
lines: vec![0], lines: vec![0],
multi_byte_chars: vec![], multi_byte_chars: Vec::new(),
non_narrow_chars: vec![(2, 4), (24, 0)], non_narrow_chars: vec![(2, 4), (24, 0)],
); );
@ -287,8 +287,8 @@ mod tests {
text: "/**\n * foo\n */\n012345678\nabcdef012345678\na", text: "/**\n * foo\n */\n012345678\nabcdef012345678\na",
source_file_start_pos: 0, source_file_start_pos: 0,
lines: vec![0, 4, 11, 15, 25, 41], lines: vec![0, 4, 11, 15, 25, 41],
multi_byte_chars: vec![], multi_byte_chars: Vec::new(),
non_narrow_chars: vec![], non_narrow_chars: Vec::new(),
); );
test!( test!(
@ -296,8 +296,8 @@ mod tests {
text: "/**\r * foo\r */\r012345678\rabcdef012345678\ra", text: "/**\r * foo\r */\r012345678\rabcdef012345678\ra",
source_file_start_pos: 0, source_file_start_pos: 0,
lines: vec![0, 4, 11, 15, 25, 41], lines: vec![0, 4, 11, 15, 25, 41],
multi_byte_chars: vec![], multi_byte_chars: Vec::new(),
non_narrow_chars: vec![], non_narrow_chars: Vec::new(),
); );
test!( test!(
@ -305,7 +305,7 @@ mod tests {
text: "/**\r\n * foo\r\n */\r\n012345678\r\nabcdef012345678\r\na", text: "/**\r\n * foo\r\n */\r\n012345678\r\nabcdef012345678\r\na",
source_file_start_pos: 0, source_file_start_pos: 0,
lines: vec![0, 5, 13, 18, 29, 46], lines: vec![0, 5, 13, 18, 29, 46],
multi_byte_chars: vec![], multi_byte_chars: Vec::new(),
non_narrow_chars: vec![], non_narrow_chars: Vec::new(),
); );
} }

View File

@ -45,7 +45,7 @@ where
impl<T> Take for Vec<T> { impl<T> Take for Vec<T> {
fn dummy() -> Self { fn dummy() -> Self {
vec![] Vec::new()
} }
} }

View File

@ -21,6 +21,7 @@ rustc-hash = { workspace = true }
serde = { workspace = true, features = ["derive"] } serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true } serde_json = { workspace = true }
sourcemap = { workspace = true } sourcemap = { workspace = true }
swc_allocator = { version = "0.1.7", path = "../swc_allocator", default-features = false }
swc_atoms = { version = "0.6.5", path = "../swc_atoms" } swc_atoms = { version = "0.6.5", path = "../swc_atoms" }
swc_common = { version = "0.36.0", path = "../swc_common", features = [ swc_common = { version = "0.36.0", path = "../swc_common", features = [

View File

@ -65,7 +65,7 @@ pub fn parse_js(
let mut res = (|| { let mut res = (|| {
let mut error = false; let mut error = false;
let mut errors = vec![]; let mut errors = std::vec::Vec::new();
let program_result = match is_module { let program_result = match is_module {
IsModule::Bool(true) => { IsModule::Bool(true) => {
parse_file_as_module(&fm, syntax, target, comments, &mut errors) parse_file_as_module(&fm, syntax, target, comments, &mut errors)
@ -171,10 +171,10 @@ where
{ {
let _timer = timer!("Compiler::print"); let _timer = timer!("Compiler::print");
let mut src_map_buf = vec![]; let mut src_map_buf = Vec::new();
let src = { let src = {
let mut buf = vec![]; let mut buf = std::vec::Vec::new();
{ {
let mut w = swc_ecma_codegen::text_writer::JsWriter::new( let mut w = swc_ecma_codegen::text_writer::JsWriter::new(
cm.clone(), cm.clone(),
@ -241,7 +241,7 @@ where
let (code, map) = match source_map { let (code, map) = match source_map {
SourceMapsConfig::Bool(v) => { SourceMapsConfig::Bool(v) => {
if v { if v {
let mut buf = vec![]; let mut buf = std::vec::Vec::new();
map.unwrap() map.unwrap()
.to_writer(&mut buf) .to_writer(&mut buf)
@ -254,7 +254,7 @@ where
} }
SourceMapsConfig::Str(_) => { SourceMapsConfig::Str(_) => {
let mut src = src; let mut src = src;
let mut buf = vec![]; let mut buf = std::vec::Vec::new();
map.unwrap() map.unwrap()
.to_writer(&mut buf) .to_writer(&mut buf)
@ -346,7 +346,7 @@ pub fn minify_file_comments(
BoolOr::Bool(true) | BoolOr::Data(JsMinifyCommentOption::PreserveAllComments) => {} BoolOr::Bool(true) | BoolOr::Data(JsMinifyCommentOption::PreserveAllComments) => {}
BoolOr::Data(JsMinifyCommentOption::PreserveSomeComments) => { BoolOr::Data(JsMinifyCommentOption::PreserveSomeComments) => {
let preserve_excl = |_: &BytePos, vc: &mut Vec<Comment>| -> bool { let preserve_excl = |_: &BytePos, vc: &mut std::vec::Vec<Comment>| -> bool {
// Preserve license comments. // Preserve license comments.
// //
// See https://github.com/terser/terser/blob/798135e04baddd94fea403cfaab4ba8b22b1b524/lib/output.js#L175-L181 // See https://github.com/terser/terser/blob/798135e04baddd94fea403cfaab4ba8b22b1b524/lib/output.js#L175-L181

View File

@ -242,7 +242,7 @@ where
} }
fn compute_line_starts(s: &str) -> Vec<usize> { fn compute_line_starts(s: &str) -> Vec<usize> {
let mut res = vec![]; let mut res = Vec::new();
let mut line_start = 0; let mut line_start = 0;
let mut chars = s.char_indices().peekable(); let mut chars = s.char_indices().peekable();

View File

@ -45,7 +45,7 @@ fn run(input: &Path, minify: bool) {
eprintln!("==== ==== Input ==== ====\n{}\n", fm.src); eprintln!("==== ==== Input ==== ====\n{}\n", fm.src);
let mut errors = vec![]; let mut errors = Vec::new();
let mut stylesheet: Stylesheet = let mut stylesheet: Stylesheet =
parse_file(&fm, Some(&comments), Default::default(), &mut errors).unwrap(); parse_file(&fm, Some(&comments), Default::default(), &mut errors).unwrap();
@ -54,7 +54,7 @@ fn run(input: &Path, minify: bool) {
} }
let mut css_str = String::new(); let mut css_str = String::new();
// let mut src_map_buf = vec![]; // let mut src_map_buf = Vec::new();
{ {
let wr = BasicCssWriter::new( let wr = BasicCssWriter::new(
@ -69,7 +69,7 @@ fn run(input: &Path, minify: bool) {
} }
// let source_map = cm.build_source_map(&mut src_map_buf); // let source_map = cm.build_source_map(&mut src_map_buf);
// let mut source_map_output: Vec<u8> = vec![]; // let mut source_map_output: Vec<u8> = Vec::new();
// source_map.to_writer(&mut source_map_output).unwrap(); // source_map.to_writer(&mut source_map_output).unwrap();
// let str_source_map_output = String::from_utf8_lossy(&source_map_output); // let str_source_map_output = String::from_utf8_lossy(&source_map_output);
// std::fs::write(map, &*str_source_map_output).expect("Unable to write file"); // std::fs::write(map, &*str_source_map_output).expect("Unable to write file");
@ -86,7 +86,7 @@ fn run(input: &Path, minify: bool) {
return Ok(()); return Ok(());
} }
let mut errors = vec![]; let mut errors = Vec::new();
let mut stylesheet_output: Stylesheet = let mut stylesheet_output: Stylesheet =
parse_file(&fm_output, None, Default::default(), &mut errors).map_err(|err| { parse_file(&fm_output, None, Default::default(), &mut errors).map_err(|err| {
err.to_diagnostics(&handler).emit(); err.to_diagnostics(&handler).emit();
@ -353,7 +353,7 @@ fn indent_type(input: PathBuf) {
let comments = SingleThreadedComments::default(); let comments = SingleThreadedComments::default();
let mut errors = vec![]; let mut errors = Vec::new();
let mut stylesheet: Stylesheet = let mut stylesheet: Stylesheet =
parse_file(&fm, Some(&comments), Default::default(), &mut errors).unwrap(); parse_file(&fm, Some(&comments), Default::default(), &mut errors).unwrap();
@ -385,7 +385,7 @@ fn indent_type(input: PathBuf) {
.compare_to_file(output) .compare_to_file(output)
.unwrap(); .unwrap();
let mut errors = vec![]; let mut errors = Vec::new();
let mut stylesheet_output: Stylesheet = let mut stylesheet_output: Stylesheet =
parse_file(&fm_output, Some(&comments), Default::default(), &mut errors).map_err( parse_file(&fm_output, Some(&comments), Default::default(), &mut errors).map_err(
|err| { |err| {
@ -422,7 +422,7 @@ fn indent_width(input: PathBuf) {
eprintln!("==== ==== Input ==== ====\n{}\n", fm.src); eprintln!("==== ==== Input ==== ====\n{}\n", fm.src);
let mut errors = vec![]; let mut errors = Vec::new();
let mut stylesheet: Stylesheet = let mut stylesheet: Stylesheet =
parse_file(&fm, Some(&comments), Default::default(), &mut errors).unwrap(); parse_file(&fm, Some(&comments), Default::default(), &mut errors).unwrap();
@ -454,7 +454,7 @@ fn indent_width(input: PathBuf) {
.compare_to_file(output) .compare_to_file(output)
.unwrap(); .unwrap();
let mut errors = vec![]; let mut errors = Vec::new();
let mut stylesheet_output: Stylesheet = let mut stylesheet_output: Stylesheet =
parse_file(&fm_output, Some(&comments), Default::default(), &mut errors).map_err( parse_file(&fm_output, Some(&comments), Default::default(), &mut errors).map_err(
|err| { |err| {
@ -491,7 +491,7 @@ fn linefeed_lf(input: PathBuf) {
eprintln!("==== ==== Input ==== ====\n{}\n", fm.src); eprintln!("==== ==== Input ==== ====\n{}\n", fm.src);
let mut errors = vec![]; let mut errors = Vec::new();
let mut stylesheet: Stylesheet = let mut stylesheet: Stylesheet =
parse_file(&fm, Some(&comments), Default::default(), &mut errors).unwrap(); parse_file(&fm, Some(&comments), Default::default(), &mut errors).unwrap();
@ -525,7 +525,7 @@ fn linefeed_lf(input: PathBuf) {
.compare_to_file(output) .compare_to_file(output)
.unwrap(); .unwrap();
let mut errors = vec![]; let mut errors = Vec::new();
let mut stylesheet_output: Stylesheet = let mut stylesheet_output: Stylesheet =
parse_file(&fm_output, Some(&comments), Default::default(), &mut errors).map_err( parse_file(&fm_output, Some(&comments), Default::default(), &mut errors).map_err(
|err| { |err| {
@ -562,7 +562,7 @@ fn linefeed_crlf(input: PathBuf) {
eprintln!("==== ==== Input ==== ====\n{}\n", fm.src); eprintln!("==== ==== Input ==== ====\n{}\n", fm.src);
let mut errors = vec![]; let mut errors = Vec::new();
let mut stylesheet: Stylesheet = let mut stylesheet: Stylesheet =
parse_file(&fm, Some(&comments), Default::default(), &mut errors).unwrap(); parse_file(&fm, Some(&comments), Default::default(), &mut errors).unwrap();
@ -596,7 +596,7 @@ fn linefeed_crlf(input: PathBuf) {
.compare_to_file(output) .compare_to_file(output)
.unwrap(); .unwrap();
let mut errors = vec![]; let mut errors = Vec::new();
let mut stylesheet_output: Stylesheet = let mut stylesheet_output: Stylesheet =
parse_file(&fm_output, Some(&comments), Default::default(), &mut errors).map_err( parse_file(&fm_output, Some(&comments), Default::default(), &mut errors).map_err(
|err| { |err| {
@ -629,7 +629,7 @@ fn parse_again(input: PathBuf) {
eprintln!("==== ==== Input ==== ====\n{}\n", fm.src); eprintln!("==== ==== Input ==== ====\n{}\n", fm.src);
let mut errors = vec![]; let mut errors = Vec::new();
let mut stylesheet: Stylesheet = let mut stylesheet: Stylesheet =
parse_file(&fm, Some(&comments), Default::default(), &mut errors).map_err(|err| { parse_file(&fm, Some(&comments), Default::default(), &mut errors).map_err(|err| {
err.to_diagnostics(&handler).emit(); err.to_diagnostics(&handler).emit();
@ -650,7 +650,7 @@ fn parse_again(input: PathBuf) {
eprintln!("==== ==== Codegen ==== ====\n{}\n", css_str); eprintln!("==== ==== Codegen ==== ====\n{}\n", css_str);
let new_fm = cm.new_source_file(Lrc::new(FileName::Anon), css_str); let new_fm = cm.new_source_file(Lrc::new(FileName::Anon), css_str);
let mut parsed_errors = vec![]; let mut parsed_errors = Vec::new();
let mut parsed: Stylesheet = parse_file( let mut parsed: Stylesheet = parse_file(
&new_fm, &new_fm,
Some(&comments), Some(&comments),

View File

@ -68,7 +68,7 @@ impl CustomMediaHandler {
} }
pub(crate) fn process_media_condition(&mut self, media_condition: &mut MediaCondition) { pub(crate) fn process_media_condition(&mut self, media_condition: &mut MediaCondition) {
let mut remove_rules_list = vec![]; let mut remove_rules_list = Vec::new();
for (i, node) in media_condition.conditions.iter_mut().enumerate() { for (i, node) in media_condition.conditions.iter_mut().enumerate() {
match node { match node {
@ -155,7 +155,7 @@ impl CustomMediaHandler {
&mut self, &mut self,
media_condition: &mut MediaConditionWithoutOr, media_condition: &mut MediaConditionWithoutOr,
) { ) {
let mut remove_rules_list = vec![]; let mut remove_rules_list = Vec::new();
for (i, node) in media_condition.conditions.iter_mut().enumerate() { for (i, node) in media_condition.conditions.iter_mut().enumerate() {
match node { match node {
@ -233,7 +233,7 @@ impl CustomMediaHandler {
if let Some(custom_media) = self.medias.iter().find(|m| m.name.value == name.value) { if let Some(custom_media) = self.medias.iter().find(|m| m.name.value == name.value) {
let mut new_media_condition = MediaCondition { let mut new_media_condition = MediaCondition {
span: DUMMY_SP, span: DUMMY_SP,
conditions: vec![], conditions: Vec::new(),
}; };
let queries = match &custom_media.media { let queries = match &custom_media.media {
@ -370,7 +370,7 @@ impl CustomMediaHandler {
) -> MediaCondition { ) -> MediaCondition {
let mut new_media_condition = MediaCondition { let mut new_media_condition = MediaCondition {
span: DUMMY_SP, span: DUMMY_SP,
conditions: vec![], conditions: Vec::new(),
}; };
for n in &media_condition.conditions { for n in &media_condition.conditions {

View File

@ -89,7 +89,7 @@ impl VisitMut for Compiler {
fn visit_mut_rules(&mut self, n: &mut Vec<Rule>) { fn visit_mut_rules(&mut self, n: &mut Vec<Rule>) {
if self.c.process.contains(Features::NESTING) { if self.c.process.contains(Features::NESTING) {
let mut new = vec![]; let mut new = Vec::new();
for n in n.take() { for n in n.take() {
match n { match n {

View File

@ -19,7 +19,7 @@ impl Compiler {
{ {
for c in children { for c in children {
if let PseudoClassSelectorChildren::ForgivingSelectorList(c) = c { if let PseudoClassSelectorChildren::ForgivingSelectorList(c) = c {
let mut selectors = vec![]; let mut selectors = Vec::new();
for sel in &mut c.children { for sel in &mut c.children {
match sel { match sel {
@ -53,7 +53,7 @@ impl Compiler {
prelude: &SelectorList, prelude: &SelectorList,
selectors: &mut Vec<ComplexSelector>, selectors: &mut Vec<ComplexSelector>,
) { ) {
let mut new_selectors = vec![]; let mut new_selectors = Vec::new();
'complex: for complex in selectors.take() { 'complex: for complex in selectors.take() {
for compound in &complex.children { for compound in &complex.children {
@ -142,7 +142,7 @@ impl Compiler {
base: &SelectorList, base: &SelectorList,
relative_selector_list: &RelativeSelectorList, relative_selector_list: &RelativeSelectorList,
) -> SelectorList { ) -> SelectorList {
let mut children = vec![]; let mut children = Vec::new();
for base_complex in &base.children { for base_complex in &base.children {
for relative_selector in &relative_selector_list.children { for relative_selector in &relative_selector_list.children {
@ -221,8 +221,8 @@ impl Compiler {
} }
pub(crate) fn extract_nested_rules(&mut self, rule: &mut QualifiedRule) -> Vec<Rule> { pub(crate) fn extract_nested_rules(&mut self, rule: &mut QualifiedRule) -> Vec<Rule> {
let mut nested_rules = vec![]; let mut nested_rules = Vec::new();
let mut block_values = vec![]; let mut block_values = Vec::new();
for value in rule.block.value.take() { for value in rule.block.value.take() {
match value { match value {
@ -242,8 +242,8 @@ impl Compiler {
) = at_rule.prelude.as_deref() ) = at_rule.prelude.as_deref()
{ {
if let Some(block) = &at_rule.block { if let Some(block) = &at_rule.block {
let mut decls_of_media = vec![]; let mut decls_of_media = Vec::new();
let mut nested_of_media = vec![]; let mut nested_of_media = Vec::new();
for n in &block.value { for n in &block.value {
match n { match n {

View File

@ -22,7 +22,7 @@ use swc_css_visit::VisitMutWith;
use testing::NormalizedOutput; use testing::NormalizedOutput;
fn parse_stylesheet(fm: &Lrc<SourceFile>) -> Stylesheet { fn parse_stylesheet(fm: &Lrc<SourceFile>) -> Stylesheet {
let mut errors = vec![]; let mut errors = Vec::new();
let ss: Stylesheet = parse_file( let ss: Stylesheet = parse_file(
fm, fm,
None, None,

View File

@ -9,7 +9,7 @@ pub fn declaration_no_important(ctx: LintRuleContext<()>) -> Box<dyn LintRule> {
ctx.reaction(), ctx.reaction(),
DeclarationNoImportant { DeclarationNoImportant {
ctx, ctx,
keyframe_rules: vec![], keyframe_rules: Vec::new(),
}, },
) )
} }

View File

@ -38,7 +38,7 @@ fn run(src: &str) {
HANDLER.set(&handler, || { HANDLER.set(&handler, || {
let fm = cm.new_source_file(FileName::Anon.into(), src.into()); let fm = cm.new_source_file(FileName::Anon.into(), src.into());
let mut errors = vec![]; let mut errors = Vec::new();
let mut ss: Stylesheet = let mut ss: Stylesheet =
parse_file(&fm, None, Default::default(), &mut errors).unwrap(); parse_file(&fm, None, Default::default(), &mut errors).unwrap();

View File

@ -36,7 +36,7 @@ fn get_precision(n: f64) -> u32 {
// https://www.w3.org/TR/css-values-4/#parse-a-calculation // https://www.w3.org/TR/css-values-4/#parse-a-calculation
fn collect_calc_sum_into_calc_node(calc_sum: &CalcSum) -> CalcNode { fn collect_calc_sum_into_calc_node(calc_sum: &CalcSum) -> CalcNode {
let mut is_negated = false; let mut is_negated = false;
let mut operands: Vec<CalcNode> = vec![]; let mut operands: Vec<CalcNode> = Vec::new();
for node in &calc_sum.expressions { for node in &calc_sum.expressions {
match &node { match &node {
CalcProductOrOperator::Product(calc_product) => { CalcProductOrOperator::Product(calc_product) => {
@ -71,7 +71,7 @@ fn collect_calc_sum_into_calc_node(calc_sum: &CalcSum) -> CalcNode {
fn collect_calc_product_into_calc_node(calc_product: &CalcProduct) -> CalcNode { fn collect_calc_product_into_calc_node(calc_product: &CalcProduct) -> CalcNode {
let mut is_inverted = false; let mut is_inverted = false;
let mut operands: Vec<CalcNode> = vec![]; let mut operands: Vec<CalcNode> = Vec::new();
for node in &calc_product.expressions { for node in &calc_product.expressions {
match &node { match &node {
CalcValueOrOperator::Value(calc_value) => { CalcValueOrOperator::Value(calc_value) => {
@ -603,7 +603,7 @@ fn try_to_multiply_all_numeric_sum_children_by_value(
nodes: &[CalcNode], nodes: &[CalcNode],
value: f64, value: f64,
) -> Option<CalcNode> { ) -> Option<CalcNode> {
let mut operands = vec![]; let mut operands = Vec::new();
for calc_node in nodes { for calc_node in nodes {
match calc_node { match calc_node {
@ -837,7 +837,7 @@ fn serialize_calculation_node_into_calc_sum(calc_node: &CalcNode) -> CalcSum {
}, },
CalcNode::OperatorNode(op) => match &**op { CalcNode::OperatorNode(op) => match &**op {
CalcOperatorNode::Sum(nodes) => { CalcOperatorNode::Sum(nodes) => {
let mut expr: Vec<CalcProductOrOperator> = vec![]; let mut expr: Vec<CalcProductOrOperator> = Vec::new();
let nodes = sort_calculations_children(nodes); let nodes = sort_calculations_children(nodes);
@ -951,7 +951,7 @@ fn serialize_calc_node_into_calc_product(calc_node: &CalcNode) -> CalcProductOrO
span: Span::dummy_with_cmt(), span: Span::dummy_with_cmt(),
}), }),
CalcOperatorNode::Product(nodes) => { CalcOperatorNode::Product(nodes) => {
let mut expr: Vec<CalcValueOrOperator> = vec![]; let mut expr: Vec<CalcValueOrOperator> = Vec::new();
let nodes = sort_calculations_children(nodes); let nodes = sort_calculations_children(nodes);
@ -1041,7 +1041,7 @@ fn serialize_calc_node_into_calc_value(calc_node: &CalcNode) -> CalcValue {
// loss of precision), we need to keep all numbers, percentages, and so on // loss of precision), we need to keep all numbers, percentages, and so on
// (instead of only one) // (instead of only one)
fn sort_calculations_children(nodes: &[CalcNode]) -> Vec<CalcNode> { fn sort_calculations_children(nodes: &[CalcNode]) -> Vec<CalcNode> {
let mut ret: Vec<CalcNode> = vec![]; let mut ret: Vec<CalcNode> = Vec::new();
// If nodes contains a number, remove it from nodes and append it to ret. // If nodes contains a number, remove it from nodes and append it to ret.
let mut numbers: Vec<CalcNode> = nodes let mut numbers: Vec<CalcNode> = nodes

View File

@ -374,7 +374,7 @@ impl Compressor {
pub(super) fn compress_stylesheet(&mut self, stylesheet: &mut Stylesheet) { pub(super) fn compress_stylesheet(&mut self, stylesheet: &mut Stylesheet) {
let mut names: AHashMap<Name, isize> = Default::default(); let mut names: AHashMap<Name, isize> = Default::default();
let mut prev_rule_idx = None; let mut prev_rule_idx = None;
let mut remove_rules_list = vec![]; let mut remove_rules_list = Vec::new();
let mut prev_index = 0; let mut prev_index = 0;
for index in 0..stylesheet.rules.len() { for index in 0..stylesheet.rules.len() {
@ -511,7 +511,7 @@ impl Compressor {
pub(super) fn compress_simple_block(&mut self, simple_block: &mut SimpleBlock) { pub(super) fn compress_simple_block(&mut self, simple_block: &mut SimpleBlock) {
let mut names: AHashMap<Name, isize> = Default::default(); let mut names: AHashMap<Name, isize> = Default::default();
let mut prev_rule_idx = None; let mut prev_rule_idx = None;
let mut remove_rules_list = vec![]; let mut remove_rules_list = Vec::new();
let mut prev_index = 0; let mut prev_index = 0;
for index in 0..simple_block.value.len() { for index in 0..simple_block.value.len() {

View File

@ -6,7 +6,7 @@ pub(crate) fn dedup<T>(v: &mut Vec<T>)
where where
T: EqIgnoreSpan, T: EqIgnoreSpan,
{ {
let mut remove_list = vec![]; let mut remove_list = Vec::new();
for (i, i1) in v.iter().enumerate() { for (i, i1) in v.iter().enumerate() {
for (j, j1) in v.iter().enumerate() { for (j, j1) in v.iter().enumerate() {

View File

@ -20,7 +20,7 @@ fn minify_fixtures(input: PathBuf) {
testing::run_test(false, |cm, handler| { testing::run_test(false, |cm, handler| {
let fm = cm.load_file(&input).unwrap(); let fm = cm.load_file(&input).unwrap();
let mut errors = vec![]; let mut errors = Vec::new();
let res: Result<Stylesheet, _> = parse_file(&fm, None, Default::default(), &mut errors); let res: Result<Stylesheet, _> = parse_file(&fm, None, Default::default(), &mut errors);
for err in errors { for err in errors {

View File

@ -61,7 +61,7 @@ pub fn compile<'a>(ss: &mut Stylesheet, config: impl 'a + TransformConfig) -> Tr
ss.visit_mut_with(&mut compiler); ss.visit_mut_with(&mut compiler);
fn add(result: &mut TransformResult, data: &Data, key: &JsWord, composes: &[CssClassName]) { fn add(result: &mut TransformResult, data: &Data, key: &JsWord, composes: &[CssClassName]) {
let mut extra_classes = vec![]; let mut extra_classes = Vec::new();
{ {
let class_names = result.renamed.entry(key.clone()).or_default(); let class_names = result.renamed.entry(key.clone()).or_default();

View File

@ -15,7 +15,7 @@ use testing::NormalizedOutput;
fn imports(input: PathBuf) { fn imports(input: PathBuf) {
testing::run_test(false, |cm, _| { testing::run_test(false, |cm, _| {
let fm = cm.load_file(&input).unwrap(); let fm = cm.load_file(&input).unwrap();
let mut errors = vec![]; let mut errors = Vec::new();
let ss = swc_css_parser::parse_file( let ss = swc_css_parser::parse_file(
&fm, &fm,
None, None,
@ -49,7 +49,7 @@ fn imports(input: PathBuf) {
fn compile(input: PathBuf) { fn compile(input: PathBuf) {
testing::run_test(false, |cm, _| { testing::run_test(false, |cm, _| {
let fm = cm.load_file(&input).unwrap(); let fm = cm.load_file(&input).unwrap();
let mut errors = vec![]; let mut errors = Vec::new();
let mut ss = swc_css_parser::parse_file( let mut ss = swc_css_parser::parse_file(
&fm, &fm,
None, None,

View File

@ -31,7 +31,7 @@ fn test_full(input: PathBuf, suffix: Option<&str>) {
testing::run_test2(false, |cm, handler| { testing::run_test2(false, |cm, handler| {
// //
let fm = cm.load_file(&input).unwrap(); let fm = cm.load_file(&input).unwrap();
let mut errors = vec![]; let mut errors = Vec::new();
let mut ss: Stylesheet = parse_file( let mut ss: Stylesheet = parse_file(
&fm, &fm,
None, None,

View File

@ -225,7 +225,7 @@ where
self.input.skip_ws(); self.input.skip_ws();
if is!(self, Ident) { if is!(self, Ident) {
let mut name_list: Vec<LayerName> = vec![]; let mut name_list: Vec<LayerName> = Vec::new();
name_list.push(self.parse()?); name_list.push(self.parse()?);
@ -976,7 +976,7 @@ where
fn parse(&mut self) -> PResult<SupportsCondition> { fn parse(&mut self) -> PResult<SupportsCondition> {
let start_pos = self.input.cur_span().lo; let start_pos = self.input.cur_span().lo;
let mut last_pos; let mut last_pos;
let mut conditions = vec![]; let mut conditions = Vec::new();
if is_case_insensitive_ident!(self, "not") { if is_case_insensitive_ident!(self, "not") {
let not = self.parse()?; let not = self.parse()?;
@ -1462,7 +1462,7 @@ where
fn parse(&mut self) -> PResult<MediaCondition> { fn parse(&mut self) -> PResult<MediaCondition> {
let start_pos = self.input.cur_span().lo; let start_pos = self.input.cur_span().lo;
let mut last_pos; let mut last_pos;
let mut conditions = vec![]; let mut conditions = Vec::new();
if is_case_insensitive_ident!(self, "not") { if is_case_insensitive_ident!(self, "not") {
let not = self.parse()?; let not = self.parse()?;
@ -1516,7 +1516,7 @@ where
fn parse(&mut self) -> PResult<MediaConditionWithoutOr> { fn parse(&mut self) -> PResult<MediaConditionWithoutOr> {
let start_pos = self.input.cur_span().lo; let start_pos = self.input.cur_span().lo;
let mut last_pos; let mut last_pos;
let mut conditions = vec![]; let mut conditions = Vec::new();
if is_case_insensitive_ident!(self, "not") { if is_case_insensitive_ident!(self, "not") {
let not = self.parse()?; let not = self.parse()?;
@ -1978,7 +1978,7 @@ where
}; };
let pseudos = if is!(self, ":") { let pseudos = if is!(self, ":") {
let mut pseudos = vec![]; let mut pseudos = Vec::new();
loop { loop {
if !is!(self, ":") { if !is!(self, ":") {
@ -2058,7 +2058,7 @@ where
{ {
fn parse(&mut self) -> PResult<LayerName> { fn parse(&mut self) -> PResult<LayerName> {
let start = self.input.cur_span().lo; let start = self.input.cur_span().lo;
let mut name = vec![]; let mut name = Vec::new();
while is!(self, Ident) { while is!(self, Ident) {
name.push(self.parse()?); name.push(self.parse()?);
@ -2128,7 +2128,7 @@ where
let start_pos = self.input.cur_span().lo; let start_pos = self.input.cur_span().lo;
let mut last_pos; let mut last_pos;
let mut queries = vec![]; let mut queries = Vec::new();
if is_case_insensitive_ident!(self, "not") { if is_case_insensitive_ident!(self, "not") {
let not = self.parse()?; let not = self.parse()?;

View File

@ -463,7 +463,7 @@ impl<'a> ParserInput for Input<'a> {
} }
fn take_errors(&mut self) -> Vec<Error> { fn take_errors(&mut self) -> Vec<Error> {
vec![] Vec::new()
} }
fn skip_ws(&mut self) -> Option<BytePos> { fn skip_ws(&mut self) -> Option<BytePos> {

View File

@ -68,7 +68,7 @@ where
parser.input.reset(&state); parser.input.reset(&state);
let span = parser.input.cur_span(); let span = parser.input.cur_span();
let mut children = vec![]; let mut children = Vec::new();
while !is_one_of!(parser, EOF, ",", ")") { while !is_one_of!(parser, EOF, ",", ")") {
if let Some(token_and_span) = parser.input.bump() { if let Some(token_and_span) = parser.input.bump() {
@ -223,7 +223,7 @@ where
parser.input.reset(&state); parser.input.reset(&state);
let span = parser.input.cur_span(); let span = parser.input.cur_span();
let mut children = vec![]; let mut children = Vec::new();
while !is_one_of!(parser, EOF, ",", ")") { while !is_one_of!(parser, EOF, ",", ")") {
if let Some(token_and_span) = parser.input.bump() { if let Some(token_and_span) = parser.input.bump() {
@ -420,7 +420,7 @@ where
} else { } else {
None None
}; };
let mut subclass_selectors = vec![]; let mut subclass_selectors = Vec::new();
loop { loop {
if !(is!(self, "#") if !(is!(self, "#")
@ -857,7 +857,7 @@ where
let state = self.input.state(); let state = self.input.state();
let mut parse_pseudo_class_children = let mut parse_pseudo_class_children =
|| -> PResult<Vec<PseudoClassSelectorChildren>> { || -> PResult<Vec<PseudoClassSelectorChildren>> {
let mut children = vec![]; let mut children = Vec::new();
match &*names.0 { match &*names.0 {
"local" | "global" if self.config.css_modules => { "local" | "global" if self.config.css_modules => {
@ -1090,7 +1090,7 @@ where
let state = self.input.state(); let state = self.input.state();
let mut parse_pseudo_element_children = let mut parse_pseudo_element_children =
|| -> PResult<Vec<PseudoElementSelectorChildren>> { || -> PResult<Vec<PseudoElementSelectorChildren>> {
let mut children = vec![]; let mut children = Vec::new();
match &*names.0 { match &*names.0 {
"cue" | "cue-region" => { "cue" | "cue-region" => {

View File

@ -43,7 +43,7 @@ where
// To consume a list of rules, given a top-level flag: // To consume a list of rules, given a top-level flag:
// Create an initially empty list of rules. // Create an initially empty list of rules.
let mut rules = vec![]; let mut rules = Vec::new();
// Repeatedly consume the next input token: // Repeatedly consume the next input token:
@ -107,7 +107,7 @@ where
let span = self.input.cur_span(); let span = self.input.cur_span();
let mut list_of_component_values = ListOfComponentValues { let mut list_of_component_values = ListOfComponentValues {
span: Default::default(), span: Default::default(),
children: vec![], children: Vec::new(),
}; };
while !is_one_of!(self, EOF) { while !is_one_of!(self, EOF) {
@ -161,7 +161,7 @@ where
raw: Some(at_keyword_name.1), raw: Some(at_keyword_name.1),
}) })
}; };
let mut prelude = vec![]; let mut prelude = Vec::new();
let mut at_rule = AtRule { let mut at_rule = AtRule {
span: Default::default(), span: Default::default(),
name, name,
@ -256,7 +256,7 @@ where
// Create a new qualified rule with its prelude initially set to an empty list, // Create a new qualified rule with its prelude initially set to an empty list,
// and its value initially set to nothing. // and its value initially set to nothing.
let span = self.input.cur_span(); let span = self.input.cur_span();
let mut prelude = vec![]; let mut prelude = Vec::new();
// Repeatedly consume the next input token: // Repeatedly consume the next input token:
loop { loop {
@ -323,8 +323,8 @@ where
I: ParserInput, I: ParserInput,
{ {
fn parse(&mut self) -> PResult<Vec<StyleBlock>> { fn parse(&mut self) -> PResult<Vec<StyleBlock>> {
let mut declarations = vec![]; let mut declarations = Vec::new();
let mut rules = vec![]; let mut rules = Vec::new();
loop { loop {
// <EOF-token> // <EOF-token>
@ -393,7 +393,7 @@ where
let span = self.input.cur_span(); let span = self.input.cur_span();
let mut temporary_list = ListOfComponentValues { let mut temporary_list = ListOfComponentValues {
span: Default::default(), span: Default::default(),
children: vec![], children: Vec::new(),
}; };
while !is_one_of!(self, ";", EOF) { while !is_one_of!(self, ";", EOF) {
@ -443,7 +443,7 @@ where
// For recovery mode // For recovery mode
let mut list_of_component_values = ListOfComponentValues { let mut list_of_component_values = ListOfComponentValues {
span: Default::default(), span: Default::default(),
children: vec![], children: Vec::new(),
}; };
while !is_one_of!(self, ";", EOF) { while !is_one_of!(self, ";", EOF) {
@ -471,7 +471,7 @@ where
{ {
fn parse(&mut self) -> PResult<Vec<DeclarationOrAtRule>> { fn parse(&mut self) -> PResult<Vec<DeclarationOrAtRule>> {
// Create an initially empty list of declarations. // Create an initially empty list of declarations.
let mut declarations = vec![]; let mut declarations = Vec::new();
// Repeatedly consume the next input token: // Repeatedly consume the next input token:
loop { loop {
@ -527,7 +527,7 @@ where
let span = self.input.cur_span(); let span = self.input.cur_span();
let mut temporary_list = ListOfComponentValues { let mut temporary_list = ListOfComponentValues {
span: Default::default(), span: Default::default(),
children: vec![], children: Vec::new(),
}; };
while !is_one_of!(self, ";", EOF) { while !is_one_of!(self, ";", EOF) {
@ -568,7 +568,7 @@ where
// For recovery mode // For recovery mode
let mut list_of_component_values = ListOfComponentValues { let mut list_of_component_values = ListOfComponentValues {
span: Default::default(), span: Default::default(),
children: vec![], children: Vec::new(),
}; };
while !is_one_of!(self, ";", EOF) { while !is_one_of!(self, ";", EOF) {
@ -630,7 +630,7 @@ where
let mut declaration = Declaration { let mut declaration = Declaration {
span: Default::default(), span: Default::default(),
name, name,
value: vec![], value: Vec::new(),
important: None, important: None,
}; };
@ -852,7 +852,7 @@ where
let mut simple_block = SimpleBlock { let mut simple_block = SimpleBlock {
span: Default::default(), span: Default::default(),
name, name,
value: vec![], value: Vec::new(),
}; };
// Repeatedly consume the next input token and process it as follows: // Repeatedly consume the next input token and process it as follows:
@ -948,7 +948,7 @@ where
let mut function = Function { let mut function = Function {
span: Default::default(), span: Default::default(),
name, name,
value: vec![], value: Vec::new(),
}; };
// Repeatedly consume the next input token and process it as follows: // Repeatedly consume the next input token and process it as follows:
@ -1000,7 +1000,7 @@ where
{ {
fn parse(&mut self) -> PResult<ListOfComponentValues> { fn parse(&mut self) -> PResult<ListOfComponentValues> {
let span = self.input.cur_span(); let span = self.input.cur_span();
let mut children = vec![]; let mut children = Vec::new();
// Repeatedly consume a component value from input until an <EOF-token> is // Repeatedly consume a component value from input until an <EOF-token> is
// returned, appending the returned values (except the final <EOF-token>) into a // returned, appending the returned values (except the final <EOF-token>) into a

View File

@ -287,7 +287,7 @@ where
let locv = self.create_locv(declaration.value); let locv = self.create_locv(declaration.value);
let value = self.parse_according_to_grammar(&locv, |parser| { let value = self.parse_according_to_grammar(&locv, |parser| {
let mut values = vec![]; let mut values = Vec::new();
loop { loop {
if is!(parser, EOF) { if is!(parser, EOF) {
@ -336,7 +336,7 @@ where
pub(super) fn try_to_parse_declaration_in_parens(&mut self) -> Option<Declaration> { pub(super) fn try_to_parse_declaration_in_parens(&mut self) -> Option<Declaration> {
let mut temporary_list = ListOfComponentValues { let mut temporary_list = ListOfComponentValues {
span: Default::default(), span: Default::default(),
children: vec![], children: Vec::new(),
}; };
while !is_one_of!(self, ")", EOF) { while !is_one_of!(self, ")", EOF) {

View File

@ -13,7 +13,7 @@ where
I: ParserInput, I: ParserInput,
{ {
pub(super) fn parse_generic_values(&mut self) -> PResult<Vec<ComponentValue>> { pub(super) fn parse_generic_values(&mut self) -> PResult<Vec<ComponentValue>> {
let mut values = vec![]; let mut values = Vec::new();
loop { loop {
self.input.skip_ws(); self.input.skip_ws();
@ -119,8 +119,8 @@ where
/// Parse value as <any-value>. /// Parse value as <any-value>.
pub(super) fn parse_any_value(&mut self) -> PResult<Vec<TokenAndSpan>> { pub(super) fn parse_any_value(&mut self) -> PResult<Vec<TokenAndSpan>> {
let mut tokens = vec![]; let mut tokens = Vec::new();
let mut balance_stack: Vec<Option<char>> = vec![]; let mut balance_stack: Vec<Option<char>> = Vec::new();
// The <any-value> production matches any sequence of one or more tokens, // The <any-value> production matches any sequence of one or more tokens,
// so long as the sequence ... // so long as the sequence ...
@ -192,7 +192,7 @@ where
} }
}; };
let mut values = vec![]; let mut values = Vec::new();
let lower_fname = function_name.to_ascii_lowercase(); let lower_fname = function_name.to_ascii_lowercase();
@ -2628,7 +2628,7 @@ where
self.input.skip_ws(); self.input.skip_ws();
let mut modifiers = vec![]; let mut modifiers = Vec::new();
loop { loop {
if is!(self, ")") { if is!(self, ")") {
@ -3042,7 +3042,7 @@ where
{ {
fn parse(&mut self) -> PResult<CalcSum> { fn parse(&mut self) -> PResult<CalcSum> {
let start = self.input.cur_span().lo; let start = self.input.cur_span().lo;
let mut expressions = vec![]; let mut expressions = Vec::new();
let calc_product = CalcProductOrOperator::Product(self.parse()?); let calc_product = CalcProductOrOperator::Product(self.parse()?);
let mut end = match calc_product { let mut end = match calc_product {
CalcProductOrOperator::Product(ref calc_product) => calc_product.span.hi, CalcProductOrOperator::Product(ref calc_product) => calc_product.span.hi,
@ -3098,7 +3098,7 @@ where
{ {
fn parse(&mut self) -> PResult<CalcProduct> { fn parse(&mut self) -> PResult<CalcProduct> {
let start = self.input.cur_span().lo; let start = self.input.cur_span().lo;
let mut expressions = vec![]; let mut expressions = Vec::new();
let calc_value = CalcValueOrOperator::Value(self.parse()?); let calc_value = CalcValueOrOperator::Value(self.parse()?);
let mut end = match calc_value { let mut end = match calc_value {
CalcValueOrOperator::Value(ref calc_value) => match calc_value { CalcValueOrOperator::Value(ref calc_value) => match calc_value {

View File

@ -82,10 +82,10 @@ fn stylesheet_test_tokens(input: PathBuf, config: ParserConfig) {
testing::run_test2(false, |cm, handler| { testing::run_test2(false, |cm, handler| {
let fm = cm.load_file(&input).unwrap(); let fm = cm.load_file(&input).unwrap();
let mut errors = vec![]; let mut errors = Vec::new();
let tokens = { let tokens = {
let mut lexer = Lexer::new(SourceFileInput::from(&*fm), None, Default::default()); let mut lexer = Lexer::new(SourceFileInput::from(&*fm), None, Default::default());
let mut tokens = vec![]; let mut tokens = Vec::new();
for token_and_span in lexer.by_ref() { for token_and_span in lexer.by_ref() {
tokens.push(token_and_span); tokens.push(token_and_span);
@ -208,10 +208,10 @@ fn stylesheet_recovery_test_tokens(input: PathBuf, config: ParserConfig) {
} }
let fm = cm.load_file(&input).unwrap(); let fm = cm.load_file(&input).unwrap();
let mut lexer_errors = vec![]; let mut lexer_errors = Vec::new();
let tokens = { let tokens = {
let mut lexer = Lexer::new(SourceFileInput::from(&*fm), None, Default::default()); let mut lexer = Lexer::new(SourceFileInput::from(&*fm), None, Default::default());
let mut tokens = vec![]; let mut tokens = Vec::new();
for token_and_span in lexer.by_ref() { for token_and_span in lexer.by_ref() {
tokens.push(token_and_span); tokens.push(token_and_span);
@ -225,7 +225,7 @@ fn stylesheet_recovery_test_tokens(input: PathBuf, config: ParserConfig) {
} }
}; };
let mut parser_errors = vec![]; let mut parser_errors = Vec::new();
let stylesheet: PResult<Stylesheet> = let stylesheet: PResult<Stylesheet> =
parse_input(InputType::Tokens(&tokens), config, &mut parser_errors); parse_input(InputType::Tokens(&tokens), config, &mut parser_errors);

View File

@ -125,7 +125,7 @@ impl VisitMut for CrossFadeFunctionReplacerOnLegacyVariant<'_> {
n.visit_mut_children_with(self); n.visit_mut_children_with(self);
if n.name == *self.from { if n.name == *self.from {
let mut transparency_values = vec![]; let mut transparency_values = Vec::new();
for group in n.value.split_mut(|n| { for group in n.value.split_mut(|n| {
matches!( matches!(
@ -262,7 +262,7 @@ impl VisitMut for ImageSetFunctionReplacerOnLegacyVariant<'_> {
value: node.value.as_ref().into(), value: node.value.as_ref().into(),
raw: None, raw: None,
}))), }))),
modifiers: Some(vec![]), modifiers: Some(Vec::new()),
})) }))
} }
} }
@ -467,7 +467,7 @@ impl VisitMut for LinearGradientFunctionReplacerOnLegacyVariant<'_> {
}); });
if let (Some(at_index), Some(first_comma_index)) = (at_index, first_comma_index) { if let (Some(at_index), Some(first_comma_index)) = (at_index, first_comma_index) {
let mut new_value = vec![]; let mut new_value = Vec::new();
new_value.append(&mut n.value[at_index + 1..first_comma_index].to_vec()); new_value.append(&mut n.value[at_index + 1..first_comma_index].to_vec());
new_value.append(&mut vec![ComponentValue::Delimiter(Box::new(Delimiter { new_value.append(&mut vec![ComponentValue::Delimiter(Box::new(Delimiter {
@ -1104,7 +1104,7 @@ impl VisitMut for Prefixer {
fn visit_mut_media_query_list(&mut self, media_query_list: &mut MediaQueryList) { fn visit_mut_media_query_list(&mut self, media_query_list: &mut MediaQueryList) {
media_query_list.visit_mut_children_with(self); media_query_list.visit_mut_children_with(self);
let mut new_queries = vec![]; let mut new_queries = Vec::new();
for n in &media_query_list.queries { for n in &media_query_list.queries {
if should_prefix("-webkit-min-device-pixel-ratio", self.env, false) { if should_prefix("-webkit-min-device-pixel-ratio", self.env, false) {

View File

@ -28,7 +28,7 @@ fn prefix(input: PathBuf, options: Options, suffix: Option<&str>) {
testing::run_test2(false, |cm, handler| { testing::run_test2(false, |cm, handler| {
// //
let fm = cm.load_file(&input).unwrap(); let fm = cm.load_file(&input).unwrap();
let mut errors = vec![]; let mut errors = Vec::new();
let mut ss: Stylesheet = parse_file( let mut ss: Stylesheet = parse_file(
&fm, &fm,
None, None,

View File

@ -528,7 +528,7 @@ impl ObjectLit {
/// ///
/// Returns [None] if this is not a valid for `with` of [crate::ImportDecl]. /// Returns [None] if this is not a valid for `with` of [crate::ImportDecl].
pub fn as_import_with(&self) -> Option<ImportWith> { pub fn as_import_with(&self) -> Option<ImportWith> {
let mut values = vec![]; let mut values = Vec::new();
for prop in &self.props { for prop in &self.props {
match prop { match prop {
PropOrSpread::Spread(..) => return None, PropOrSpread::Spread(..) => return None,

View File

@ -25,7 +25,7 @@ impl Take for BlockStmt {
fn dummy() -> Self { fn dummy() -> Self {
BlockStmt { BlockStmt {
span: DUMMY_SP, span: DUMMY_SP,
stmts: vec![], stmts: Vec::new(),
ctxt: Default::default(), ctxt: Default::default(),
} }
} }

View File

@ -25,6 +25,7 @@ serde = { workspace = true }
sourcemap = { workspace = true } sourcemap = { workspace = true }
tracing = { workspace = true } tracing = { workspace = true }
swc_allocator = { version = "0.1.7", path = "../swc_allocator", default-features = false }
swc_atoms = { version = "0.6.5", path = "../swc_atoms" } swc_atoms = { version = "0.6.5", path = "../swc_atoms" }
swc_common = { version = "0.36.0", path = "../swc_common" } swc_common = { version = "0.36.0", path = "../swc_common" }
swc_ecma_ast = { version = "0.117.0", path = "../swc_ecma_ast" } swc_ecma_ast = { version = "0.117.0", path = "../swc_ecma_ast" }

View File

@ -84,7 +84,6 @@ fn bench_emitter(b: &mut Bencher, s: &str) {
let fm = cm.new_source_file(FileName::Anon.into(), s.into()); let fm = cm.new_source_file(FileName::Anon.into(), s.into());
let mut parser = Parser::new(Syntax::default(), StringInput::from(&*fm), None); let mut parser = Parser::new(Syntax::default(), StringInput::from(&*fm), None);
let mut src_map_buf = vec![];
let module = parser let module = parser
.parse_module() .parse_module()
.map_err(|e| e.into_diagnostic(handler).emit()) .map_err(|e| e.into_diagnostic(handler).emit())
@ -95,7 +94,8 @@ fn bench_emitter(b: &mut Bencher, s: &str) {
} }
b.iter(|| { b.iter(|| {
let mut buf = vec![]; let mut src_map_buf = Vec::new();
let mut buf = Vec::new();
{ {
let mut emitter = Emitter { let mut emitter = Emitter {
cfg: Default::default(), cfg: Default::default(),

View File

@ -84,7 +84,6 @@ fn bench_emitter(b: &mut Bencher, s: &str) {
b.iter(|| { b.iter(|| {
let fm = cm.new_source_file(FileName::Anon.into(), s.into()); let fm = cm.new_source_file(FileName::Anon.into(), s.into());
let mut parser = Parser::new(Syntax::default(), StringInput::from(&*fm), None); let mut parser = Parser::new(Syntax::default(), StringInput::from(&*fm), None);
let mut src_map_buf = vec![];
let module = parser let module = parser
.parse_module() .parse_module()
.map_err(|e| e.into_diagnostic(handler).emit()) .map_err(|e| e.into_diagnostic(handler).emit())
@ -94,7 +93,8 @@ fn bench_emitter(b: &mut Bencher, s: &str) {
err.into_diagnostic(handler).emit(); err.into_diagnostic(handler).emit();
} }
let mut buf = vec![]; let mut src_map_buf = Vec::new();
let mut buf = Vec::new();
{ {
let mut emitter = Emitter { let mut emitter = Emitter {
cfg: Default::default(), cfg: Default::default(),

View File

@ -24,7 +24,7 @@ fn parse_and_gen(entry: &Path) {
.expect("failed to parse input as a module"); .expect("failed to parse input as a module");
let code = { let code = {
let mut buf = vec![]; let mut buf = Vec::new();
{ {
let mut emitter = Emitter { let mut emitter = Emitter {

View File

@ -29,8 +29,8 @@ fn parse_and_gen(entry: &Path) {
.parse_module() .parse_module()
.expect("failed to parse input as a module"); .expect("failed to parse input as a module");
let mut code = vec![]; let mut code = Vec::new();
let mut srcmap = vec![]; let mut srcmap = Vec::new();
{ {
let mut emitter = Emitter { let mut emitter = Emitter {

View File

@ -44,7 +44,7 @@ pub fn to_code_default(
comments: Option<&dyn Comments>, comments: Option<&dyn Comments>,
node: &impl Node, node: &impl Node,
) -> String { ) -> String {
let mut buf = vec![]; let mut buf = Vec::new();
{ {
let mut emitter = Emitter { let mut emitter = Emitter {
cfg: Default::default(), cfg: Default::default(),
@ -332,7 +332,7 @@ where
formatting_space!(); formatting_space!();
} }
let mut specifiers = vec![]; let mut specifiers = Vec::new();
let mut emitted_default = false; let mut emitted_default = false;
let mut emitted_ns = false; let mut emitted_ns = false;
for specifier in &n.specifiers { for specifier in &n.specifiers {
@ -497,7 +497,7 @@ where
has_namespace_spec: false, has_namespace_spec: false,
namespace_spec: None, namespace_spec: None,
has_named_specs: false, has_named_specs: false,
named_specs: vec![], named_specs: Vec::new(),
}, },
|mut result, s| match s { |mut result, s| match s {
ExportSpecifier::Namespace(spec) => { ExportSpecifier::Namespace(spec) => {
@ -1290,7 +1290,7 @@ where
{ {
let mut left = Some(node); let mut left = Some(node);
let mut lefts = vec![]; let mut lefts = Vec::new();
while let Some(l) = left { while let Some(l) = left {
lefts.push(l); lefts.push(l);

View File

@ -44,7 +44,7 @@ impl Builder {
where where
F: for<'aa> FnOnce(&mut Emitter<'aa, Box<(dyn WriteJs + 'aa)>, SourceMap>), F: for<'aa> FnOnce(&mut Emitter<'aa, Box<(dyn WriteJs + 'aa)>, SourceMap>),
{ {
let mut buf = vec![]; let mut buf = Vec::new();
self.with(src, &mut buf, op); self.with(src, &mut buf, op);
@ -974,7 +974,7 @@ fn run_node(code: &str) -> String {
JsExecOptions { JsExecOptions {
cache: true, cache: true,
module: false, module: false,
args: vec![], args: Vec::new(),
}, },
) )
.expect("failed to execute node.js") .expect("failed to execute node.js")

View File

@ -34,11 +34,11 @@ fn run(input: &Path, minify: bool) {
}), }),
EsVersion::latest(), EsVersion::latest(),
None, None,
&mut vec![], &mut Vec::new(),
) )
.expect("failed to parse input as a module"); .expect("failed to parse input as a module");
let mut buf = vec![]; let mut buf = Vec::new();
{ {
let mut wr = let mut wr =

View File

@ -288,7 +288,7 @@ fn identity(entry: PathBuf) {
"\n\n========== Running codegen test {}\nSource:\n{}\n", "\n\n========== Running codegen test {}\nSource:\n{}\n",
file_name, input file_name, input
); );
let mut wr = vec![]; let mut wr = std::vec::Vec::new();
::testing::run_test(false, |cm, handler| { ::testing::run_test(false, |cm, handler| {
let fm = cm.load_file(&entry).expect("failed to load file"); let fm = cm.load_file(&entry).expect("failed to load file");
@ -315,7 +315,7 @@ fn identity(entry: PathBuf) {
Some(&comments), Some(&comments),
); );
let mut parser: Parser<Lexer> = Parser::new_from(lexer); let mut parser: Parser<Lexer> = Parser::new_from(lexer);
let mut src_map = vec![]; let mut src_map = Vec::new();
{ {
let mut wr = Box::new(swc_ecma_codegen::text_writer::JsWriter::new( let mut wr = Box::new(swc_ecma_codegen::text_writer::JsWriter::new(
@ -488,7 +488,7 @@ fn assert_eq_same_map(expected: &SourceMap, actual: &SourceMap) {
/// Creates a url for https://evanw.github.io/source-map-visualization/ /// Creates a url for https://evanw.github.io/source-map-visualization/
fn visualizer_url(code: &str, map: &SourceMap) -> String { fn visualizer_url(code: &str, map: &SourceMap) -> String {
let map = { let map = {
let mut buf = vec![]; let mut buf = std::vec::Vec::new();
map.to_writer(&mut buf).unwrap(); map.to_writer(&mut buf).unwrap();
String::from_utf8(buf).unwrap() String::from_utf8(buf).unwrap()
}; };

View File

@ -102,7 +102,7 @@ fn do_test(entry: &Path, minify: bool) {
"\n\n========== Running codegen test {}\nSource:\n{}\n", "\n\n========== Running codegen test {}\nSource:\n{}\n",
file_name, input file_name, input
); );
let mut wr = vec![]; let mut wr = Vec::new();
::testing::run_test(false, |cm, handler| { ::testing::run_test(false, |cm, handler| {
let src = cm.load_file(entry).expect("failed to load file"); let src = cm.load_file(entry).expect("failed to load file");

View File

@ -77,7 +77,7 @@ macro_rules! impl_visit_mut_fn {
let (mut params, body) = self.visit_mut_fn_like( let (mut params, body) = self.visit_mut_fn_like(
&mut vec![Param { &mut vec![Param {
span: DUMMY_SP, span: DUMMY_SP,
decorators: vec![], decorators: Vec::new(),
pat: *f.param.take(), pat: *f.param.take(),
}], }],
&mut f.body.take().unwrap(), &mut f.body.take().unwrap(),
@ -95,8 +95,9 @@ macro_rules! impl_visit_mut_fn {
f.visit_mut_children_with(self); f.visit_mut_children_with(self);
let (params, body) = self.visit_mut_fn_like(&mut vec![], &mut f.body.take().unwrap()); let (params, body) =
debug_assert_eq!(params, vec![]); self.visit_mut_fn_like(&mut Vec::new(), &mut f.body.take().unwrap());
debug_assert_eq!(params, Vec::new());
f.body = Some(body); f.body = Some(body);
} }
@ -108,12 +109,12 @@ macro_rules! impl_visit_mut_fn {
Some(pat) => self.visit_mut_fn_like( Some(pat) => self.visit_mut_fn_like(
&mut vec![Param { &mut vec![Param {
span: DUMMY_SP, span: DUMMY_SP,
decorators: vec![], decorators: Vec::new(),
pat: pat.take(), pat: pat.take(),
}], }],
&mut f.body.take(), &mut f.body.take(),
), ),
None => self.visit_mut_fn_like(&mut vec![], &mut f.body.take()), None => self.visit_mut_fn_like(&mut Vec::new(), &mut f.body.take()),
}; };
assert!( assert!(
params.len() == 0 || params.len() == 1, params.len() == 0 || params.len() == 1,

View File

@ -138,7 +138,7 @@ impl VisitMut for Arrow {
body.visit_mut_with(&mut self.hoister); body.visit_mut_with(&mut self.hoister);
let fn_expr = Function { let fn_expr = Function {
decorators: vec![], decorators: Vec::new(),
span: *span, span: *span,
params, params,
is_async: *is_async, is_async: *is_async,

View File

@ -41,7 +41,7 @@ pub fn block_scoping(unresolved_mark: Mark) -> impl VisitMut + Fold {
BlockScoping { BlockScoping {
unresolved_mark, unresolved_mark,
scope: Default::default(), scope: Default::default(),
vars: vec![], vars: Vec::new(),
var_decl_kind: VarDeclKind::Var, var_decl_kind: VarDeclKind::Var,
} }
)) ))
@ -143,7 +143,7 @@ impl BlockScoping {
let mut env_hoister = let mut env_hoister =
FnEnvHoister::new(SyntaxContext::empty().apply_mark(self.unresolved_mark)); FnEnvHoister::new(SyntaxContext::empty().apply_mark(self.unresolved_mark));
body_stmt.visit_mut_with(&mut env_hoister); body_stmt.visit_mut_with(&mut env_hoister);
let mut inits: Vec<Box<Expr>> = vec![]; let mut inits: Vec<Box<Expr>> = Vec::new();
for mut var in env_hoister.to_decl() { for mut var in env_hoister.to_decl() {
if let Some(init) = var.init.take() { if let Some(init) = var.init.take() {
@ -445,7 +445,7 @@ impl VisitMut for BlockScoping {
fn visit_mut_block_stmt(&mut self, n: &mut BlockStmt) { fn visit_mut_block_stmt(&mut self, n: &mut BlockStmt) {
let vars = take(&mut self.vars); let vars = take(&mut self.vars);
n.visit_mut_children_with(self); n.visit_mut_children_with(self);
debug_assert_eq!(self.vars, vec![]); debug_assert_eq!(self.vars, Vec::new());
self.vars = vars; self.vars = vars;
} }
@ -478,7 +478,7 @@ impl VisitMut for BlockScoping {
let kind = ScopeKind::Loop { let kind = ScopeKind::Loop {
lexical_var, lexical_var,
args, args,
used: vec![], used: Vec::new(),
mutated: Default::default(), mutated: Default::default(),
}; };
@ -504,7 +504,7 @@ impl VisitMut for BlockScoping {
let kind = ScopeKind::Loop { let kind = ScopeKind::Loop {
lexical_var: vars, lexical_var: vars,
args, args,
used: vec![], used: Vec::new(),
mutated: Default::default(), mutated: Default::default(),
}; };
@ -530,7 +530,7 @@ impl VisitMut for BlockScoping {
let kind = ScopeKind::Loop { let kind = ScopeKind::Loop {
lexical_var, lexical_var,
args, args,
used: vec![], used: Vec::new(),
mutated: Default::default(), mutated: Default::default(),
}; };
self.visit_mut_with_scope(kind, &mut node.body); self.visit_mut_with_scope(kind, &mut node.body);

View File

@ -446,7 +446,7 @@ where
(params, vec![super_class.as_arg()], Some(super_param)) (params, vec![super_class.as_arg()], Some(super_param))
} }
} else { } else {
(vec![], vec![], None) (Vec::new(), Vec::new(), None)
}; };
let mut stmts = self.class_to_stmts(class_name, super_ident, class); let mut stmts = self.class_to_stmts(class_name, super_ident, class);
@ -532,9 +532,9 @@ where
class: Box<Class>, class: Box<Class>,
) -> Vec<Stmt> { ) -> Vec<Stmt> {
let class_name = class_name.unwrap_or_else(|| quote_ident!("_class").into()); let class_name = class_name.unwrap_or_else(|| quote_ident!("_class").into());
let mut stmts = vec![]; let mut stmts = Vec::new();
let mut methods = vec![]; let mut methods = Vec::new();
let mut constructor = None; let mut constructor = None;
for member in class.body { for member in class.body {
match member { match member {
@ -632,7 +632,7 @@ where
let is_constructor_default = constructor.span.is_dummy(); let is_constructor_default = constructor.span.is_dummy();
if is_constructor_default { if is_constructor_default {
debug!("Dropping constructor parameters because the constructor is injected"); debug!("Dropping constructor parameters because the constructor is injected");
constructor.params = vec![]; constructor.params = Vec::new();
} }
let mut insert_this = false; let mut insert_this = false;
@ -643,7 +643,7 @@ where
insert_this |= inserted_this; insert_this |= inserted_this;
} }
let mut vars = vec![]; let mut vars = Vec::new();
let mut body = constructor.body.unwrap().stmts; let mut body = constructor.body.unwrap().stmts;
// should we insert `var _this`? // should we insert `var _this`?
@ -835,7 +835,7 @@ where
mut body: Vec<Stmt>, mut body: Vec<Stmt>,
this_mark: Option<Mark>, this_mark: Option<Mark>,
) -> Vec<Stmt> { ) -> Vec<Stmt> {
let mut vars = vec![]; let mut vars = Vec::new();
let mut folder = SuperFieldAccessFolder { let mut folder = SuperFieldAccessFolder {
class_name, class_name,
vars: &mut vars, vars: &mut vars,
@ -896,7 +896,7 @@ where
methods: Vec<ClassMethod>, methods: Vec<ClassMethod>,
) -> Vec<Stmt> { ) -> Vec<Stmt> {
if methods.is_empty() { if methods.is_empty() {
return vec![]; return Vec::new();
} }
/// { key: "prop" } /// { key: "prop" }
@ -1038,7 +1038,7 @@ where
&mut props &mut props
}; };
let mut vars = vec![]; let mut vars = Vec::new();
let mut folder = SuperFieldAccessFolder { let mut folder = SuperFieldAccessFolder {
class_name, class_name,
vars: &mut vars, vars: &mut vars,

View File

@ -168,7 +168,7 @@ impl VisitMut for ComputedProps {
body, body,
is_async: false, is_async: false,
is_generator: false, is_generator: false,
params: vec![], params: Vec::new(),
..Default::default() ..Default::default()
}), }),
), ),
@ -210,7 +210,7 @@ impl VisitMut for ComputedProps {
op: op!("||"), op: op!("||"),
right: Box::new(Expr::Object(ObjectLit { right: Box::new(Expr::Object(ObjectLit {
span, span,
props: vec![], props: Vec::new(),
})), })),
} }
.into(), .into(),
@ -307,7 +307,7 @@ impl VisitMut for ComputedProps {
init: Some( init: Some(
ObjectLit { ObjectLit {
span: DUMMY_SP, span: DUMMY_SP,
props: vec![], props: Vec::new(),
} }
.into(), .into(),
), ),

View File

@ -494,8 +494,8 @@ impl Destructuring {
ps: &mut Vec<Param>, ps: &mut Vec<Param>,
body: &mut BlockStmt, body: &mut BlockStmt,
) -> (Vec<Param>, BlockStmt) { ) -> (Vec<Param>, BlockStmt) {
let mut params = vec![]; let mut params = Vec::new();
let mut decls = vec![]; let mut decls = Vec::new();
for param in ps.drain(..) { for param in ps.drain(..) {
let span = param.span(); let span = param.span();
@ -1077,7 +1077,7 @@ impl Destructuring {
let mut folder = AssignFolder { let mut folder = AssignFolder {
c: self.c, c: self.c,
exporting: false, exporting: false,
vars: vec![], vars: Vec::new(),
ignore_return_value: None, ignore_return_value: None,
}; };

View File

@ -298,7 +298,7 @@ impl ForOf {
right: CallExpr { right: CallExpr {
span: DUMMY_SP, span: DUMMY_SP,
callee: iterator.as_callee(), callee: iterator.as_callee(),
args: vec![], args: Vec::new(),
..Default::default() ..Default::default()
} }
.into(), .into(),
@ -426,7 +426,7 @@ impl ForOf {
Symbol.iterator Symbol.iterator
)) ))
.as_callee(), .as_callee(),
args: vec![], args: Vec::new(),
..Default::default() ..Default::default()
}))), }))),
definite: false, definite: false,
@ -457,7 +457,7 @@ impl ForOf {
span: DUMMY_SP, span: DUMMY_SP,
// `_iterator.next` // `_iterator.next`
callee: iterator.make_member(quote_ident!("next")).as_callee(), callee: iterator.make_member(quote_ident!("next")).as_callee(),
args: vec![], args: Vec::new(),
..Default::default() ..Default::default()
})), })),
} }
@ -598,7 +598,7 @@ fn make_finally_block(
stmts: vec![CallExpr { stmts: vec![CallExpr {
span: DUMMY_SP, span: DUMMY_SP,
callee: iterator_return.as_callee(), callee: iterator_return.as_callee(),
args: vec![], args: Vec::new(),
..Default::default() ..Default::default()
} }
.into_stmt()], .into_stmt()],

View File

@ -98,7 +98,7 @@ impl VisitMut for Wrapper {
..Default::default() ..Default::default()
} }
.into(); .into();
let mut stmts = vec![]; let mut stmts = Vec::new();
if !v.hoisted_vars.is_empty() { if !v.hoisted_vars.is_empty() {
stmts.push( stmts.push(
VarDecl { VarDecl {
@ -516,7 +516,7 @@ impl VisitMut for Generator {
Expr::Seq(node) => { Expr::Seq(node) => {
// // flattened version of `visitCommaExpression` // // flattened version of `visitCommaExpression`
let mut pending_expressions = vec![]; let mut pending_expressions = Vec::new();
for mut elem in node.exprs.take() { for mut elem in node.exprs.take() {
if let Expr::Seq(mut elem) = *elem { if let Expr::Seq(mut elem) = *elem {
@ -741,7 +741,7 @@ impl VisitMut for Generator {
props props
}) })
.into_iter() .into_iter()
.fold(vec![], |exprs, property| { .fold(Vec::new(), |exprs, property| {
self.reduce_property(exprs, property, &mut temp) self.reduce_property(exprs, property, &mut temp)
}); });
@ -1117,7 +1117,7 @@ impl Generator {
.iter_mut() .iter_mut()
.skip(num_initial_elements) .skip(num_initial_elements)
.map(|v| v.take()) .map(|v| v.take())
.fold(vec![], |exprs, element| { .fold(Vec::new(), |exprs, element| {
self.reduce_element(exprs, element, &mut leading_element, &mut temp) self.reduce_element(exprs, element, &mut leading_element, &mut temp)
}); });
@ -1285,7 +1285,7 @@ impl Generator {
.map(|g| KeyValueProp { .map(|g| KeyValueProp {
key: quote_ident!("get").into(), key: quote_ident!("get").into(),
value: Function { value: Function {
params: vec![], params: Vec::new(),
span: g.span, span: g.span,
body: g.body, body: g.body,
is_generator: false, is_generator: false,
@ -1504,7 +1504,7 @@ impl Generator {
let mut variables = self.get_initialized_variables(&mut node); let mut variables = self.get_initialized_variables(&mut node);
let var_len = variables.len(); let var_len = variables.len();
let mut variables_written = 0; let mut variables_written = 0;
let mut pending_expressions = vec![]; let mut pending_expressions = Vec::new();
let mut cnt = 0; let mut cnt = 0;
while variables_written < var_len { while variables_written < var_len {
@ -1976,7 +1976,7 @@ impl Generator {
// `yield` in its expression, up to the next case clause // `yield` in its expression, up to the next case clause
// with a `yield` in its expression. // with a `yield` in its expression.
let mut clauses_written = 0; let mut clauses_written = 0;
let mut pending_clauses = vec![]; let mut pending_clauses = Vec::new();
while clauses_written < node.cases.len() { while clauses_written < node.cases.len() {
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
@ -2354,7 +2354,7 @@ impl Generator {
.clone() .clone()
.make_member(quote_ident!("sent")) .make_member(quote_ident!("sent"))
.as_callee(), .as_callee(),
args: vec![], args: Vec::new(),
..Default::default() ..Default::default()
} }
.into(), .into(),
@ -2630,7 +2630,7 @@ impl Generator {
}; };
if label_expressions.get(label.0 as usize).is_none() { if label_expressions.get(label.0 as usize).is_none() {
if label.0 as usize >= label_expressions.len() { if label.0 as usize >= label_expressions.len() {
label_expressions.resize(label.0 as usize + 1, vec![]); label_expressions.resize(label.0 as usize + 1, Vec::new());
} }
label_expressions[label.0 as usize] = vec![expr]; label_expressions[label.0 as usize] = vec![expr];
@ -2720,7 +2720,7 @@ impl Generator {
.clone() .clone()
.make_member(quote_ident!("sent")) .make_member(quote_ident!("sent"))
.as_callee(), .as_callee(),
args: vec![], args: Vec::new(),
..Default::default() ..Default::default()
} }
.into() .into()
@ -2831,9 +2831,9 @@ impl Generator {
/// - `args`: The optional arguments for the operation. /// - `args`: The optional arguments for the operation.
fn emit_worker(&mut self, code: OpCode, args: Option<OpArgs>, loc: Option<Span>) { fn emit_worker(&mut self, code: OpCode, args: Option<OpArgs>, loc: Option<Span>) {
if self.operations.is_none() { if self.operations.is_none() {
self.operations = Some(vec![]); self.operations = Some(Vec::new());
self.operation_args = Some(vec![]); self.operation_args = Some(Vec::new());
self.operation_locs = Some(vec![]); self.operation_locs = Some(Vec::new());
} }
if self.label_offsets.is_none() { if self.label_offsets.is_none() {
// mark entry point // mark entry point
@ -2884,7 +2884,7 @@ impl Generator {
return stmts; return stmts;
} }
vec![] Vec::new()
} }
/// Flush the current label and advance to a new label. /// Flush the current label and advance to a new label.
@ -3099,7 +3099,7 @@ impl Generator {
self.flush_label(); self.flush_label();
if self.label_numbers.is_none() { if self.label_numbers.is_none() {
self.label_numbers = Some(vec![]); self.label_numbers = Some(Vec::new());
} }
if let Some(v) = self if let Some(v) = self
@ -3114,7 +3114,7 @@ impl Generator {
self.label_numbers self.label_numbers
.as_mut() .as_mut()
.unwrap() .unwrap()
.resize(self.label_number + 1, vec![]); .resize(self.label_number + 1, Vec::new());
} }
self.label_numbers.as_mut().unwrap()[self.label_number] = vec![label]; self.label_numbers.as_mut().unwrap()[self.label_number] = vec![label];

View File

@ -72,11 +72,11 @@ pub struct Config {
#[swc_trace] #[swc_trace]
impl Params { impl Params {
fn visit_mut_fn_like(&mut self, ps: &mut Vec<Param>, body: &mut BlockStmt, is_setter: bool) { fn visit_mut_fn_like(&mut self, ps: &mut Vec<Param>, body: &mut BlockStmt, is_setter: bool) {
let mut params = vec![]; let mut params = Vec::new();
let mut decls = vec![]; let mut decls = Vec::new();
let mut loose_stmt = vec![]; let mut loose_stmt = Vec::new();
let mut unpack_rest = None; let mut unpack_rest = None;
let mut decls_after_unpack = vec![]; let mut decls_after_unpack = Vec::new();
let mut after_default = false; let mut after_default = false;
@ -523,7 +523,7 @@ impl VisitMut for Params {
if let Some(decls) = decls { if let Some(decls) = decls {
if let BlockStmtOrExpr::Expr(v) = body { if let BlockStmtOrExpr::Expr(v) = body {
let mut stmts = vec![]; let mut stmts = Vec::new();
prepend_stmt(&mut stmts, decls); prepend_stmt(&mut stmts, decls);
stmts.push( stmts.push(
ReturnStmt { ReturnStmt {
@ -544,11 +544,11 @@ impl VisitMut for Params {
fn visit_mut_catch_clause(&mut self, f: &mut CatchClause) { fn visit_mut_catch_clause(&mut self, f: &mut CatchClause) {
f.visit_mut_children_with(self); f.visit_mut_children_with(self);
let mut params = vec![]; let mut params = Vec::new();
if f.param.is_some() { if f.param.is_some() {
params.push(Param { params.push(Param {
span: DUMMY_SP, span: DUMMY_SP,
decorators: vec![], decorators: Vec::new(),
pat: f.param.take().unwrap(), pat: f.param.take().unwrap(),
}); });
} }
@ -750,10 +750,10 @@ impl VisitMut for Params {
f.visit_mut_children_with(self); f.visit_mut_children_with(self);
let mut params = vec![]; let mut params = Vec::new();
let mut body = f.body.take().unwrap(); let mut body = f.body.take().unwrap();
self.visit_mut_fn_like(&mut params, &mut body, false); self.visit_mut_fn_like(&mut params, &mut body, false);
debug_assert_eq!(params, vec![]); debug_assert_eq!(params, Vec::new());
f.body = Some(body); f.body = Some(body);
} }

View File

@ -237,8 +237,8 @@ impl Spread {
// //
let mut first_arr = None; let mut first_arr = None;
let mut tmp_arr = vec![]; let mut tmp_arr = Vec::new();
let mut buf = vec![]; let mut buf = Vec::new();
let args_len = args.len(); let args_len = args.len();
macro_rules! make_arr { macro_rules! make_arr {
@ -265,8 +265,8 @@ impl Spread {
// contiguous slice of non-spread args in an array, which will protect // contiguous slice of non-spread args in an array, which will protect
// array args from being flattened. // array args from being flattened.
if self.c.loose { if self.c.loose {
let mut arg_list = vec![]; let mut arg_list = Vec::new();
let mut current_elems = vec![]; let mut current_elems = Vec::new();
for arg in args.flatten() { for arg in args.flatten() {
let expr = arg.expr; let expr = arg.expr;
match arg.spread { match arg.spread {
@ -279,7 +279,7 @@ impl Spread {
} }
.as_arg(), .as_arg(),
); );
current_elems = vec![]; current_elems = Vec::new();
} }
arg_list.push(expr.as_arg()); arg_list.push(expr.as_arg());
} }
@ -302,7 +302,7 @@ impl Spread {
span: DUMMY_SP, span: DUMMY_SP,
callee: ArrayLit { callee: ArrayLit {
span: DUMMY_SP, span: DUMMY_SP,
elems: vec![], elems: Vec::new(),
} }
.make_member(quote_ident!("concat")) .make_member(quote_ident!("concat"))
.as_callee(), .as_callee(),
@ -391,7 +391,7 @@ impl Spread {
span: DUMMY_SP, span: DUMMY_SP,
callee: ArrayLit { callee: ArrayLit {
span: DUMMY_SP, span: DUMMY_SP,
elems: vec![], elems: Vec::new(),
} }
.make_member(quote_ident!("concat")) .make_member(quote_ident!("concat"))
.as_callee(), .as_callee(),
@ -449,7 +449,7 @@ impl Spread {
// assert!(args.is_empty()); // assert!(args.is_empty());
Expr::Array(ArrayLit { Expr::Array(ArrayLit {
span, span,
elems: vec![], elems: Vec::new(),
}) })
}) })
.make_member(IdentName::new("concat".into(), span)) .make_member(IdentName::new("concat".into(), span))

View File

@ -76,7 +76,7 @@ impl VisitMut for TemplateLiteral {
let len = quasis.len() + exprs.len(); let len = quasis.len() + exprs.len();
let mut args = vec![]; let mut args = Vec::new();
let mut quasis = quasis.iter_mut(); let mut quasis = quasis.iter_mut();
let mut exprs = exprs.take().into_iter(); let mut exprs = exprs.take().into_iter();
@ -244,7 +244,7 @@ impl VisitMut for TemplateLiteral {
span: DUMMY_SP, span: DUMMY_SP,
is_async: false, is_async: false,
is_generator: false, is_generator: false,
params: vec![], params: Vec::new(),
body: { body: {
// const data = _tagged_template_literal(["first", "second"]); // const data = _tagged_template_literal(["first", "second"]);
let data_decl = VarDecl { let data_decl = VarDecl {
@ -321,7 +321,7 @@ impl VisitMut for TemplateLiteral {
span: DUMMY_SP, span: DUMMY_SP,
is_async: false, is_async: false,
is_generator: false, is_generator: false,
params: vec![], params: Vec::new(),
body: Some(BlockStmt { body: Some(BlockStmt {
span: DUMMY_SP, span: DUMMY_SP,
stmts: vec![Stmt::Return(ReturnStmt { stmts: vec![Stmt::Return(ReturnStmt {
@ -370,7 +370,7 @@ impl VisitMut for TemplateLiteral {
CallExpr { CallExpr {
span: DUMMY_SP, span: DUMMY_SP,
callee: fn_ident.as_callee(), callee: fn_ident.as_callee(),
args: vec![], args: Vec::new(),
..Default::default() ..Default::default()
} }
.as_arg(), .as_arg(),

View File

@ -102,8 +102,8 @@ impl<C: Comments + Clone> AsyncToGenerator<C> {
c: self.c, c: self.c,
comments: self.comments.clone(), comments: self.comments.clone(),
unresolved_ctxt: self.unresolved_ctxt, unresolved_ctxt: self.unresolved_ctxt,
extra_stmts: vec![], extra_stmts: Vec::new(),
hoist_stmts: vec![], hoist_stmts: Vec::new(),
}; };
stmt.visit_mut_with(&mut actual); stmt.visit_mut_with(&mut actual);
@ -160,7 +160,7 @@ impl<C: Comments> VisitMut for Actual<C> {
CallExpr { CallExpr {
span: DUMMY_SP, span: DUMMY_SP,
callee: expr.as_callee(), callee: expr.as_callee(),
args: vec![], args: Vec::new(),
..Default::default() ..Default::default()
} }
.into(), .into(),
@ -263,19 +263,19 @@ impl<C: Comments> VisitMut for Actual<C> {
let fn_ref = make_fn_ref( let fn_ref = make_fn_ref(
Function { Function {
params: vec![], params: Vec::new(),
..*prop.function.take() ..*prop.function.take()
} }
.into(), .into(),
); );
let fn_ref = if is_this_used { let fn_ref = if is_this_used {
fn_ref.apply(DUMMY_SP, ThisExpr { span: DUMMY_SP }.into(), vec![]) fn_ref.apply(DUMMY_SP, ThisExpr { span: DUMMY_SP }.into(), Vec::new())
} else { } else {
CallExpr { CallExpr {
span: DUMMY_SP, span: DUMMY_SP,
callee: fn_ref.as_callee(), callee: fn_ref.as_callee(),
args: vec![], args: Vec::new(),
..Default::default() ..Default::default()
} }
.into() .into()
@ -583,7 +583,7 @@ fn handle_await_for(stmt: &mut Stmt, is_async_generator: bool) {
_ => vec![*s.body], _ => vec![*s.body],
}; };
let mut for_loop_body = vec![]; let mut for_loop_body = Vec::new();
{ {
// let value = _step.value; // let value = _step.value;
let value_var = VarDeclarator { let value_var = VarDeclarator {
@ -653,7 +653,7 @@ fn handle_await_for(stmt: &mut Stmt, is_async_generator: bool) {
..Default::default() ..Default::default()
}; };
let mut init_var_decls = vec![]; let mut init_var_decls = Vec::new();
// _iterator = _async_iterator(lol()) // _iterator = _async_iterator(lol())
init_var_decls.push(VarDeclarator { init_var_decls.push(VarDeclarator {
span: DUMMY_SP, span: DUMMY_SP,
@ -828,7 +828,7 @@ fn handle_await_for(stmt: &mut Stmt, is_async_generator: bool) {
.clone() .clone()
.make_member(quote_ident!("return")) .make_member(quote_ident!("return"))
.as_callee(), .as_callee(),
args: vec![], args: Vec::new(),
..Default::default() ..Default::default()
} }
.into(); .into();

View File

@ -281,7 +281,7 @@ impl VisitMut for ObjectRest {
.. ..
}) if var_decl.decls.iter().any(|v| v.name.is_object()) => { }) if var_decl.decls.iter().any(|v| v.name.is_object()) => {
let specifiers = { let specifiers = {
let mut found: Vec<Ident> = vec![]; let mut found: Vec<Ident> = Vec::new();
let mut finder = VarCollector { to: &mut found }; let mut finder = VarCollector { to: &mut found };
var_decl.visit_with(&mut finder); var_decl.visit_with(&mut finder);
found found
@ -376,7 +376,7 @@ impl VisitMut for ObjectRest {
args: vec![ args: vec![
ObjectLit { ObjectLit {
span: DUMMY_SP, span: DUMMY_SP,
props: vec![], props: Vec::new(),
} }
.as_arg(), .as_arg(),
helper_expr!(object_destructuring_empty) helper_expr!(object_destructuring_empty)
@ -902,7 +902,7 @@ fn object_without_properties(
args: vec![ args: vec![
ObjectLit { ObjectLit {
span: DUMMY_SP, span: DUMMY_SP,
props: vec![], props: Vec::new(),
} }
.as_arg(), .as_arg(),
helper_expr!(object_destructuring_empty) helper_expr!(object_destructuring_empty)

View File

@ -43,10 +43,10 @@ impl VisitMut for ObjectSpread {
// { foo, ...x } => ({ foo }, x) // { foo, ...x } => ({ foo }, x)
let args = { let args = {
let mut buf = vec![]; let mut buf = Vec::new();
let mut obj = ObjectLit { let mut obj = ObjectLit {
span: DUMMY_SP, span: DUMMY_SP,
props: vec![], props: Vec::new(),
}; };
let mut first = true; let mut first = true;
for prop in props.take() { for prop in props.take() {

View File

@ -42,10 +42,10 @@ impl VisitMut for ExportNamespaceFrom {
type_only: false, type_only: false,
with, with,
})) if specifiers.iter().any(|s| s.is_namespace()) => { })) if specifiers.iter().any(|s| s.is_namespace()) => {
let mut origin_specifiers = vec![]; let mut origin_specifiers = Vec::new();
let mut import_specifiers = vec![]; let mut import_specifiers = Vec::new();
let mut export_specifiers = vec![]; let mut export_specifiers = Vec::new();
for s in specifiers.into_iter() { for s in specifiers.into_iter() {
match s { match s {

View File

@ -74,8 +74,8 @@ impl MemberInitRecord {
} }
pub fn into_init(self) -> Vec<Box<Expr>> { pub fn into_init(self) -> Vec<Box<Expr>> {
let mut normal_init = vec![]; let mut normal_init = Vec::new();
let mut value_init = vec![]; let mut value_init = Vec::new();
for init in self.record { for init in self.record {
match init { match init {
MemberInit::PrivMethod(PrivMethod { MemberInit::PrivMethod(PrivMethod {
@ -184,8 +184,8 @@ impl MemberInitRecord {
} }
pub fn into_init_static(self, class_ident: Ident) -> Vec<Stmt> { pub fn into_init_static(self, class_ident: Ident) -> Vec<Stmt> {
let mut normal_init = vec![]; let mut normal_init = Vec::new();
let mut value_init = vec![]; let mut value_init = Vec::new();
for value in self.record { for value in self.record {
match value { match value {

View File

@ -181,7 +181,7 @@ impl<C: Comments> VisitMut for ClassProperties<C> {
BlockStmtOrExpr::Expr(expr) if expr.is_class() => { BlockStmtOrExpr::Expr(expr) if expr.is_class() => {
let ClassExpr { ident, class } = expr.take().class().unwrap(); let ClassExpr { ident, class } = expr.take().class().unwrap();
let mut stmts = vec![]; let mut stmts = Vec::new();
let ident = ident.unwrap_or_else(|| private_ident!("_class")); let ident = ident.unwrap_or_else(|| private_ident!("_class"));
let (decl, extra) = self.visit_mut_class_as_decl(ident.clone(), class); let (decl, extra) = self.visit_mut_class_as_decl(ident.clone(), class);
@ -516,14 +516,14 @@ impl<C: Comments> ClassProperties<C> {
let has_super = class.super_class.is_some(); let has_super = class.super_class.is_some();
let mut constructor_inits = MemberInitRecord::new(self.c); let mut constructor_inits = MemberInitRecord::new(self.c);
let mut vars = vec![]; let mut vars = Vec::new();
let mut lets = vec![]; let mut lets = Vec::new();
let mut extra_inits = MemberInitRecord::new(self.c); let mut extra_inits = MemberInitRecord::new(self.c);
let mut private_method_fn_decls = vec![]; let mut private_method_fn_decls = Vec::new();
let mut members = vec![]; let mut members = Vec::new();
let mut constructor = None; let mut constructor = None;
let mut used_names = vec![]; let mut used_names = Vec::new();
let mut used_key_names = vec![]; let mut used_key_names = Vec::new();
let mut super_ident = None; let mut super_ident = None;
class.body.visit_mut_with(&mut BrandCheckHandler { class.body.visit_mut_with(&mut BrandCheckHandler {
@ -980,7 +980,7 @@ impl<C: Comments> ClassProperties<C> {
private_method_fn_decls.visit_mut_with(&mut PrivateAccessVisitor { private_method_fn_decls.visit_mut_with(&mut PrivateAccessVisitor {
private: &self.private, private: &self.private,
vars: vec![], vars: Vec::new(),
private_access_type: Default::default(), private_access_type: Default::default(),
c: self.c, c: self.c,
unresolved_mark: self.unresolved_mark, unresolved_mark: self.unresolved_mark,
@ -992,7 +992,7 @@ impl<C: Comments> ClassProperties<C> {
members.visit_mut_with(&mut PrivateAccessVisitor { members.visit_mut_with(&mut PrivateAccessVisitor {
private: &self.private, private: &self.private,
vars: vec![], vars: Vec::new(),
private_access_type: Default::default(), private_access_type: Default::default(),
c: self.c, c: self.c,
unresolved_mark: self.unresolved_mark, unresolved_mark: self.unresolved_mark,

View File

@ -575,7 +575,7 @@ pub(super) fn visit_private_in_expr(
) -> Vec<VarDeclarator> { ) -> Vec<VarDeclarator> {
let mut priv_visitor = PrivateAccessVisitor { let mut priv_visitor = PrivateAccessVisitor {
private, private,
vars: vec![], vars: Vec::new(),
private_access_type: Default::default(), private_access_type: Default::default(),
c: config, c: config,
unresolved_mark, unresolved_mark,

View File

@ -67,7 +67,7 @@ impl VisitMut for OptionalChaining {
match e { match e {
// foo?.bar -> foo == null ? void 0 : foo.bar // foo?.bar -> foo == null ? void 0 : foo.bar
Expr::OptChain(v) => { Expr::OptChain(v) => {
let data = self.gather(v.take(), vec![]); let data = self.gather(v.take(), Vec::new());
*e = self.construct(data, false); *e = self.construct(data, false);
} }
@ -79,7 +79,7 @@ impl VisitMut for OptionalChaining {
match &mut **arg { match &mut **arg {
// delete foo?.bar -> foo == null ? true : delete foo.bar // delete foo?.bar -> foo == null ? true : delete foo.bar
Expr::OptChain(v) => { Expr::OptChain(v) => {
let data = self.gather(v.take(), vec![]); let data = self.gather(v.take(), Vec::new());
*e = self.construct(data, true); *e = self.construct(data, true);
} }
_ => e.visit_mut_children_with(self), _ => e.visit_mut_children_with(self),
@ -120,7 +120,7 @@ impl VisitMut for OptionalChaining {
span: DUMMY_SP, span: DUMMY_SP,
callee: ArrowExpr { callee: ArrowExpr {
span: DUMMY_SP, span: DUMMY_SP,
params: vec![], params: Vec::new(),
body: Box::new(BlockStmtOrExpr::BlockStmt(BlockStmt { body: Box::new(BlockStmtOrExpr::BlockStmt(BlockStmt {
span: DUMMY_SP, span: DUMMY_SP,
stmts, stmts,
@ -131,7 +131,7 @@ impl VisitMut for OptionalChaining {
..Default::default() ..Default::default()
} }
.as_callee(), .as_callee(),
args: vec![], args: Vec::new(),
..Default::default() ..Default::default()
} }
.into(); .into();

View File

@ -261,7 +261,7 @@ impl VisitMut for PrivateInObject {
} else { } else {
let mut bs = BlockStmt { let mut bs = BlockStmt {
span: DUMMY_SP, span: DUMMY_SP,
stmts: vec![], stmts: Vec::new(),
..Default::default() ..Default::default()
}; };
bs.stmts.push( bs.stmts.push(

View File

@ -30,7 +30,7 @@ impl VisitMut for ReservedWord {
noop_visit_mut_type!(fail); noop_visit_mut_type!(fail);
fn visit_mut_module_items(&mut self, n: &mut Vec<ModuleItem>) { fn visit_mut_module_items(&mut self, n: &mut Vec<ModuleItem>) {
let mut extra_exports = vec![]; let mut extra_exports = Vec::new();
n.iter_mut().for_each(|module_item| { n.iter_mut().for_each(|module_item| {
match module_item { match module_item {

View File

@ -18,7 +18,7 @@ fn main() {
Syntax::default(), Syntax::default(),
EsVersion::latest(), EsVersion::latest(),
None, None,
&mut vec![], &mut Vec::new(),
); );
let mut program = match module { let mut program = match module {
Ok(v) => Program::Module(v), Ok(v) => Program::Module(v),

View File

@ -37,7 +37,7 @@ macro_rules! check {
// This vector allocates only if there are duplicate parameters. // This vector allocates only if there are duplicate parameters.
// This is used to handle the case where the same parameter is used 3 or more // This is used to handle the case where the same parameter is used 3 or more
// times. // times.
let mut done = vec![]; let mut done = Vec::new();
let mut hash_mode = false; let mut hash_mode = false;

View File

@ -49,7 +49,7 @@ impl NoParamReassign {
Self { Self {
expected_reaction: config.get_rule_reaction(), expected_reaction: config.get_rule_reaction(),
scoped_params: Default::default(), scoped_params: Default::default(),
scopes: vec![], scopes: Vec::new(),
check_props: rule_config.props.unwrap_or(true), check_props: rule_config.props.unwrap_or(true),
ignore_names: rule_config.ignore_property_modifications_for.clone(), ignore_names: rule_config.ignore_property_modifications_for.clone(),
ignore_names_patterns: rule_config.ignore_property_modifications_for_regex.clone(), ignore_names_patterns: rule_config.ignore_property_modifications_for_regex.clone(),

View File

@ -232,7 +232,7 @@ where
debug!("Extra: `{}`", extra); debug!("Extra: `{}`", extra);
} }
let mut errors = vec![]; let mut errors = Vec::new();
for target in to { for target in to {
let replaced = target.replace('*', extra); let replaced = target.replace('*', extra);

Some files were not shown because too many files have changed in this diff Show More