From a417ff4d868b45a2157154e2334b8e1177c369e1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Donny/=EA=B0=95=EB=8F=99=EC=9C=A4?= Date: Fri, 19 Jul 2024 13:22:34 +0900 Subject: [PATCH] feat(allocator): Add `maybe` types (#9278) --- Cargo.lock | 4 ++ bindings/binding_core_node/src/bundle.rs | 2 +- crates/ast_node/src/ast_node_macro.rs | 4 +- crates/ast_node/src/enum_deserialize.rs | 4 +- crates/dbg-swc/src/util/mod.rs | 8 +-- crates/from_variant/src/lib.rs | 2 +- crates/jsdoc/src/lib.rs | 4 +- crates/jsdoc/tests/fixture.rs | 4 +- crates/swc/src/config/mod.rs | 2 +- crates/swc/tests/tsc.rs | 6 +- crates/swc_allocator/src/lib.rs | 9 +++ crates/swc_allocator/src/vec/mod.rs | 6 ++ crates/swc_bundler/examples/bundle.rs | 4 +- crates/swc_bundler/examples/path.rs | 4 +- crates/swc_bundler/src/bundler/chunk/cjs.rs | 12 ++-- .../src/bundler/chunk/computed_key.rs | 2 +- crates/swc_bundler/src/bundler/chunk/merge.rs | 8 +-- crates/swc_bundler/src/bundler/finalize.rs | 2 +- crates/swc_bundler/src/bundler/helpers/mod.rs | 4 +- crates/swc_bundler/src/bundler/import/mod.rs | 4 +- crates/swc_bundler/src/bundler/load.rs | 8 +-- crates/swc_bundler/src/bundler/tests.rs | 2 +- crates/swc_bundler/src/modules/mod.rs | 2 +- crates/swc_bundler/src/modules/sort/chunk.rs | 6 +- crates/swc_bundler/src/modules/sort/stmt.rs | 10 +-- crates/swc_bundler/src/modules/sort/tests.rs | 2 +- crates/swc_bundler/src/util.rs | 4 +- crates/swc_bundler/tests/common/mod.rs | 4 +- crates/swc_bundler/tests/deno.rs | 2 +- crates/swc_bundler/tests/fixture.rs | 2 +- crates/swc_common/src/errors/diagnostic.rs | 4 +- crates/swc_common/src/errors/emitter.rs | 12 ++-- crates/swc_common/src/errors/styled_buffer.rs | 16 ++--- crates/swc_common/src/source_map.rs | 6 +- crates/swc_common/src/syntax_pos.rs | 4 +- .../src/syntax_pos/analyze_source_file.rs | 46 ++++++------ crates/swc_common/src/util/take.rs | 2 +- crates/swc_compiler_base/Cargo.toml | 17 ++--- crates/swc_compiler_base/src/lib.rs | 12 ++-- crates/swc_css_codegen/src/writer/basic.rs | 2 +- crates/swc_css_codegen/tests/fixture.rs | 28 ++++---- .../src/compiler/custom_media.rs | 8 +-- crates/swc_css_compat/src/compiler/mod.rs | 2 +- crates/swc_css_compat/src/compiler/nesting.rs | 14 ++-- crates/swc_css_compat/tests/fixture.rs | 2 +- .../src/rules/declaration_no_important.rs | 2 +- crates/swc_css_minifier/benches/full.rs | 2 +- .../src/compressor/calc_sum.rs | 12 ++-- .../swc_css_minifier/src/compressor/rules.rs | 4 +- crates/swc_css_minifier/src/util.rs | 2 +- crates/swc_css_minifier/tests/fixture.rs | 2 +- crates/swc_css_modules/src/lib.rs | 2 +- crates/swc_css_modules/tests/fixture.rs | 4 +- crates/swc_css_modules/tests/with_compat.rs | 2 +- .../swc_css_parser/src/parser/at_rules/mod.rs | 14 ++-- crates/swc_css_parser/src/parser/input.rs | 2 +- .../src/parser/selectors/mod.rs | 10 +-- .../swc_css_parser/src/parser/syntax/mod.rs | 30 ++++---- crates/swc_css_parser/src/parser/util.rs | 4 +- .../src/parser/values_and_units/mod.rs | 14 ++-- crates/swc_css_parser/tests/fixture.rs | 10 +-- crates/swc_css_prefixer/src/prefixer.rs | 8 +-- crates/swc_css_prefixer/tests/prefixer.rs | 2 +- crates/swc_ecma_ast/src/expr.rs | 2 +- crates/swc_ecma_ast/src/stmt.rs | 2 +- crates/swc_ecma_codegen/Cargo.toml | 1 + crates/swc_ecma_codegen/benches/bench.rs | 4 +- crates/swc_ecma_codegen/benches/with_parse.rs | 4 +- crates/swc_ecma_codegen/examples/gen.rs | 2 +- crates/swc_ecma_codegen/examples/sourcemap.rs | 4 +- crates/swc_ecma_codegen/src/lib.rs | 8 +-- crates/swc_ecma_codegen/src/tests.rs | 4 +- crates/swc_ecma_codegen/tests/fixture.rs | 4 +- crates/swc_ecma_codegen/tests/sourcemap.rs | 6 +- crates/swc_ecma_codegen/tests/test262.rs | 2 +- crates/swc_ecma_compat_common/src/macros.rs | 11 +-- crates/swc_ecma_compat_es2015/src/arrow.rs | 2 +- .../src/block_scoping/mod.rs | 12 ++-- .../swc_ecma_compat_es2015/src/classes/mod.rs | 16 ++--- .../src/computed_props.rs | 6 +- .../src/destructuring.rs | 6 +- crates/swc_ecma_compat_es2015/src/for_of.rs | 8 +-- .../swc_ecma_compat_es2015/src/generator.rs | 32 ++++----- .../swc_ecma_compat_es2015/src/parameters.rs | 18 ++--- crates/swc_ecma_compat_es2015/src/spread.rs | 16 ++--- .../src/template_literal.rs | 8 +-- .../src/async_to_generator.rs | 18 ++--- .../swc_ecma_compat_es2018/src/object_rest.rs | 6 +- .../src/object_spread.rs | 4 +- .../src/export_namespace_from.rs | 6 +- .../src/class_properties/member_init.rs | 8 +-- .../src/class_properties/mod.rs | 18 ++--- .../src/class_properties/private_field.rs | 2 +- .../src/optional_chaining_impl.rs | 8 +-- .../src/private_in_object.rs | 2 +- .../swc_ecma_compat_es3/src/reserved_word.rs | 2 +- crates/swc_ecma_lints/examples/all.rs | 2 +- .../swc_ecma_lints/src/rules/no_dupe_args.rs | 2 +- .../src/rules/no_param_reassign.rs | 2 +- crates/swc_ecma_loader/src/resolvers/tsc.rs | 2 +- crates/swc_ecma_loader/tests/tsc_resolver.rs | 2 +- crates/swc_ecma_minifier/benches/full.rs | 4 +- crates/swc_ecma_minifier/examples/compress.rs | 4 +- crates/swc_ecma_minifier/examples/minifier.rs | 4 +- .../swc_ecma_minifier/examples/minify-all.rs | 4 +- .../fuzz/fuzz_targets/bug.rs | 4 +- .../src/compress/hoist_decls.rs | 4 +- .../src/compress/optimize/conditionals.rs | 4 +- .../src/compress/optimize/evaluate.rs | 2 +- .../src/compress/optimize/if_return.rs | 6 +- .../src/compress/optimize/iife.rs | 2 +- .../src/compress/optimize/mod.rs | 12 ++-- .../src/compress/optimize/props.rs | 2 +- .../src/compress/optimize/sequences.rs | 10 +-- .../src/compress/optimize/switches.rs | 2 +- .../src/compress/optimize/util.rs | 2 +- .../src/compress/pure/dead_code.rs | 2 +- .../src/compress/pure/member_expr.rs | 6 +- .../src/compress/pure/misc.rs | 10 +-- .../src/compress/pure/mod.rs | 2 +- .../src/compress/pure/sequences.rs | 2 +- .../src/compress/pure/strings.rs | 4 +- .../src/compress/pure/vars.rs | 2 +- .../src/compress/util/mod.rs | 4 +- .../src/compress/util/tests.rs | 2 +- crates/swc_ecma_minifier/src/debug.rs | 6 +- crates/swc_ecma_minifier/src/eval.rs | 2 +- crates/swc_ecma_minifier/src/option/terser.rs | 4 +- crates/swc_ecma_minifier/tests/compress.rs | 2 +- crates/swc_ecma_minifier/tests/eval.rs | 12 ++-- crates/swc_ecma_minifier/tests/exec.rs | 4 +- crates/swc_ecma_minifier/tests/format.rs | 4 +- crates/swc_ecma_minifier/tests/mangle.rs | 4 +- crates/swc_ecma_minifier/tests/terser_exec.rs | 2 +- crates/swc_ecma_parser/examples/parse-all.rs | 2 +- crates/swc_ecma_parser/src/lexer/mod.rs | 2 +- crates/swc_ecma_parser/src/lexer/tests.rs | 26 +++---- .../src/parser/class_and_fn.rs | 20 +++--- crates/swc_ecma_parser/src/parser/expr.rs | 6 +- .../swc_ecma_parser/src/parser/expr/tests.rs | 14 ++-- .../src/parser/expr/verifier.rs | 2 +- crates/swc_ecma_parser/src/parser/jsx.rs | 4 +- .../swc_ecma_parser/src/parser/jsx/tests.rs | 10 +-- crates/swc_ecma_parser/src/parser/object.rs | 12 ++-- crates/swc_ecma_parser/src/parser/pat.rs | 10 +-- crates/swc_ecma_parser/src/parser/stmt.rs | 16 ++--- .../src/parser/stmt/module_item.rs | 6 +- crates/swc_ecma_parser/src/parser/tests.rs | 8 +-- .../swc_ecma_parser/src/parser/typescript.rs | 10 +-- crates/swc_ecma_parser/tests/common/mod.rs | 4 +- crates/swc_ecma_preset_env/src/corejs2/mod.rs | 2 +- .../swc_ecma_preset_env/src/corejs3/usage.rs | 2 +- crates/swc_ecma_preset_env/src/lib.rs | 4 +- crates/swc_ecma_preset_env/tests/test.rs | 4 +- crates/swc_ecma_quote_macros/src/ctxt.rs | 2 +- .../swc_ecma_transforms_base/benches/deps.rs | 10 +-- .../src/helpers/mod.rs | 10 +-- .../src/hygiene/tests.rs | 18 ++--- crates/swc_ecma_transforms_base/src/perf.rs | 4 +- .../src/rename/ops.rs | 6 +- .../src/resolver/mod.rs | 4 +- crates/swc_ecma_transforms_base/src/tests.rs | 2 +- .../tests/fixer_test262.rs | 6 +- .../swc_ecma_transforms_base/tests/fixture.rs | 2 +- .../tests/ts_resolver.rs | 2 +- .../src/class_fields_use_set.rs | 2 +- .../src/common_js.rs | 2 +- .../src/system_js.rs | 70 +++++++++---------- crates/swc_ecma_transforms_module/src/umd.rs | 8 +-- .../src/umd/config.rs | 2 +- .../src/const_modules.rs | 2 +- .../src/simplify/branch/mod.rs | 14 ++-- .../src/simplify/expr/mod.rs | 2 +- .../src/decorator_2022_03.rs | 24 +++---- .../src/decorators/legacy/mod.rs | 2 +- .../src/decorators/mod.rs | 10 +-- .../src/explicit_resource_management.rs | 8 +-- .../src/export_default_from.rs | 4 +- crates/swc_ecma_transforms_react/Cargo.toml | 1 + .../swc_ecma_transforms_react/src/jsx/mod.rs | 8 +-- .../src/jsx/tests.rs | 2 +- .../src/pure_annotations/tests.rs | 4 +- .../src/babel_like.rs | 4 +- crates/swc_ecma_transforms_testing/src/lib.rs | 10 ++- .../src/transform.rs | 8 +-- crates/swc_ecma_utils/src/lib.rs | 10 +-- crates/swc_ecma_visit/tests/main.rs | 2 +- crates/swc_eq_ignore_macros/src/lib.rs | 2 +- crates/swc_estree_compat/src/babelify/expr.rs | 2 +- crates/swc_estree_compat/tests/convert.rs | 2 +- crates/swc_fast_ts_strip/Cargo.toml | 5 +- crates/swc_fast_ts_strip/src/lib.rs | 10 +-- crates/swc_graph_analyzer/tests/cycle.rs | 4 +- crates/swc_html_codegen/src/writer/basic.rs | 2 +- crates/swc_html_codegen/tests/fixture.rs | 24 +++---- crates/swc_html_minifier/benches/full.rs | 8 +-- crates/swc_html_minifier/src/lib.rs | 30 ++++---- crates/swc_html_minifier/tests/fixture.rs | 10 +-- crates/swc_html_parser/benches/compare.rs | 4 +- crates/swc_html_parser/benches/parser.rs | 4 +- crates/swc_html_parser/src/lexer/mod.rs | 6 +- crates/swc_html_parser/src/parser/mod.rs | 8 +-- crates/swc_html_parser/src/parser/node.rs | 2 +- .../swc_html_parser/tests/html5lib_tests.rs | 30 ++++---- crates/swc_macros_common/src/binder.rs | 6 +- crates/swc_macros_common/src/derive.rs | 2 +- .../swc_macros_common/src/derive/generics.rs | 2 +- crates/swc_node_bundler/src/loaders/json.rs | 10 ++- crates/swc_node_bundler/src/loaders/swc.rs | 2 +- crates/swc_plugin/src/allocation.rs | 2 +- .../swc_plugin_runner/benches/ecma_invoke.rs | 2 +- .../src/transform_executor.rs | 10 +-- crates/swc_plugin_runner/tests/css_rkyv.rs | 4 +- .../tests/ecma_integration.rs | 4 +- crates/swc_plugin_runner/tests/ecma_rkyv.rs | 4 +- crates/swc_plugin_runner/tests/issues.rs | 2 +- crates/swc_typescript/src/fast_dts/mod.rs | 6 +- crates/swc_typescript/tests/fast_dts_deno.rs | 2 +- crates/swc_visit_macros/src/lib.rs | 68 +++++++++--------- crates/swc_xml_codegen/src/writer/basic.rs | 2 +- crates/swc_xml_codegen/tests/fixture.rs | 8 +-- crates/swc_xml_parser/src/lexer/mod.rs | 4 +- crates/swc_xml_parser/src/parser/node.rs | 2 +- crates/testing_macros/src/fixture.rs | 4 +- scripts/git-diff.sh | 7 ++ tools/generate-code/src/generators/visitor.rs | 24 +++---- 226 files changed, 821 insertions(+), 778 deletions(-) create mode 100755 scripts/git-diff.sh diff --git a/Cargo.lock b/Cargo.lock index 265deb06790..d3f38ecd6c5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3866,6 +3866,7 @@ dependencies = [ "serde", "serde_json", "sourcemap", + "swc_allocator", "swc_atoms", "swc_common", "swc_config", @@ -4176,6 +4177,7 @@ dependencies = [ "serde", "serde_json", "sourcemap", + "swc_allocator", "swc_atoms", "swc_common", "swc_ecma_ast", @@ -4788,6 +4790,7 @@ dependencies = [ "serde", "sha1", "string_enum", + "swc_allocator", "swc_atoms", "swc_common", "swc_config", @@ -4991,6 +4994,7 @@ dependencies = [ "codspeed-criterion-compat", "criterion", "serde", + "swc_allocator", "swc_common", "swc_ecma_ast", "swc_ecma_codegen", diff --git a/bindings/binding_core_node/src/bundle.rs b/bindings/binding_core_node/src/bundle.rs index c0348b84ec0..93c05d3f1d8 100644 --- a/bindings/binding_core_node/src/bundle.rs +++ b/bindings/binding_core_node/src/bundle.rs @@ -63,7 +63,7 @@ impl Task for BundleTask { .map(JsWord::from) .collect::>() } else { - vec![] + Vec::new() }; // Defaults to es3 diff --git a/crates/ast_node/src/ast_node_macro.rs b/crates/ast_node/src/ast_node_macro.rs index e67e08926ed..1b76b3dfa29 100644 --- a/crates/ast_node/src/ast_node_macro.rs +++ b/crates/ast_node/src/ast_node_macro.rs @@ -16,7 +16,7 @@ impl Parse for Args { } pub fn expand_struct(args: Args, i: DeriveInput) -> Vec { - let mut items = vec![]; + let mut items = Vec::new(); let generics = i.generics.clone(); // let item_ident = Ident::new("Item", i.ident.span()); @@ -128,7 +128,7 @@ pub fn expand_struct(args: Args, i: DeriveInput) -> Vec { // let item = DeriveInput { // vis: Visibility::Inherited, // ident: item_ident, - // attrs: vec![], + // attrs: Vec::new(), // data: item_data, // ..cloned // }; diff --git a/crates/ast_node/src/enum_deserialize.rs b/crates/ast_node/src/enum_deserialize.rs index a6ea5e61ba5..018539846f6 100644 --- a/crates/ast_node/src/enum_deserialize.rs +++ b/crates/ast_node/src/enum_deserialize.rs @@ -113,8 +113,8 @@ pub fn expand( .collect::>(); let tag_expr: Expr = { - let mut visit_str_arms = vec![]; - let mut visit_bytes_arms = vec![]; + let mut visit_str_arms = Vec::new(); + let mut visit_bytes_arms = Vec::new(); for variant in &data.variants { let tags = variant diff --git a/crates/dbg-swc/src/util/mod.rs b/crates/dbg-swc/src/util/mod.rs index 00f0bb30334..ab288f58cf3 100644 --- a/crates/dbg-swc/src/util/mod.rs +++ b/crates/dbg-swc/src/util/mod.rs @@ -49,7 +49,7 @@ pub fn parse_js(fm: Arc) -> Result { let unresolved_mark = Mark::new(); let top_level_mark = Mark::new(); - let mut errors = vec![]; + let mut errors = Vec::new(); let comments = SingleThreadedComments::default(); let res = parse_file_as_module( &fm, @@ -80,7 +80,7 @@ pub fn parse_js(fm: Arc) -> Result { } pub fn print_js(cm: Arc, m: &Module, minify: bool) -> Result { - let mut buf = vec![]; + let mut buf = Vec::new(); { let mut wr = Box::new(JsWriter::new(cm.clone(), "\n", &mut buf, None)) as Box; @@ -112,7 +112,7 @@ pub struct ModuleRecord { pub fn all_js_files(path: &Path) -> Result> { wrap_task(|| { if path.is_dir() { - let mut files = vec![]; + let mut files = Vec::new(); for entry in path.read_dir().context("failed to read dir")? { let entry = entry.context("read_dir returned an error")?; let path = entry.path(); @@ -122,7 +122,7 @@ pub fn all_js_files(path: &Path) -> Result> { } else if path.extension() == Some("js".as_ref()) { Ok(vec![path.to_path_buf()]) } else { - Ok(vec![]) + Ok(Vec::new()) } }) .with_context(|| format!("failed to get list of `.js` files in {}", path.display())) diff --git a/crates/from_variant/src/lib.rs b/crates/from_variant/src/lib.rs index 99341f81729..1f809dfedbf 100644 --- a/crates/from_variant/src/lib.rs +++ b/crates/from_variant/src/lib.rs @@ -32,7 +32,7 @@ fn derive( _ => panic!("#[derive(FromVariant)] only works for an enum."), }; - let mut from_impls: Vec = vec![]; + let mut from_impls: Vec = Vec::new(); for v in variants { let variant_name = v.ident; diff --git a/crates/jsdoc/src/lib.rs b/crates/jsdoc/src/lib.rs index c6dc567f154..9dcad21edd4 100644 --- a/crates/jsdoc/src/lib.rs +++ b/crates/jsdoc/src/lib.rs @@ -14,7 +14,7 @@ mod input; pub fn parse(i: Input) -> IResult { let i = skip(i); - let mut tags = vec![]; + let mut tags = Vec::new(); let lo = i.span().lo; let (description, mut i) = take_while(|c| c != '@')(i)?; let description = trim(description).into(); @@ -546,7 +546,7 @@ fn parse_one_of<'i>(i: Input<'i>, list: &[&str]) -> IResult, Text> { fn parse_name_path(mut i: Input) -> IResult { let lo = i.span().lo; - let mut components = vec![]; + let mut components = Vec::new(); loop { let (input, component) = parse_word(i)?; diff --git a/crates/jsdoc/tests/fixture.rs b/crates/jsdoc/tests/fixture.rs index ba692056b7d..309eee2c37d 100644 --- a/crates/jsdoc/tests/fixture.rs +++ b/crates/jsdoc/tests/fixture.rs @@ -15,7 +15,7 @@ fn fixture(path: PathBuf) { let fm = cm.load_file(&path).expect("failed to load fixture file"); - let mut errors = vec![]; + let mut errors = Vec::new(); if let Err(err) = parse_file_as_module( &fm, @@ -35,7 +35,7 @@ fn fixture(path: PathBuf) { if handler.has_errors() { return Err(()); } - let mut res = vec![]; + let mut res = Vec::new(); let mut comments: Vec<_> = comments.leading.into_iter().collect(); comments.sort_by_key(|v| v.0); diff --git a/crates/swc/src/config/mod.rs b/crates/swc/src/config/mod.rs index 11b17cf3a17..fa7b420cda4 100644 --- a/crates/swc/src/config/mod.rs +++ b/crates/swc/src/config/mod.rs @@ -1548,7 +1548,7 @@ impl GlobalPassOption { fn expr(cm: &SourceMap, handler: &Handler, src: String) -> Box { let fm = cm.new_source_file(FileName::Anon.into(), src); - let mut errors = vec![]; + let mut errors = Vec::new(); let expr = parse_file_as_expr( &fm, Syntax::Es(Default::default()), diff --git a/crates/swc/tests/tsc.rs b/crates/swc/tests/tsc.rs index a9185575d69..9ad671bb19b 100644 --- a/crates/swc/tests/tsc.rs +++ b/crates/swc/tests/tsc.rs @@ -113,7 +113,7 @@ fn matrix(input: &Path) -> Vec { let mut sub_filename = filename; - let mut files = vec![]; + let mut files = Vec::new(); let mut buffer = String::default(); for line in fm.src.lines() { @@ -344,7 +344,7 @@ fn matrix(input: &Path) -> Vec { "#, ); - let mut test_unit_data_list = vec![]; + let mut test_unit_data_list = Vec::new(); let is_jsx = input .extension() @@ -357,7 +357,7 @@ fn matrix(input: &Path) -> Vec { for minify in [None, Some(default_minify)] { for target in targets.clone() { for module in modules.clone() { - let mut vary_name = vec![]; + let mut vary_name = Vec::new(); if modules.len() > 1 { vary_name.push(format!("module={}", &module)); diff --git a/crates/swc_allocator/src/lib.rs b/crates/swc_allocator/src/lib.rs index c56bde3c133..79ea78bfe80 100644 --- a/crates/swc_allocator/src/lib.rs +++ b/crates/swc_allocator/src/lib.rs @@ -42,6 +42,15 @@ pub mod boxed; #[cfg(feature = "nightly")] pub mod vec; +/// Box and Vec depeding on the feature. +pub mod maybe { + #[cfg(not(feature = "nightly"))] + pub use std::{boxed, vec}; + + #[cfg(feature = "nightly")] + pub use crate::{boxed, vec}; +} + /// Fast allocator, effectively working as a cache. /// /// This type implements [Default] and [Copy]. This type is intended to stored diff --git a/crates/swc_allocator/src/vec/mod.rs b/crates/swc_allocator/src/vec/mod.rs index 7569af262f9..e5607b0f3d3 100644 --- a/crates/swc_allocator/src/vec/mod.rs +++ b/crates/swc_allocator/src/vec/mod.rs @@ -381,3 +381,9 @@ impl io::Write for Vec { self } } + +impl AsRef<[T]> for Vec { + fn as_ref(&self) -> &[T] { + self.0.as_ref() + } +} diff --git a/crates/swc_bundler/examples/bundle.rs b/crates/swc_bundler/examples/bundle.rs index 17e1e9efd01..37394cf4532 100644 --- a/crates/swc_bundler/examples/bundle.rs +++ b/crates/swc_bundler/examples/bundle.rs @@ -36,7 +36,7 @@ use swc_ecma_visit::VisitMutWith; fn print_bundles(cm: Lrc, modules: Vec, minify: bool) { for bundled in modules { let code = { - let mut buf = vec![]; + let mut buf = Vec::new(); { let wr = JsWriter::new(cm.clone(), "\n", &mut buf, None); @@ -232,7 +232,7 @@ impl Load for Loader { Syntax::Es(Default::default()), EsVersion::Es2020, None, - &mut vec![], + &mut Vec::new(), ) .unwrap_or_else(|err| { let handler = diff --git a/crates/swc_bundler/examples/path.rs b/crates/swc_bundler/examples/path.rs index 9c5f33b95a5..3eb0f753546 100644 --- a/crates/swc_bundler/examples/path.rs +++ b/crates/swc_bundler/examples/path.rs @@ -14,7 +14,7 @@ fn main() { let globals = Globals::new(); let cm = Lrc::new(SourceMap::new(FilePathMapping::empty())); // This example does not use core modules. - let external_modules = vec![]; + let external_modules = Vec::new(); let mut bundler = Bundler::new( &globals, cm.clone(), @@ -74,7 +74,7 @@ impl Load for PathLoader { Syntax::Es(Default::default()), Default::default(), None, - &mut vec![], + &mut Vec::new(), ) .expect("This should not happen"); diff --git a/crates/swc_bundler/src/bundler/chunk/cjs.rs b/crates/swc_bundler/src/bundler/chunk/cjs.rs index d95849f43fa..9b27a7423df 100644 --- a/crates/swc_bundler/src/bundler/chunk/cjs.rs +++ b/crates/swc_bundler/src/bundler/chunk/cjs.rs @@ -126,7 +126,7 @@ fn wrap_module( pat: Pat::Ident(Ident::new("exports".into(), DUMMY_SP, local_ctxt).into()), }, ], - decorators: vec![], + decorators: Vec::new(), span: DUMMY_SP, body: Some(BlockStmt { span: dep.span, @@ -205,7 +205,7 @@ where let load = CallExpr { span: node.span, callee: Ident::new("load".into(), i.span, i.ctxt).as_callee(), - args: vec![], + args: Vec::new(), ..Default::default() }; self.replaced = true; @@ -253,7 +253,7 @@ where *node = CallExpr { span: DUMMY_SP, callee: load_var.as_callee(), - args: vec![], + args: Vec::new(), ..Default::default() } @@ -262,7 +262,7 @@ where return; } - let mut props = vec![]; + let mut props = Vec::new(); // TODO for spec in i.specifiers.clone() { match spec { @@ -303,7 +303,7 @@ where CallExpr { span: DUMMY_SP, callee: load_var.as_callee(), - args: vec![], + args: Vec::new(), ..Default::default() } @@ -335,7 +335,7 @@ where init: Some(Box::new(Expr::Call(CallExpr { span: DUMMY_SP, callee: load_var.as_callee(), - args: vec![], + args: Vec::new(), ..Default::default() }))), definite: false, diff --git a/crates/swc_bundler/src/bundler/chunk/computed_key.rs b/crates/swc_bundler/src/bundler/chunk/computed_key.rs index 7deeb228672..d234a593cd8 100644 --- a/crates/swc_bundler/src/bundler/chunk/computed_key.rs +++ b/crates/swc_bundler/src/bundler/chunk/computed_key.rs @@ -48,7 +48,7 @@ where let is_async = module.iter().any(|m| contains_top_level_await(m.1)); - let mut additional_items = vec![]; + let mut additional_items = Vec::new(); module.iter().for_each(|(module_id, item)| { match item { diff --git a/crates/swc_bundler/src/bundler/chunk/merge.rs b/crates/swc_bundler/src/bundler/chunk/merge.rs index 5eedbe9be59..ff0d193533c 100644 --- a/crates/swc_bundler/src/bundler/chunk/merge.rs +++ b/crates/swc_bundler/src/bundler/chunk/merge.rs @@ -183,7 +183,7 @@ where { // Handle `export *` for non-wrapped modules. - let mut vars = vec![]; + let mut vars = Vec::new(); /// We recurse if `export *` is nested. fn add_var( injected_ctxt: SyntaxContext, @@ -568,7 +568,7 @@ where return; } - let mut extra = vec![]; + let mut extra = Vec::new(); module.map_any_items(|_, items| { let mut new = Vec::with_capacity(items.len() * 11 / 10); @@ -977,7 +977,7 @@ where if !dep.is_es6 { dep.helpers.require.store(true, Ordering::SeqCst); - let mut vars = vec![]; + let mut vars = Vec::new(); let mod_var = private_ident!("_cjs_module_"); vars.push(VarDeclarator { @@ -1234,7 +1234,7 @@ where pub(super) fn replace_import_specifiers(&self, info: &TransformedModule, module: &mut Modules) { let injected_ctxt = self.injected_ctxt; - let mut vars = vec![]; + let mut vars = Vec::new(); module.map_any_items(|module_id, stmts| { let mut new = Vec::with_capacity(stmts.len() + 32); diff --git a/crates/swc_bundler/src/bundler/finalize.rs b/crates/swc_bundler/src/bundler/finalize.rs index b3bd6220c88..18eb7158170 100644 --- a/crates/swc_bundler/src/bundler/finalize.rs +++ b/crates/swc_bundler/src/bundler/finalize.rs @@ -150,7 +150,7 @@ where let is_async = contains_top_level_await(&module); // Properties of returned object - let mut props = vec![]; + let mut props = Vec::new(); let mut body = BlockStmt { span: module.span, diff --git a/crates/swc_bundler/src/bundler/helpers/mod.rs b/crates/swc_bundler/src/bundler/helpers/mod.rs index a405af1d628..c275045bc59 100644 --- a/crates/swc_bundler/src/bundler/helpers/mod.rs +++ b/crates/swc_bundler/src/bundler/helpers/mod.rs @@ -20,7 +20,7 @@ fn parse(code: &'static str, name: &'static str) -> Vec { Default::default(), Default::default(), None, - &mut vec![], + &mut Vec::new(), ) .map(|script| drop_span(script.body)) .map_err(|_| {}) @@ -59,7 +59,7 @@ impl Helpers { } pub fn add_to(&self, to: &mut Vec) { - let mut buf = vec![]; + let mut buf = Vec::new(); if self.require.load(SeqCst) { build_swcpack_require(&mut buf); diff --git a/crates/swc_bundler/src/bundler/import/mod.rs b/crates/swc_bundler/src/bundler/import/mod.rs index bcb25a43970..53244ebcfee 100644 --- a/crates/swc_bundler/src/bundler/import/mod.rs +++ b/crates/swc_bundler/src/bundler/import/mod.rs @@ -239,7 +239,7 @@ where let decl = ImportDecl { span, - specifiers: vec![], + specifiers: Vec::new(), src: Box::new(src.clone()), type_only: false, with: None, @@ -544,7 +544,7 @@ where }); if self.deglob_phase { - let mut wrapping_required = vec![]; + let mut wrapping_required = Vec::new(); for import in self.info.imports.iter_mut() { let use_ns = self.info.forced_ns.contains(&import.src.value) || self diff --git a/crates/swc_bundler/src/bundler/load.rs b/crates/swc_bundler/src/bundler/load.rs index 49603c5749d..374e7ecf0a2 100644 --- a/crates/swc_bundler/src/bundler/load.rs +++ b/crates/swc_bundler/src/bundler/load.rs @@ -225,7 +225,7 @@ where ) -> Result<(Exports, Vec<(Source, Lrc)>), Error> { self.run(|| { tracing::trace!("resolve_exports({})", base); - let mut files = vec![]; + let mut files = Vec::new(); let mut exports = Exports::default(); @@ -282,7 +282,7 @@ where ) -> Result<(Imports, Vec<(Source, Lrc)>), Error> { self.run(|| { tracing::trace!("resolve_imports({})", base); - let mut files = vec![]; + let mut files = Vec::new(); let mut merged = Imports::default(); let RawImports { @@ -300,7 +300,7 @@ where ( ImportDecl { span: src.span, - specifiers: vec![], + specifiers: Vec::new(), src: Box::new(src), type_only: false, with: None, @@ -346,7 +346,7 @@ where files.push((src.clone(), file_name)); // TODO: Handle rename - let mut specifiers = vec![]; + let mut specifiers = Vec::new(); for s in decl.specifiers { match s { ImportSpecifier::Named(s) => { diff --git a/crates/swc_bundler/src/bundler/tests.rs b/crates/swc_bundler/src/bundler/tests.rs index 19c44c2bbe3..5bc6dbdf097 100644 --- a/crates/swc_bundler/src/bundler/tests.rs +++ b/crates/swc_bundler/src/bundler/tests.rs @@ -141,7 +141,7 @@ impl TestBuilder { disable_hygiene: false, disable_fixer: false, disable_dce: false, - external_modules: vec![], + external_modules: Vec::new(), module: Default::default(), }, Box::new(Hook), diff --git a/crates/swc_bundler/src/modules/mod.rs b/crates/swc_bundler/src/modules/mod.rs index a50fa6bc4d7..f0d9a6167e5 100644 --- a/crates/swc_bundler/src/modules/mod.rs +++ b/crates/swc_bundler/src/modules/mod.rs @@ -266,7 +266,7 @@ impl Modules { }) .collect::(); let mut cloned = self.clone(); - let mut stmts = vec![]; + let mut stmts = Vec::new(); for (id, mut module) in cloned.modules { swc_ecma_utils::prepend_stmts( diff --git a/crates/swc_bundler/src/modules/sort/chunk.rs b/crates/swc_bundler/src/modules/sort/chunk.rs index a960464d9e1..755c1cb360e 100644 --- a/crates/swc_bundler/src/modules/sort/chunk.rs +++ b/crates/swc_bundler/src/modules/sort/chunk.rs @@ -30,7 +30,7 @@ impl Modules { cm: &Lrc, ) -> Vec { let injected_ctxt = self.injected_ctxt; - let mut chunks = vec![]; + let mut chunks = Vec::new(); 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::>(); queue.push_front(entry); - let mut chunks = vec![]; + let mut chunks = Vec::new(); tracing::debug!( "Topologically sorting modules based on the dependency graph: ({} items)", @@ -88,7 +88,7 @@ fn toposort_real_modules<'a>( continue; } - let mut stmts = vec![]; + let mut stmts = Vec::new(); for id in ids.iter().copied().rev() { if let Some((_, module)) = modules.iter_mut().find(|(module_id, _)| *module_id == id) { diff --git a/crates/swc_bundler/src/modules/sort/stmt.rs b/crates/swc_bundler/src/modules/sort/stmt.rs index 7315f61327d..c68d5251f48 100644 --- a/crates/swc_bundler/src/modules/sort/stmt.rs +++ b/crates/swc_bundler/src/modules/sort/stmt.rs @@ -22,10 +22,10 @@ pub(super) fn sort_stmts( ) -> Vec { let total_len: usize = modules.iter().map(|v| v.len()).sum(); - let mut stmts = vec![]; - let mut free = vec![]; - let mut same_module_ranges = vec![]; - let mut module_starts = vec![]; + let mut stmts = Vec::new(); + let mut free = Vec::new(); + let mut same_module_ranges = Vec::new(); + let mut module_starts = Vec::new(); for module in modules { let start = stmts.len(); @@ -226,7 +226,7 @@ fn iter<'a>( // dbg!(&deps); if !deps.is_empty() { - let mut deps_to_push = vec![]; + let mut deps_to_push = Vec::new(); for dep in deps.iter().rev().copied() { if deps_to_push.contains(&dep) { continue; diff --git a/crates/swc_bundler/src/modules/sort/tests.rs b/crates/swc_bundler/src/modules/sort/tests.rs index 43648ac25be..f46b037adbf 100644 --- a/crates/swc_bundler/src/modules/sort/tests.rs +++ b/crates/swc_bundler/src/modules/sort/tests.rs @@ -16,7 +16,7 @@ fn assert_sorted_with_free(src: &[&str], free: &str, res: &str) { s = s.file(&format!("{}.js", i), src); } s.run(|t| { - let mut modules = vec![]; + let mut modules = Vec::new(); let mut entry = None; let mut free: Module = drop_span(t.parse(free)); diff --git a/crates/swc_bundler/src/util.rs b/crates/swc_bundler/src/util.rs index de329eb3fac..0bf3ea4a0ff 100644 --- a/crates/swc_bundler/src/util.rs +++ b/crates/swc_bundler/src/util.rs @@ -204,7 +204,7 @@ impl ExportMetadata { pub fn into_with(self) -> Box { let mut obj = Some(Box::new(ObjectLit { span: DUMMY_SP, - props: vec![], + props: Vec::new(), })); self.encode(&mut obj); @@ -213,7 +213,7 @@ impl ExportMetadata { } pub fn encode(&self, to: &mut Option>) { - let mut props = vec![]; + let mut props = Vec::new(); if self.injected { props.push(metadata("__swc_bundler__injected__", "1")); diff --git a/crates/swc_bundler/tests/common/mod.rs b/crates/swc_bundler/tests/common/mod.rs index 4761ea207fc..6850690a70f 100644 --- a/crates/swc_bundler/tests/common/mod.rs +++ b/crates/swc_bundler/tests/common/mod.rs @@ -78,7 +78,7 @@ fn load_url(url: Url) -> Result { .bytes() .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(); content.extend_from_slice(&bytes); @@ -124,7 +124,7 @@ impl Load for Loader { }), EsVersion::Es2020, None, - &mut vec![], + &mut Vec::new(), ) .unwrap_or_else(|err| { let handler = diff --git a/crates/swc_bundler/tests/deno.rs b/crates/swc_bundler/tests/deno.rs index b587134570d..f5ab0644e46 100644 --- a/crates/swc_bundler/tests/deno.rs +++ b/crates/swc_bundler/tests/deno.rs @@ -1074,7 +1074,7 @@ fn bundle(url: &str, minify: bool) -> String { module.visit_mut_with(&mut fixer(None)); } - let mut buf = vec![]; + let mut buf = Vec::new(); { let mut wr: Box = Box::new(JsWriter::new(cm.clone(), "\n", &mut buf, None)); diff --git a/crates/swc_bundler/tests/fixture.rs b/crates/swc_bundler/tests/fixture.rs index a2e00ead825..7c8bed4151d 100644 --- a/crates/swc_bundler/tests/fixture.rs +++ b/crates/swc_bundler/tests/fixture.rs @@ -51,7 +51,7 @@ fn do_test(entry: &Path, entries: HashMap, inline: bool) { for bundled in modules { let code = { - let mut buf = vec![]; + let mut buf = Vec::new(); { let mut emitter = Emitter { diff --git a/crates/swc_common/src/errors/diagnostic.rs b/crates/swc_common/src/errors/diagnostic.rs index cb33fc6b88f..5bed0f239e0 100644 --- a/crates/swc_common/src/errors/diagnostic.rs +++ b/crates/swc_common/src/errors/diagnostic.rs @@ -136,8 +136,8 @@ impl Diagnostic { message: vec![Message(message.to_owned(), Style::NoStyle)], code, span: MultiSpan::new(), - children: vec![], - suggestions: vec![], + children: Vec::new(), + suggestions: Vec::new(), } } diff --git a/crates/swc_common/src/errors/emitter.rs b/crates/swc_common/src/errors/emitter.rs index e9d102ce107..d5537f765d7 100644 --- a/crates/swc_common/src/errors/emitter.rs +++ b/crates/swc_common/src/errors/emitter.rs @@ -241,8 +241,8 @@ impl EmitterWriter { }); } - let mut output = vec![]; - let mut multiline_annotations = vec![]; + let mut output = Vec::new(); + let mut multiline_annotations = Vec::new(); if let Some(ref sm) = self.sm { for span_label in msp.span_labels() { @@ -496,7 +496,7 @@ impl EmitterWriter { // | x_span // // - let mut annotations_position = vec![]; + let mut annotations_position = Vec::new(); let mut line_len = 0; let mut p = 0; 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 // MultilineLine, then there's only code being shown, stop processing. if line.annotations.iter().all(|a| a.is_line()) { - return vec![]; + return Vec::new(); } // Write the column separator. @@ -792,8 +792,8 @@ impl EmitterWriter { let mut spans_updated = false; if let Some(ref sm) = self.sm { - let mut before_after: Vec<(Span, Span)> = vec![]; - let new_labels: Vec<(Span, String)> = vec![]; + let mut before_after: Vec<(Span, Span)> = Vec::new(); + let new_labels: Vec<(Span, String)> = Vec::new(); // First, find all the spans in <*macros> and point instead at their use site for sp in span.primary_spans() { diff --git a/crates/swc_common/src/errors/styled_buffer.rs b/crates/swc_common/src/errors/styled_buffer.rs index 2df9be2e59c..bfa3b325f47 100644 --- a/crates/swc_common/src/errors/styled_buffer.rs +++ b/crates/swc_common/src/errors/styled_buffer.rs @@ -21,14 +21,14 @@ pub struct StyledBuffer { impl StyledBuffer { pub fn new() -> StyledBuffer { StyledBuffer { - text: vec![], - styles: vec![], + text: Vec::new(), + styles: Vec::new(), } } fn replace_tabs(&mut self) { 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() { if *c == '\t' { tab_pos.push(pos); @@ -48,8 +48,8 @@ impl StyledBuffer { } pub fn render(&mut self) -> Vec> { - let mut output: Vec> = vec![]; - let mut styled_vec: Vec = vec![]; + let mut output: Vec> = Vec::new(); + let mut styled_vec: Vec = Vec::new(); // before we render, replace tabs with spaces self.replace_tabs(); @@ -81,7 +81,7 @@ impl StyledBuffer { // We're done with the row, push and keep going output.push(styled_vec); - styled_vec = vec![]; + styled_vec = Vec::new(); } output @@ -89,8 +89,8 @@ impl StyledBuffer { fn ensure_lines(&mut self, line: usize) { while line >= self.text.len() { - self.text.push(vec![]); - self.styles.push(vec![]); + self.text.push(Vec::new()); + self.styles.push(Vec::new()); } } diff --git a/crates/swc_common/src/source_map.rs b/crates/swc_common/src/source_map.rs index 5b9c23bc131..bc7e7c606ac 100644 --- a/crates/swc_common/src/source_map.rs +++ b/crates/swc_common/src/source_map.rs @@ -516,7 +516,7 @@ impl SourceMap { if lo.file.src.is_empty() { return Ok(FileLines { file: lo.file, - lines: vec![], + lines: Vec::new(), }); } @@ -1434,7 +1434,9 @@ pub struct FilePathMapping { impl FilePathMapping { pub fn empty() -> FilePathMapping { - FilePathMapping { mapping: vec![] } + FilePathMapping { + mapping: Vec::new(), + } } pub fn new(mapping: Vec<(PathBuf, PathBuf)>) -> FilePathMapping { diff --git a/crates/swc_common/src/syntax_pos.rs b/crates/swc_common/src/syntax_pos.rs index 43a9951b38a..2da052b2ab3 100644 --- a/crates/swc_common/src/syntax_pos.rs +++ b/crates/swc_common/src/syntax_pos.rs @@ -535,14 +535,14 @@ impl MultiSpan { pub fn from_span(primary_span: Span) -> MultiSpan { MultiSpan { primary_spans: vec![primary_span], - span_labels: vec![], + span_labels: Vec::new(), } } pub fn from_spans(vec: Vec) -> MultiSpan { MultiSpan { primary_spans: vec, - span_labels: vec![], + span_labels: Vec::new(), } } diff --git a/crates/swc_common/src/syntax_pos/analyze_source_file.rs b/crates/swc_common/src/syntax_pos/analyze_source_file.rs index 1e81ec45289..89029e22dba 100644 --- a/crates/swc_common/src/syntax_pos/analyze_source_file.rs +++ b/crates/swc_common/src/syntax_pos/analyze_source_file.rs @@ -21,8 +21,8 @@ pub fn analyze_source_file( source_file_start_pos: BytePos, ) -> (Vec, Vec, Vec) { let mut lines = vec![source_file_start_pos]; - let mut multi_byte_chars = vec![]; - let mut non_narrow_chars = vec![]; + let mut multi_byte_chars = Vec::new(); + let mut non_narrow_chars = Vec::new(); // Calls the right implementation, depending on hardware support available. analyze_source_file_generic( @@ -178,9 +178,9 @@ mod tests { case: empty_text, text: "", source_file_start_pos: 0, - lines: vec![], - multi_byte_chars: vec![], - non_narrow_chars: vec![], + lines: Vec::new(), + multi_byte_chars: Vec::new(), + non_narrow_chars: Vec::new(), ); test!( @@ -188,8 +188,8 @@ mod tests { text: "a\nc", source_file_start_pos: 0, lines: vec![0, 2], - multi_byte_chars: vec![], - non_narrow_chars: vec![], + multi_byte_chars: Vec::new(), + non_narrow_chars: Vec::new(), ); test!( @@ -197,8 +197,8 @@ mod tests { text: "012345678\nabcdef012345678\na", source_file_start_pos: 0, lines: vec![0, 10, 26], - multi_byte_chars: vec![], - non_narrow_chars: vec![], + multi_byte_chars: Vec::new(), + non_narrow_chars: Vec::new(), ); test!( @@ -207,7 +207,7 @@ mod tests { source_file_start_pos: 0, lines: vec![0, 11], multi_byte_chars: vec![(5, 2)], - non_narrow_chars: vec![], + non_narrow_chars: Vec::new(), ); test!( @@ -215,7 +215,7 @@ mod tests { text: "01234\u{07}6789\nbcdef0123456789abcdef", source_file_start_pos: 0, lines: vec![0, 11], - multi_byte_chars: vec![], + multi_byte_chars: Vec::new(), non_narrow_chars: vec![(5, 0)], ); @@ -225,7 +225,7 @@ mod tests { source_file_start_pos: 0, lines: vec![0], multi_byte_chars: vec![(1, 2)], - non_narrow_chars: vec![], + non_narrow_chars: Vec::new(), ); test!( @@ -234,7 +234,7 @@ mod tests { source_file_start_pos: 0, lines: vec![0], multi_byte_chars: vec![(13, 2), (22, 2)], - non_narrow_chars: vec![], + non_narrow_chars: Vec::new(), ); test!( @@ -243,7 +243,7 @@ mod tests { source_file_start_pos: 0, lines: vec![0], multi_byte_chars: vec![(15, 2)], - non_narrow_chars: vec![], + non_narrow_chars: Vec::new(), ); test!( @@ -252,7 +252,7 @@ mod tests { source_file_start_pos: 0, lines: vec![0], multi_byte_chars: vec![(15, 2)], - non_narrow_chars: vec![], + non_narrow_chars: Vec::new(), ); test!( @@ -260,7 +260,7 @@ mod tests { text: "0\t2", source_file_start_pos: 0, lines: vec![0], - multi_byte_chars: vec![], + multi_byte_chars: Vec::new(), non_narrow_chars: vec![(1, 4)], ); @@ -269,7 +269,7 @@ mod tests { text: "01\t3456789abcdef01234567\u{07}9", source_file_start_pos: 0, lines: vec![0], - multi_byte_chars: vec![], + multi_byte_chars: Vec::new(), non_narrow_chars: vec![(2, 4), (24, 0)], ); @@ -287,8 +287,8 @@ mod tests { text: "/**\n * foo\n */\n012345678\nabcdef012345678\na", source_file_start_pos: 0, lines: vec![0, 4, 11, 15, 25, 41], - multi_byte_chars: vec![], - non_narrow_chars: vec![], + multi_byte_chars: Vec::new(), + non_narrow_chars: Vec::new(), ); test!( @@ -296,8 +296,8 @@ mod tests { text: "/**\r * foo\r */\r012345678\rabcdef012345678\ra", source_file_start_pos: 0, lines: vec![0, 4, 11, 15, 25, 41], - multi_byte_chars: vec![], - non_narrow_chars: vec![], + multi_byte_chars: Vec::new(), + non_narrow_chars: Vec::new(), ); test!( @@ -305,7 +305,7 @@ mod tests { text: "/**\r\n * foo\r\n */\r\n012345678\r\nabcdef012345678\r\na", source_file_start_pos: 0, lines: vec![0, 5, 13, 18, 29, 46], - multi_byte_chars: vec![], - non_narrow_chars: vec![], + multi_byte_chars: Vec::new(), + non_narrow_chars: Vec::new(), ); } diff --git a/crates/swc_common/src/util/take.rs b/crates/swc_common/src/util/take.rs index ae067258432..38c16ea196c 100644 --- a/crates/swc_common/src/util/take.rs +++ b/crates/swc_common/src/util/take.rs @@ -45,7 +45,7 @@ where impl Take for Vec { fn dummy() -> Self { - vec![] + Vec::new() } } diff --git a/crates/swc_compiler_base/Cargo.toml b/crates/swc_compiler_base/Cargo.toml index a0dcc587156..fab6b0d5703 100644 --- a/crates/swc_compiler_base/Cargo.toml +++ b/crates/swc_compiler_base/Cargo.toml @@ -13,14 +13,15 @@ version = "0.15.0" node = ["napi", "napi-derive"] [dependencies] -anyhow = { workspace = true } -base64 = { workspace = true } -once_cell = { workspace = true } -pathdiff = { workspace = true } -rustc-hash = { workspace = true } -serde = { workspace = true, features = ["derive"] } -serde_json = { workspace = true } -sourcemap = { workspace = true } +anyhow = { workspace = true } +base64 = { workspace = true } +once_cell = { workspace = true } +pathdiff = { workspace = true } +rustc-hash = { workspace = true } +serde = { workspace = true, features = ["derive"] } +serde_json = { 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_common = { version = "0.36.0", path = "../swc_common", features = [ diff --git a/crates/swc_compiler_base/src/lib.rs b/crates/swc_compiler_base/src/lib.rs index 2def122b13b..ba870df5cac 100644 --- a/crates/swc_compiler_base/src/lib.rs +++ b/crates/swc_compiler_base/src/lib.rs @@ -65,7 +65,7 @@ pub fn parse_js( let mut res = (|| { let mut error = false; - let mut errors = vec![]; + let mut errors = std::vec::Vec::new(); let program_result = match is_module { IsModule::Bool(true) => { parse_file_as_module(&fm, syntax, target, comments, &mut errors) @@ -171,10 +171,10 @@ where { let _timer = timer!("Compiler::print"); - let mut src_map_buf = vec![]; + let mut src_map_buf = Vec::new(); let src = { - let mut buf = vec![]; + let mut buf = std::vec::Vec::new(); { let mut w = swc_ecma_codegen::text_writer::JsWriter::new( cm.clone(), @@ -241,7 +241,7 @@ where let (code, map) = match source_map { SourceMapsConfig::Bool(v) => { if v { - let mut buf = vec![]; + let mut buf = std::vec::Vec::new(); map.unwrap() .to_writer(&mut buf) @@ -254,7 +254,7 @@ where } SourceMapsConfig::Str(_) => { let mut src = src; - let mut buf = vec![]; + let mut buf = std::vec::Vec::new(); map.unwrap() .to_writer(&mut buf) @@ -346,7 +346,7 @@ pub fn minify_file_comments( BoolOr::Bool(true) | BoolOr::Data(JsMinifyCommentOption::PreserveAllComments) => {} BoolOr::Data(JsMinifyCommentOption::PreserveSomeComments) => { - let preserve_excl = |_: &BytePos, vc: &mut Vec| -> bool { + let preserve_excl = |_: &BytePos, vc: &mut std::vec::Vec| -> bool { // Preserve license comments. // // See https://github.com/terser/terser/blob/798135e04baddd94fea403cfaab4ba8b22b1b524/lib/output.js#L175-L181 diff --git a/crates/swc_css_codegen/src/writer/basic.rs b/crates/swc_css_codegen/src/writer/basic.rs index c9a1a227769..3b7accf1ecb 100644 --- a/crates/swc_css_codegen/src/writer/basic.rs +++ b/crates/swc_css_codegen/src/writer/basic.rs @@ -242,7 +242,7 @@ where } fn compute_line_starts(s: &str) -> Vec { - let mut res = vec![]; + let mut res = Vec::new(); let mut line_start = 0; let mut chars = s.char_indices().peekable(); diff --git a/crates/swc_css_codegen/tests/fixture.rs b/crates/swc_css_codegen/tests/fixture.rs index 174c57e7bf3..d4b273b86ff 100644 --- a/crates/swc_css_codegen/tests/fixture.rs +++ b/crates/swc_css_codegen/tests/fixture.rs @@ -45,7 +45,7 @@ fn run(input: &Path, minify: bool) { eprintln!("==== ==== Input ==== ====\n{}\n", fm.src); - let mut errors = vec![]; + let mut errors = Vec::new(); let mut stylesheet: Stylesheet = 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 src_map_buf = vec![]; + // let mut src_map_buf = Vec::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 mut source_map_output: Vec = vec![]; + // let mut source_map_output: Vec = Vec::new(); // source_map.to_writer(&mut source_map_output).unwrap(); // 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"); @@ -86,7 +86,7 @@ fn run(input: &Path, minify: bool) { return Ok(()); } - let mut errors = vec![]; + let mut errors = Vec::new(); let mut stylesheet_output: Stylesheet = parse_file(&fm_output, None, Default::default(), &mut errors).map_err(|err| { err.to_diagnostics(&handler).emit(); @@ -353,7 +353,7 @@ fn indent_type(input: PathBuf) { let comments = SingleThreadedComments::default(); - let mut errors = vec![]; + let mut errors = Vec::new(); let mut stylesheet: Stylesheet = parse_file(&fm, Some(&comments), Default::default(), &mut errors).unwrap(); @@ -385,7 +385,7 @@ fn indent_type(input: PathBuf) { .compare_to_file(output) .unwrap(); - let mut errors = vec![]; + let mut errors = Vec::new(); let mut stylesheet_output: Stylesheet = parse_file(&fm_output, Some(&comments), Default::default(), &mut errors).map_err( |err| { @@ -422,7 +422,7 @@ fn indent_width(input: PathBuf) { eprintln!("==== ==== Input ==== ====\n{}\n", fm.src); - let mut errors = vec![]; + let mut errors = Vec::new(); let mut stylesheet: Stylesheet = parse_file(&fm, Some(&comments), Default::default(), &mut errors).unwrap(); @@ -454,7 +454,7 @@ fn indent_width(input: PathBuf) { .compare_to_file(output) .unwrap(); - let mut errors = vec![]; + let mut errors = Vec::new(); let mut stylesheet_output: Stylesheet = parse_file(&fm_output, Some(&comments), Default::default(), &mut errors).map_err( |err| { @@ -491,7 +491,7 @@ fn linefeed_lf(input: PathBuf) { eprintln!("==== ==== Input ==== ====\n{}\n", fm.src); - let mut errors = vec![]; + let mut errors = Vec::new(); let mut stylesheet: Stylesheet = parse_file(&fm, Some(&comments), Default::default(), &mut errors).unwrap(); @@ -525,7 +525,7 @@ fn linefeed_lf(input: PathBuf) { .compare_to_file(output) .unwrap(); - let mut errors = vec![]; + let mut errors = Vec::new(); let mut stylesheet_output: Stylesheet = parse_file(&fm_output, Some(&comments), Default::default(), &mut errors).map_err( |err| { @@ -562,7 +562,7 @@ fn linefeed_crlf(input: PathBuf) { eprintln!("==== ==== Input ==== ====\n{}\n", fm.src); - let mut errors = vec![]; + let mut errors = Vec::new(); let mut stylesheet: Stylesheet = parse_file(&fm, Some(&comments), Default::default(), &mut errors).unwrap(); @@ -596,7 +596,7 @@ fn linefeed_crlf(input: PathBuf) { .compare_to_file(output) .unwrap(); - let mut errors = vec![]; + let mut errors = Vec::new(); let mut stylesheet_output: Stylesheet = parse_file(&fm_output, Some(&comments), Default::default(), &mut errors).map_err( |err| { @@ -629,7 +629,7 @@ fn parse_again(input: PathBuf) { eprintln!("==== ==== Input ==== ====\n{}\n", fm.src); - let mut errors = vec![]; + let mut errors = Vec::new(); let mut stylesheet: Stylesheet = parse_file(&fm, Some(&comments), Default::default(), &mut errors).map_err(|err| { err.to_diagnostics(&handler).emit(); @@ -650,7 +650,7 @@ fn parse_again(input: PathBuf) { eprintln!("==== ==== Codegen ==== ====\n{}\n", 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( &new_fm, Some(&comments), diff --git a/crates/swc_css_compat/src/compiler/custom_media.rs b/crates/swc_css_compat/src/compiler/custom_media.rs index c33e2a34f96..6eb668c4ccd 100644 --- a/crates/swc_css_compat/src/compiler/custom_media.rs +++ b/crates/swc_css_compat/src/compiler/custom_media.rs @@ -68,7 +68,7 @@ impl CustomMediaHandler { } 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() { match node { @@ -155,7 +155,7 @@ impl CustomMediaHandler { &mut self, 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() { match node { @@ -233,7 +233,7 @@ impl CustomMediaHandler { if let Some(custom_media) = self.medias.iter().find(|m| m.name.value == name.value) { let mut new_media_condition = MediaCondition { span: DUMMY_SP, - conditions: vec![], + conditions: Vec::new(), }; let queries = match &custom_media.media { @@ -370,7 +370,7 @@ impl CustomMediaHandler { ) -> MediaCondition { let mut new_media_condition = MediaCondition { span: DUMMY_SP, - conditions: vec![], + conditions: Vec::new(), }; for n in &media_condition.conditions { diff --git a/crates/swc_css_compat/src/compiler/mod.rs b/crates/swc_css_compat/src/compiler/mod.rs index 00dc41a9793..3e67def13fc 100644 --- a/crates/swc_css_compat/src/compiler/mod.rs +++ b/crates/swc_css_compat/src/compiler/mod.rs @@ -89,7 +89,7 @@ impl VisitMut for Compiler { fn visit_mut_rules(&mut self, n: &mut Vec) { if self.c.process.contains(Features::NESTING) { - let mut new = vec![]; + let mut new = Vec::new(); for n in n.take() { match n { diff --git a/crates/swc_css_compat/src/compiler/nesting.rs b/crates/swc_css_compat/src/compiler/nesting.rs index 6b3e0153901..fd72afc380b 100644 --- a/crates/swc_css_compat/src/compiler/nesting.rs +++ b/crates/swc_css_compat/src/compiler/nesting.rs @@ -19,7 +19,7 @@ impl Compiler { { for c in children { if let PseudoClassSelectorChildren::ForgivingSelectorList(c) = c { - let mut selectors = vec![]; + let mut selectors = Vec::new(); for sel in &mut c.children { match sel { @@ -53,7 +53,7 @@ impl Compiler { prelude: &SelectorList, selectors: &mut Vec, ) { - let mut new_selectors = vec![]; + let mut new_selectors = Vec::new(); 'complex: for complex in selectors.take() { for compound in &complex.children { @@ -142,7 +142,7 @@ impl Compiler { base: &SelectorList, relative_selector_list: &RelativeSelectorList, ) -> SelectorList { - let mut children = vec![]; + let mut children = Vec::new(); for base_complex in &base.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 { - let mut nested_rules = vec![]; - let mut block_values = vec![]; + let mut nested_rules = Vec::new(); + let mut block_values = Vec::new(); for value in rule.block.value.take() { match value { @@ -242,8 +242,8 @@ impl Compiler { ) = at_rule.prelude.as_deref() { if let Some(block) = &at_rule.block { - let mut decls_of_media = vec![]; - let mut nested_of_media = vec![]; + let mut decls_of_media = Vec::new(); + let mut nested_of_media = Vec::new(); for n in &block.value { match n { diff --git a/crates/swc_css_compat/tests/fixture.rs b/crates/swc_css_compat/tests/fixture.rs index c4eb6d2badb..3c6e3b11199 100644 --- a/crates/swc_css_compat/tests/fixture.rs +++ b/crates/swc_css_compat/tests/fixture.rs @@ -22,7 +22,7 @@ use swc_css_visit::VisitMutWith; use testing::NormalizedOutput; fn parse_stylesheet(fm: &Lrc) -> Stylesheet { - let mut errors = vec![]; + let mut errors = Vec::new(); let ss: Stylesheet = parse_file( fm, None, diff --git a/crates/swc_css_lints/src/rules/declaration_no_important.rs b/crates/swc_css_lints/src/rules/declaration_no_important.rs index 852c7458353..51e99576d81 100644 --- a/crates/swc_css_lints/src/rules/declaration_no_important.rs +++ b/crates/swc_css_lints/src/rules/declaration_no_important.rs @@ -9,7 +9,7 @@ pub fn declaration_no_important(ctx: LintRuleContext<()>) -> Box { ctx.reaction(), DeclarationNoImportant { ctx, - keyframe_rules: vec![], + keyframe_rules: Vec::new(), }, ) } diff --git a/crates/swc_css_minifier/benches/full.rs b/crates/swc_css_minifier/benches/full.rs index a33d0f5f766..3d00261cf38 100644 --- a/crates/swc_css_minifier/benches/full.rs +++ b/crates/swc_css_minifier/benches/full.rs @@ -38,7 +38,7 @@ fn run(src: &str) { HANDLER.set(&handler, || { let fm = cm.new_source_file(FileName::Anon.into(), src.into()); - let mut errors = vec![]; + let mut errors = Vec::new(); let mut ss: Stylesheet = parse_file(&fm, None, Default::default(), &mut errors).unwrap(); diff --git a/crates/swc_css_minifier/src/compressor/calc_sum.rs b/crates/swc_css_minifier/src/compressor/calc_sum.rs index 83b2c5098f6..ea30b2a317b 100644 --- a/crates/swc_css_minifier/src/compressor/calc_sum.rs +++ b/crates/swc_css_minifier/src/compressor/calc_sum.rs @@ -36,7 +36,7 @@ fn get_precision(n: f64) -> u32 { // https://www.w3.org/TR/css-values-4/#parse-a-calculation fn collect_calc_sum_into_calc_node(calc_sum: &CalcSum) -> CalcNode { let mut is_negated = false; - let mut operands: Vec = vec![]; + let mut operands: Vec = Vec::new(); for node in &calc_sum.expressions { match &node { 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 { let mut is_inverted = false; - let mut operands: Vec = vec![]; + let mut operands: Vec = Vec::new(); for node in &calc_product.expressions { match &node { CalcValueOrOperator::Value(calc_value) => { @@ -603,7 +603,7 @@ fn try_to_multiply_all_numeric_sum_children_by_value( nodes: &[CalcNode], value: f64, ) -> Option { - let mut operands = vec![]; + let mut operands = Vec::new(); for calc_node in nodes { match calc_node { @@ -837,7 +837,7 @@ fn serialize_calculation_node_into_calc_sum(calc_node: &CalcNode) -> CalcSum { }, CalcNode::OperatorNode(op) => match &**op { CalcOperatorNode::Sum(nodes) => { - let mut expr: Vec = vec![]; + let mut expr: Vec = Vec::new(); 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(), }), CalcOperatorNode::Product(nodes) => { - let mut expr: Vec = vec![]; + let mut expr: Vec = Vec::new(); 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 // (instead of only one) fn sort_calculations_children(nodes: &[CalcNode]) -> Vec { - let mut ret: Vec = vec![]; + let mut ret: Vec = Vec::new(); // If nodes contains a number, remove it from nodes and append it to ret. let mut numbers: Vec = nodes diff --git a/crates/swc_css_minifier/src/compressor/rules.rs b/crates/swc_css_minifier/src/compressor/rules.rs index 5ac920456bc..874c3ab429c 100644 --- a/crates/swc_css_minifier/src/compressor/rules.rs +++ b/crates/swc_css_minifier/src/compressor/rules.rs @@ -374,7 +374,7 @@ impl Compressor { pub(super) fn compress_stylesheet(&mut self, stylesheet: &mut Stylesheet) { let mut names: AHashMap = Default::default(); let mut prev_rule_idx = None; - let mut remove_rules_list = vec![]; + let mut remove_rules_list = Vec::new(); let mut prev_index = 0; 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) { let mut names: AHashMap = Default::default(); let mut prev_rule_idx = None; - let mut remove_rules_list = vec![]; + let mut remove_rules_list = Vec::new(); let mut prev_index = 0; for index in 0..simple_block.value.len() { diff --git a/crates/swc_css_minifier/src/util.rs b/crates/swc_css_minifier/src/util.rs index b08b2783442..bdd87adf361 100644 --- a/crates/swc_css_minifier/src/util.rs +++ b/crates/swc_css_minifier/src/util.rs @@ -6,7 +6,7 @@ pub(crate) fn dedup(v: &mut Vec) where T: EqIgnoreSpan, { - let mut remove_list = vec![]; + let mut remove_list = Vec::new(); for (i, i1) in v.iter().enumerate() { for (j, j1) in v.iter().enumerate() { diff --git a/crates/swc_css_minifier/tests/fixture.rs b/crates/swc_css_minifier/tests/fixture.rs index af17cafa3eb..43e0eb13a9f 100644 --- a/crates/swc_css_minifier/tests/fixture.rs +++ b/crates/swc_css_minifier/tests/fixture.rs @@ -20,7 +20,7 @@ fn minify_fixtures(input: PathBuf) { testing::run_test(false, |cm, handler| { let fm = cm.load_file(&input).unwrap(); - let mut errors = vec![]; + let mut errors = Vec::new(); let res: Result = parse_file(&fm, None, Default::default(), &mut errors); for err in errors { diff --git a/crates/swc_css_modules/src/lib.rs b/crates/swc_css_modules/src/lib.rs index 8137ed799e3..3aff45b5663 100644 --- a/crates/swc_css_modules/src/lib.rs +++ b/crates/swc_css_modules/src/lib.rs @@ -61,7 +61,7 @@ pub fn compile<'a>(ss: &mut Stylesheet, config: impl 'a + TransformConfig) -> Tr ss.visit_mut_with(&mut compiler); 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(); diff --git a/crates/swc_css_modules/tests/fixture.rs b/crates/swc_css_modules/tests/fixture.rs index 6294a8e81bb..3a32be73997 100644 --- a/crates/swc_css_modules/tests/fixture.rs +++ b/crates/swc_css_modules/tests/fixture.rs @@ -15,7 +15,7 @@ use testing::NormalizedOutput; fn imports(input: PathBuf) { testing::run_test(false, |cm, _| { let fm = cm.load_file(&input).unwrap(); - let mut errors = vec![]; + let mut errors = Vec::new(); let ss = swc_css_parser::parse_file( &fm, None, @@ -49,7 +49,7 @@ fn imports(input: PathBuf) { fn compile(input: PathBuf) { testing::run_test(false, |cm, _| { let fm = cm.load_file(&input).unwrap(); - let mut errors = vec![]; + let mut errors = Vec::new(); let mut ss = swc_css_parser::parse_file( &fm, None, diff --git a/crates/swc_css_modules/tests/with_compat.rs b/crates/swc_css_modules/tests/with_compat.rs index e569c076b8c..4ac38a77177 100644 --- a/crates/swc_css_modules/tests/with_compat.rs +++ b/crates/swc_css_modules/tests/with_compat.rs @@ -31,7 +31,7 @@ fn test_full(input: PathBuf, suffix: Option<&str>) { testing::run_test2(false, |cm, handler| { // let fm = cm.load_file(&input).unwrap(); - let mut errors = vec![]; + let mut errors = Vec::new(); let mut ss: Stylesheet = parse_file( &fm, None, diff --git a/crates/swc_css_parser/src/parser/at_rules/mod.rs b/crates/swc_css_parser/src/parser/at_rules/mod.rs index 9cfe996cc4f..300b091ea08 100644 --- a/crates/swc_css_parser/src/parser/at_rules/mod.rs +++ b/crates/swc_css_parser/src/parser/at_rules/mod.rs @@ -225,7 +225,7 @@ where self.input.skip_ws(); if is!(self, Ident) { - let mut name_list: Vec = vec![]; + let mut name_list: Vec = Vec::new(); name_list.push(self.parse()?); @@ -976,7 +976,7 @@ where fn parse(&mut self) -> PResult { let start_pos = self.input.cur_span().lo; let mut last_pos; - let mut conditions = vec![]; + let mut conditions = Vec::new(); if is_case_insensitive_ident!(self, "not") { let not = self.parse()?; @@ -1462,7 +1462,7 @@ where fn parse(&mut self) -> PResult { let start_pos = self.input.cur_span().lo; let mut last_pos; - let mut conditions = vec![]; + let mut conditions = Vec::new(); if is_case_insensitive_ident!(self, "not") { let not = self.parse()?; @@ -1516,7 +1516,7 @@ where fn parse(&mut self) -> PResult { let start_pos = self.input.cur_span().lo; let mut last_pos; - let mut conditions = vec![]; + let mut conditions = Vec::new(); if is_case_insensitive_ident!(self, "not") { let not = self.parse()?; @@ -1978,7 +1978,7 @@ where }; let pseudos = if is!(self, ":") { - let mut pseudos = vec![]; + let mut pseudos = Vec::new(); loop { if !is!(self, ":") { @@ -2058,7 +2058,7 @@ where { fn parse(&mut self) -> PResult { let start = self.input.cur_span().lo; - let mut name = vec![]; + let mut name = Vec::new(); while is!(self, Ident) { name.push(self.parse()?); @@ -2128,7 +2128,7 @@ where let start_pos = self.input.cur_span().lo; let mut last_pos; - let mut queries = vec![]; + let mut queries = Vec::new(); if is_case_insensitive_ident!(self, "not") { let not = self.parse()?; diff --git a/crates/swc_css_parser/src/parser/input.rs b/crates/swc_css_parser/src/parser/input.rs index b0a2d94673c..0ab56b18c90 100644 --- a/crates/swc_css_parser/src/parser/input.rs +++ b/crates/swc_css_parser/src/parser/input.rs @@ -463,7 +463,7 @@ impl<'a> ParserInput for Input<'a> { } fn take_errors(&mut self) -> Vec { - vec![] + Vec::new() } fn skip_ws(&mut self) -> Option { diff --git a/crates/swc_css_parser/src/parser/selectors/mod.rs b/crates/swc_css_parser/src/parser/selectors/mod.rs index c923a8818d2..9e50d65cc0c 100644 --- a/crates/swc_css_parser/src/parser/selectors/mod.rs +++ b/crates/swc_css_parser/src/parser/selectors/mod.rs @@ -68,7 +68,7 @@ where parser.input.reset(&state); let span = parser.input.cur_span(); - let mut children = vec![]; + let mut children = Vec::new(); while !is_one_of!(parser, EOF, ",", ")") { if let Some(token_and_span) = parser.input.bump() { @@ -223,7 +223,7 @@ where parser.input.reset(&state); let span = parser.input.cur_span(); - let mut children = vec![]; + let mut children = Vec::new(); while !is_one_of!(parser, EOF, ",", ")") { if let Some(token_and_span) = parser.input.bump() { @@ -420,7 +420,7 @@ where } else { None }; - let mut subclass_selectors = vec![]; + let mut subclass_selectors = Vec::new(); loop { if !(is!(self, "#") @@ -857,7 +857,7 @@ where let state = self.input.state(); let mut parse_pseudo_class_children = || -> PResult> { - let mut children = vec![]; + let mut children = Vec::new(); match &*names.0 { "local" | "global" if self.config.css_modules => { @@ -1090,7 +1090,7 @@ where let state = self.input.state(); let mut parse_pseudo_element_children = || -> PResult> { - let mut children = vec![]; + let mut children = Vec::new(); match &*names.0 { "cue" | "cue-region" => { diff --git a/crates/swc_css_parser/src/parser/syntax/mod.rs b/crates/swc_css_parser/src/parser/syntax/mod.rs index 42e66f94bde..e21e1b93c78 100644 --- a/crates/swc_css_parser/src/parser/syntax/mod.rs +++ b/crates/swc_css_parser/src/parser/syntax/mod.rs @@ -43,7 +43,7 @@ where // To consume a list of rules, given a top-level flag: // Create an initially empty list of rules. - let mut rules = vec![]; + let mut rules = Vec::new(); // Repeatedly consume the next input token: @@ -107,7 +107,7 @@ where let span = self.input.cur_span(); let mut list_of_component_values = ListOfComponentValues { span: Default::default(), - children: vec![], + children: Vec::new(), }; while !is_one_of!(self, EOF) { @@ -161,7 +161,7 @@ where raw: Some(at_keyword_name.1), }) }; - let mut prelude = vec![]; + let mut prelude = Vec::new(); let mut at_rule = AtRule { span: Default::default(), name, @@ -256,7 +256,7 @@ where // Create a new qualified rule with its prelude initially set to an empty list, // and its value initially set to nothing. let span = self.input.cur_span(); - let mut prelude = vec![]; + let mut prelude = Vec::new(); // Repeatedly consume the next input token: loop { @@ -323,8 +323,8 @@ where I: ParserInput, { fn parse(&mut self) -> PResult> { - let mut declarations = vec![]; - let mut rules = vec![]; + let mut declarations = Vec::new(); + let mut rules = Vec::new(); loop { // @@ -393,7 +393,7 @@ where let span = self.input.cur_span(); let mut temporary_list = ListOfComponentValues { span: Default::default(), - children: vec![], + children: Vec::new(), }; while !is_one_of!(self, ";", EOF) { @@ -443,7 +443,7 @@ where // For recovery mode let mut list_of_component_values = ListOfComponentValues { span: Default::default(), - children: vec![], + children: Vec::new(), }; while !is_one_of!(self, ";", EOF) { @@ -471,7 +471,7 @@ where { fn parse(&mut self) -> PResult> { // Create an initially empty list of declarations. - let mut declarations = vec![]; + let mut declarations = Vec::new(); // Repeatedly consume the next input token: loop { @@ -527,7 +527,7 @@ where let span = self.input.cur_span(); let mut temporary_list = ListOfComponentValues { span: Default::default(), - children: vec![], + children: Vec::new(), }; while !is_one_of!(self, ";", EOF) { @@ -568,7 +568,7 @@ where // For recovery mode let mut list_of_component_values = ListOfComponentValues { span: Default::default(), - children: vec![], + children: Vec::new(), }; while !is_one_of!(self, ";", EOF) { @@ -630,7 +630,7 @@ where let mut declaration = Declaration { span: Default::default(), name, - value: vec![], + value: Vec::new(), important: None, }; @@ -852,7 +852,7 @@ where let mut simple_block = SimpleBlock { span: Default::default(), name, - value: vec![], + value: Vec::new(), }; // Repeatedly consume the next input token and process it as follows: @@ -948,7 +948,7 @@ where let mut function = Function { span: Default::default(), name, - value: vec![], + value: Vec::new(), }; // Repeatedly consume the next input token and process it as follows: @@ -1000,7 +1000,7 @@ where { fn parse(&mut self) -> PResult { let span = self.input.cur_span(); - let mut children = vec![]; + let mut children = Vec::new(); // Repeatedly consume a component value from input until an is // returned, appending the returned values (except the final ) into a diff --git a/crates/swc_css_parser/src/parser/util.rs b/crates/swc_css_parser/src/parser/util.rs index b47da94b2c7..eebb3e4480d 100644 --- a/crates/swc_css_parser/src/parser/util.rs +++ b/crates/swc_css_parser/src/parser/util.rs @@ -287,7 +287,7 @@ where let locv = self.create_locv(declaration.value); let value = self.parse_according_to_grammar(&locv, |parser| { - let mut values = vec![]; + let mut values = Vec::new(); loop { if is!(parser, EOF) { @@ -336,7 +336,7 @@ where pub(super) fn try_to_parse_declaration_in_parens(&mut self) -> Option { let mut temporary_list = ListOfComponentValues { span: Default::default(), - children: vec![], + children: Vec::new(), }; while !is_one_of!(self, ")", EOF) { diff --git a/crates/swc_css_parser/src/parser/values_and_units/mod.rs b/crates/swc_css_parser/src/parser/values_and_units/mod.rs index a9e4cb0490c..b5f3e1e70f0 100644 --- a/crates/swc_css_parser/src/parser/values_and_units/mod.rs +++ b/crates/swc_css_parser/src/parser/values_and_units/mod.rs @@ -13,7 +13,7 @@ where I: ParserInput, { pub(super) fn parse_generic_values(&mut self) -> PResult> { - let mut values = vec![]; + let mut values = Vec::new(); loop { self.input.skip_ws(); @@ -119,8 +119,8 @@ where /// Parse value as . pub(super) fn parse_any_value(&mut self) -> PResult> { - let mut tokens = vec![]; - let mut balance_stack: Vec> = vec![]; + let mut tokens = Vec::new(); + let mut balance_stack: Vec> = Vec::new(); // The production matches any sequence of one or more tokens, // 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(); @@ -2628,7 +2628,7 @@ where self.input.skip_ws(); - let mut modifiers = vec![]; + let mut modifiers = Vec::new(); loop { if is!(self, ")") { @@ -3042,7 +3042,7 @@ where { fn parse(&mut self) -> PResult { let start = self.input.cur_span().lo; - let mut expressions = vec![]; + let mut expressions = Vec::new(); let calc_product = CalcProductOrOperator::Product(self.parse()?); let mut end = match calc_product { CalcProductOrOperator::Product(ref calc_product) => calc_product.span.hi, @@ -3098,7 +3098,7 @@ where { fn parse(&mut self) -> PResult { let start = self.input.cur_span().lo; - let mut expressions = vec![]; + let mut expressions = Vec::new(); let calc_value = CalcValueOrOperator::Value(self.parse()?); let mut end = match calc_value { CalcValueOrOperator::Value(ref calc_value) => match calc_value { diff --git a/crates/swc_css_parser/tests/fixture.rs b/crates/swc_css_parser/tests/fixture.rs index 9798288da14..a0e5db5a5ff 100644 --- a/crates/swc_css_parser/tests/fixture.rs +++ b/crates/swc_css_parser/tests/fixture.rs @@ -82,10 +82,10 @@ fn stylesheet_test_tokens(input: PathBuf, config: ParserConfig) { testing::run_test2(false, |cm, handler| { let fm = cm.load_file(&input).unwrap(); - let mut errors = vec![]; + let mut errors = Vec::new(); let tokens = { 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() { 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 mut lexer_errors = vec![]; + let mut lexer_errors = Vec::new(); let tokens = { 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() { 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 = parse_input(InputType::Tokens(&tokens), config, &mut parser_errors); diff --git a/crates/swc_css_prefixer/src/prefixer.rs b/crates/swc_css_prefixer/src/prefixer.rs index 292060b1516..caeef9aae3d 100644 --- a/crates/swc_css_prefixer/src/prefixer.rs +++ b/crates/swc_css_prefixer/src/prefixer.rs @@ -125,7 +125,7 @@ impl VisitMut for CrossFadeFunctionReplacerOnLegacyVariant<'_> { n.visit_mut_children_with(self); if n.name == *self.from { - let mut transparency_values = vec![]; + let mut transparency_values = Vec::new(); for group in n.value.split_mut(|n| { matches!( @@ -262,7 +262,7 @@ impl VisitMut for ImageSetFunctionReplacerOnLegacyVariant<'_> { value: node.value.as_ref().into(), 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) { - 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 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) { 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 { if should_prefix("-webkit-min-device-pixel-ratio", self.env, false) { diff --git a/crates/swc_css_prefixer/tests/prefixer.rs b/crates/swc_css_prefixer/tests/prefixer.rs index 67a65220dd4..d3828461fea 100644 --- a/crates/swc_css_prefixer/tests/prefixer.rs +++ b/crates/swc_css_prefixer/tests/prefixer.rs @@ -28,7 +28,7 @@ fn prefix(input: PathBuf, options: Options, suffix: Option<&str>) { testing::run_test2(false, |cm, handler| { // let fm = cm.load_file(&input).unwrap(); - let mut errors = vec![]; + let mut errors = Vec::new(); let mut ss: Stylesheet = parse_file( &fm, None, diff --git a/crates/swc_ecma_ast/src/expr.rs b/crates/swc_ecma_ast/src/expr.rs index 489daa80759..11563d040c7 100644 --- a/crates/swc_ecma_ast/src/expr.rs +++ b/crates/swc_ecma_ast/src/expr.rs @@ -528,7 +528,7 @@ impl ObjectLit { /// /// Returns [None] if this is not a valid for `with` of [crate::ImportDecl]. pub fn as_import_with(&self) -> Option { - let mut values = vec![]; + let mut values = Vec::new(); for prop in &self.props { match prop { PropOrSpread::Spread(..) => return None, diff --git a/crates/swc_ecma_ast/src/stmt.rs b/crates/swc_ecma_ast/src/stmt.rs index 32665b359a7..e8469893f8d 100644 --- a/crates/swc_ecma_ast/src/stmt.rs +++ b/crates/swc_ecma_ast/src/stmt.rs @@ -25,7 +25,7 @@ impl Take for BlockStmt { fn dummy() -> Self { BlockStmt { span: DUMMY_SP, - stmts: vec![], + stmts: Vec::new(), ctxt: Default::default(), } } diff --git a/crates/swc_ecma_codegen/Cargo.toml b/crates/swc_ecma_codegen/Cargo.toml index b36f51fe34e..f434fa26e4c 100644 --- a/crates/swc_ecma_codegen/Cargo.toml +++ b/crates/swc_ecma_codegen/Cargo.toml @@ -25,6 +25,7 @@ serde = { workspace = true } sourcemap = { 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_common = { version = "0.36.0", path = "../swc_common" } swc_ecma_ast = { version = "0.117.0", path = "../swc_ecma_ast" } diff --git a/crates/swc_ecma_codegen/benches/bench.rs b/crates/swc_ecma_codegen/benches/bench.rs index 9c820aeeac3..01ffdd3bae7 100644 --- a/crates/swc_ecma_codegen/benches/bench.rs +++ b/crates/swc_ecma_codegen/benches/bench.rs @@ -84,7 +84,6 @@ fn bench_emitter(b: &mut Bencher, s: &str) { let fm = cm.new_source_file(FileName::Anon.into(), s.into()); let mut parser = Parser::new(Syntax::default(), StringInput::from(&*fm), None); - let mut src_map_buf = vec![]; let module = parser .parse_module() .map_err(|e| e.into_diagnostic(handler).emit()) @@ -95,7 +94,8 @@ fn bench_emitter(b: &mut Bencher, s: &str) { } b.iter(|| { - let mut buf = vec![]; + let mut src_map_buf = Vec::new(); + let mut buf = Vec::new(); { let mut emitter = Emitter { cfg: Default::default(), diff --git a/crates/swc_ecma_codegen/benches/with_parse.rs b/crates/swc_ecma_codegen/benches/with_parse.rs index d0ff27b97d6..dc3a2aa7c94 100644 --- a/crates/swc_ecma_codegen/benches/with_parse.rs +++ b/crates/swc_ecma_codegen/benches/with_parse.rs @@ -84,7 +84,6 @@ fn bench_emitter(b: &mut Bencher, s: &str) { b.iter(|| { let fm = cm.new_source_file(FileName::Anon.into(), s.into()); let mut parser = Parser::new(Syntax::default(), StringInput::from(&*fm), None); - let mut src_map_buf = vec![]; let module = parser .parse_module() .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(); } - let mut buf = vec![]; + let mut src_map_buf = Vec::new(); + let mut buf = Vec::new(); { let mut emitter = Emitter { cfg: Default::default(), diff --git a/crates/swc_ecma_codegen/examples/gen.rs b/crates/swc_ecma_codegen/examples/gen.rs index 195f8b05fe0..2a6a9a0d564 100644 --- a/crates/swc_ecma_codegen/examples/gen.rs +++ b/crates/swc_ecma_codegen/examples/gen.rs @@ -24,7 +24,7 @@ fn parse_and_gen(entry: &Path) { .expect("failed to parse input as a module"); let code = { - let mut buf = vec![]; + let mut buf = Vec::new(); { let mut emitter = Emitter { diff --git a/crates/swc_ecma_codegen/examples/sourcemap.rs b/crates/swc_ecma_codegen/examples/sourcemap.rs index e1852208624..09f93cb74eb 100644 --- a/crates/swc_ecma_codegen/examples/sourcemap.rs +++ b/crates/swc_ecma_codegen/examples/sourcemap.rs @@ -29,8 +29,8 @@ fn parse_and_gen(entry: &Path) { .parse_module() .expect("failed to parse input as a module"); - let mut code = vec![]; - let mut srcmap = vec![]; + let mut code = Vec::new(); + let mut srcmap = Vec::new(); { let mut emitter = Emitter { diff --git a/crates/swc_ecma_codegen/src/lib.rs b/crates/swc_ecma_codegen/src/lib.rs index f1a0c7f1bed..3a3e1f3dc09 100644 --- a/crates/swc_ecma_codegen/src/lib.rs +++ b/crates/swc_ecma_codegen/src/lib.rs @@ -44,7 +44,7 @@ pub fn to_code_default( comments: Option<&dyn Comments>, node: &impl Node, ) -> String { - let mut buf = vec![]; + let mut buf = Vec::new(); { let mut emitter = Emitter { cfg: Default::default(), @@ -332,7 +332,7 @@ where formatting_space!(); } - let mut specifiers = vec![]; + let mut specifiers = Vec::new(); let mut emitted_default = false; let mut emitted_ns = false; for specifier in &n.specifiers { @@ -497,7 +497,7 @@ where has_namespace_spec: false, namespace_spec: None, has_named_specs: false, - named_specs: vec![], + named_specs: Vec::new(), }, |mut result, s| match s { ExportSpecifier::Namespace(spec) => { @@ -1290,7 +1290,7 @@ where { let mut left = Some(node); - let mut lefts = vec![]; + let mut lefts = Vec::new(); while let Some(l) = left { lefts.push(l); diff --git a/crates/swc_ecma_codegen/src/tests.rs b/crates/swc_ecma_codegen/src/tests.rs index 3a89dd94d4f..e5486a471c2 100644 --- a/crates/swc_ecma_codegen/src/tests.rs +++ b/crates/swc_ecma_codegen/src/tests.rs @@ -44,7 +44,7 @@ impl Builder { where 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); @@ -974,7 +974,7 @@ fn run_node(code: &str) -> String { JsExecOptions { cache: true, module: false, - args: vec![], + args: Vec::new(), }, ) .expect("failed to execute node.js") diff --git a/crates/swc_ecma_codegen/tests/fixture.rs b/crates/swc_ecma_codegen/tests/fixture.rs index d2146753f24..09a7ed8853e 100644 --- a/crates/swc_ecma_codegen/tests/fixture.rs +++ b/crates/swc_ecma_codegen/tests/fixture.rs @@ -34,11 +34,11 @@ fn run(input: &Path, minify: bool) { }), EsVersion::latest(), None, - &mut vec![], + &mut Vec::new(), ) .expect("failed to parse input as a module"); - let mut buf = vec![]; + let mut buf = Vec::new(); { let mut wr = diff --git a/crates/swc_ecma_codegen/tests/sourcemap.rs b/crates/swc_ecma_codegen/tests/sourcemap.rs index 1fdaec75919..dc8a30cf8ec 100644 --- a/crates/swc_ecma_codegen/tests/sourcemap.rs +++ b/crates/swc_ecma_codegen/tests/sourcemap.rs @@ -288,7 +288,7 @@ fn identity(entry: PathBuf) { "\n\n========== Running codegen test {}\nSource:\n{}\n", file_name, input ); - let mut wr = vec![]; + let mut wr = std::vec::Vec::new(); ::testing::run_test(false, |cm, handler| { let fm = cm.load_file(&entry).expect("failed to load file"); @@ -315,7 +315,7 @@ fn identity(entry: PathBuf) { Some(&comments), ); let mut parser: Parser = 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( @@ -488,7 +488,7 @@ fn assert_eq_same_map(expected: &SourceMap, actual: &SourceMap) { /// Creates a url for https://evanw.github.io/source-map-visualization/ fn visualizer_url(code: &str, map: &SourceMap) -> String { let map = { - let mut buf = vec![]; + let mut buf = std::vec::Vec::new(); map.to_writer(&mut buf).unwrap(); String::from_utf8(buf).unwrap() }; diff --git a/crates/swc_ecma_codegen/tests/test262.rs b/crates/swc_ecma_codegen/tests/test262.rs index 9bd02b6ae1d..8b481a193bb 100644 --- a/crates/swc_ecma_codegen/tests/test262.rs +++ b/crates/swc_ecma_codegen/tests/test262.rs @@ -102,7 +102,7 @@ fn do_test(entry: &Path, minify: bool) { "\n\n========== Running codegen test {}\nSource:\n{}\n", file_name, input ); - let mut wr = vec![]; + let mut wr = Vec::new(); ::testing::run_test(false, |cm, handler| { let src = cm.load_file(entry).expect("failed to load file"); diff --git a/crates/swc_ecma_compat_common/src/macros.rs b/crates/swc_ecma_compat_common/src/macros.rs index 3ea66af7355..2bf89c9a602 100644 --- a/crates/swc_ecma_compat_common/src/macros.rs +++ b/crates/swc_ecma_compat_common/src/macros.rs @@ -77,7 +77,7 @@ macro_rules! impl_visit_mut_fn { let (mut params, body) = self.visit_mut_fn_like( &mut vec![Param { span: DUMMY_SP, - decorators: vec![], + decorators: Vec::new(), pat: *f.param.take(), }], &mut f.body.take().unwrap(), @@ -95,8 +95,9 @@ macro_rules! impl_visit_mut_fn { f.visit_mut_children_with(self); - let (params, body) = self.visit_mut_fn_like(&mut vec![], &mut f.body.take().unwrap()); - debug_assert_eq!(params, vec![]); + let (params, body) = + self.visit_mut_fn_like(&mut Vec::new(), &mut f.body.take().unwrap()); + debug_assert_eq!(params, Vec::new()); f.body = Some(body); } @@ -108,12 +109,12 @@ macro_rules! impl_visit_mut_fn { Some(pat) => self.visit_mut_fn_like( &mut vec![Param { span: DUMMY_SP, - decorators: vec![], + decorators: Vec::new(), pat: pat.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!( params.len() == 0 || params.len() == 1, diff --git a/crates/swc_ecma_compat_es2015/src/arrow.rs b/crates/swc_ecma_compat_es2015/src/arrow.rs index 381ca909f58..1a8a7596e85 100644 --- a/crates/swc_ecma_compat_es2015/src/arrow.rs +++ b/crates/swc_ecma_compat_es2015/src/arrow.rs @@ -138,7 +138,7 @@ impl VisitMut for Arrow { body.visit_mut_with(&mut self.hoister); let fn_expr = Function { - decorators: vec![], + decorators: Vec::new(), span: *span, params, is_async: *is_async, diff --git a/crates/swc_ecma_compat_es2015/src/block_scoping/mod.rs b/crates/swc_ecma_compat_es2015/src/block_scoping/mod.rs index 72fa7357ba7..76508e13fa1 100644 --- a/crates/swc_ecma_compat_es2015/src/block_scoping/mod.rs +++ b/crates/swc_ecma_compat_es2015/src/block_scoping/mod.rs @@ -41,7 +41,7 @@ pub fn block_scoping(unresolved_mark: Mark) -> impl VisitMut + Fold { BlockScoping { unresolved_mark, scope: Default::default(), - vars: vec![], + vars: Vec::new(), var_decl_kind: VarDeclKind::Var, } )) @@ -143,7 +143,7 @@ impl BlockScoping { let mut env_hoister = FnEnvHoister::new(SyntaxContext::empty().apply_mark(self.unresolved_mark)); body_stmt.visit_mut_with(&mut env_hoister); - let mut inits: Vec> = vec![]; + let mut inits: Vec> = Vec::new(); for mut var in env_hoister.to_decl() { 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) { let vars = take(&mut self.vars); n.visit_mut_children_with(self); - debug_assert_eq!(self.vars, vec![]); + debug_assert_eq!(self.vars, Vec::new()); self.vars = vars; } @@ -478,7 +478,7 @@ impl VisitMut for BlockScoping { let kind = ScopeKind::Loop { lexical_var, args, - used: vec![], + used: Vec::new(), mutated: Default::default(), }; @@ -504,7 +504,7 @@ impl VisitMut for BlockScoping { let kind = ScopeKind::Loop { lexical_var: vars, args, - used: vec![], + used: Vec::new(), mutated: Default::default(), }; @@ -530,7 +530,7 @@ impl VisitMut for BlockScoping { let kind = ScopeKind::Loop { lexical_var, args, - used: vec![], + used: Vec::new(), mutated: Default::default(), }; self.visit_mut_with_scope(kind, &mut node.body); diff --git a/crates/swc_ecma_compat_es2015/src/classes/mod.rs b/crates/swc_ecma_compat_es2015/src/classes/mod.rs index 2a36ad07ab4..7a2337a0815 100644 --- a/crates/swc_ecma_compat_es2015/src/classes/mod.rs +++ b/crates/swc_ecma_compat_es2015/src/classes/mod.rs @@ -446,7 +446,7 @@ where (params, vec![super_class.as_arg()], Some(super_param)) } } else { - (vec![], vec![], None) + (Vec::new(), Vec::new(), None) }; let mut stmts = self.class_to_stmts(class_name, super_ident, class); @@ -532,9 +532,9 @@ where class: Box, ) -> Vec { 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; for member in class.body { match member { @@ -632,7 +632,7 @@ where let is_constructor_default = constructor.span.is_dummy(); if is_constructor_default { debug!("Dropping constructor parameters because the constructor is injected"); - constructor.params = vec![]; + constructor.params = Vec::new(); } let mut insert_this = false; @@ -643,7 +643,7 @@ where insert_this |= inserted_this; } - let mut vars = vec![]; + let mut vars = Vec::new(); let mut body = constructor.body.unwrap().stmts; // should we insert `var _this`? @@ -835,7 +835,7 @@ where mut body: Vec, this_mark: Option, ) -> Vec { - let mut vars = vec![]; + let mut vars = Vec::new(); let mut folder = SuperFieldAccessFolder { class_name, vars: &mut vars, @@ -896,7 +896,7 @@ where methods: Vec, ) -> Vec { if methods.is_empty() { - return vec![]; + return Vec::new(); } /// { key: "prop" } @@ -1038,7 +1038,7 @@ where &mut props }; - let mut vars = vec![]; + let mut vars = Vec::new(); let mut folder = SuperFieldAccessFolder { class_name, vars: &mut vars, diff --git a/crates/swc_ecma_compat_es2015/src/computed_props.rs b/crates/swc_ecma_compat_es2015/src/computed_props.rs index c37fc5c4eef..16eee883f22 100644 --- a/crates/swc_ecma_compat_es2015/src/computed_props.rs +++ b/crates/swc_ecma_compat_es2015/src/computed_props.rs @@ -168,7 +168,7 @@ impl VisitMut for ComputedProps { body, is_async: false, is_generator: false, - params: vec![], + params: Vec::new(), ..Default::default() }), ), @@ -210,7 +210,7 @@ impl VisitMut for ComputedProps { op: op!("||"), right: Box::new(Expr::Object(ObjectLit { span, - props: vec![], + props: Vec::new(), })), } .into(), @@ -307,7 +307,7 @@ impl VisitMut for ComputedProps { init: Some( ObjectLit { span: DUMMY_SP, - props: vec![], + props: Vec::new(), } .into(), ), diff --git a/crates/swc_ecma_compat_es2015/src/destructuring.rs b/crates/swc_ecma_compat_es2015/src/destructuring.rs index 47108f1b93e..bc2118a73ef 100644 --- a/crates/swc_ecma_compat_es2015/src/destructuring.rs +++ b/crates/swc_ecma_compat_es2015/src/destructuring.rs @@ -494,8 +494,8 @@ impl Destructuring { ps: &mut Vec, body: &mut BlockStmt, ) -> (Vec, BlockStmt) { - let mut params = vec![]; - let mut decls = vec![]; + let mut params = Vec::new(); + let mut decls = Vec::new(); for param in ps.drain(..) { let span = param.span(); @@ -1077,7 +1077,7 @@ impl Destructuring { let mut folder = AssignFolder { c: self.c, exporting: false, - vars: vec![], + vars: Vec::new(), ignore_return_value: None, }; diff --git a/crates/swc_ecma_compat_es2015/src/for_of.rs b/crates/swc_ecma_compat_es2015/src/for_of.rs index 6803e839836..c04ec264126 100644 --- a/crates/swc_ecma_compat_es2015/src/for_of.rs +++ b/crates/swc_ecma_compat_es2015/src/for_of.rs @@ -298,7 +298,7 @@ impl ForOf { right: CallExpr { span: DUMMY_SP, callee: iterator.as_callee(), - args: vec![], + args: Vec::new(), ..Default::default() } .into(), @@ -426,7 +426,7 @@ impl ForOf { Symbol.iterator )) .as_callee(), - args: vec![], + args: Vec::new(), ..Default::default() }))), definite: false, @@ -457,7 +457,7 @@ impl ForOf { span: DUMMY_SP, // `_iterator.next` callee: iterator.make_member(quote_ident!("next")).as_callee(), - args: vec![], + args: Vec::new(), ..Default::default() })), } @@ -598,7 +598,7 @@ fn make_finally_block( stmts: vec![CallExpr { span: DUMMY_SP, callee: iterator_return.as_callee(), - args: vec![], + args: Vec::new(), ..Default::default() } .into_stmt()], diff --git a/crates/swc_ecma_compat_es2015/src/generator.rs b/crates/swc_ecma_compat_es2015/src/generator.rs index 18d6428ca6a..834c6b0d88a 100644 --- a/crates/swc_ecma_compat_es2015/src/generator.rs +++ b/crates/swc_ecma_compat_es2015/src/generator.rs @@ -98,7 +98,7 @@ impl VisitMut for Wrapper { ..Default::default() } .into(); - let mut stmts = vec![]; + let mut stmts = Vec::new(); if !v.hoisted_vars.is_empty() { stmts.push( VarDecl { @@ -516,7 +516,7 @@ impl VisitMut for Generator { Expr::Seq(node) => { // // flattened version of `visitCommaExpression` - let mut pending_expressions = vec![]; + let mut pending_expressions = Vec::new(); for mut elem in node.exprs.take() { if let Expr::Seq(mut elem) = *elem { @@ -741,7 +741,7 @@ impl VisitMut for Generator { props }) .into_iter() - .fold(vec![], |exprs, property| { + .fold(Vec::new(), |exprs, property| { self.reduce_property(exprs, property, &mut temp) }); @@ -1117,7 +1117,7 @@ impl Generator { .iter_mut() .skip(num_initial_elements) .map(|v| v.take()) - .fold(vec![], |exprs, element| { + .fold(Vec::new(), |exprs, element| { self.reduce_element(exprs, element, &mut leading_element, &mut temp) }); @@ -1285,7 +1285,7 @@ impl Generator { .map(|g| KeyValueProp { key: quote_ident!("get").into(), value: Function { - params: vec![], + params: Vec::new(), span: g.span, body: g.body, is_generator: false, @@ -1504,7 +1504,7 @@ impl Generator { let mut variables = self.get_initialized_variables(&mut node); let var_len = variables.len(); let mut variables_written = 0; - let mut pending_expressions = vec![]; + let mut pending_expressions = Vec::new(); let mut cnt = 0; while variables_written < var_len { @@ -1976,7 +1976,7 @@ impl Generator { // `yield` in its expression, up to the next case clause // with a `yield` in its expression. let mut clauses_written = 0; - let mut pending_clauses = vec![]; + let mut pending_clauses = Vec::new(); while clauses_written < node.cases.len() { #[cfg(debug_assertions)] @@ -2354,7 +2354,7 @@ impl Generator { .clone() .make_member(quote_ident!("sent")) .as_callee(), - args: vec![], + args: Vec::new(), ..Default::default() } .into(), @@ -2630,7 +2630,7 @@ impl Generator { }; if label_expressions.get(label.0 as usize).is_none() { 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]; @@ -2720,7 +2720,7 @@ impl Generator { .clone() .make_member(quote_ident!("sent")) .as_callee(), - args: vec![], + args: Vec::new(), ..Default::default() } .into() @@ -2831,9 +2831,9 @@ impl Generator { /// - `args`: The optional arguments for the operation. fn emit_worker(&mut self, code: OpCode, args: Option, loc: Option) { if self.operations.is_none() { - self.operations = Some(vec![]); - self.operation_args = Some(vec![]); - self.operation_locs = Some(vec![]); + self.operations = Some(Vec::new()); + self.operation_args = Some(Vec::new()); + self.operation_locs = Some(Vec::new()); } if self.label_offsets.is_none() { // mark entry point @@ -2884,7 +2884,7 @@ impl Generator { return stmts; } - vec![] + Vec::new() } /// Flush the current label and advance to a new label. @@ -3099,7 +3099,7 @@ impl Generator { self.flush_label(); if self.label_numbers.is_none() { - self.label_numbers = Some(vec![]); + self.label_numbers = Some(Vec::new()); } if let Some(v) = self @@ -3114,7 +3114,7 @@ impl Generator { self.label_numbers .as_mut() .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]; diff --git a/crates/swc_ecma_compat_es2015/src/parameters.rs b/crates/swc_ecma_compat_es2015/src/parameters.rs index 86c0c36fa64..91078a1d223 100644 --- a/crates/swc_ecma_compat_es2015/src/parameters.rs +++ b/crates/swc_ecma_compat_es2015/src/parameters.rs @@ -72,11 +72,11 @@ pub struct Config { #[swc_trace] impl Params { fn visit_mut_fn_like(&mut self, ps: &mut Vec, body: &mut BlockStmt, is_setter: bool) { - let mut params = vec![]; - let mut decls = vec![]; - let mut loose_stmt = vec![]; + let mut params = Vec::new(); + let mut decls = Vec::new(); + let mut loose_stmt = Vec::new(); let mut unpack_rest = None; - let mut decls_after_unpack = vec![]; + let mut decls_after_unpack = Vec::new(); let mut after_default = false; @@ -523,7 +523,7 @@ impl VisitMut for Params { if let Some(decls) = decls { if let BlockStmtOrExpr::Expr(v) = body { - let mut stmts = vec![]; + let mut stmts = Vec::new(); prepend_stmt(&mut stmts, decls); stmts.push( ReturnStmt { @@ -544,11 +544,11 @@ impl VisitMut for Params { fn visit_mut_catch_clause(&mut self, f: &mut CatchClause) { f.visit_mut_children_with(self); - let mut params = vec![]; + let mut params = Vec::new(); if f.param.is_some() { params.push(Param { span: DUMMY_SP, - decorators: vec![], + decorators: Vec::new(), pat: f.param.take().unwrap(), }); } @@ -750,10 +750,10 @@ impl VisitMut for Params { f.visit_mut_children_with(self); - let mut params = vec![]; + let mut params = Vec::new(); let mut body = f.body.take().unwrap(); 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); } diff --git a/crates/swc_ecma_compat_es2015/src/spread.rs b/crates/swc_ecma_compat_es2015/src/spread.rs index 75a6bade4b5..1810383df83 100644 --- a/crates/swc_ecma_compat_es2015/src/spread.rs +++ b/crates/swc_ecma_compat_es2015/src/spread.rs @@ -237,8 +237,8 @@ impl Spread { // let mut first_arr = None; - let mut tmp_arr = vec![]; - let mut buf = vec![]; + let mut tmp_arr = Vec::new(); + let mut buf = Vec::new(); let args_len = args.len(); macro_rules! make_arr { @@ -265,8 +265,8 @@ impl Spread { // contiguous slice of non-spread args in an array, which will protect // array args from being flattened. if self.c.loose { - let mut arg_list = vec![]; - let mut current_elems = vec![]; + let mut arg_list = Vec::new(); + let mut current_elems = Vec::new(); for arg in args.flatten() { let expr = arg.expr; match arg.spread { @@ -279,7 +279,7 @@ impl Spread { } .as_arg(), ); - current_elems = vec![]; + current_elems = Vec::new(); } arg_list.push(expr.as_arg()); } @@ -302,7 +302,7 @@ impl Spread { span: DUMMY_SP, callee: ArrayLit { span: DUMMY_SP, - elems: vec![], + elems: Vec::new(), } .make_member(quote_ident!("concat")) .as_callee(), @@ -391,7 +391,7 @@ impl Spread { span: DUMMY_SP, callee: ArrayLit { span: DUMMY_SP, - elems: vec![], + elems: Vec::new(), } .make_member(quote_ident!("concat")) .as_callee(), @@ -449,7 +449,7 @@ impl Spread { // assert!(args.is_empty()); Expr::Array(ArrayLit { span, - elems: vec![], + elems: Vec::new(), }) }) .make_member(IdentName::new("concat".into(), span)) diff --git a/crates/swc_ecma_compat_es2015/src/template_literal.rs b/crates/swc_ecma_compat_es2015/src/template_literal.rs index cb557ab52d5..3f423ead6b6 100644 --- a/crates/swc_ecma_compat_es2015/src/template_literal.rs +++ b/crates/swc_ecma_compat_es2015/src/template_literal.rs @@ -76,7 +76,7 @@ impl VisitMut for TemplateLiteral { let len = quasis.len() + exprs.len(); - let mut args = vec![]; + let mut args = Vec::new(); let mut quasis = quasis.iter_mut(); let mut exprs = exprs.take().into_iter(); @@ -244,7 +244,7 @@ impl VisitMut for TemplateLiteral { span: DUMMY_SP, is_async: false, is_generator: false, - params: vec![], + params: Vec::new(), body: { // const data = _tagged_template_literal(["first", "second"]); let data_decl = VarDecl { @@ -321,7 +321,7 @@ impl VisitMut for TemplateLiteral { span: DUMMY_SP, is_async: false, is_generator: false, - params: vec![], + params: Vec::new(), body: Some(BlockStmt { span: DUMMY_SP, stmts: vec![Stmt::Return(ReturnStmt { @@ -370,7 +370,7 @@ impl VisitMut for TemplateLiteral { CallExpr { span: DUMMY_SP, callee: fn_ident.as_callee(), - args: vec![], + args: Vec::new(), ..Default::default() } .as_arg(), diff --git a/crates/swc_ecma_compat_es2017/src/async_to_generator.rs b/crates/swc_ecma_compat_es2017/src/async_to_generator.rs index 949abd3c015..be6b1c04f5f 100644 --- a/crates/swc_ecma_compat_es2017/src/async_to_generator.rs +++ b/crates/swc_ecma_compat_es2017/src/async_to_generator.rs @@ -102,8 +102,8 @@ impl AsyncToGenerator { c: self.c, comments: self.comments.clone(), unresolved_ctxt: self.unresolved_ctxt, - extra_stmts: vec![], - hoist_stmts: vec![], + extra_stmts: Vec::new(), + hoist_stmts: Vec::new(), }; stmt.visit_mut_with(&mut actual); @@ -160,7 +160,7 @@ impl VisitMut for Actual { CallExpr { span: DUMMY_SP, callee: expr.as_callee(), - args: vec![], + args: Vec::new(), ..Default::default() } .into(), @@ -263,19 +263,19 @@ impl VisitMut for Actual { let fn_ref = make_fn_ref( Function { - params: vec![], + params: Vec::new(), ..*prop.function.take() } .into(), ); 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 { CallExpr { span: DUMMY_SP, callee: fn_ref.as_callee(), - args: vec![], + args: Vec::new(), ..Default::default() } .into() @@ -583,7 +583,7 @@ fn handle_await_for(stmt: &mut Stmt, is_async_generator: bool) { _ => vec![*s.body], }; - let mut for_loop_body = vec![]; + let mut for_loop_body = Vec::new(); { // let value = _step.value; let value_var = VarDeclarator { @@ -653,7 +653,7 @@ fn handle_await_for(stmt: &mut Stmt, is_async_generator: bool) { ..Default::default() }; - let mut init_var_decls = vec![]; + let mut init_var_decls = Vec::new(); // _iterator = _async_iterator(lol()) init_var_decls.push(VarDeclarator { span: DUMMY_SP, @@ -828,7 +828,7 @@ fn handle_await_for(stmt: &mut Stmt, is_async_generator: bool) { .clone() .make_member(quote_ident!("return")) .as_callee(), - args: vec![], + args: Vec::new(), ..Default::default() } .into(); diff --git a/crates/swc_ecma_compat_es2018/src/object_rest.rs b/crates/swc_ecma_compat_es2018/src/object_rest.rs index bbe8f553df2..e59d970a838 100644 --- a/crates/swc_ecma_compat_es2018/src/object_rest.rs +++ b/crates/swc_ecma_compat_es2018/src/object_rest.rs @@ -281,7 +281,7 @@ impl VisitMut for ObjectRest { .. }) if var_decl.decls.iter().any(|v| v.name.is_object()) => { let specifiers = { - let mut found: Vec = vec![]; + let mut found: Vec = Vec::new(); let mut finder = VarCollector { to: &mut found }; var_decl.visit_with(&mut finder); found @@ -376,7 +376,7 @@ impl VisitMut for ObjectRest { args: vec![ ObjectLit { span: DUMMY_SP, - props: vec![], + props: Vec::new(), } .as_arg(), helper_expr!(object_destructuring_empty) @@ -902,7 +902,7 @@ fn object_without_properties( args: vec![ ObjectLit { span: DUMMY_SP, - props: vec![], + props: Vec::new(), } .as_arg(), helper_expr!(object_destructuring_empty) diff --git a/crates/swc_ecma_compat_es2018/src/object_spread.rs b/crates/swc_ecma_compat_es2018/src/object_spread.rs index 6b1b6ab67ad..5c9403b1952 100644 --- a/crates/swc_ecma_compat_es2018/src/object_spread.rs +++ b/crates/swc_ecma_compat_es2018/src/object_spread.rs @@ -43,10 +43,10 @@ impl VisitMut for ObjectSpread { // { foo, ...x } => ({ foo }, x) let args = { - let mut buf = vec![]; + let mut buf = Vec::new(); let mut obj = ObjectLit { span: DUMMY_SP, - props: vec![], + props: Vec::new(), }; let mut first = true; for prop in props.take() { diff --git a/crates/swc_ecma_compat_es2020/src/export_namespace_from.rs b/crates/swc_ecma_compat_es2020/src/export_namespace_from.rs index e1a50376c07..6a5b9c890aa 100644 --- a/crates/swc_ecma_compat_es2020/src/export_namespace_from.rs +++ b/crates/swc_ecma_compat_es2020/src/export_namespace_from.rs @@ -42,10 +42,10 @@ impl VisitMut for ExportNamespaceFrom { type_only: false, with, })) 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 export_specifiers = vec![]; + let mut import_specifiers = Vec::new(); + let mut export_specifiers = Vec::new(); for s in specifiers.into_iter() { match s { diff --git a/crates/swc_ecma_compat_es2022/src/class_properties/member_init.rs b/crates/swc_ecma_compat_es2022/src/class_properties/member_init.rs index b2e6ea49d01..384cc07b612 100644 --- a/crates/swc_ecma_compat_es2022/src/class_properties/member_init.rs +++ b/crates/swc_ecma_compat_es2022/src/class_properties/member_init.rs @@ -74,8 +74,8 @@ impl MemberInitRecord { } pub fn into_init(self) -> Vec> { - let mut normal_init = vec![]; - let mut value_init = vec![]; + let mut normal_init = Vec::new(); + let mut value_init = Vec::new(); for init in self.record { match init { MemberInit::PrivMethod(PrivMethod { @@ -184,8 +184,8 @@ impl MemberInitRecord { } pub fn into_init_static(self, class_ident: Ident) -> Vec { - let mut normal_init = vec![]; - let mut value_init = vec![]; + let mut normal_init = Vec::new(); + let mut value_init = Vec::new(); for value in self.record { match value { diff --git a/crates/swc_ecma_compat_es2022/src/class_properties/mod.rs b/crates/swc_ecma_compat_es2022/src/class_properties/mod.rs index 296ec963e9e..b815b66500f 100644 --- a/crates/swc_ecma_compat_es2022/src/class_properties/mod.rs +++ b/crates/swc_ecma_compat_es2022/src/class_properties/mod.rs @@ -181,7 +181,7 @@ impl VisitMut for ClassProperties { BlockStmtOrExpr::Expr(expr) if expr.is_class() => { 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 (decl, extra) = self.visit_mut_class_as_decl(ident.clone(), class); @@ -516,14 +516,14 @@ impl ClassProperties { let has_super = class.super_class.is_some(); let mut constructor_inits = MemberInitRecord::new(self.c); - let mut vars = vec![]; - let mut lets = vec![]; + let mut vars = Vec::new(); + let mut lets = Vec::new(); let mut extra_inits = MemberInitRecord::new(self.c); - let mut private_method_fn_decls = vec![]; - let mut members = vec![]; + let mut private_method_fn_decls = Vec::new(); + let mut members = Vec::new(); let mut constructor = None; - let mut used_names = vec![]; - let mut used_key_names = vec![]; + let mut used_names = Vec::new(); + let mut used_key_names = Vec::new(); let mut super_ident = None; class.body.visit_mut_with(&mut BrandCheckHandler { @@ -980,7 +980,7 @@ impl ClassProperties { private_method_fn_decls.visit_mut_with(&mut PrivateAccessVisitor { private: &self.private, - vars: vec![], + vars: Vec::new(), private_access_type: Default::default(), c: self.c, unresolved_mark: self.unresolved_mark, @@ -992,7 +992,7 @@ impl ClassProperties { members.visit_mut_with(&mut PrivateAccessVisitor { private: &self.private, - vars: vec![], + vars: Vec::new(), private_access_type: Default::default(), c: self.c, unresolved_mark: self.unresolved_mark, diff --git a/crates/swc_ecma_compat_es2022/src/class_properties/private_field.rs b/crates/swc_ecma_compat_es2022/src/class_properties/private_field.rs index 3924c82db96..28ec3860ce8 100644 --- a/crates/swc_ecma_compat_es2022/src/class_properties/private_field.rs +++ b/crates/swc_ecma_compat_es2022/src/class_properties/private_field.rs @@ -575,7 +575,7 @@ pub(super) fn visit_private_in_expr( ) -> Vec { let mut priv_visitor = PrivateAccessVisitor { private, - vars: vec![], + vars: Vec::new(), private_access_type: Default::default(), c: config, unresolved_mark, diff --git a/crates/swc_ecma_compat_es2022/src/optional_chaining_impl.rs b/crates/swc_ecma_compat_es2022/src/optional_chaining_impl.rs index c0d47541229..510464e6333 100644 --- a/crates/swc_ecma_compat_es2022/src/optional_chaining_impl.rs +++ b/crates/swc_ecma_compat_es2022/src/optional_chaining_impl.rs @@ -67,7 +67,7 @@ impl VisitMut for OptionalChaining { match e { // foo?.bar -> foo == null ? void 0 : foo.bar Expr::OptChain(v) => { - let data = self.gather(v.take(), vec![]); + let data = self.gather(v.take(), Vec::new()); *e = self.construct(data, false); } @@ -79,7 +79,7 @@ impl VisitMut for OptionalChaining { match &mut **arg { // delete foo?.bar -> foo == null ? true : delete foo.bar Expr::OptChain(v) => { - let data = self.gather(v.take(), vec![]); + let data = self.gather(v.take(), Vec::new()); *e = self.construct(data, true); } _ => e.visit_mut_children_with(self), @@ -120,7 +120,7 @@ impl VisitMut for OptionalChaining { span: DUMMY_SP, callee: ArrowExpr { span: DUMMY_SP, - params: vec![], + params: Vec::new(), body: Box::new(BlockStmtOrExpr::BlockStmt(BlockStmt { span: DUMMY_SP, stmts, @@ -131,7 +131,7 @@ impl VisitMut for OptionalChaining { ..Default::default() } .as_callee(), - args: vec![], + args: Vec::new(), ..Default::default() } .into(); diff --git a/crates/swc_ecma_compat_es2022/src/private_in_object.rs b/crates/swc_ecma_compat_es2022/src/private_in_object.rs index 695b3ccdfe6..f0bfe4a9706 100644 --- a/crates/swc_ecma_compat_es2022/src/private_in_object.rs +++ b/crates/swc_ecma_compat_es2022/src/private_in_object.rs @@ -261,7 +261,7 @@ impl VisitMut for PrivateInObject { } else { let mut bs = BlockStmt { span: DUMMY_SP, - stmts: vec![], + stmts: Vec::new(), ..Default::default() }; bs.stmts.push( diff --git a/crates/swc_ecma_compat_es3/src/reserved_word.rs b/crates/swc_ecma_compat_es3/src/reserved_word.rs index 19c2e68a905..ada479f5d78 100644 --- a/crates/swc_ecma_compat_es3/src/reserved_word.rs +++ b/crates/swc_ecma_compat_es3/src/reserved_word.rs @@ -30,7 +30,7 @@ impl VisitMut for ReservedWord { noop_visit_mut_type!(fail); fn visit_mut_module_items(&mut self, n: &mut Vec) { - let mut extra_exports = vec![]; + let mut extra_exports = Vec::new(); n.iter_mut().for_each(|module_item| { match module_item { diff --git a/crates/swc_ecma_lints/examples/all.rs b/crates/swc_ecma_lints/examples/all.rs index 2d3d63f1ef7..9504c524645 100644 --- a/crates/swc_ecma_lints/examples/all.rs +++ b/crates/swc_ecma_lints/examples/all.rs @@ -18,7 +18,7 @@ fn main() { Syntax::default(), EsVersion::latest(), None, - &mut vec![], + &mut Vec::new(), ); let mut program = match module { Ok(v) => Program::Module(v), diff --git a/crates/swc_ecma_lints/src/rules/no_dupe_args.rs b/crates/swc_ecma_lints/src/rules/no_dupe_args.rs index 755c999d2c1..6e948ffbc76 100644 --- a/crates/swc_ecma_lints/src/rules/no_dupe_args.rs +++ b/crates/swc_ecma_lints/src/rules/no_dupe_args.rs @@ -37,7 +37,7 @@ macro_rules! check { // 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 // times. - let mut done = vec![]; + let mut done = Vec::new(); let mut hash_mode = false; diff --git a/crates/swc_ecma_lints/src/rules/no_param_reassign.rs b/crates/swc_ecma_lints/src/rules/no_param_reassign.rs index 68b7061dd1b..da884d9d7ad 100644 --- a/crates/swc_ecma_lints/src/rules/no_param_reassign.rs +++ b/crates/swc_ecma_lints/src/rules/no_param_reassign.rs @@ -49,7 +49,7 @@ impl NoParamReassign { Self { expected_reaction: config.get_rule_reaction(), scoped_params: Default::default(), - scopes: vec![], + scopes: Vec::new(), check_props: rule_config.props.unwrap_or(true), ignore_names: rule_config.ignore_property_modifications_for.clone(), ignore_names_patterns: rule_config.ignore_property_modifications_for_regex.clone(), diff --git a/crates/swc_ecma_loader/src/resolvers/tsc.rs b/crates/swc_ecma_loader/src/resolvers/tsc.rs index 844686d8581..a0577320977 100644 --- a/crates/swc_ecma_loader/src/resolvers/tsc.rs +++ b/crates/swc_ecma_loader/src/resolvers/tsc.rs @@ -232,7 +232,7 @@ where debug!("Extra: `{}`", extra); } - let mut errors = vec![]; + let mut errors = Vec::new(); for target in to { let replaced = target.replace('*', extra); diff --git a/crates/swc_ecma_loader/tests/tsc_resolver.rs b/crates/swc_ecma_loader/tests/tsc_resolver.rs index 583486b576c..36cda70a385 100644 --- a/crates/swc_ecma_loader/tests/tsc_resolver.rs +++ b/crates/swc_ecma_loader/tests/tsc_resolver.rs @@ -158,7 +158,7 @@ fn base_url_precedence() { map.insert("jquery".to_string(), "jq in node module".to_string()); map.insert("react".to_string(), "react in node module".to_string()); - let r = TsConfigResolver::new(TestResolver(map), ".".into(), vec![]); + let r = TsConfigResolver::new(TestResolver(map), ".".into(), Vec::new()); { let resolved = r diff --git a/crates/swc_ecma_minifier/benches/full.rs b/crates/swc_ecma_minifier/benches/full.rs index 9b662abe9ac..5f5f3244fa6 100644 --- a/crates/swc_ecma_minifier/benches/full.rs +++ b/crates/swc_ecma_minifier/benches/full.rs @@ -60,7 +60,7 @@ fn run(src: &str) { Default::default(), Default::default(), None, - &mut vec![], + &mut Vec::new(), ) .map_err(|err| { err.into_diagnostic(&handler).emit(); @@ -107,7 +107,7 @@ fn run(src: &str) { } fn print(cm: Lrc, nodes: &[N], minify: bool) -> String { - let mut buf = vec![]; + let mut buf = Vec::new(); { let mut emitter = swc_ecma_codegen::Emitter { diff --git a/crates/swc_ecma_minifier/examples/compress.rs b/crates/swc_ecma_minifier/examples/compress.rs index d215f13b425..6c22076e897 100644 --- a/crates/swc_ecma_minifier/examples/compress.rs +++ b/crates/swc_ecma_minifier/examples/compress.rs @@ -37,7 +37,7 @@ fn main() { Default::default(), Default::default(), None, - &mut vec![], + &mut Vec::new(), ) .map_err(|err| { err.into_diagnostic(&handler).emit(); @@ -75,7 +75,7 @@ fn main() { } fn print(cm: Lrc, nodes: &[N], minify: bool) -> String { - let mut buf = vec![]; + let mut buf = Vec::new(); { let mut emitter = swc_ecma_codegen::Emitter { diff --git a/crates/swc_ecma_minifier/examples/minifier.rs b/crates/swc_ecma_minifier/examples/minifier.rs index fc6f10fc2c9..b5277b388a4 100644 --- a/crates/swc_ecma_minifier/examples/minifier.rs +++ b/crates/swc_ecma_minifier/examples/minifier.rs @@ -34,7 +34,7 @@ fn main() { Default::default(), Default::default(), None, - &mut vec![], + &mut Vec::new(), ) .map_err(|err| { err.into_diagnostic(&handler).emit(); @@ -76,7 +76,7 @@ fn main() { } fn print(cm: Lrc, nodes: &[N], minify: bool) -> String { - let mut buf = vec![]; + let mut buf = Vec::new(); { let mut emitter = swc_ecma_codegen::Emitter { diff --git a/crates/swc_ecma_minifier/examples/minify-all.rs b/crates/swc_ecma_minifier/examples/minify-all.rs index e466197138d..2678fcfe29c 100644 --- a/crates/swc_ecma_minifier/examples/minify-all.rs +++ b/crates/swc_ecma_minifier/examples/minify-all.rs @@ -43,7 +43,7 @@ fn main() { Default::default(), Default::default(), None, - &mut vec![], + &mut Vec::new(), ) .map_err(|err| { err.into_diagnostic(&handler).emit(); @@ -122,7 +122,7 @@ fn expand_dirs(dirs: Vec) -> Vec { } fn print(cm: Lrc, nodes: &[N], minify: bool) -> String { - let mut buf = vec![]; + let mut buf = Vec::new(); { let mut emitter = swc_ecma_codegen::Emitter { diff --git a/crates/swc_ecma_minifier/fuzz/fuzz_targets/bug.rs b/crates/swc_ecma_minifier/fuzz/fuzz_targets/bug.rs index 302cf7b118f..6857c4d3116 100644 --- a/crates/swc_ecma_minifier/fuzz/fuzz_targets/bug.rs +++ b/crates/swc_ecma_minifier/fuzz/fuzz_targets/bug.rs @@ -42,7 +42,7 @@ fuzz_target!(|module: Module| { Default::default(), Default::default(), None, - &mut vec![], + &mut Vec::new(), ) .map_err(|err| { err.into_diagnostic(handler).emit(); @@ -91,7 +91,7 @@ fuzz_target!(|module: Module| { }); fn print(cm: Lrc, nodes: &[N], minify: bool) -> String { - let mut buf = vec![]; + let mut buf = Vec::new(); { let mut emitter = swc_ecma_codegen::Emitter { diff --git a/crates/swc_ecma_minifier/src/compress/hoist_decls.rs b/crates/swc_ecma_minifier/src/compress/hoist_decls.rs index a9d917a7a2a..706287f4d3c 100644 --- a/crates/swc_ecma_minifier/src/compress/hoist_decls.rs +++ b/crates/swc_ecma_minifier/src/compress/hoist_decls.rs @@ -102,7 +102,7 @@ impl Hoister<'_> { } self.changed = true; - let mut var_decls = vec![]; + let mut var_decls = Vec::new(); let mut fn_decls = Vec::with_capacity(stmts.len()); let mut new_stmts = Vec::with_capacity(stmts.len()); let mut done = AHashSet::default(); @@ -127,7 +127,7 @@ impl Hoister<'_> { } ) && found_non_var_decl => { - let mut exprs = vec![]; + let mut exprs = Vec::new(); for decl in var.decls { let ids: Vec = find_pat_ids(&decl.name); diff --git a/crates/swc_ecma_minifier/src/compress/optimize/conditionals.rs b/crates/swc_ecma_minifier/src/compress/optimize/conditionals.rs index 52b8660915a..c862a894485 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/conditionals.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/conditionals.rs @@ -426,7 +426,7 @@ impl Optimizer<'_> { .position(|(cons, alt)| !cons.eq_ignore_span(alt)) .unwrap(); - let mut new_args = vec![]; + let mut new_args = Vec::new(); for (idx, arg) in cons.args.take().into_iter().enumerate() { if idx == diff_idx { @@ -539,7 +539,7 @@ impl Optimizer<'_> { .iter() .all(|arg| arg.spread.is_none())) { - let mut args = vec![]; + let mut args = Vec::new(); if cons.args.as_ref().map(|v| v.len()).unwrap_or(0) == 1 { args = vec![ExprOrSpread { diff --git a/crates/swc_ecma_minifier/src/compress/optimize/evaluate.rs b/crates/swc_ecma_minifier/src/compress/optimize/evaluate.rs index d91c6a846bf..1a10aedddc8 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/evaluate.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/evaluate.rs @@ -271,7 +271,7 @@ impl Optimizer<'_> { _ => return, }; - let mut keys = vec![]; + let mut keys = Vec::new(); for prop in &obj.props { match prop { diff --git a/crates/swc_ecma_minifier/src/compress/optimize/if_return.rs b/crates/swc_ecma_minifier/src/compress/optimize/if_return.rs index cc326cf5dce..78d0c47bbde 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/if_return.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/if_return.rs @@ -296,7 +296,7 @@ impl Optimizer<'_> { stmt }; let is_nonconditional_return = matches!(stmt, Stmt::Return(..)); - let new_expr = self.merge_if_returns_to(stmt, vec![]); + let new_expr = self.merge_if_returns_to(stmt, Vec::new()); match new_expr { Expr::Seq(v) => match &mut cur { Some(cur) => match &mut **cur { @@ -436,9 +436,9 @@ impl Optimizer<'_> { alt, .. }) => { - let cons = Box::new(self.merge_if_returns_to(*cons, vec![])); + let cons = Box::new(self.merge_if_returns_to(*cons, Vec::new())); let alt = match alt { - Some(alt) => Box::new(self.merge_if_returns_to(*alt, vec![])), + Some(alt) => Box::new(self.merge_if_returns_to(*alt, Vec::new())), None => Expr::undefined(DUMMY_SP), }; diff --git a/crates/swc_ecma_minifier/src/compress/optimize/iife.rs b/crates/swc_ecma_minifier/src/compress/optimize/iife.rs index fb90c9d1b65..7666322c06e 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/iife.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/iife.rs @@ -357,7 +357,7 @@ impl Optimizer<'_> { } } - let mut removed = vec![]; + let mut removed = Vec::new(); let params = find_params(callee); if let Some(mut params) = params { // We check for parameter and argument diff --git a/crates/swc_ecma_minifier/src/compress/optimize/mod.rs b/crates/swc_ecma_minifier/src/compress/optimize/mod.rs index 59a45ba9b92..e518cf303c2 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/mod.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/mod.rs @@ -439,8 +439,8 @@ impl Optimizer<'_> { let mut new = Vec::with_capacity(stmts.len() * 11 / 10); for (i, mut stmt) in stmts.take().into_iter().enumerate() { - // debug_assert_eq!(self.prepend_stmts, vec![]); - // debug_assert_eq!(self.append_stmts, vec![]); + // debug_assert_eq!(self.prepend_stmts, Vec::new()); + // debug_assert_eq!(self.append_stmts, Vec::new()); if i < directive_count { // Don't set in_strict for directive itself. @@ -520,7 +520,7 @@ impl Optimizer<'_> { drop_invalid_stmts(stmts); - // debug_assert_eq!(self.prepend_stmts, vec![]); + // debug_assert_eq!(self.prepend_stmts, Vec::new()); self.prepend_stmts = prepend_stmts; self.append_stmts = append_stmts; } @@ -1060,7 +1060,7 @@ impl Optimizer<'_> { ); } - let mut exprs = vec![]; + let mut exprs = Vec::new(); self.changed = true; report_change!("ignore_return_value: Inverting an array literal"); exprs.extend( @@ -1087,7 +1087,7 @@ impl Optimizer<'_> { } Expr::Object(obj) => { - let mut exprs = vec![]; + let mut exprs = Vec::new(); self.changed = true; report_change!("ignore_return_value: Inverting an object literal"); for prop in obj.props.take() { @@ -3036,7 +3036,7 @@ impl VisitMut for Optimizer<'_> { } let mut can_prepend = true; - let mut side_effects = vec![]; + let mut side_effects = Vec::new(); for v in vars.iter_mut() { let mut storage = None; diff --git a/crates/swc_ecma_minifier/src/compress/optimize/props.rs b/crates/swc_ecma_minifier/src/compress/optimize/props.rs index 50960b10958..c4fbc9df3e3 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/props.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/props.rs @@ -117,7 +117,7 @@ impl Optimizer<'_> { self.mode.store(name.to_id(), init); } - let mut new_vars = vec![]; + let mut new_vars = Vec::new(); let object = n.init.as_mut()?.as_mut_object()?; diff --git a/crates/swc_ecma_minifier/src/compress/optimize/sequences.rs b/crates/swc_ecma_minifier/src/compress/optimize/sequences.rs index 501ca1e27eb..4d46aa950ee 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/sequences.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/sequences.rs @@ -151,7 +151,7 @@ impl Optimizer<'_> { report_change!("sequences: Compressing statements as a sequences"); self.changed = true; - let mut exprs = vec![]; + let mut exprs = Vec::new(); // This is bigger than required. let mut new_stmts = Vec::with_capacity(stmts.len()); @@ -395,7 +395,7 @@ impl Optimizer<'_> { return; } - let mut new_stmts = vec![]; + let mut new_stmts = Vec::new(); for stmt in stmts.take() { match stmt.try_into_stmt() { @@ -646,8 +646,8 @@ impl Optimizer<'_> { return; } - let mut exprs = vec![]; - let mut buf = vec![]; + let mut exprs = Vec::new(); + let mut buf = Vec::new(); for stmt in stmts.iter_mut() { let is_end = matches!( @@ -747,7 +747,7 @@ impl Optimizer<'_> { } if seq.exprs.iter().any(|v| v.is_seq()) { - let mut new = vec![]; + let mut new = Vec::new(); for e in seq.exprs.take() { match *e { diff --git a/crates/swc_ecma_minifier/src/compress/optimize/switches.rs b/crates/swc_ecma_minifier/src/compress/optimize/switches.rs index c3e1c720ab4..ea6f2fe729c 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/switches.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/switches.rs @@ -36,7 +36,7 @@ impl Optimizer<'_> { return; }; - let mut var_ids = vec![]; + let mut var_ids = Vec::new(); let mut cases = Vec::new(); let mut exact = None; let mut may_match_other_than_exact = false; diff --git a/crates/swc_ecma_minifier/src/compress/optimize/util.rs b/crates/swc_ecma_minifier/src/compress/optimize/util.rs index bd14f03146d..0b4ef1a7228 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/util.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/util.rs @@ -30,7 +30,7 @@ impl<'b> Optimizer<'b> { } if seq.exprs.iter().any(|v| v.is_seq()) { - let mut new = vec![]; + let mut new = Vec::new(); for e in seq.exprs.take() { match *e { diff --git a/crates/swc_ecma_minifier/src/compress/pure/dead_code.rs b/crates/swc_ecma_minifier/src/compress/pure/dead_code.rs index 47010c05a25..9bb3b7f8a8f 100644 --- a/crates/swc_ecma_minifier/src/compress/pure/dead_code.rs +++ b/crates/swc_ecma_minifier/src/compress/pure/dead_code.rs @@ -517,7 +517,7 @@ impl Pure<'_> { Ok(stmt) => match stmt { Stmt::If(mut s) => { if let Value::Known(v) = s.test.cast_to_bool(&self.expr_ctx).1 { - let mut var_ids = vec![]; + let mut var_ids = Vec::new(); new.push(T::from( ExprStmt { span: DUMMY_SP, diff --git a/crates/swc_ecma_minifier/src/compress/pure/member_expr.rs b/crates/swc_ecma_minifier/src/compress/pure/member_expr.rs index 200c3ffb0a1..59e8329b541 100644 --- a/crates/swc_ecma_minifier/src/compress/pure/member_expr.rs +++ b/crates/swc_ecma_minifier/src/compress/pure/member_expr.rs @@ -373,7 +373,7 @@ impl Pure<'_> { // Replacement is certain at this point, and is always undefined // Extract side effects - let mut exprs = vec![]; + let mut exprs = Vec::new(); elems.drain(..).flatten().for_each(|elem| { self.expr_ctx.extract_side_effects_to(&mut exprs, *elem.expr); }); @@ -422,7 +422,7 @@ impl Pure<'_> { } // Extract side effects - let mut exprs = vec![]; + let mut exprs = Vec::new(); elems.drain(..).flatten().for_each(|elem| { self.expr_ctx.extract_side_effects_to(&mut exprs, *elem.expr); }); @@ -532,7 +532,7 @@ impl Pure<'_> { span: *span, obj: ObjectLit { span: *span, - props: vec![], + props: Vec::new(), } .into(), prop: MemberProp::Ident(IdentName::new(key, *span)), diff --git a/crates/swc_ecma_minifier/src/compress/pure/misc.rs b/crates/swc_ecma_minifier/src/compress/pure/misc.rs index ddea65eafd3..40606317680 100644 --- a/crates/swc_ecma_minifier/src/compress/pure/misc.rs +++ b/crates/swc_ecma_minifier/src/compress/pure/misc.rs @@ -66,7 +66,7 @@ impl Pure<'_> { return; } - let mut new_args = vec![]; + let mut new_args = Vec::new(); for arg in args.take() { match arg { ExprOrSpread { @@ -755,8 +755,8 @@ impl Pure<'_> { let mut new_tpl = Tpl { span, - quasis: vec![], - exprs: vec![], + quasis: Vec::new(), + exprs: Vec::new(), }; let mut cur_raw = String::new(); let mut cur_cooked = String::new(); @@ -1400,7 +1400,7 @@ impl Pure<'_> { Prop::Shorthand(_) | Prop::KeyValue(_) | Prop::Method(..) ), }) { - let mut exprs = vec![]; + let mut exprs = Vec::new(); for prop in obj.props.take() { if let PropOrSpread::Prop(p) = prop { @@ -1479,7 +1479,7 @@ impl Pure<'_> { return; } - let mut exprs = vec![]; + let mut exprs = Vec::new(); // diff --git a/crates/swc_ecma_minifier/src/compress/pure/mod.rs b/crates/swc_ecma_minifier/src/compress/pure/mod.rs index 9174adb7359..31a7450011f 100644 --- a/crates/swc_ecma_minifier/src/compress/pure/mod.rs +++ b/crates/swc_ecma_minifier/src/compress/pure/mod.rs @@ -807,7 +807,7 @@ impl VisitMut for Pure<'_> { exprs.iter().any(|e| e.is_seq()), *crate::LIGHT_TASK_PARALLELS ) { - let mut exprs = vec![]; + let mut exprs = Vec::new(); for e in e.exprs.take() { if let Expr::Seq(seq) = *e { diff --git a/crates/swc_ecma_minifier/src/compress/pure/sequences.rs b/crates/swc_ecma_minifier/src/compress/pure/sequences.rs index cf80181716c..671eceb2fe2 100644 --- a/crates/swc_ecma_minifier/src/compress/pure/sequences.rs +++ b/crates/swc_ecma_minifier/src/compress/pure/sequences.rs @@ -91,7 +91,7 @@ impl Pure<'_> { if let Expr::Seq(test) = &mut *cond.test { // if test.exprs.len() >= 2 { - let mut new_seq = vec![]; + let mut new_seq = Vec::new(); new_seq.extend(test.exprs.drain(..test.exprs.len() - 1)); self.changed = true; diff --git a/crates/swc_ecma_minifier/src/compress/pure/strings.rs b/crates/swc_ecma_minifier/src/compress/pure/strings.rs index ae089dd74ec..9c6fefa8a6d 100644 --- a/crates/swc_ecma_minifier/src/compress/pure/strings.rs +++ b/crates/swc_ecma_minifier/src/compress/pure/strings.rs @@ -264,8 +264,8 @@ impl Pure<'_> { trace_op!("compress_tpl"); - let mut quasis = vec![]; - let mut exprs = vec![]; + let mut quasis = Vec::new(); + let mut exprs = Vec::new(); let mut cur_raw = String::new(); let mut cur_cooked = Some(String::new()); diff --git a/crates/swc_ecma_minifier/src/compress/pure/vars.rs b/crates/swc_ecma_minifier/src/compress/pure/vars.rs index b30bcb58aea..483aef84355 100644 --- a/crates/swc_ecma_minifier/src/compress/pure/vars.rs +++ b/crates/swc_ecma_minifier/src/compress/pure/vars.rs @@ -459,7 +459,7 @@ impl VisitMut for VarMover { *d = new; } - let mut new = vec![]; + let mut new = Vec::new(); if has_init { new.append(&mut self.vars); diff --git a/crates/swc_ecma_minifier/src/compress/util/mod.rs b/crates/swc_ecma_minifier/src/compress/util/mod.rs index 948b8aa4c59..dd4092d57dc 100644 --- a/crates/swc_ecma_minifier/src/compress/util/mod.rs +++ b/crates/swc_ecma_minifier/src/compress/util/mod.rs @@ -473,7 +473,7 @@ pub(crate) fn eval_as_number(expr_ctx: &ExprCtx, e: &Expr) -> Option { } "max" => { - let mut numbers = vec![]; + let mut numbers = Vec::new(); for arg in args { let v = eval_as_number(expr_ctx, &arg.expr)?; if v.is_infinite() || v.is_nan() { @@ -491,7 +491,7 @@ pub(crate) fn eval_as_number(expr_ctx: &ExprCtx, e: &Expr) -> Option { } "min" => { - let mut numbers = vec![]; + let mut numbers = Vec::new(); for arg in args { let v = eval_as_number(expr_ctx, &arg.expr)?; if v.is_infinite() || v.is_nan() { diff --git a/crates/swc_ecma_minifier/src/compress/util/tests.rs b/crates/swc_ecma_minifier/src/compress/util/tests.rs index 171ff070b8e..23cc2171109 100644 --- a/crates/swc_ecma_minifier/src/compress/util/tests.rs +++ b/crates/swc_ecma_minifier/src/compress/util/tests.rs @@ -31,7 +31,7 @@ fn assert_negate_cost(s: &str, in_bool_ctx: bool, is_ret_val_ignored: bool, expe Default::default(), swc_ecma_ast::EsVersion::latest(), None, - &mut vec![], + &mut Vec::new(), ) .map_err(|e| { e.into_diagnostic(&handler).emit(); diff --git a/crates/swc_ecma_minifier/src/debug.rs b/crates/swc_ecma_minifier/src/debug.rs index d512b2c60a2..e570b871c3e 100644 --- a/crates/swc_ecma_minifier/src/debug.rs +++ b/crates/swc_ecma_minifier/src/debug.rs @@ -45,7 +45,7 @@ where let mut node = node.clone(); node.visit_mut_with(&mut Debugger {}); node = drop_span(node); - let mut buf = vec![]; + let mut buf = Vec::new(); let cm = Lrc::new(SourceMap::default()); { @@ -85,7 +85,7 @@ pub(crate) fn invoke_module(module: &Module) { .fold_with(&mut fixer(None)); let module = drop_span(module); - let mut buf = vec![]; + let mut buf = Vec::new(); let cm = Lrc::new(SourceMap::default()); { @@ -177,7 +177,7 @@ pub(crate) fn invoke_script(script: &Script) { .fold_with(&mut fixer(None)); let script = drop_span(script); - let mut buf = vec![]; + let mut buf = Vec::new(); let cm = Lrc::new(SourceMap::default()); { diff --git a/crates/swc_ecma_minifier/src/eval.rs b/crates/swc_ecma_minifier/src/eval.rs index 688699e2d4d..d5d25f34076 100644 --- a/crates/swc_ecma_minifier/src/eval.rs +++ b/crates/swc_ecma_minifier/src/eval.rs @@ -222,7 +222,7 @@ impl Evaluator { pub fn eval_tpl(&mut self, q: &Tpl) -> Option { self.run(); - let mut exprs = vec![]; + let mut exprs = Vec::new(); for expr in &q.exprs { let res = self.eval(expr)?; diff --git a/crates/swc_ecma_minifier/src/option/terser.rs b/crates/swc_ecma_minifier/src/option/terser.rs index 5c8708df09f..704fd867632 100644 --- a/crates/swc_ecma_minifier/src/option/terser.rs +++ b/crates/swc_ecma_minifier/src/option/terser.rs @@ -274,7 +274,7 @@ impl TerserCompressorOptions { Default::default(), Default::default(), None, - &mut vec![], + &mut Vec::new(), ) .map(drop_span) .unwrap_or_else(|err| { @@ -388,7 +388,7 @@ impl TerserCompressorOptions { Default::default(), Default::default(), None, - &mut vec![], + &mut Vec::new(), ) .map(drop_span) .unwrap_or_else(|err| { diff --git a/crates/swc_ecma_minifier/tests/compress.rs b/crates/swc_ecma_minifier/tests/compress.rs index fe764084a30..aee393dcae7 100644 --- a/crates/swc_ecma_minifier/tests/compress.rs +++ b/crates/swc_ecma_minifier/tests/compress.rs @@ -705,7 +705,7 @@ fn print( minify: bool, skip_semi: bool, ) -> String { - let mut buf = vec![]; + let mut buf = Vec::new(); { let mut wr: Box = Box::new(JsWriter::new(cm.clone(), "\n", &mut buf, None)); diff --git a/crates/swc_ecma_minifier/tests/eval.rs b/crates/swc_ecma_minifier/tests/eval.rs index d530a264923..5bcd1295272 100644 --- a/crates/swc_ecma_minifier/tests/eval.rs +++ b/crates/swc_ecma_minifier/tests/eval.rs @@ -23,7 +23,7 @@ fn eval(module: &str, expr: &str) -> Option { Default::default(), EsVersion::latest(), None, - &mut vec![], + &mut Vec::new(), ) .unwrap(); @@ -34,7 +34,7 @@ fn eval(module: &str, expr: &str) -> Option { Default::default(), EsVersion::latest(), None, - &mut vec![], + &mut Vec::new(), ) .unwrap() }; @@ -94,7 +94,7 @@ impl PartialInliner { }), EsVersion::latest(), None, - &mut vec![], + &mut Vec::new(), ) .unwrap(); module.visit_mut_with(&mut resolver(Mark::new(), Mark::new(), false)); @@ -127,12 +127,12 @@ impl PartialInliner { }), EsVersion::latest(), None, - &mut vec![], + &mut Vec::new(), ) .unwrap() }; let expected = { - let mut buf = vec![]; + let mut buf = Vec::new(); { let mut emitter = Emitter { @@ -148,7 +148,7 @@ impl PartialInliner { }; let actual = { - let mut buf = vec![]; + let mut buf = Vec::new(); { let mut emitter = Emitter { diff --git a/crates/swc_ecma_minifier/tests/exec.rs b/crates/swc_ecma_minifier/tests/exec.rs index 6512fdbc95c..11f71aaca2b 100644 --- a/crates/swc_ecma_minifier/tests/exec.rs +++ b/crates/swc_ecma_minifier/tests/exec.rs @@ -68,7 +68,7 @@ fn print( minify: bool, skip_semi: bool, ) -> String { - let mut buf = vec![]; + let mut buf = Vec::new(); { let mut wr: Box = Box::new(JsWriter::new(cm.clone(), "\n", &mut buf, None)); @@ -120,7 +120,7 @@ fn run( }), Default::default(), Some(&comments), - &mut vec![], + &mut Vec::new(), ) .map_err(|err| { err.into_diagnostic(handler).emit(); diff --git a/crates/swc_ecma_minifier/tests/format.rs b/crates/swc_ecma_minifier/tests/format.rs index 5e0ab2615d3..733232c8cf1 100644 --- a/crates/swc_ecma_minifier/tests/format.rs +++ b/crates/swc_ecma_minifier/tests/format.rs @@ -9,7 +9,7 @@ use swc_ecma_parser::{parse_file_as_module, Syntax}; use testing::NormalizedOutput; fn print(cm: Lrc, m: &Module, config: Config) -> 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; @@ -40,7 +40,7 @@ fn assert_format(src: &str, expected: &str, opts: Config) { Syntax::Es(Default::default()), Default::default(), None, - &mut vec![], + &mut Vec::new(), ) .unwrap(); diff --git a/crates/swc_ecma_minifier/tests/mangle.rs b/crates/swc_ecma_minifier/tests/mangle.rs index f96c453b71c..b38a24d13a2 100644 --- a/crates/swc_ecma_minifier/tests/mangle.rs +++ b/crates/swc_ecma_minifier/tests/mangle.rs @@ -23,7 +23,7 @@ use testing::{assert_eq, NormalizedOutput}; use tracing::warn; fn print(cm: Lrc, p: &Program, minify: bool) -> 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; @@ -56,7 +56,7 @@ fn parse_fm(handler: &Handler, fm: Lrc) -> Result { Default::default(), EsVersion::latest(), None, - &mut vec![], + &mut Vec::new(), ) .map_err(|err| { err.into_diagnostic(handler).emit(); diff --git a/crates/swc_ecma_minifier/tests/terser_exec.rs b/crates/swc_ecma_minifier/tests/terser_exec.rs index df828b34027..0ca5e51b51d 100644 --- a/crates/swc_ecma_minifier/tests/terser_exec.rs +++ b/crates/swc_ecma_minifier/tests/terser_exec.rs @@ -306,7 +306,7 @@ fn print( minify: bool, skip_semi: bool, ) -> String { - let mut buf = vec![]; + let mut buf = Vec::new(); { let mut wr: Box = Box::new(JsWriter::new(cm.clone(), "\n", &mut buf, None)); diff --git a/crates/swc_ecma_parser/examples/parse-all.rs b/crates/swc_ecma_parser/examples/parse-all.rs index 004ecad9297..283ba7d4c37 100644 --- a/crates/swc_ecma_parser/examples/parse-all.rs +++ b/crates/swc_ecma_parser/examples/parse-all.rs @@ -29,7 +29,7 @@ fn main() { Default::default(), Default::default(), None, - &mut vec![], + &mut Vec::new(), ) .map_err(|err| { err.into_diagnostic(&handler).emit(); diff --git a/crates/swc_ecma_parser/src/lexer/mod.rs b/crates/swc_ecma_parser/src/lexer/mod.rs index b28c7c5f05a..7a37b549dde 100644 --- a/crates/swc_ecma_parser/src/lexer/mod.rs +++ b/crates/swc_ecma_parser/src/lexer/mod.rs @@ -913,7 +913,7 @@ impl<'a> Lexer<'a> { fn read_unicode_escape(&mut self) -> LexResult> { debug_assert_eq!(self.cur(), Some('u')); - let mut chars = vec![]; + let mut chars = Vec::new(); let mut is_curly = false; self.bump(); // 'u' diff --git a/crates/swc_ecma_parser/src/lexer/tests.rs b/crates/swc_ecma_parser/src/lexer/tests.rs index 3ea37307198..613cfccf3b6 100644 --- a/crates/swc_ecma_parser/src/lexer/tests.rs +++ b/crates/swc_ecma_parser/src/lexer/tests.rs @@ -1091,7 +1091,7 @@ fn shebang() { #[test] fn empty() { - assert_eq!(lex_tokens(crate::Syntax::default(), "",), vec![]); + assert_eq!(lex_tokens(crate::Syntax::default(), "",), Vec::new()); } #[test] @@ -1844,14 +1844,14 @@ fn lex_semicolons(b: &mut Bencher) { fn issue_1272_1_ts() { let (tokens, errors) = lex_errors(crate::Syntax::Typescript(Default::default()), "\\u{16}"); assert_eq!(tokens.len(), 1); - assert_ne!(errors, vec![]); + assert_ne!(errors, Vec::new()); } #[test] fn issue_1272_1_js() { let (tokens, errors) = lex_errors(crate::Syntax::Es(Default::default()), "\\u{16}"); assert_eq!(tokens.len(), 1); - assert_ne!(errors, vec![]); + assert_ne!(errors, Vec::new()); } #[test] @@ -1859,7 +1859,7 @@ fn issue_1272_2_ts() { // Not recoverable yet let (tokens, errors) = lex_errors(crate::Syntax::Typescript(Default::default()), "\u{16}"); assert_eq!(tokens.len(), 1); - assert_eq!(errors, vec![]); + assert_eq!(errors, Vec::new()); } #[test] @@ -1867,14 +1867,14 @@ fn issue_1272_2_js() { // Not recoverable yet let (tokens, errors) = lex_errors(crate::Syntax::Es(Default::default()), "\u{16}"); assert_eq!(tokens.len(), 1); - assert_eq!(errors, vec![]); + assert_eq!(errors, Vec::new()); } #[test] fn issue_2853_1_js() { let (tokens, errors) = lex_errors(crate::Syntax::Es(Default::default()), "const a = \"\\0a\""); - assert_eq!(errors, vec![]); + assert_eq!(errors, Vec::new()); assert_eq!( tokens, vec![ @@ -1896,7 +1896,7 @@ fn issue_2853_2_ts() { "const a = \"\\0a\"", ); - assert_eq!(errors, vec![]); + assert_eq!(errors, Vec::new()); assert_eq!( tokens, vec![ @@ -1918,7 +1918,7 @@ fn issue_2853_3_js() { "const a = \"\u{0000}a\"", ); - assert_eq!(errors, vec![]); + assert_eq!(errors, Vec::new()); assert_eq!( tokens, vec![ @@ -1940,7 +1940,7 @@ fn issue_2853_4_ts() { "const a = \"\u{0000}a\"", ); - assert_eq!(errors, vec![]); + assert_eq!(errors, Vec::new()); assert_eq!( tokens, vec![ @@ -1965,7 +1965,7 @@ fn issue_2853_5_jsx() { "const a = \"\\0a\"", ); - assert_eq!(errors, vec![]); + assert_eq!(errors, Vec::new()); assert_eq!( tokens, vec![ @@ -1990,7 +1990,7 @@ fn issue_2853_6_tsx() { "const a = \"\\0a\"", ); - assert_eq!(errors, vec![]); + assert_eq!(errors, Vec::new()); assert_eq!( tokens, vec![ @@ -2015,7 +2015,7 @@ fn issue_2853_7_jsx() { "const a = \"\u{0000}a\"", ); - assert_eq!(errors, vec![]); + assert_eq!(errors, Vec::new()); assert_eq!( tokens, vec![ @@ -2040,7 +2040,7 @@ fn issue_2853_8_tsx() { "const a = \"\u{0000}a\"", ); - assert_eq!(errors, vec![]); + assert_eq!(errors, Vec::new()); assert_eq!( tokens, vec![ diff --git a/crates/swc_ecma_parser/src/parser/class_and_fn.rs b/crates/swc_ecma_parser/src/parser/class_and_fn.rs index 16bb7a6bc75..ac171620eb3 100644 --- a/crates/swc_ecma_parser/src/parser/class_and_fn.rs +++ b/crates/swc_ecma_parser/src/parser/class_and_fn.rs @@ -8,12 +8,12 @@ impl Parser { pub(super) fn parse_async_fn_expr(&mut self) -> PResult> { let start = cur_pos!(self); expect!(self, "async"); - self.parse_fn(None, Some(start), vec![]) + self.parse_fn(None, Some(start), Vec::new()) } /// Parse function expression pub(super) fn parse_fn_expr(&mut self) -> PResult> { - self.parse_fn(None, None, vec![]) + self.parse_fn(None, None, Vec::new()) } pub(super) fn parse_async_fn_decl(&mut self, decorators: Vec) -> PResult { @@ -124,7 +124,7 @@ impl Parser { let implements = if p.input.syntax().typescript() && eat!(p, "implements") { p.parse_ts_heritage_clause()? } else { - vec![] + Vec::new() }; { @@ -251,11 +251,11 @@ impl Parser { pub(super) fn parse_decorators(&mut self, allow_export: bool) -> PResult> { if !self.syntax().decorators() { - return Ok(vec![]); + return Ok(Vec::new()); } trace_cur!(self, parse_decorators); - let mut decorators = vec![]; + let mut decorators = Vec::new(); let start = cur_pos!(self); while is!(self, '@') { @@ -333,7 +333,7 @@ impl Parser { } fn parse_class_body(&mut self) -> PResult> { - let mut elems = vec![]; + let mut elems = Vec::new(); let mut has_constructor_with_body = false; while !eof!(self) && !is!(self, '}') { if eat_exact!(self, ';') { @@ -1413,7 +1413,7 @@ impl Parser { ..self.ctx() }; let state = State { - labels: vec![], + labels: Vec::new(), ..Default::default() }; self.with_ctx(ctx) @@ -1792,11 +1792,11 @@ mod tests { expr: Box::new(Expr::Class(ClassExpr { ident: None, class: Box::new(Class { - decorators: vec![], + decorators: Vec::new(), span, - body: vec![], + body: Vec::new(), super_class: Some(expr("a")), - implements: vec![], + implements: Vec::new(), is_abstract: false, ..Default::default() }), diff --git a/crates/swc_ecma_parser/src/parser/expr.rs b/crates/swc_ecma_parser/src/parser/expr.rs index 918105619a6..9f714ddb15b 100644 --- a/crates/swc_ecma_parser/src/parser/expr.rs +++ b/crates/swc_ecma_parser/src/parser/expr.rs @@ -500,7 +500,7 @@ impl Parser { let start = cur_pos!(self); assert_and_bump!(self, '['); - let mut elems = vec![]; + let mut elems = Vec::new(); while !eof!(self) && !is!(self, ']') { if is!(self, ',') { @@ -1013,7 +1013,7 @@ impl Parser { ) -> PResult<(Vec>, Vec)> { trace_cur!(self, parse_tpl_elements); - let mut exprs = vec![]; + let mut exprs = Vec::new(); let cur_elem = self.parse_tpl_element(is_tagged_tpl)?; let mut is_tail = cur_elem.tail; @@ -1731,7 +1731,7 @@ impl Parser { expect!(self, '('); - let mut items = vec![]; + let mut items = Vec::new(); let mut trailing_comma = None; // TODO(kdy1): optimize (once we parsed a pattern, we can parse everything else diff --git a/crates/swc_ecma_parser/src/parser/expr/tests.rs b/crates/swc_ecma_parser/src/parser/expr/tests.rs index 5f211dcc82f..b27d8e9dc6b 100644 --- a/crates/swc_ecma_parser/src/parser/expr/tests.rs +++ b/crates/swc_ecma_parser/src/parser/expr/tests.rs @@ -98,7 +98,7 @@ fn async_call() { Box::new(Expr::Call(CallExpr { span, callee: Callee::Expr(expr("async")), - args: vec![], + args: Vec::new(), ..Default::default() })) ); @@ -112,7 +112,7 @@ fn async_arrow() { span, is_async: true, is_generator: false, - params: vec![], + params: Vec::new(), body: Box::new(BlockStmtOrExpr::Expr(expr("foo"))), ..Default::default() })) @@ -188,7 +188,7 @@ fn lhs_expr_as_new_expr_prod() { Box::new(Expr::New(NewExpr { span, callee: lhs("Date.toString"), - args: Some(vec![]), + args: Some(Vec::new()), ..Default::default() })) ); @@ -201,7 +201,7 @@ fn lhs_expr_as_call() { Box::new(Expr::Call(CallExpr { span, callee: Callee::Expr(lhs("new Date.toString()")), - args: vec![], + args: Vec::new(), ..Default::default() })) ) @@ -215,7 +215,7 @@ fn arrow_fn_no_args() { span, is_async: false, is_generator: false, - params: vec![], + params: Vec::new(), body: Box::new(BlockStmtOrExpr::Expr(expr("1"))), ..Default::default() })) @@ -342,7 +342,7 @@ fn iife() { Box::new(Expr::Call(CallExpr { span, callee: Callee::Expr(expr("(function(){})")), - args: vec![], + args: Vec::new(), ..Default::default() })) ) @@ -515,7 +515,7 @@ fn issue_5947() { fn issue_6781() { let cm = SourceMap::default(); let fm = cm.new_source_file(FileName::Anon.into(), "import.meta.env".to_string()); - let mut errors = vec![]; + let mut errors = Vec::new(); let expr = parse_file_as_expr( &fm, Default::default(), diff --git a/crates/swc_ecma_parser/src/parser/expr/verifier.rs b/crates/swc_ecma_parser/src/parser/expr/verifier.rs index c38f41aee6f..a99d352ca2f 100644 --- a/crates/swc_ecma_parser/src/parser/expr/verifier.rs +++ b/crates/swc_ecma_parser/src/parser/expr/verifier.rs @@ -6,7 +6,7 @@ use super::*; impl Parser { #[cfg(feature = "verify")] pub(in crate::parser) fn verify_expr(&mut self, expr: Box) -> PResult> { - let mut v = Verifier { errors: vec![] }; + let mut v = Verifier { errors: Vec::new() }; v.visit_expr(&expr); diff --git a/crates/swc_ecma_parser/src/parser/jsx.rs b/crates/swc_ecma_parser/src/parser/jsx.rs index 55c2da134bd..28b1410951e 100644 --- a/crates/swc_ecma_parser/src/parser/jsx.rs +++ b/crates/swc_ecma_parser/src/parser/jsx.rs @@ -232,7 +232,7 @@ impl Parser { None }; - let mut attrs = vec![]; + let mut attrs = Vec::new(); while cur!(self, false).is_ok() { trace_cur!(self, parse_jsx_opening__attrs_loop); @@ -307,7 +307,7 @@ impl Parser { trace_cur!(p, parse_jsx_element__after_opening_element); - let mut children = vec![]; + let mut children = Vec::new(); let mut closing_element = None; let self_closing = match opening_element { diff --git a/crates/swc_ecma_parser/src/parser/jsx/tests.rs b/crates/swc_ecma_parser/src/parser/jsx/tests.rs index 8db4229470d..ef9c9bdc016 100644 --- a/crates/swc_ecma_parser/src/parser/jsx/tests.rs +++ b/crates/swc_ecma_parser/src/parser/jsx/tests.rs @@ -24,10 +24,10 @@ fn self_closing_01() { span, name: JSXElementName::Ident(Ident::new_no_ctxt("a".into(), span)), self_closing: true, - attrs: vec![], + attrs: Vec::new(), type_args: None, }, - children: vec![], + children: Vec::new(), closing: None, }))) ); @@ -43,7 +43,7 @@ fn normal_01() { span, name: JSXElementName::Ident(Ident::new_no_ctxt("a".into(), span)), self_closing: false, - attrs: vec![], + attrs: Vec::new(), type_args: None, }, children: vec![JSXElementChild::JSXText(JSXText { @@ -80,7 +80,7 @@ fn escape_in_attr() { self_closing: true, type_args: None, }, - children: vec![], + children: Vec::new(), closing: None }))) ); @@ -110,7 +110,7 @@ fn issue_584() { self_closing: true, type_args: None, }, - children: vec![], + children: Vec::new(), closing: None }))) ); diff --git a/crates/swc_ecma_parser/src/parser/object.rs b/crates/swc_ecma_parser/src/parser/object.rs index 5ccb22ed9f0..c3da76d2f8f 100644 --- a/crates/swc_ecma_parser/src/parser/object.rs +++ b/crates/swc_ecma_parser/src/parser/object.rs @@ -22,7 +22,7 @@ impl Parser { let mut trailing_comma = None; assert_and_bump!(p, '{'); - let mut props = vec![]; + let mut props = Vec::new(); while !eat!(p, '}') { props.push(p.parse_object_prop()?); @@ -163,7 +163,7 @@ impl ParseObject> for Parser { }) .parse_fn_args_body( // no decorator in an object literal - vec![], + Vec::new(), start, |p| p.parse_unique_formal_params(), false, @@ -221,7 +221,7 @@ impl ParseObject> for Parser { }) .parse_fn_args_body( // no decorator in an object literal - vec![], + Vec::new(), start, |p| p.parse_unique_formal_params(), false, @@ -287,7 +287,7 @@ impl ParseObject> for Parser { "get" => parser .parse_fn_args_body( // no decorator in an object literal - vec![], + Vec::new(), start, |p| { let params = p.parse_formal_params()?; @@ -324,7 +324,7 @@ impl ParseObject> for Parser { parser .parse_fn_args_body( // no decorator in an object literal - vec![], + Vec::new(), start, |p| { let params = p.parse_formal_params()?; @@ -392,7 +392,7 @@ impl ParseObject> for Parser { "async" => parser .parse_fn_args_body( // no decorator in an object literal - vec![], + Vec::new(), start, |p| p.parse_unique_formal_params(), true, diff --git a/crates/swc_ecma_parser/src/parser/pat.rs b/crates/swc_ecma_parser/src/parser/pat.rs index 90b411a48c4..ba501bba7e1 100644 --- a/crates/swc_ecma_parser/src/parser/pat.rs +++ b/crates/swc_ecma_parser/src/parser/pat.rs @@ -92,7 +92,7 @@ impl Parser { assert_and_bump!(self, '['); - let mut elems = vec![]; + let mut elems = Vec::new(); let mut comma = 0; let mut rest_span = Span::default(); @@ -282,7 +282,7 @@ impl Parser { } pub(super) fn parse_constructor_params(&mut self) -> PResult> { - let mut params = vec![]; + let mut params = Vec::new(); let mut rest_span = Span::default(); while !eof!(self) && !is!(self, ')') { @@ -397,7 +397,7 @@ impl Parser { } pub(super) fn parse_formal_params(&mut self) -> PResult> { - let mut params = vec![]; + let mut params = Vec::new(); let mut rest_span = Span::default(); while !eof!(self) && !is!(self, ')') { @@ -707,7 +707,7 @@ impl Parser { if exprs.is_empty() { return Ok(ArrayPat { span, - elems: vec![], + elems: Vec::new(), optional: false, type_ann: None, } @@ -819,7 +819,7 @@ impl Parser { let len = exprs.len(); if len == 0 { - return Ok(vec![]); + return Ok(Vec::new()); } let mut params = Vec::with_capacity(len); diff --git a/crates/swc_ecma_parser/src/parser/stmt.rs b/crates/swc_ecma_parser/src/parser/stmt.rs index 63ab239de0d..0cf7905ca47 100644 --- a/crates/swc_ecma_parser/src/parser/stmt.rs +++ b/crates/swc_ecma_parser/src/parser/stmt.rs @@ -631,7 +631,7 @@ impl<'a, I: Tokens> Parser { let discriminant = self.include_in_expr(true).parse_expr()?; expect!(self, ')'); - let mut cases = vec![]; + let mut cases = Vec::new(); let mut span_of_previous_default = None; expect!(self, '{'); @@ -642,7 +642,7 @@ impl<'a, I: Tokens> Parser { self.with_ctx(ctx).parse_with(|p| { while is_one_of!(p, "case", "default") { - let mut cons = vec![]; + let mut cons = Vec::new(); let is_case = is!(p, "case"); let case_start = cur_pos!(p); bump!(p); @@ -808,7 +808,7 @@ impl<'a, I: Tokens> Parser { assert_and_bump!(self, "using"); - let mut decls = vec![]; + let mut decls = Vec::new(); let mut first = true; while first || eat!(self, ',') { if first { @@ -894,7 +894,7 @@ impl<'a, I: Tokens> Parser { span: span!(self, start), kind, declare: false, - decls: vec![], + decls: Vec::new(), ..Default::default() })); } @@ -903,7 +903,7 @@ impl<'a, I: Tokens> Parser { } } - let mut decls = vec![]; + let mut decls = Vec::new(); let mut first = true; while first || eat!(self, ',') { if first { @@ -1138,7 +1138,7 @@ impl<'a, I: Tokens> Parser { self.with_ctx(ctx).parse_with(|p| { let start = l.span.lo(); - let mut errors = vec![]; + let mut errors = Vec::new(); for lb in &p.state.labels { if l.sym == *lb { errors.push(Error::new( @@ -1150,7 +1150,7 @@ impl<'a, I: Tokens> Parser { p.state.labels.push(l.sym.clone()); let body = Box::new(if is!(p, "function") { - let f = p.parse_fn_decl(vec![])?; + let f = p.parse_fn_decl(Vec::new())?; if let Decl::Fn(FnDecl { function, .. }) = &f { if p.ctx().strict { p.emit_err(function.span, SyntaxError::LabelledFunctionInStrict) @@ -1667,7 +1667,7 @@ mod tests { } ], super_class: None, - body: vec![], + body: Vec::new(), is_abstract: false, ..Default::default() }), diff --git a/crates/swc_ecma_parser/src/parser/stmt/module_item.rs b/crates/swc_ecma_parser/src/parser/stmt/module_item.rs index 056b55eb8de..3d12b988998 100644 --- a/crates/swc_ecma_parser/src/parser/stmt/module_item.rs +++ b/crates/swc_ecma_parser/src/parser/stmt/module_item.rs @@ -69,7 +69,7 @@ impl Parser { return Ok(ImportDecl { span: span!(self, start), src, - specifiers: vec![], + specifiers: Vec::new(), type_only: false, with, phase: Default::default(), @@ -79,7 +79,7 @@ impl Parser { let mut type_only = false; let mut phase = ImportPhase::Evaluation; - let mut specifiers = vec![]; + let mut specifiers = Vec::new(); 'import_maybe_ident: { if is!(self, BindingIdent) { @@ -611,7 +611,7 @@ impl Parser { .into()); } - let mut specifiers = vec![]; + let mut specifiers = Vec::new(); let mut has_default = false; let mut has_ns = false; diff --git a/crates/swc_ecma_parser/src/parser/tests.rs b/crates/swc_ecma_parser/src/parser/tests.rs index 99de14b1a79..c5fa4d73c8b 100644 --- a/crates/swc_ecma_parser/src/parser/tests.rs +++ b/crates/swc_ecma_parser/src/parser/tests.rs @@ -24,7 +24,7 @@ fn assert_module_error(src: &'static str) -> Module { let program = p.parse_program()?; let errors = p.take_errors(); - assert_ne!(errors, vec![]); + assert_ne!(errors, Vec::new()); let module = program.expect_module(); @@ -274,8 +274,8 @@ fn issue_2853_1() { let program = p.parse_program()?; let errors = p.take_errors(); - assert_eq!(errors, vec![]); - assert_eq!(errors, vec![]); + assert_eq!(errors, Vec::new()); + assert_eq!(errors, Vec::new()); Ok(program) }); @@ -287,7 +287,7 @@ fn issue_2853_2() { let program = p.parse_program()?; let errors = p.take_errors(); - assert_eq!(errors, vec![]); + assert_eq!(errors, Vec::new()); Ok(program) }); diff --git a/crates/swc_ecma_parser/src/parser/typescript.rs b/crates/swc_ecma_parser/src/parser/typescript.rs index 714ed00d104..13e91ddb52b 100644 --- a/crates/swc_ecma_parser/src/parser/typescript.rs +++ b/crates/swc_ecma_parser/src/parser/typescript.rs @@ -80,7 +80,7 @@ impl Parser { { debug_assert!(self.input.syntax().typescript()); - let mut buf = vec![]; + let mut buf = Vec::new(); while !self.is_ts_list_terminator(kind)? { // Skipping "parseListElement" from the TS source since that's just for error // handling. @@ -116,7 +116,7 @@ impl Parser { { debug_assert!(self.input.syntax().typescript()); - let mut buf = vec![]; + let mut buf = Vec::new(); loop { trace_cur!(self, parse_ts_delimited_list_inner__element); @@ -1079,7 +1079,7 @@ impl Parser { let extends = if eat!(self, "extends") { self.parse_ts_heritage_clause()? } else { - vec![] + Vec::new() }; // Recover from @@ -1902,7 +1902,7 @@ impl Parser { trace_cur!(self, parse_tpl_elements); - let mut types = vec![]; + let mut types = Vec::new(); let cur_elem = self.parse_tpl_element(false)?; let mut is_tail = cur_elem.tail; @@ -1931,7 +1931,7 @@ impl Parser { debug_assert!(self.input.syntax().typescript()); let params = self.parse_formal_params()?; - let mut list = vec![]; + let mut list = Vec::new(); for param in params { let item = match param.pat { diff --git a/crates/swc_ecma_parser/tests/common/mod.rs b/crates/swc_ecma_parser/tests/common/mod.rs index d1c194db26e..530a2861470 100644 --- a/crates/swc_ecma_parser/tests/common/mod.rs +++ b/crates/swc_ecma_parser/tests/common/mod.rs @@ -26,7 +26,7 @@ impl Fold for Normalizer { match e { Expr::Paren(ParenExpr { expr, .. }) if self.is_test262 => *expr, Expr::New(n @ NewExpr { args: None, .. }) if self.is_test262 => NewExpr { - args: Some(vec![]), + args: Some(Vec::new()), ..n } .into(), @@ -35,7 +35,7 @@ impl Fold for Normalizer { let need_work = exprs.iter().any(|n| matches!(**n, Expr::Seq(..))); if need_work { - exprs = exprs.into_iter().fold(vec![], |mut v, e| { + exprs = exprs.into_iter().fold(Vec::new(), |mut v, e| { match *e { Expr::Seq(SeqExpr { exprs, .. }) => v.extend(exprs), _ => v.push(e), diff --git a/crates/swc_ecma_preset_env/src/corejs2/mod.rs b/crates/swc_ecma_preset_env/src/corejs2/mod.rs index cb671645bec..0b1d9a677bd 100644 --- a/crates/swc_ecma_preset_env/src/corejs2/mod.rs +++ b/crates/swc_ecma_preset_env/src/corejs2/mod.rs @@ -24,7 +24,7 @@ pub(crate) struct UsageVisitor { impl UsageVisitor { pub fn new(target: Versions) -> Self { - // let mut v = Self { required: vec![] }; + // let mut v = Self { required: Vec::new() }; // // // let is_web_target = target diff --git a/crates/swc_ecma_preset_env/src/corejs3/usage.rs b/crates/swc_ecma_preset_env/src/corejs3/usage.rs index e30be057735..57b478a18c5 100644 --- a/crates/swc_ecma_preset_env/src/corejs3/usage.rs +++ b/crates/swc_ecma_preset_env/src/corejs3/usage.rs @@ -25,7 +25,7 @@ pub(crate) struct UsageVisitor { impl UsageVisitor { pub fn new(target: Versions, shipped_proposals: bool, corejs_version: Version) -> Self { - // let mut v = Self { required: vec![] }; + // let mut v = Self { required: Vec::new() }; // // // let is_web_target = target diff --git a/crates/swc_ecma_preset_env/src/lib.rs b/crates/swc_ecma_preset_env/src/lib.rs index 52f5e8178ff..bd733197f1f 100644 --- a/crates/swc_ecma_preset_env/src/lib.rs +++ b/crates/swc_ecma_preset_env/src/lib.rs @@ -461,7 +461,7 @@ impl VisitMut for Polyfills { v.into_iter().map(|src| { ImportDecl { span, - specifiers: vec![], + specifiers: Vec::new(), src: Str { span: DUMMY_SP, raw: None, @@ -481,7 +481,7 @@ impl VisitMut for Polyfills { required.into_iter().map(|src| { ImportDecl { span, - specifiers: vec![], + specifiers: Vec::new(), src: Str { span: DUMMY_SP, raw: None, diff --git a/crates/swc_ecma_preset_env/tests/test.rs b/crates/swc_ecma_preset_env/tests/test.rs index 1379699a01c..74aac848570 100644 --- a/crates/swc_ecma_preset_env/tests/test.rs +++ b/crates/swc_ecma_preset_env/tests/test.rs @@ -133,7 +133,7 @@ fn exec(c: PresetConfig, dir: PathBuf) -> Result<(), Error> { UseBuiltIns::Str(ref s) if s == "entry" => Some(Mode::Entry), v => unreachable!("invalid: {:?}", v), }, - skip: vec![], + skip: Vec::new(), loose: true, // TODO dynamic_import: true, @@ -156,7 +156,7 @@ fn exec(c: PresetConfig, dir: PathBuf) -> Result<(), Error> { ); let print = |m: &Module| { - let mut buf = vec![]; + let mut buf = Vec::new(); { let mut emitter = Emitter { cfg: swc_ecma_codegen::Config::default(), diff --git a/crates/swc_ecma_quote_macros/src/ctxt.rs b/crates/swc_ecma_quote_macros/src/ctxt.rs index 3a4cd7bccf8..14b4ac369d6 100644 --- a/crates/swc_ecma_quote_macros/src/ctxt.rs +++ b/crates/swc_ecma_quote_macros/src/ctxt.rs @@ -82,7 +82,7 @@ pub(super) fn prepare_vars( src: &dyn ToCode, vars: Punctuated, ) -> (Vec, AHashMap) { - let mut stmts = vec![]; + let mut stmts = Vec::new(); let mut init_map = AHashMap::<_, Vars>::default(); for var in vars { diff --git a/crates/swc_ecma_transforms_base/benches/deps.rs b/crates/swc_ecma_transforms_base/benches/deps.rs index a2d02559d6d..e2f1e49d933 100644 --- a/crates/swc_ecma_transforms_base/benches/deps.rs +++ b/crates/swc_ecma_transforms_base/benches/deps.rs @@ -12,7 +12,7 @@ fn module_clone(b: &mut Bencher) { let _ = ::testing::run_test(false, |cm, handler| { let fm = cm.new_source_file(FileName::Anon.into(), SOURCE.into()); - let mut errors = vec![]; + let mut errors = Vec::new(); let module = parse_file_as_module( &fm, Syntax::Typescript(Default::default()), @@ -38,7 +38,7 @@ fn fold_empty(b: &mut Bencher) { let _ = ::testing::run_test(false, |cm, handler| { let fm = cm.new_source_file(FileName::Anon.into(), SOURCE.into()); - let mut errors = vec![]; + let mut errors = Vec::new(); let module = parse_file_as_module( &fm, Syntax::Typescript(Default::default()), @@ -68,7 +68,7 @@ fn fold_noop_impl_all(b: &mut Bencher) { let _ = ::testing::run_test(false, |cm, handler| { let fm = cm.new_source_file(FileName::Anon.into(), SOURCE.into()); - let mut errors = vec![]; + let mut errors = Vec::new(); let module = parse_file_as_module( &fm, Syntax::Typescript(Default::default()), @@ -95,7 +95,7 @@ fn fold_noop_impl_all(b: &mut Bencher) { fn fold_noop_impl_vec(b: &mut Bencher) { let _ = ::testing::run_test(false, |cm, handler| { let fm = cm.new_source_file(FileName::Anon.into(), SOURCE.into()); - let mut errors = vec![]; + let mut errors = Vec::new(); let module = parse_file_as_module( &fm, Syntax::Typescript(Default::default()), @@ -123,7 +123,7 @@ fn mk_expr() -> Expr { CallExpr { span: DUMMY_SP, callee: Ident::new_no_ctxt("foo".into(), DUMMY_SP).as_callee(), - args: vec![], + args: Vec::new(), ..Default::default() } .into() diff --git a/crates/swc_ecma_transforms_base/src/helpers/mod.rs b/crates/swc_ecma_transforms_base/src/helpers/mod.rs index cc59f2ad26a..412b6a8fe23 100644 --- a/crates/swc_ecma_transforms_base/src/helpers/mod.rs +++ b/crates/swc_ecma_transforms_base/src/helpers/mod.rs @@ -33,7 +33,7 @@ fn parse(code: &str) -> Vec { Default::default(), Default::default(), None, - &mut vec![], + &mut Vec::new(), ) .map(|mut script| { script.body.visit_mut_with(&mut DropSpan); @@ -180,7 +180,7 @@ macro_rules! define_helpers { } fn build_helpers(&self) -> Vec { - let mut buf = vec![]; + let mut buf = Vec::new(); HELPERS.with(|helpers|{ debug_assert!(!helpers.external); @@ -193,7 +193,7 @@ macro_rules! define_helpers { } fn build_imports(&self) -> Vec { - let mut buf = vec![]; + let mut buf = Vec::new(); HELPERS.with(|helpers|{ debug_assert!(helpers.external); @@ -206,7 +206,7 @@ macro_rules! define_helpers { } fn build_requires(&self) -> Vec{ - let mut buf = vec![]; + let mut buf = Vec::new(); HELPERS.with(|helpers|{ debug_assert!(helpers.external); $( @@ -406,7 +406,7 @@ impl InjectHelpers { self.helper_ctxt = Some(SyntaxContext::empty().apply_mark(helper_mark)); self.build_imports() } else { - vec![] + Vec::new() } } else { self.build_helpers() diff --git a/crates/swc_ecma_transforms_base/src/hygiene/tests.rs b/crates/swc_ecma_transforms_base/src/hygiene/tests.rs index ded15291d58..0bb4980b83b 100644 --- a/crates/swc_ecma_transforms_base/src/hygiene/tests.rs +++ b/crates/swc_ecma_transforms_base/src/hygiene/tests.rs @@ -418,7 +418,7 @@ fn mark_root() { span: DUMMY_SP, is_async: false, is_generator: false, - decorators: vec![], + decorators: Vec::new(), body: Some(BlockStmt { stmts: vec![ tester @@ -431,7 +431,7 @@ fn mark_root() { ], ..Default::default() }), - params: vec![], + params: Vec::new(), ..Default::default() }), @@ -504,7 +504,7 @@ fn fn_args() { span: DUMMY_SP, is_async: false, is_generator: false, - decorators: vec![], + decorators: Vec::new(), body: Some(BlockStmt { stmts: vec![tester .parse_stmt("actual1.js", "_define_property(this, 'force', force);")? @@ -513,7 +513,7 @@ fn fn_args() { }), params: vec![Param { span: DUMMY_SP, - decorators: vec![], + decorators: Vec::new(), pat: quote_ident!("force").into(), } .fold_with(&mut marker(&[("force", mark1)]))], @@ -544,7 +544,7 @@ fn block_in_fn() { span: DUMMY_SP, is_async: false, is_generator: false, - decorators: vec![], + decorators: Vec::new(), body: Some(BlockStmt { stmts: vec![ tester @@ -556,7 +556,7 @@ fn block_in_fn() { ], ..Default::default() }), - params: vec![], + params: Vec::new(), ..Default::default() }), @@ -596,7 +596,7 @@ fn flat_in_fn() { span: DUMMY_SP, is_async: false, is_generator: false, - decorators: vec![], + decorators: Vec::new(), body: Some(BlockStmt { stmts: vec![ tester @@ -608,7 +608,7 @@ fn flat_in_fn() { ], ..Default::default() }), - params: vec![], + params: Vec::new(), ..Default::default() }), @@ -637,7 +637,7 @@ fn params_in_fn() { span: DUMMY_SP, is_async: false, is_generator: false, - decorators: vec![], + decorators: Vec::new(), body: Some(BlockStmt { ..Default::default() }), diff --git a/crates/swc_ecma_transforms_base/src/perf.rs b/crates/swc_ecma_transforms_base/src/perf.rs index fe6e9efdc14..30d6e68bc91 100644 --- a/crates/swc_ecma_transforms_base/src/perf.rs +++ b/crates/swc_ecma_transforms_base/src/perf.rs @@ -186,7 +186,7 @@ where }) }) .fold( - || (Parallel::create(&*self), vec![]), + || (Parallel::create(&*self), Vec::new()), |mut a, b| { Parallel::merge(&mut a.0, b.0); @@ -196,7 +196,7 @@ where }, ) .reduce( - || (Parallel::create(&*self), vec![]), + || (Parallel::create(&*self), Vec::new()), |mut a, b| { Parallel::merge(&mut a.0, b.0); diff --git a/crates/swc_ecma_transforms_base/src/rename/ops.rs b/crates/swc_ecma_transforms_base/src/rename/ops.rs index 4a0b967df14..3e582ccf048 100644 --- a/crates/swc_ecma_transforms_base/src/rename/ops.rs +++ b/crates/swc_ecma_transforms_base/src/rename/ops.rs @@ -349,7 +349,7 @@ where })) => { let decls = var.decls.take(); - let mut renamed: Vec = vec![]; + let mut renamed: Vec = Vec::new(); let decls = decls.move_map(|mut decl| { decl.name.visit_mut_with(&mut VarFolder { orig: self, @@ -418,7 +418,7 @@ where }) }) .reduce( - || (Parallel::create(&*self), vec![]), + || (Parallel::create(&*self), Vec::new()), |mut a, b| { Parallel::merge(&mut a.0, b.0); @@ -555,7 +555,7 @@ where }) }) .reduce( - || (Parallel::create(&*self), vec![]), + || (Parallel::create(&*self), Vec::new()), |mut a, b| { Parallel::merge(&mut a.0, b.0); diff --git a/crates/swc_ecma_transforms_base/src/resolver/mod.rs b/crates/swc_ecma_transforms_base/src/resolver/mod.rs index f216976b381..3ce1585723c 100644 --- a/crates/swc_ecma_transforms_base/src/resolver/mod.rs +++ b/crates/swc_ecma_transforms_base/src/resolver/mod.rs @@ -1913,7 +1913,7 @@ impl VisitMut for Hoister<'_, '_> { /// that there is already an global declaration of Ic when deal with the try /// block. fn visit_mut_module_items(&mut self, items: &mut Vec) { - let mut other_items = vec![]; + let mut other_items = Vec::new(); for item in items { match item { @@ -1952,7 +1952,7 @@ impl VisitMut for Hoister<'_, '_> { /// see docs for `self.visit_mut_module_items` fn visit_mut_stmts(&mut self, stmts: &mut Vec) { - let mut other_stmts = vec![]; + let mut other_stmts = Vec::new(); for item in stmts { match item { diff --git a/crates/swc_ecma_transforms_base/src/tests.rs b/crates/swc_ecma_transforms_base/src/tests.rs index 9bd7ceda934..7f6812b2fe1 100644 --- a/crates/swc_ecma_transforms_base/src/tests.rs +++ b/crates/swc_ecma_transforms_base/src/tests.rs @@ -116,7 +116,7 @@ impl<'a> Tester<'a> { } pub fn print(&mut self, module: &Module) -> String { - let mut buf = vec![]; + let mut buf = Vec::new(); { let mut emitter = Emitter { cfg: Default::default(), diff --git a/crates/swc_ecma_transforms_base/tests/fixer_test262.rs b/crates/swc_ecma_transforms_base/tests/fixer_test262.rs index 0c57f978373..89c1f6b53a2 100644 --- a/crates/swc_ecma_transforms_base/tests/fixer_test262.rs +++ b/crates/swc_ecma_transforms_base/tests/fixer_test262.rs @@ -172,8 +172,8 @@ fn identity_tests(tests: &mut Vec) -> Result<(), io::Error> { .load_file(&normal.join(file_name)) .expect("failed to load reference file"); - let mut wr = Buf(Arc::new(RwLock::new(vec![]))); - let mut wr2 = Buf(Arc::new(RwLock::new(vec![]))); + let mut wr = Buf(Arc::new(RwLock::new(Vec::new()))); + let mut wr2 = Buf(Arc::new(RwLock::new(Vec::new()))); let mut parser: Parser = Parser::new(Syntax::default(), (&*src).into(), None); @@ -298,7 +298,7 @@ impl Fold for Normalizer { expr.args = match expr.args { Some(..) => expr.args, - None => Some(vec![]), + None => Some(Vec::new()), }; expr diff --git a/crates/swc_ecma_transforms_base/tests/fixture.rs b/crates/swc_ecma_transforms_base/tests/fixture.rs index 6001406cdbd..581258c0121 100644 --- a/crates/swc_ecma_transforms_base/tests/fixture.rs +++ b/crates/swc_ecma_transforms_base/tests/fixture.rs @@ -11,7 +11,7 @@ use swc_ecma_visit::{ use testing::{fixture, run_test2, NormalizedOutput}; pub fn print(cm: Lrc, program: &Program) -> String { - let mut buf = vec![]; + let mut buf = Vec::new(); { let mut emitter = Emitter { cfg: Default::default(), diff --git a/crates/swc_ecma_transforms_base/tests/ts_resolver.rs b/crates/swc_ecma_transforms_base/tests/ts_resolver.rs index e2d70637700..e6a033a6452 100644 --- a/crates/swc_ecma_transforms_base/tests/ts_resolver.rs +++ b/crates/swc_ecma_transforms_base/tests/ts_resolver.rs @@ -27,7 +27,7 @@ fn no_empty(input: PathBuf) { }), EsVersion::latest(), None, - &mut vec![], + &mut Vec::new(), ) { Ok(v) => v, // We are not testing parser diff --git a/crates/swc_ecma_transforms_compat/src/class_fields_use_set.rs b/crates/swc_ecma_transforms_compat/src/class_fields_use_set.rs index 76689e2e225..d8f84f74d70 100644 --- a/crates/swc_ecma_transforms_compat/src/class_fields_use_set.rs +++ b/crates/swc_ecma_transforms_compat/src/class_fields_use_set.rs @@ -174,7 +174,7 @@ impl VisitMut for FieldsHandler { } fn visit_mut_class_members(&mut self, n: &mut Vec) { - let mut constructor_inits = vec![]; + let mut constructor_inits = Vec::new(); for member in n.iter_mut() { match member { diff --git a/crates/swc_ecma_transforms_module/src/common_js.rs b/crates/swc_ecma_transforms_module/src/common_js.rs index d9d8f10a285..ed9289157c2 100644 --- a/crates/swc_ecma_transforms_module/src/common_js.rs +++ b/crates/swc_ecma_transforms_module/src/common_js.rs @@ -591,7 +591,7 @@ pub(crate) fn cjs_dynamic_import( let p = private_ident!("p"); let (resolve_args, callback_params, require_args) = if is_lit_path { - (vec![], vec![], args) + (Vec::new(), Vec::new(), args) } else { (args, vec![p.clone().into()], vec![p.as_arg()]) }; diff --git a/crates/swc_ecma_transforms_module/src/system_js.rs b/crates/swc_ecma_transforms_module/src/system_js.rs index 5fbdc31ac15..7c0324c7787 100644 --- a/crates/swc_ecma_transforms_module/src/system_js.rs +++ b/crates/swc_ecma_transforms_module/src/system_js.rs @@ -47,15 +47,15 @@ pub fn system_js(unresolved_mark: Mark, config: Config) -> impl Fold { resolver: Resolver::Default, config, - declare_var_idents: vec![], + declare_var_idents: Vec::new(), export_map: Default::default(), - export_names: vec![], - export_values: vec![], + export_names: Vec::new(), + export_values: Vec::new(), tla: false, enter_async_fn: 0, - root_fn_decl_idents: vec![], - module_item_meta_list: vec![], - import_idents: vec![], + root_fn_decl_idents: Vec::new(), + module_item_meta_list: Vec::new(), + import_idents: Vec::new(), export_ident: private_ident!("_export"), context_ident: private_ident!("_context"), } @@ -71,15 +71,15 @@ pub fn system_js_with_resolver( unresolved_mark, resolver: Resolver::Real { base, resolver }, config, - declare_var_idents: vec![], + declare_var_idents: Vec::new(), export_map: Default::default(), - export_names: vec![], - export_values: vec![], + export_names: Vec::new(), + export_values: Vec::new(), tla: false, enter_async_fn: 0, - root_fn_decl_idents: vec![], - module_item_meta_list: vec![], - import_idents: vec![], + root_fn_decl_idents: Vec::new(), + module_item_meta_list: Vec::new(), + import_idents: Vec::new(), export_ident: private_ident!("_export"), context_ident: private_ident!("_context"), } @@ -132,7 +132,7 @@ impl SystemJs { _ => assign_expr.into(), }, AssignTarget::Pat(pat) => { - let mut to: Vec = vec![]; + let mut to: Vec = Vec::new(); pat.visit_with(&mut VarCollector { to: &mut to }); match pat { @@ -229,12 +229,12 @@ impl SystemJs { export_values: &mut Vec>, ) -> Vec { match export_names.len() { - 0 => vec![], + 0 => Vec::new(), 1 => vec![self .export_call(export_names.remove(0), DUMMY_SP, *export_values.remove(0)) .into_stmt()], _ => { - let mut props = vec![]; + let mut props = Vec::new(); for (sym, value) in export_names.drain(..).zip(export_values.drain(..)) { props.push(PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp { key: match Ident::verify_symbol(&sym) { @@ -276,7 +276,7 @@ impl SystemJs { name: export_obj.clone().into(), init: Some(Box::new(Expr::Object(ObjectLit { span: DUMMY_SP, - props: vec![], + props: Vec::new(), }))), definite: false, }], @@ -392,9 +392,9 @@ impl SystemJs { #[allow(clippy::boxed_local)] fn hoist_var_decl(&mut self, var_decl: Box) -> Option { - let mut exprs = vec![]; + let mut exprs = Vec::new(); for var_declarator in var_decl.decls { - let mut tos: Vec = vec![]; + let mut tos: Vec = Vec::new(); var_declarator.visit_with(&mut VarCollector { to: &mut tos }); for (sym, ctxt) in tos { @@ -441,7 +441,7 @@ impl SystemJs { if let ForHead::VarDecl(mut var_decl) = var_decl_or_pat { if var_decl.kind == VarDeclKind::Var { let var_declarator = var_decl.decls.remove(0); - let mut tos: Vec = vec![]; + let mut tos: Vec = Vec::new(); var_declarator.visit_with(&mut VarCollector { to: &mut tos }); for to in tos { @@ -646,8 +646,8 @@ impl Fold for SystemJs { } module }; - let mut before_body_stmts: Vec = vec![]; - let mut execute_stmts = vec![]; + let mut before_body_stmts: Vec = Vec::new(); + let mut execute_stmts = Vec::new(); // collect top level fn decl for item in &module.body { @@ -672,7 +672,7 @@ impl Fold for SystemJs { let source_alias = local_name_for_src(&src); - let mut setter_fn_stmts = vec![]; + let mut setter_fn_stmts = Vec::new(); for specifier in import.specifiers { match specifier { @@ -732,8 +732,8 @@ impl Fold for SystemJs { } self.add_module_item_meta(ModuleItemMeta { - export_names: vec![], - export_values: vec![], + export_names: Vec::new(), + export_values: Vec::new(), has_export_all: false, src: src.clone(), setter_fn_stmts, @@ -752,8 +752,8 @@ impl Fold for SystemJs { }; for specifier in decl.specifiers { let source_alias = local_name_for_src(&src); - let mut export_names = vec![]; - let mut export_values = vec![]; + let mut export_names = Vec::new(); + let mut export_values = Vec::new(); match specifier { ExportSpecifier::Named(specifier) => { @@ -795,7 +795,7 @@ impl Fold for SystemJs { export_values, has_export_all: false, src: src.clone(), - setter_fn_stmts: vec![], + setter_fn_stmts: Vec::new(), }); } } @@ -871,11 +871,11 @@ impl Fold for SystemJs { } Decl::Var(var_decl) => { let mut decl = VarDecl { - decls: vec![], + decls: Vec::new(), ..*var_decl }; for var_declarator in var_decl.decls { - let mut tos: Vec = vec![]; + let mut tos: Vec = Vec::new(); var_declarator.visit_with(&mut VarCollector { to: &mut tos }); for to in tos { let ident = Ident::new(to.0.clone(), DUMMY_SP, to.1); @@ -939,11 +939,11 @@ impl Fold for SystemJs { } ModuleDecl::ExportAll(decl) => { self.add_module_item_meta(ModuleItemMeta { - export_names: vec![], - export_values: vec![], + export_names: Vec::new(), + export_values: Vec::new(), has_export_all: true, src: decl.src.value, - setter_fn_stmts: vec![], + setter_fn_stmts: Vec::new(), }); } _ => {} @@ -1003,12 +1003,12 @@ impl Fold for SystemJs { let mut setters = ArrayLit { span: DUMMY_SP, - elems: vec![], + elems: Vec::new(), }; let mut dep_module_names = ArrayLit { span: DUMMY_SP, - elems: vec![], + elems: Vec::new(), }; let module_item_meta_list: Vec = @@ -1039,7 +1039,7 @@ impl Fold for SystemJs { } let execute = Box::new(Function { - params: vec![], + params: Vec::new(), decorators: Default::default(), span: DUMMY_SP, body: Some(BlockStmt { diff --git a/crates/swc_ecma_transforms_module/src/umd.rs b/crates/swc_ecma_transforms_module/src/umd.rs index 46c873b9324..d79d50a60fb 100644 --- a/crates/swc_ecma_transforms_module/src/umd.rs +++ b/crates/swc_ecma_transforms_module/src/umd.rs @@ -399,11 +399,11 @@ where let module_exports = module.clone().make_member(quote_ident!("exports")); let define_amd = define.clone().make_member(quote_ident!("amd")); - let mut cjs_args = vec![]; - let mut amd_dep_list = vec![]; - let mut browser_args = vec![]; + let mut cjs_args = Vec::new(); + let mut amd_dep_list = Vec::new(); + let mut browser_args = Vec::new(); - let mut factory_params = vec![]; + let mut factory_params = Vec::new(); if !is_export_assign && self.exports.is_some() { let filename = self.cm.span_to_filename(module_span); diff --git a/crates/swc_ecma_transforms_module/src/umd/config.rs b/crates/swc_ecma_transforms_module/src/umd/config.rs index 7094a643395..c0e94eeef90 100644 --- a/crates/swc_ecma_transforms_module/src/umd/config.rs +++ b/crates/swc_ecma_transforms_module/src/umd/config.rs @@ -39,7 +39,7 @@ impl Config { Syntax::default(), Default::default(), None, - &mut vec![], + &mut Vec::new(), ) .map_err(|e| { if HANDLER.is_set() { diff --git a/crates/swc_ecma_transforms_optimization/src/const_modules.rs b/crates/swc_ecma_transforms_optimization/src/const_modules.rs index 7cf68962031..99176f60561 100644 --- a/crates/swc_ecma_transforms_optimization/src/const_modules.rs +++ b/crates/swc_ecma_transforms_optimization/src/const_modules.rs @@ -59,7 +59,7 @@ fn parse_option(cm: &SourceMap, name: &str, src: String) -> Arc { Default::default(), Default::default(), None, - &mut vec![], + &mut Vec::new(), ) .map_err(|e| { if HANDLER.is_set() { diff --git a/crates/swc_ecma_transforms_optimization/src/simplify/branch/mod.rs b/crates/swc_ecma_transforms_optimization/src/simplify/branch/mod.rs index effbd510a9e..1ddeaf3c153 100644 --- a/crates/swc_ecma_transforms_optimization/src/simplify/branch/mod.rs +++ b/crates/swc_ecma_transforms_optimization/src/simplify/branch/mod.rs @@ -388,7 +388,7 @@ impl VisitMut for Remover { .into(); } - let mut stmts = vec![]; + let mut stmts = Vec::new(); if let (p, Known(v)) = test.cast_to_bool(&self.expr_ctx) { if cfg!(feature = "debug") { trace!("The condition for if statement is always {}", v); @@ -730,10 +730,10 @@ impl VisitMut for Remover { .map(|case| case.test.as_deref()) .all(|s| matches!(s, Some(Expr::Lit(..)) | None)); - let mut var_ids = vec![]; + let mut var_ids = Vec::new(); if let Some(i) = selected { if !has_conditional_stopper(&s.cases[i].cons) { - let mut exprs = vec![]; + let mut exprs = Vec::new(); exprs.extend(ignore_result(s.discriminant, true, &self.expr_ctx)); let mut stmts = s.cases[i].cons.take(); @@ -813,7 +813,7 @@ impl VisitMut for Remover { return block; } } else if are_all_tests_known { - let mut vars = vec![]; + let mut vars = Vec::new(); if let Expr::Lit(..) = *s.discriminant { let idx = s.cases.iter().position(|v| v.test.is_none()); @@ -950,7 +950,7 @@ impl VisitMut for Remover { && is_all_case_side_effect_free && !has_conditional_stopper(&s.cases.last().unwrap().cons) { - let mut exprs = vec![]; + let mut exprs = Vec::new(); exprs.extend(ignore_result(s.discriminant, true, &self.expr_ctx)); exprs.extend( @@ -1299,8 +1299,8 @@ impl Remover { | Stmt::Continue { .. } | Stmt::Break { .. } => { // Hoist function and `var` declarations above return. - let mut decls = vec![]; - let mut hoisted_fns = vec![]; + let mut decls = Vec::new(); + let mut hoisted_fns = Vec::new(); for t in iter { match t.try_into_stmt() { Ok(Stmt::Decl(Decl::Fn(f))) => { diff --git a/crates/swc_ecma_transforms_optimization/src/simplify/expr/mod.rs b/crates/swc_ecma_transforms_optimization/src/simplify/expr/mod.rs index 734f6399c30..f09c720cfe5 100644 --- a/crates/swc_ecma_transforms_optimization/src/simplify/expr/mod.rs +++ b/crates/swc_ecma_transforms_optimization/src/simplify/expr/mod.rs @@ -291,7 +291,7 @@ impl SimplifyExpr { }; // Replacement expressions. - let mut exprs = vec![]; + let mut exprs = Vec::new(); // Add before side effects. for elem in before.into_iter().flatten() { diff --git a/crates/swc_ecma_transforms_proposal/src/decorator_2022_03.rs b/crates/swc_ecma_transforms_proposal/src/decorator_2022_03.rs index 3bca3770569..52bef3f58ef 100644 --- a/crates/swc_ecma_transforms_proposal/src/decorator_2022_03.rs +++ b/crates/swc_ecma_transforms_proposal/src/decorator_2022_03.rs @@ -104,7 +104,7 @@ impl Decorator2022_03 { return; } - let mut e_lhs = vec![]; + let mut e_lhs = Vec::new(); let mut combined_args = vec![ThisExpr { span: DUMMY_SP }.as_arg()]; for id in self @@ -354,10 +354,10 @@ impl Decorator2022_03 { ClassMember::Constructor(Constructor { span: DUMMY_SP, key: PropName::Ident("constructor".into()), - params: vec![], + params: Vec::new(), body: Some(BlockStmt { span: DUMMY_SP, - stmts: vec![], + stmts: Vec::new(), ..Default::default() }), ..Default::default() @@ -439,7 +439,7 @@ impl Decorator2022_03 { let call_stmt = CallExpr { span: DUMMY_SP, callee: init_class.as_callee(), - args: vec![], + args: Vec::new(), ..Default::default() } .into_stmt(); @@ -524,7 +524,7 @@ impl Decorator2022_03 { span: DUMMY_SP, callee: ArrowExpr { span: DUMMY_SP, - params: vec![], + params: Vec::new(), body: Box::new(BlockStmtOrExpr::BlockStmt( BlockStmt { span: DUMMY_SP, @@ -537,7 +537,7 @@ impl Decorator2022_03 { ..Default::default() } .as_callee(), - args: vec![], + args: Vec::new(), ..Default::default() })), value.take(), @@ -579,7 +579,7 @@ impl Decorator2022_03 { declare: Default::default(), class: Box::new(Class { span: DUMMY_SP, - decorators: vec![], + decorators: Vec::new(), body, super_class: c.class.super_class.take(), ..Default::default() @@ -648,7 +648,7 @@ impl Decorator2022_03 { span: DUMMY_SP, callee: ArrowExpr { span: DUMMY_SP, - params: vec![], + params: Vec::new(), body: Box::new(BlockStmtOrExpr::BlockStmt(BlockStmt { span: DUMMY_SP, stmts: last, @@ -659,7 +659,7 @@ impl Decorator2022_03 { ..Default::default() } .as_callee(), - args: vec![], + args: Vec::new(), ..Default::default() } .into() @@ -699,7 +699,7 @@ impl Decorator2022_03 { return NewExpr { span: DUMMY_SP, callee: ClassExpr { ident: None, class }.into(), - args: Some(vec![]), + args: Some(Vec::new()), ..Default::default() } .into_stmt(); @@ -721,7 +721,7 @@ impl Decorator2022_03 { stmts: vec![CallExpr { span: DUMMY_SP, callee: init_class.as_callee(), - args: vec![], + args: Vec::new(), ..Default::default() } .into_stmt()], @@ -1205,7 +1205,7 @@ impl VisitMut for Decorator2022_03 { }); getter_function = Box::new(Function { - params: vec![], + params: Vec::new(), span: DUMMY_SP, body: Some(BlockStmt { span: DUMMY_SP, diff --git a/crates/swc_ecma_transforms_proposal/src/decorators/legacy/mod.rs b/crates/swc_ecma_transforms_proposal/src/decorators/legacy/mod.rs index 2fc0b44ed8a..28731050bec 100644 --- a/crates/swc_ecma_transforms_proposal/src/decorators/legacy/mod.rs +++ b/crates/swc_ecma_transforms_proposal/src/decorators/legacy/mod.rs @@ -57,7 +57,7 @@ impl TscDecorator { let old_appended_exprs = self.appended_exprs.take(); let old_prepended_exprs = self.prepended_exprs.take(); - let mut new = vec![]; + let mut new = Vec::new(); for mut s in stmts.take() { debug_assert!(self.appended_exprs.is_empty()); diff --git a/crates/swc_ecma_transforms_proposal/src/decorators/mod.rs b/crates/swc_ecma_transforms_proposal/src/decorators/mod.rs index b612c76a186..642ca4563f3 100644 --- a/crates/swc_ecma_transforms_proposal/src/decorators/mod.rs +++ b/crates/swc_ecma_transforms_proposal/src/decorators/mod.rs @@ -327,7 +327,7 @@ impl Decorators { } }; - let mut vars = vec![]; + let mut vars = Vec::new(); macro_rules! fold_method { ($method:expr, $fn_name:expr, $key_prop_value:expr) => {{ @@ -411,7 +411,7 @@ impl Decorators { FnExpr { ident: fn_name.map(Ident::from).map(Ident::into_private), function: Function { - decorators: vec![], + decorators: Vec::new(), ..*method.function } .into(), @@ -524,8 +524,8 @@ impl Decorators { span: DUMMY_SP, is_async: false, is_generator: false, - decorators: vec![], - params: vec![], + decorators: Vec::new(), + params: Vec::new(), body: Some(BlockStmt { span: DUMMY_SP, @@ -568,7 +568,7 @@ impl Decorators { .chain(super_class_ident.map(Pat::from)) .map(|pat| Param { span: DUMMY_SP, - decorators: vec![], + decorators: Vec::new(), pat, }) .collect(), diff --git a/crates/swc_ecma_transforms_proposal/src/explicit_resource_management.rs b/crates/swc_ecma_transforms_proposal/src/explicit_resource_management.rs index 859efab6b11..73515461b11 100644 --- a/crates/swc_ecma_transforms_proposal/src/explicit_resource_management.rs +++ b/crates/swc_ecma_transforms_proposal/src/explicit_resource_management.rs @@ -56,9 +56,9 @@ impl ExplicitResourceManagement { where T: StmtLike + ModuleItemLike, { - let mut new = vec![]; - let mut extras = vec![]; - let mut try_body = vec![]; + let mut new = Vec::new(); + let mut extras = Vec::new(); + let mut try_body = Vec::new(); let using_ctx_var = VarDeclarator { span: DUMMY_SP, @@ -367,7 +367,7 @@ impl ExplicitResourceManagement { .clone() .make_member(quote_ident!("d")) .as_callee(), - args: vec![], + args: Vec::new(), ..Default::default() }; let dispose_stmt = if state.has_await { diff --git a/crates/swc_ecma_transforms_proposal/src/export_default_from.rs b/crates/swc_ecma_transforms_proposal/src/export_default_from.rs index 2e27ee49d13..dfda16d920d 100644 --- a/crates/swc_ecma_transforms_proposal/src/export_default_from.rs +++ b/crates/swc_ecma_transforms_proposal/src/export_default_from.rs @@ -41,9 +41,9 @@ impl VisitMut for ExportDefaultFrom { type_only: false, with, })) if specifiers.iter().any(|s| s.is_default()) => { - let mut origin_specifiers = vec![]; + let mut origin_specifiers = Vec::new(); - let mut export_specifiers = vec![]; + let mut export_specifiers = Vec::new(); let mut has_namespace = false; diff --git a/crates/swc_ecma_transforms_react/Cargo.toml b/crates/swc_ecma_transforms_react/Cargo.toml index d042db2dd2c..3e00b8ae2e4 100644 --- a/crates/swc_ecma_transforms_react/Cargo.toml +++ b/crates/swc_ecma_transforms_react/Cargo.toml @@ -27,6 +27,7 @@ serde = { workspace = true, features = ["derive"], optional = true } sha1 = { workspace = true } string_enum = { version = "0.4.4", path = "../string_enum" } +swc_allocator = { version = "0.1.7", path = "../swc_allocator", default-features = false } swc_atoms = { version = "0.6.5", path = "../swc_atoms" } swc_common = { version = "0.36.0", path = "../swc_common" } swc_config = { version = "0.1.13", path = "../swc_config" } diff --git a/crates/swc_ecma_transforms_react/src/jsx/mod.rs b/crates/swc_ecma_transforms_react/src/jsx/mod.rs index fae7124c620..3ed7374896f 100644 --- a/crates/swc_ecma_transforms_react/src/jsx/mod.rs +++ b/crates/swc_ecma_transforms_react/src/jsx/mod.rs @@ -126,7 +126,7 @@ pub fn parse_expr_for_jsx( Syntax::default(), Default::default(), None, - &mut vec![], + &mut Vec::new(), ) .map_err(|e| { if HANDLER.is_set() { @@ -493,7 +493,7 @@ where let mut props_obj = ObjectLit { span: DUMMY_SP, - props: vec![], + props: Vec::new(), }; let children = el @@ -615,7 +615,7 @@ where let mut props_obj = ObjectLit { span: DUMMY_SP, - props: vec![], + props: Vec::new(), }; let mut key = None; @@ -898,7 +898,7 @@ where } let attr_cnt = attrs.len(); - let mut props = vec![]; + let mut props = Vec::new(); for attr in attrs { match attr { JSXAttrOrSpread::JSXAttr(attr) => { diff --git a/crates/swc_ecma_transforms_react/src/jsx/tests.rs b/crates/swc_ecma_transforms_react/src/jsx/tests.rs index 49bee89999b..11a26ebc5be 100644 --- a/crates/swc_ecma_transforms_react/src/jsx/tests.rs +++ b/crates/swc_ecma_transforms_react/src/jsx/tests.rs @@ -1083,7 +1083,7 @@ fn test_script(src: &str, output: &Path, options: Options) { fixer(Some(&tester.comments)) )); - let mut buf = vec![]; + let mut buf = Vec::new(); let mut emitter = Emitter { cfg: Config::default() diff --git a/crates/swc_ecma_transforms_react/src/pure_annotations/tests.rs b/crates/swc_ecma_transforms_react/src/pure_annotations/tests.rs index b7aeb94bf43..e97a3eef016 100644 --- a/crates/swc_ecma_transforms_react/src/pure_annotations/tests.rs +++ b/crates/swc_ecma_transforms_react/src/pure_annotations/tests.rs @@ -40,8 +40,8 @@ fn emit( comments: Lrc, program: &Module, ) -> String { - let mut src_map_buf = vec![]; - let mut buf = vec![]; + let mut src_map_buf = Vec::new(); + let mut buf = std::vec::Vec::new(); { let writer = Box::new(JsWriter::new( source_map.clone(), diff --git a/crates/swc_ecma_transforms_testing/src/babel_like.rs b/crates/swc_ecma_transforms_testing/src/babel_like.rs index ec045430c17..d44ae2e303e 100644 --- a/crates/swc_ecma_transforms_testing/src/babel_like.rs +++ b/crates/swc_ecma_transforms_testing/src/babel_like.rs @@ -136,7 +136,7 @@ impl<'a> BabelLikeFixtureTest<'a> { src, ); - let mut errors = vec![]; + let mut errors = Vec::new(); let input_program = parse_file_as_program( &fm, self.syntax, @@ -273,7 +273,7 @@ pub struct PassContext { impl PassContext { fn print(&mut self, program: &Program) -> String { - let mut buf = vec![]; + let mut buf = Vec::new(); { let mut emitter = Emitter { cfg: Default::default(), diff --git a/crates/swc_ecma_transforms_testing/src/lib.rs b/crates/swc_ecma_transforms_testing/src/lib.rs index 76ca6ba2de7..4f53427b3de 100644 --- a/crates/swc_ecma_transforms_testing/src/lib.rs +++ b/crates/swc_ecma_transforms_testing/src/lib.rs @@ -866,7 +866,11 @@ fn test_fixture_inner<'a>( Ok(expected_src) }); - let mut src_map = if config.sourcemap { Some(vec![]) } else { None }; + let mut src_map = if config.sourcemap { + Some(Vec::new()) + } else { + None + }; let mut sourcemap = None; @@ -944,7 +948,7 @@ fn test_fixture_inner<'a>( if let Some(sourcemap) = sourcemap { let map = { - let mut buf = vec![]; + let mut buf = Vec::new(); sourcemap.to_writer(&mut buf).unwrap(); String::from_utf8(buf).unwrap() }; @@ -957,7 +961,7 @@ fn test_fixture_inner<'a>( /// Creates a url for https://evanw.github.io/source-map-visualization/ fn visualizer_url(code: &str, map: &sourcemap::SourceMap) -> String { let map = { - let mut buf = vec![]; + let mut buf = Vec::new(); map.to_writer(&mut buf).unwrap(); String::from_utf8(buf).unwrap() }; diff --git a/crates/swc_ecma_transforms_typescript/src/transform.rs b/crates/swc_ecma_transforms_typescript/src/transform.rs index bfe4ce4de3e..91720cdfb90 100644 --- a/crates/swc_ecma_transforms_typescript/src/transform.rs +++ b/crates/swc_ecma_transforms_typescript/src/transform.rs @@ -447,7 +447,7 @@ impl Transform { } fn transform_ts_module_block(id: Id, TsModuleBlock { span, body }: TsModuleBlock) -> BlockStmt { - let mut stmts = vec![]; + let mut stmts = Vec::new(); let mut mutable_export_ids = Default::default(); for module_item in body { @@ -544,7 +544,7 @@ impl Transform { debug_assert!(!declare); let mut default_init = 0.0.into(); - let mut member_list = vec![]; + let mut member_list = Vec::new(); let mut local_record = if self.ts_enum_is_mutable && !is_const { Some(TsEnumRecord::default()) } else { @@ -817,7 +817,7 @@ impl Transform { value: None, type_ann: None, is_static: false, - decorators: vec![], + decorators: Vec::new(), accessibility: None, is_abstract: false, is_optional: false, @@ -908,7 +908,7 @@ impl Transform { right: Box::new( ObjectLit { span: DUMMY_SP, - props: vec![], + props: Vec::new(), } .into(), ), diff --git a/crates/swc_ecma_utils/src/lib.rs b/crates/swc_ecma_utils/src/lib.rs index 859372c1295..c5490e650eb 100644 --- a/crates/swc_ecma_utils/src/lib.rs +++ b/crates/swc_ecma_utils/src/lib.rs @@ -388,7 +388,7 @@ impl IsEmpty for Vec { /// Extracts hoisted variables pub fn extract_var_ids>(node: &T) -> Vec { - let mut v = Hoister { vars: vec![] }; + let mut v = Hoister { vars: Vec::new() }; node.visit_with(&mut v); v.vars } @@ -2139,7 +2139,7 @@ pub fn default_constructor(has_super: bool) -> Constructor { params: if has_super { vec![ParamOrTsParamProp::Param(Param { span, - decorators: vec![], + decorators: Vec::new(), pat: Pat::Rest(RestPat { span: DUMMY_SP, dot3_token: DUMMY_SP, @@ -2148,7 +2148,7 @@ pub fn default_constructor(has_super: bool) -> Constructor { }), })] } else { - vec![] + Vec::new() }, body: Some(BlockStmt { stmts: if has_super { @@ -2163,7 +2163,7 @@ pub fn default_constructor(has_super: bool) -> Constructor { } .into_stmt()] } else { - vec![] + Vec::new() }, ..Default::default() }), @@ -2445,7 +2445,7 @@ impl ExprCtx { where I: IntoIterator>, { - let mut exprs = exprs.into_iter().fold(vec![], |mut v, e| { + let mut exprs = exprs.into_iter().fold(Vec::new(), |mut v, e| { self.extract_side_effects_to(&mut v, *e); v }); diff --git a/crates/swc_ecma_visit/tests/main.rs b/crates/swc_ecma_visit/tests/main.rs index bf128f77087..cfd78bb62f1 100644 --- a/crates/swc_ecma_visit/tests/main.rs +++ b/crates/swc_ecma_visit/tests/main.rs @@ -17,7 +17,7 @@ fn should_visit_program() { let n = Program::Module(Module { span: DUMMY_SP, - body: vec![], + body: Vec::new(), shebang: None, }); diff --git a/crates/swc_eq_ignore_macros/src/lib.rs b/crates/swc_eq_ignore_macros/src/lib.rs index 7466f5e2b4d..cc8d13319a3 100644 --- a/crates/swc_eq_ignore_macros/src/lib.rs +++ b/crates/swc_eq_ignore_macros/src/lib.rs @@ -102,7 +102,7 @@ impl Deriver { fn make_arm_from_fields(&self, pat_path: Path, fields: &Fields) -> Arm { let mut l_pat_fields = Punctuated::<_, Token![,]>::default(); let mut r_pat_fields = Punctuated::<_, Token![,]>::default(); - let mut exprs = vec![]; + let mut exprs = Vec::new(); for (i, field) in fields .iter() diff --git a/crates/swc_estree_compat/src/babelify/expr.rs b/crates/swc_estree_compat/src/babelify/expr.rs index 8bc0d845dbd..3f86586c9fe 100644 --- a/crates/swc_estree_compat/src/babelify/expr.rs +++ b/crates/swc_estree_compat/src/babelify/expr.rs @@ -478,7 +478,7 @@ impl Babelify for NewExpr { .into_iter() .map(|arg| arg.babelify(ctx).into()) .collect(), - None => vec![], + None => Vec::new(), }, type_parameters: self.type_args.map(|t| t.babelify(ctx)), type_arguments: Default::default(), diff --git a/crates/swc_estree_compat/tests/convert.rs b/crates/swc_estree_compat/tests/convert.rs index ab021e4f8e1..b178e807ad6 100644 --- a/crates/swc_estree_compat/tests/convert.rs +++ b/crates/swc_estree_compat/tests/convert.rs @@ -24,7 +24,7 @@ use walkdir::WalkDir; #[test] fn fixtures() -> Result<(), Error> { - let mut tests = vec![]; + let mut tests = Vec::new(); let fixtures_path = PathBuf::from("tests").join("fixtures"); for entry in WalkDir::new(&fixtures_path).into_iter() { diff --git a/crates/swc_fast_ts_strip/Cargo.toml b/crates/swc_fast_ts_strip/Cargo.toml index e3c8ebed013..5533fd323c6 100644 --- a/crates/swc_fast_ts_strip/Cargo.toml +++ b/crates/swc_fast_ts_strip/Cargo.toml @@ -11,8 +11,9 @@ version = "0.4.0" [dependencies] -anyhow = { workspace = true } -serde = { workspace = true, features = ["derive"] } +anyhow = { workspace = true } +serde = { workspace = true, features = ["derive"] } +swc_allocator = { version = "0.1.7", path = "../swc_allocator", default-features = false } swc_common = { version = "0.36.0", path = "../swc_common", features = [ "sourcemap", diff --git a/crates/swc_fast_ts_strip/src/lib.rs b/crates/swc_fast_ts_strip/src/lib.rs index f2ea8400834..f383b77c51e 100644 --- a/crates/swc_fast_ts_strip/src/lib.rs +++ b/crates/swc_fast_ts_strip/src/lib.rs @@ -239,9 +239,9 @@ pub fn operate( program.visit_mut_with(&mut fixer(Some(&comments))); }); - let mut src = vec![]; + let mut src = std::vec::Vec::new(); let mut src_map_buf = if options.source_map { - Some(vec![]) + Some(Vec::new()) } else { None }; @@ -270,7 +270,7 @@ pub fn operate( let map = cm.build_source_map_with_config(&map, None, DefaultSourceMapGenConfig); - let mut s = vec![]; + let mut s = std::vec::Vec::new(); map.to_writer(&mut s) .context("failed to write source map")?; @@ -296,11 +296,11 @@ struct TsStrip { // should be string, but we use u8 for only `)` usage. overwrites: Vec<(BytePos, u8)>, - tokens: Vec, + tokens: std::vec::Vec, } impl TsStrip { - fn new(src: Lrc, tokens: Vec) -> Self { + fn new(src: Lrc, tokens: std::vec::Vec) -> Self { TsStrip { src, replacements: Default::default(), diff --git a/crates/swc_graph_analyzer/tests/cycle.rs b/crates/swc_graph_analyzer/tests/cycle.rs index 5d1cc133d25..2be40e93da9 100644 --- a/crates/swc_graph_analyzer/tests/cycle.rs +++ b/crates/swc_graph_analyzer/tests/cycle.rs @@ -54,11 +54,11 @@ fn stc_1() { assert_cycles( &[ (0, vec![2]), - (1, vec![]), + (1, Vec::new()), (2, vec![1]), (3, vec![0]), (4, vec![2, 3]), ], - vec![], + Vec::new(), ); } diff --git a/crates/swc_html_codegen/src/writer/basic.rs b/crates/swc_html_codegen/src/writer/basic.rs index 773ad224767..cc81c036ab2 100644 --- a/crates/swc_html_codegen/src/writer/basic.rs +++ b/crates/swc_html_codegen/src/writer/basic.rs @@ -236,7 +236,7 @@ where } fn compute_line_starts(s: &str) -> Vec { - let mut res = vec![]; + let mut res = Vec::new(); let mut line_start = 0; let mut chars = s.char_indices().peekable(); diff --git a/crates/swc_html_codegen/tests/fixture.rs b/crates/swc_html_codegen/tests/fixture.rs index 243cc4d9c1e..a357425470d 100644 --- a/crates/swc_html_codegen/tests/fixture.rs +++ b/crates/swc_html_codegen/tests/fixture.rs @@ -41,7 +41,7 @@ fn print_document( run_test2(false, |cm, handler| { let fm = cm.load_file(input).unwrap(); - let mut errors = vec![]; + let mut errors = Vec::new(); let mut document: Document = parse_file_as_document(&fm, parser_config, &mut errors).unwrap(); @@ -61,7 +61,7 @@ fn print_document( .compare_to_file(output) .unwrap(); - let mut errors = vec![]; + let mut errors = Vec::new(); let mut document_parsed_again = parse_file_as_document(&fm_output, parser_config, &mut errors).map_err(|err| { err.to_diagnostics(&handler).emit(); @@ -106,7 +106,7 @@ fn print_document_fragment( run_test2(false, |cm, handler| { let fm = cm.load_file(input).unwrap(); - let mut errors = vec![]; + let mut errors = Vec::new(); let mut document_fragment = parse_file_as_document_fragment( &fm, &context_element, @@ -133,7 +133,7 @@ fn print_document_fragment( .compare_to_file(output) .unwrap(); - let mut errors = vec![]; + let mut errors = Vec::new(); let mut document_fragment_parsed_again = parse_file_as_document_fragment( &fm_output, &context_element, @@ -173,7 +173,7 @@ fn verify_document( testing::run_test2(false, |cm, handler| { let fm = cm.load_file(input).unwrap(); - let mut errors = vec![]; + let mut errors = Vec::new(); let mut document = parse_file_as_document(&fm, parser_config, &mut errors).map_err(|err| { @@ -193,7 +193,7 @@ fn verify_document( gen.emit(&document).unwrap(); let new_fm = cm.new_source_file(FileName::Anon.into(), html_str); - let mut parsed_errors = vec![]; + let mut parsed_errors = Vec::new(); let mut document_parsed_again = parse_file_as_document(&new_fm, parser_config, &mut parsed_errors).map_err(|err| { err.to_diagnostics(&handler).emit(); @@ -231,7 +231,7 @@ fn verify_document_fragment( testing::run_test2(false, |cm, handler| { let fm = cm.load_file(input).unwrap(); - let mut errors = vec![]; + let mut errors = Vec::new(); let mut document_fragment = parse_file_as_document_fragment( &fm, @@ -258,7 +258,7 @@ fn verify_document_fragment( gen.emit(&document_fragment).unwrap(); let new_fm = cm.new_source_file(FileName::Anon.into(), html_str); - let mut parsed_errors = vec![]; + let mut parsed_errors = Vec::new(); let mut document_fragment_parsed_again = parse_file_as_document_fragment( &new_fm, &context_element, @@ -358,9 +358,9 @@ fn test_document_fragment(input: PathBuf) { span: Default::default(), tag_name: "template".into(), namespace: Namespace::HTML, - attributes: vec![], + attributes: Vec::new(), is_self_closing: false, - children: vec![], + children: Vec::new(), content: None, }; @@ -657,9 +657,9 @@ fn html5lib_tests_verify(input: PathBuf) { span: Default::default(), namespace: context_element_namespace, tag_name: context_element_tag_name.into(), - attributes: vec![], + attributes: Vec::new(), is_self_closing: false, - children: vec![], + children: Vec::new(), content: None, }; diff --git a/crates/swc_html_minifier/benches/full.rs b/crates/swc_html_minifier/benches/full.rs index 17d2b855500..4b9d306d1e6 100644 --- a/crates/swc_html_minifier/benches/full.rs +++ b/crates/swc_html_minifier/benches/full.rs @@ -76,7 +76,7 @@ fn run_document(src: &str) { HANDLER.set(&handler, || { let fm = cm.new_source_file(FileName::Anon.into(), src.into()); - let mut errors = vec![]; + let mut errors = Vec::new(); let mut document: Document = parse_file_as_document(&fm, Default::default(), &mut errors).unwrap(); @@ -113,16 +113,16 @@ fn run_document_fragment(src: &str) { HANDLER.set(&handler, || { let fm = cm.new_source_file(FileName::Anon.into(), src.into()); - let mut errors = vec![]; + let mut errors = Vec::new(); let context_element_namespace = Namespace::HTML; let context_element_tag_name = "template"; let context_element = Element { span: Default::default(), namespace: context_element_namespace, tag_name: context_element_tag_name.into(), - attributes: vec![], + attributes: Vec::new(), is_self_closing: false, - children: vec![], + children: Vec::new(), content: None, }; let mut document: DocumentFragment = parse_file_as_document_fragment( diff --git a/crates/swc_html_minifier/src/lib.rs b/crates/swc_html_minifier/src/lib.rs index 2d63c357cc2..102d77c7124 100644 --- a/crates/swc_html_minifier/src/lib.rs +++ b/crates/swc_html_minifier/src/lib.rs @@ -1355,7 +1355,7 @@ impl Minifier<'_> { } if data.is_empty() { - return Some(vec![]); + return Some(Vec::new()); } Some(vec![Child::Text(Text { @@ -1367,7 +1367,7 @@ impl Minifier<'_> { fn minify_children(&mut self, children: &mut Vec) -> Vec { if children.is_empty() { - return vec![]; + return Vec::new(); } let parent = match &self.current_element { @@ -1821,7 +1821,7 @@ impl Minifier<'_> { let cm = Lrc::new(SourceMap::new(FilePathMapping::empty())); // Left - let mut left_errors: Vec<_> = vec![]; + let mut left_errors: Vec<_> = Vec::new(); let left_fm = cm.new_source_file(FileName::Anon.into(), left); let syntax = swc_ecma_parser::Syntax::default(); // Use the latest target for merging @@ -1865,7 +1865,7 @@ impl Minifier<'_> { ); // Right - let mut right_errors: Vec<_> = vec![]; + let mut right_errors: Vec<_> = Vec::new(); let right_fm = cm.new_source_file(FileName::Anon.into(), right); let mut right_program = if is_modules { @@ -1936,7 +1936,7 @@ impl Minifier<'_> { &mut swc_ecma_transforms_base::fixer::fixer(Some(&comments)), ); - let mut buf = vec![]; + let mut buf = Vec::new(); { let wr = Box::new(swc_ecma_codegen::text_writer::JsWriter::new( @@ -1966,7 +1966,7 @@ impl Minifier<'_> { // TODO source map url output for JS and CSS? fn minify_js(&self, data: String, is_module: bool, is_attribute: bool) -> Option { - let mut errors: Vec<_> = vec![]; + let mut errors: Vec<_> = Vec::new(); let cm = Lrc::new(SourceMap::new(FilePathMapping::empty())); let fm = cm.new_source_file(FileName::Anon.into(), data); @@ -2059,7 +2059,7 @@ impl Minifier<'_> { &mut swc_ecma_transforms_base::fixer::fixer(Some(&comments)), ); - let mut buf = vec![]; + let mut buf = Vec::new(); { let mut wr = Box::new(swc_ecma_codegen::text_writer::JsWriter::new( @@ -2148,7 +2148,7 @@ impl Minifier<'_> { } fn minify_css(&self, data: String, mode: CssMinificationMode) -> Option { - let mut errors: Vec<_> = vec![]; + let mut errors: Vec<_> = Vec::new(); let cm = Lrc::new(SourceMap::new(FilePathMapping::empty())); let fm = cm.new_source_file(FileName::Anon.into(), data); @@ -2184,7 +2184,7 @@ impl Minifier<'_> { prelude: swc_css_ast::QualifiedRulePrelude::SelectorList( swc_css_ast::SelectorList { span: Default::default(), - children: vec![], + children: Vec::new(), }, ), block: swc_css_ast::SimpleBlock { @@ -2305,7 +2305,7 @@ impl Minifier<'_> { } fn minify_html(&self, data: String, mode: HtmlMinificationMode) -> Option { - let mut errors: Vec<_> = vec![]; + let mut errors: Vec<_> = Vec::new(); let cm = Lrc::new(SourceMap::new(FilePathMapping::empty())); let fm = cm.new_source_file(FileName::Anon.into(), data); @@ -2322,8 +2322,8 @@ impl Minifier<'_> { span: Default::default(), tag_name: "template".into(), namespace: Namespace::HTML, - attributes: vec![], - children: vec![], + attributes: Vec::new(), + children: Vec::new(), content: None, is_self_closing: false, }); @@ -2489,7 +2489,7 @@ impl Minifier<'_> { &["content-security-policy"], ) => { - let mut new_values = vec![]; + let mut new_values = Vec::new(); for value in value.trim().split(';') { new_values.push( @@ -2700,7 +2700,7 @@ impl VisitMut for Minifier<'_> { tag_name: n.tag_name.clone(), namespace: n.namespace, attributes: n.attributes.clone(), - children: vec![], + children: Vec::new(), content: None, is_self_closing: n.is_self_closing, }); @@ -2725,7 +2725,7 @@ impl VisitMut for Minifier<'_> { self.descendant_of_pre = old_descendant_of_pre; } - let mut remove_list = vec![]; + let mut remove_list = Vec::new(); for (i, i1) in n.attributes.iter().enumerate() { if i1.value.is_some() { diff --git a/crates/swc_html_minifier/tests/fixture.rs b/crates/swc_html_minifier/tests/fixture.rs index 0258c37d3d3..8beaaf4cb29 100644 --- a/crates/swc_html_minifier/tests/fixture.rs +++ b/crates/swc_html_minifier/tests/fixture.rs @@ -37,7 +37,7 @@ fn test_minify_document(input: PathBuf) { testing::run_test(false, |cm, handler| { let fm = cm.load_file(&input).unwrap(); - let mut errors = vec![]; + let mut errors = Vec::new(); let result: Result = parse_file_as_document(&fm, Default::default(), &mut errors); @@ -131,13 +131,13 @@ fn test_minify_document_fragment(input: PathBuf) { span: Default::default(), namespace: context_element_namespace, tag_name: context_element_tag_name.into(), - attributes: vec![], + attributes: Vec::new(), is_self_closing: false, - children: vec![], + children: Vec::new(), content: None, }; - let mut errors = vec![]; + let mut errors = Vec::new(); let result: Result = parse_file_as_document_fragment( &fm, &context_element, @@ -200,7 +200,7 @@ fn test_minify_recovery(input: PathBuf) { testing::run_test(false, |cm, handler| { let fm = cm.load_file(&input).unwrap(); - let mut errors = vec![]; + let mut errors = Vec::new(); let result: Result = parse_file_as_document(&fm, Default::default(), &mut errors); diff --git a/crates/swc_html_parser/benches/compare.rs b/crates/swc_html_parser/benches/compare.rs index 42d2d5c5fdf..77b83a210b3 100644 --- a/crates/swc_html_parser/benches/compare.rs +++ b/crates/swc_html_parser/benches/compare.rs @@ -45,9 +45,9 @@ where span: Default::default(), tag_name: "template".into(), namespace: Namespace::HTML, - attributes: vec![], + attributes: Vec::new(), is_self_closing: false, - children: vec![], + children: Vec::new(), content: None, }, DocumentMode::NoQuirks, diff --git a/crates/swc_html_parser/benches/parser.rs b/crates/swc_html_parser/benches/parser.rs index b2823d8a41f..7416781d0e6 100644 --- a/crates/swc_html_parser/benches/parser.rs +++ b/crates/swc_html_parser/benches/parser.rs @@ -36,9 +36,9 @@ fn bench_document_fragment(b: &mut Bencher, src: &'static str) { span: Default::default(), tag_name: "template".into(), namespace: Namespace::HTML, - attributes: vec![], + attributes: Vec::new(), is_self_closing: false, - children: vec![], + children: Vec::new(), content: None, }, DocumentMode::NoQuirks, diff --git a/crates/swc_html_parser/src/lexer/mod.rs b/crates/swc_html_parser/src/lexer/mod.rs index d8e141a2080..b7379faecda 100644 --- a/crates/swc_html_parser/src/lexer/mod.rs +++ b/crates/swc_html_parser/src/lexer/mod.rs @@ -135,7 +135,7 @@ where finished: false, state: State::Data, return_state: State::Data, - errors: vec![], + errors: Vec::new(), last_start_tag_name: None, pending_tokens: VecDeque::with_capacity(16), buf: Rc::new(RefCell::new(String::with_capacity(256))), @@ -620,7 +620,7 @@ where tag_name: js_word!(""), raw_tag_name: None, is_self_closing: false, - attributes: vec![], + attributes: Vec::new(), }); } @@ -632,7 +632,7 @@ where raw_tag_name: None, is_self_closing: false, // In valid HTML code closed tags do not have attributes - attributes: vec![], + attributes: Vec::new(), }); } diff --git a/crates/swc_html_parser/src/parser/mod.rs b/crates/swc_html_parser/src/parser/mod.rs index 5e8bc8290b4..d9e9374d6e3 100644 --- a/crates/swc_html_parser/src/parser/mod.rs +++ b/crates/swc_html_parser/src/parser/mod.rs @@ -475,7 +475,7 @@ where let (children, content) = if namespace == Namespace::HTML && &tag_name == "template" { ( - vec![], + Vec::new(), Some(DocumentFragment { span, children: new_children, @@ -1120,7 +1120,7 @@ where tag_name: $tag_name.to_owned(), raw_tag_name: None, is_self_closing: false, - attributes: vec![], + attributes: Vec::new(), }, }; self.process_token(&mut end_token_and_info, None)?; @@ -7664,7 +7664,7 @@ where Data::Element { tag_name: "html".into(), namespace: Namespace::HTML, - attributes: RefCell::new(vec![]), + attributes: RefCell::new(Vec::new()), is_self_closing: false, }, DUMMY_SP, @@ -7682,7 +7682,7 @@ where tag_name: tag_name.into(), raw_tag_name: None, is_self_closing: false, - attributes: vec![], + attributes: Vec::new(), }, } } diff --git a/crates/swc_html_parser/src/parser/node.rs b/crates/swc_html_parser/src/parser/node.rs index 2cc2396187f..e61ec65d247 100644 --- a/crates/swc_html_parser/src/parser/node.rs +++ b/crates/swc_html_parser/src/parser/node.rs @@ -55,7 +55,7 @@ impl Node { pub fn new(data: Data, span: Span) -> Rc { Rc::new(Node { parent: Cell::new(None), - children: RefCell::new(vec![]), + children: RefCell::new(Vec::new()), start_span: RefCell::new(span), end_span: RefCell::new(None), data, diff --git a/crates/swc_html_parser/tests/html5lib_tests.rs b/crates/swc_html_parser/tests/html5lib_tests.rs index 278885309c5..159b1b99967 100644 --- a/crates/swc_html_parser/tests/html5lib_tests.rs +++ b/crates/swc_html_parser/tests/html5lib_tests.rs @@ -74,7 +74,7 @@ fn html5lib_test_tokenizer(input: PathBuf) { .expect("failed to get input in test"); let states = if let Some(initial_states) = test.get("initialStates") { - let mut states = vec![]; + let mut states = Vec::new(); let json_states: Vec = serde_json::from_value(initial_states.clone()) .expect("failed to get input in test"); @@ -146,7 +146,7 @@ fn html5lib_test_tokenizer(input: PathBuf) { lexer.set_last_start_tag_name(&last_start_tag); } - let mut actual_tokens = vec![]; + let mut actual_tokens = Vec::new(); loop { let token_and_span = lexer.next(); @@ -168,7 +168,7 @@ fn html5lib_test_tokenizer(input: PathBuf) { } => { *raw_tag_name = None; - let mut new_attributes = vec![]; + let mut new_attributes = Vec::new(); let mut already_seen: AHashSet = Default::default(); for mut attribute in take(attributes) { @@ -201,7 +201,7 @@ fn html5lib_test_tokenizer(input: PathBuf) { } => { *raw_tag_name = None; *is_self_closing = false; - *attributes = vec![]; + *attributes = Vec::new(); } Token::Character { ref mut raw, .. } => { *raw = None; @@ -215,7 +215,7 @@ fn html5lib_test_tokenizer(input: PathBuf) { actual_tokens.push(new_token); } - let mut expected_tokens: Vec = vec![]; + let mut expected_tokens: Vec = Vec::new(); if let Some(output_tokens) = json_output.as_array() { for output_token in output_tokens { @@ -248,7 +248,7 @@ fn html5lib_test_tokenizer(input: PathBuf) { let tag_name: String = serde_json::from_value(token_parts[1].clone()) .expect("failed to deserialize"); - let mut attributes = vec![]; + let mut attributes = Vec::new(); if let Some(json_attributes) = token_parts.get(2) { let obj_attributes: Value = @@ -308,7 +308,7 @@ fn html5lib_test_tokenizer(input: PathBuf) { tag_name: tag_name.into(), raw_tag_name: None, is_self_closing: false, - attributes: vec![], + attributes: Vec::new(), }] } "Character" => { @@ -325,7 +325,7 @@ fn html5lib_test_tokenizer(input: PathBuf) { }; } - let mut tokens = vec![]; + let mut tokens = Vec::new(); for c in data.chars() { tokens.push(Token::Character { @@ -578,11 +578,11 @@ fn html5lib_test_tree_construction(input: PathBuf) { let mut counter = 0; while let Some(test) = tests.next() { - let mut data: Vec<&str> = vec![]; - let mut document: Vec<&str> = vec![]; - let mut document_fragment: Vec<&str> = vec![]; - let mut errors: Vec<&str> = vec![]; - let mut new_errors: Vec<&str> = vec![]; + let mut data: Vec<&str> = Vec::new(); + let mut document: Vec<&str> = Vec::new(); + let mut document_fragment: Vec<&str> = Vec::new(); + let mut errors: Vec<&str> = Vec::new(); + let mut new_errors: Vec<&str> = Vec::new(); let mut scripting_enabled = false; let mut state = Some(TestState::Data); @@ -760,9 +760,9 @@ fn html5lib_test_tree_construction(input: PathBuf) { span: Default::default(), namespace: context_element_namespace, tag_name: context_element_tag_name.into(), - attributes: vec![], + attributes: Vec::new(), is_self_closing: false, - children: vec![], + children: Vec::new(), content: None, }; diff --git a/crates/swc_macros_common/src/binder.rs b/crates/swc_macros_common/src/binder.rs index 921a019bc10..b4ebee72597 100644 --- a/crates/swc_macros_common/src/binder.rs +++ b/crates/swc_macros_common/src/binder.rs @@ -148,13 +148,13 @@ impl<'a> VariantBinder<'a> { }); // Unit struct does not have any field to bind - (pat, vec![]) + (pat, Vec::new()) } Fields::Named(FieldsNamed { named: ref fields, brace_token, }) => { - let mut bindings = vec![]; + let mut bindings = Vec::new(); let fields = fields .pairs() @@ -213,7 +213,7 @@ impl<'a> VariantBinder<'a> { paren_token, }) => { // TODO - let mut bindings = vec![]; + let mut bindings = Vec::new(); let pats = fields .pairs() diff --git a/crates/swc_macros_common/src/derive.rs b/crates/swc_macros_common/src/derive.rs index e9e0fb93280..630c5df76fd 100644 --- a/crates/swc_macros_common/src/derive.rs +++ b/crates/swc_macros_common/src/derive.rs @@ -59,7 +59,7 @@ impl<'a> Derive<'a> { Derive { input, out: ItemImpl { - attrs: vec![], + attrs: Vec::new(), impl_token: Token!(impl)(def_site()), brace_token: Default::default(), defaultness: None, diff --git a/crates/swc_macros_common/src/derive/generics.rs b/crates/swc_macros_common/src/derive/generics.rs index 855cb148552..d6bd4f42f23 100644 --- a/crates/swc_macros_common/src/derive/generics.rs +++ b/crates/swc_macros_common/src/derive/generics.rs @@ -67,7 +67,7 @@ impl<'a> Derive<'a> { _ => None, }) .collect(), - fields: vec![], + fields: Vec::new(), }; vis.visit_derive_input(self.input); diff --git a/crates/swc_node_bundler/src/loaders/json.rs b/crates/swc_node_bundler/src/loaders/json.rs index 9261a96bafe..c1729b5ecde 100644 --- a/crates/swc_node_bundler/src/loaders/json.rs +++ b/crates/swc_node_bundler/src/loaders/json.rs @@ -6,8 +6,14 @@ use swc_ecma_ast::*; use swc_ecma_parser::{parse_file_as_expr, Syntax}; pub(super) fn load_json_as_module(fm: &Arc) -> Result { - let expr = parse_file_as_expr(fm, Syntax::default(), EsVersion::Es2020, None, &mut vec![]) - .map_err(|err| anyhow!("failed parse json as javascript object: {:#?}", err))?; + let expr = parse_file_as_expr( + fm, + Syntax::default(), + EsVersion::Es2020, + None, + &mut Vec::new(), + ) + .map_err(|err| anyhow!("failed parse json as javascript object: {:#?}", err))?; let export = ExprStmt { span: DUMMY_SP, diff --git a/crates/swc_node_bundler/src/loaders/swc.rs b/crates/swc_node_bundler/src/loaders/swc.rs index 37653b30b7d..0de49ef8163 100644 --- a/crates/swc_node_bundler/src/loaders/swc.rs +++ b/crates/swc_node_bundler/src/loaders/swc.rs @@ -118,7 +118,7 @@ impl SwcLoader { Syntax::Es(Default::default()), Default::default(), None, - &mut vec![], + &mut Vec::new(), ) .unwrap(); return Ok(ModuleData { diff --git a/crates/swc_plugin/src/allocation.rs b/crates/swc_plugin/src/allocation.rs index 53828d2b822..df7379630ac 100644 --- a/crates/swc_plugin/src/allocation.rs +++ b/crates/swc_plugin/src/allocation.rs @@ -39,7 +39,7 @@ pub extern "C" fn __free(ptr: *mut u8, size: i32) -> i32 { /// Allocates memory area of specified size and returns its address. /// Returns 0 if supplied size is too long. /// [TODO]: This is for the experiment to alloc memory with specified layout instead of -/// manually creating vec![] and forget it. This is not used yet. +/// manually creating Vec::new() and forget it. This is not used yet. #[doc(hidden)] #[cfg(all(target_arch = "wasm32", feature = "layout_alloc"))] #[no_mangle] diff --git a/crates/swc_plugin_runner/benches/ecma_invoke.rs b/crates/swc_plugin_runner/benches/ecma_invoke.rs index 3c2c04d3124..c56930cf2bd 100644 --- a/crates/swc_plugin_runner/benches/ecma_invoke.rs +++ b/crates/swc_plugin_runner/benches/ecma_invoke.rs @@ -77,7 +77,7 @@ fn bench_transform(b: &mut Bencher, plugin_dir: &Path) { Default::default(), EsVersion::latest(), None, - &mut vec![], + &mut Vec::new(), ) .unwrap(); diff --git a/crates/swc_plugin_runner/src/transform_executor.rs b/crates/swc_plugin_runner/src/transform_executor.rs index a764d3962bb..e09d3af60e8 100644 --- a/crates/swc_plugin_runner/src/transform_executor.rs +++ b/crates/swc_plugin_runner/src/transform_executor.rs @@ -221,7 +221,7 @@ impl TransformExecutor { // corresponding store let (mut store, module) = self.module_bytes.compile_module()?; - let context_key_buffer = Arc::new(Mutex::new(vec![])); + let context_key_buffer = Arc::new(Mutex::new(Vec::new())); let metadata_env = FunctionEnv::new( &mut store, MetadataContextHostEnvironment::new( @@ -231,7 +231,7 @@ impl TransformExecutor { ), ); - let transform_result: Arc>> = Arc::new(Mutex::new(vec![])); + let transform_result: Arc>> = Arc::new(Mutex::new(Vec::new())); let transform_env = FunctionEnv::new( &mut store, TransformResultHostEnvironment::new(&transform_result), @@ -239,12 +239,12 @@ impl TransformExecutor { let base_env = FunctionEnv::new(&mut store, BaseHostEnvironment::new()); - let comment_buffer = Arc::new(Mutex::new(vec![])); + let comment_buffer = Arc::new(Mutex::new(Vec::new())); let comments_env = FunctionEnv::new(&mut store, CommentHostEnvironment::new(&comment_buffer)); - let source_map_buffer = Arc::new(Mutex::new(vec![])); + let source_map_buffer = Arc::new(Mutex::new(Vec::new())); let source_map = Arc::new(Mutex::new(self.source_map.clone())); let source_map_host_env = FunctionEnv::new( @@ -252,7 +252,7 @@ impl TransformExecutor { SourceMapHostEnvironment::new(&source_map, &source_map_buffer), ); - let diagnostics_buffer: Arc>> = Arc::new(Mutex::new(vec![])); + let diagnostics_buffer: Arc>> = Arc::new(Mutex::new(Vec::new())); let diagnostics_env = FunctionEnv::new( &mut store, DiagnosticContextHostEnvironment::new(&diagnostics_buffer), diff --git a/crates/swc_plugin_runner/tests/css_rkyv.rs b/crates/swc_plugin_runner/tests/css_rkyv.rs index 0b42d95fee4..00b2436e221 100644 --- a/crates/swc_plugin_runner/tests/css_rkyv.rs +++ b/crates/swc_plugin_runner/tests/css_rkyv.rs @@ -85,7 +85,7 @@ fn invoke(input: PathBuf) { let fm = cm.new_source_file(FileName::Anon.into(), "console.log(foo)".into()); let parsed: Stylesheet = - swc_css_parser::parse_file(&fm, None, Default::default(), &mut vec![]).unwrap(); + swc_css_parser::parse_file(&fm, None, Default::default(), &mut Vec::new()).unwrap(); let program = PluginSerializedBytes::try_serialize( &swc_common::plugin::serialized::VersionedSerializable::new(parsed.clone()), @@ -136,7 +136,7 @@ fn invoke(input: PathBuf) { let fm = cm.new_source_file(FileName::Anon.into(), "console.log(foo)".into()); let parsed: Stylesheet = - swc_css_parser::parse_file(&fm, None, Default::default(), &mut vec![]).unwrap(); + swc_css_parser::parse_file(&fm, None, Default::default(), &mut Vec::new()).unwrap(); let mut serialized_program = PluginSerializedBytes::try_serialize( &swc_common::plugin::serialized::VersionedSerializable::new(parsed.clone()), diff --git a/crates/swc_plugin_runner/tests/ecma_integration.rs b/crates/swc_plugin_runner/tests/ecma_integration.rs index 55181c83212..0b0c01cfb27 100644 --- a/crates/swc_plugin_runner/tests/ecma_integration.rs +++ b/crates/swc_plugin_runner/tests/ecma_integration.rs @@ -114,7 +114,7 @@ fn internal() { Syntax::Es(Default::default()), EsVersion::latest(), None, - &mut vec![], + &mut Vec::new(), ) .unwrap(); @@ -182,7 +182,7 @@ fn internal() { Syntax::Es(Default::default()), EsVersion::latest(), None, - &mut vec![], + &mut Vec::new(), ) .unwrap(); diff --git a/crates/swc_plugin_runner/tests/ecma_rkyv.rs b/crates/swc_plugin_runner/tests/ecma_rkyv.rs index 651be959d3e..235cd645bf8 100644 --- a/crates/swc_plugin_runner/tests/ecma_rkyv.rs +++ b/crates/swc_plugin_runner/tests/ecma_rkyv.rs @@ -92,7 +92,7 @@ fn internal(input: PathBuf) { }), EsVersion::latest(), None, - &mut vec![], + &mut Vec::new(), ) .unwrap(); @@ -149,7 +149,7 @@ fn internal(input: PathBuf) { Syntax::Es(Default::default()), EsVersion::latest(), None, - &mut vec![], + &mut Vec::new(), ) .unwrap(); diff --git a/crates/swc_plugin_runner/tests/issues.rs b/crates/swc_plugin_runner/tests/issues.rs index a4e9f9da51f..f6503639256 100644 --- a/crates/swc_plugin_runner/tests/issues.rs +++ b/crates/swc_plugin_runner/tests/issues.rs @@ -74,7 +74,7 @@ fn issue_6404() -> Result<(), Error> { Syntax::Es(Default::default()), EsVersion::latest(), None, - &mut vec![], + &mut Vec::new(), ) .unwrap(); diff --git a/crates/swc_typescript/src/fast_dts/mod.rs b/crates/swc_typescript/src/fast_dts/mod.rs index ef6152bd35d..0514ef67365 100644 --- a/crates/swc_typescript/src/fast_dts/mod.rs +++ b/crates/swc_typescript/src/fast_dts/mod.rs @@ -37,7 +37,7 @@ impl FastDts { filename, is_top_level: false, id_counter: 0, - diagnostics: vec![], + diagnostics: Vec::new(), } } @@ -249,7 +249,7 @@ impl FastDts { ) -> Option> { match *e { Expr::Array(arr) => { - let mut elem_types: Vec = vec![]; + let mut elem_types: Vec = Vec::new(); for elems in arr.elems { if let Some(expr_or_spread) = elems { @@ -285,7 +285,7 @@ impl FastDts { } Expr::Object(obj) => { - let mut members: Vec = vec![]; + let mut members: Vec = Vec::new(); // TODO: Prescan all object properties to know which ones // have a getter or a setter. This allows us to apply diff --git a/crates/swc_typescript/tests/fast_dts_deno.rs b/crates/swc_typescript/tests/fast_dts_deno.rs index 180fdd68200..a35dfd279eb 100644 --- a/crates/swc_typescript/tests/fast_dts_deno.rs +++ b/crates/swc_typescript/tests/fast_dts_deno.rs @@ -22,7 +22,7 @@ fn transform_dts_test(source: &str, expected: &str) { }), EsVersion::latest(), None, - &mut vec![], + &mut Vec::new(), ) .unwrap(); diff --git a/crates/swc_visit_macros/src/lib.rs b/crates/swc_visit_macros/src/lib.rs index 876d91fc86c..a5f769f17fd 100644 --- a/crates/swc_visit_macros/src/lib.rs +++ b/crates/swc_visit_macros/src/lib.rs @@ -140,7 +140,7 @@ pub fn define(tts: proc_macro::TokenStream) -> proc_macro::TokenStream { } )); - let mut field_module_body = vec![]; + let mut field_module_body = Vec::new(); { for stmts in block.stmts.iter() { let item = match stmts { @@ -223,24 +223,24 @@ fn make_field_enum_variant_from_named_field(type_name: &Ident, f: &Field) -> Var } fn make_field_enum(item: &Item) -> Vec { - let mut items = vec![]; + let mut items = Vec::new(); let name = match item { Item::Struct(s) => s.ident.clone(), Item::Enum(e) => { // Skip C-like enums if e.variants.iter().all(|v| v.fields.is_empty()) { - return vec![]; + return Vec::new(); } e.ident.clone() } - _ => return vec![], + _ => return Vec::new(), }; let name = Ident::new(&format!("{}Field", name), name.span()); { - let mut attrs = vec![]; + let mut attrs = Vec::new(); let variants = match item { Item::Struct(s) => { @@ -276,7 +276,7 @@ fn make_field_enum(item: &Item) -> Vec { variants } - _ => return vec![], + _ => return Vec::new(), }; attrs.push(Attribute { @@ -315,7 +315,7 @@ fn make_field_enum(item: &Item) -> Vec { } { - let mut methods = vec![]; + let mut methods = Vec::new(); methods.push(ImplItem::Fn(ImplItemFn { attrs: vec![make_doc_attr("This is not considered as a public API")], @@ -352,7 +352,7 @@ fn make_field_enum(item: &Item) -> Vec { output: ReturnType::Default, }, block: { - let mut arms = vec![]; + let mut arms = Vec::new(); if let Item::Struct(s) = item { for f in s.fields.iter() { @@ -510,7 +510,7 @@ fn make_ast_enum(stmts: &[Stmt], is_ref: bool) -> Item { discriminant: None, }); } - let mut attrs = vec![]; + let mut attrs = Vec::new(); attrs.push(Attribute { pound_token: Default::default(), @@ -621,7 +621,7 @@ fn make_impl_parent_kind(stmts: &[Stmt]) -> ItemImpl { block: Block { brace_token: Default::default(), stmts: { - let mut arms = vec![]; + let mut arms = Vec::new(); for stmt in stmts { let item = match stmt { @@ -725,7 +725,7 @@ fn make_impl_kind_for_node_ref(stmts: &[Stmt]) -> Option { block: Block { brace_token: Default::default(), stmts: { - let mut arms = vec![]; + let mut arms = Vec::new(); for stmt in stmts { let item = match stmt { @@ -856,7 +856,7 @@ fn make_impl_kind_for_node_ref(stmts: &[Stmt]) -> Option { block: Block { brace_token: Default::default(), stmts: { - let mut arms = vec![]; + let mut arms = Vec::new(); for stmt in stmts { let item = match stmt { @@ -941,8 +941,8 @@ fn make_impl_kind_for_node_ref(stmts: &[Stmt]) -> Option { } fn make(mode: Mode, stmts: &[Stmt]) -> TokenStream { - let mut types = vec![]; - let mut methods = vec![]; + let mut types = Vec::new(); + let mut methods = Vec::new(); for stmts in stmts { let item = match stmts { @@ -960,12 +960,12 @@ fn make(mode: Mode, stmts: &[Stmt]) -> TokenStream { } let mut tokens = quote!(); - let mut ref_methods = vec![]; - let mut optional_methods = vec![]; - let mut either_methods = vec![]; - let mut visit_all_methods = vec![]; + let mut ref_methods = Vec::new(); + let mut optional_methods = Vec::new(); + let mut either_methods = Vec::new(); + let mut visit_all_methods = Vec::new(); { - let mut new = vec![]; + let mut new = Vec::new(); for ty in &types { add_required(&mut new, ty); } @@ -991,7 +991,7 @@ fn make(mode: Mode, stmts: &[Stmt]) -> TokenStream { } methods.push(TraitItemFn { - attrs: vec![], + attrs: Vec::new(), sig, default: Some(create_method_body(mode, ty)), semi_token: None, @@ -1011,7 +1011,7 @@ fn make(mode: Mode, stmts: &[Stmt]) -> TokenStream { let block = parse_quote!({ #call }); ref_methods.push(ImplItemFn { - attrs: vec![], + attrs: Vec::new(), vis: Visibility::Inherited, defaultness: None, sig: sig.clone(), @@ -1023,7 +1023,7 @@ fn make(mode: Mode, stmts: &[Stmt]) -> TokenStream { // Either either_methods.push(ImplItemFn { - attrs: vec![], + attrs: Vec::new(), vis: Visibility::Inherited, defaultness: None, sig: sig.clone(), @@ -1044,7 +1044,7 @@ fn make(mode: Mode, stmts: &[Stmt]) -> TokenStream { // Optional optional_methods.push(ImplItemFn { - attrs: vec![], + attrs: Vec::new(), vis: Visibility::Inherited, defaultness: None, sig: sig.clone(), @@ -1087,7 +1087,7 @@ fn make(mode: Mode, stmts: &[Stmt]) -> TokenStream { // Visit <-> VisitAll using ::swc_visit::All visit_all_methods.push(ImplItemFn { - attrs: vec![], + attrs: Vec::new(), vis: Visibility::Inherited, defaultness: None, sig: sig.clone(), @@ -1239,7 +1239,7 @@ fn make(mode: Mode, stmts: &[Stmt]) -> TokenStream { } }); - let mut attrs = vec![]; + let mut attrs = Vec::new(); if let Some(VisitorVariant::WithPath) = mode.visitor_variant() { attrs.extend(feature_path_attrs()) @@ -2021,7 +2021,7 @@ fn make_arm_from_struct( variant: &Fields, use_ast_path: bool, ) -> Arm { - let mut stmts = vec![]; + let mut stmts = Vec::new(); let mut fields: Punctuated = Default::default(); for (i, field) in variant.iter().enumerate() { @@ -2057,7 +2057,7 @@ fn make_arm_from_struct( } fields.push(FieldPat { - attrs: vec![], + attrs: Vec::new(), member: if field.ident.is_none() { Member::Unnamed(Index { index: i as _, @@ -2091,9 +2091,9 @@ fn make_arm_from_struct( }; Arm { - attrs: vec![], + attrs: Vec::new(), pat: Pat::Struct(PatStruct { - attrs: vec![], + attrs: Vec::new(), qself: None, path: path.clone(), brace_token: Default::default(), @@ -2103,7 +2103,7 @@ fn make_arm_from_struct( guard: None, fat_arrow_token: Default::default(), body: Box::new(Expr::Block(ExprBlock { - attrs: vec![], + attrs: Vec::new(), label: None, block, })), @@ -2175,7 +2175,7 @@ fn method_sig_from_ident(mode: Mode, v: &Ident) -> Signature { /// Returns None if it's skipped. fn make_method(mode: Mode, e: &Item, types: &mut Vec) -> Option { - let mut attrs = vec![]; + let mut attrs = Vec::new(); { attrs.push(make_doc_attr( @@ -2252,7 +2252,7 @@ fn make_method(mode: Mode, e: &Item, types: &mut Vec) -> Option) -> Option Block { Mode::VisitMut { .. } => { return Block { brace_token: Default::default(), - stmts: vec![], + stmts: Vec::new(), } } Mode::Fold { .. } => return parse_quote!({ n }), diff --git a/crates/swc_xml_codegen/src/writer/basic.rs b/crates/swc_xml_codegen/src/writer/basic.rs index cc80a8d9dce..b1bdf0dc984 100644 --- a/crates/swc_xml_codegen/src/writer/basic.rs +++ b/crates/swc_xml_codegen/src/writer/basic.rs @@ -236,7 +236,7 @@ where } fn compute_line_starts(s: &str) -> Vec { - let mut res = vec![]; + let mut res = Vec::new(); let mut line_start = 0; let mut chars = s.char_indices().peekable(); diff --git a/crates/swc_xml_codegen/tests/fixture.rs b/crates/swc_xml_codegen/tests/fixture.rs index e908eb8d8ac..e4638fd59dd 100644 --- a/crates/swc_xml_codegen/tests/fixture.rs +++ b/crates/swc_xml_codegen/tests/fixture.rs @@ -39,7 +39,7 @@ fn print_document( run_test2(false, |cm, handler| { let fm = cm.load_file(input).unwrap(); - let mut errors = vec![]; + let mut errors = Vec::new(); let mut document: Document = parse_file_as_document(&fm, parser_config, &mut errors).unwrap(); @@ -59,7 +59,7 @@ fn print_document( .compare_to_file(output) .unwrap(); - let mut errors = vec![]; + let mut errors = Vec::new(); let mut document_parsed_again = parse_file_as_document(&fm_output, parser_config, &mut errors).map_err(|err| { err.to_diagnostics(&handler).emit(); @@ -92,7 +92,7 @@ fn verify_document( testing::run_test2(false, |cm, handler| { let fm = cm.load_file(input).unwrap(); - let mut errors = vec![]; + let mut errors = Vec::new(); let mut document = parse_file_as_document(&fm, parser_config, &mut errors).map_err(|err| { @@ -112,7 +112,7 @@ fn verify_document( gen.emit(&document).unwrap(); let new_fm = cm.new_source_file(FileName::Anon.into(), xml_str); - let mut parsed_errors = vec![]; + let mut parsed_errors = Vec::new(); let mut document_parsed_again = parse_file_as_document(&new_fm, parser_config, &mut parsed_errors).map_err(|err| { err.to_diagnostics(&handler).emit(); diff --git a/crates/swc_xml_parser/src/lexer/mod.rs b/crates/swc_xml_parser/src/lexer/mod.rs index 5fba293e7fb..e8aa7000580 100644 --- a/crates/swc_xml_parser/src/lexer/mod.rs +++ b/crates/swc_xml_parser/src/lexer/mod.rs @@ -156,7 +156,7 @@ where finished: false, state: State::Data, return_state: None, - errors: vec![], + errors: Vec::new(), additional_allowed_character: None, pending_tokens: VecDeque::new(), doctype_raw: None, @@ -436,7 +436,7 @@ where }, Some('#') => { let mut base = 10; - let mut characters = vec![]; + let mut characters = Vec::new(); let mut has_semicolon = false; match self.consume_next_char() { diff --git a/crates/swc_xml_parser/src/parser/node.rs b/crates/swc_xml_parser/src/parser/node.rs index 2d343b48154..676afed6d6c 100644 --- a/crates/swc_xml_parser/src/parser/node.rs +++ b/crates/swc_xml_parser/src/parser/node.rs @@ -61,7 +61,7 @@ impl Node { pub fn new(data: Data, span: Span) -> Rc { Rc::new(Node { parent: Cell::new(None), - children: RefCell::new(vec![]), + children: RefCell::new(Vec::new()), start_span: RefCell::new(span), end_span: RefCell::new(None), data, diff --git a/crates/testing_macros/src/fixture.rs b/crates/testing_macros/src/fixture.rs index 58cc2004cb2..74ddcb9fcef 100644 --- a/crates/testing_macros/src/fixture.rs +++ b/crates/testing_macros/src/fixture.rs @@ -79,7 +79,7 @@ impl Parse for Config { let mut config = Self { pattern, - exclude_patterns: vec![], + exclude_patterns: Vec::new(), }; let comma: Option = input.parse()?; @@ -101,7 +101,7 @@ pub fn expand(callee: &Ident, attr: Config) -> Result, Error> { let paths = glob(&pattern).with_context(|| format!("glob failed for whole path: `{}`", pattern))?; - let mut test_fns = vec![]; + let mut test_fns = Vec::new(); // Allow only alphanumeric and underscore characters for the test_name. static RE: Lazy = Lazy::new(|| Regex::new(r"[^A-Za-z0-9_]").unwrap()); diff --git a/scripts/git-diff.sh b/scripts/git-diff.sh new file mode 100755 index 00000000000..5bf675d2efa --- /dev/null +++ b/scripts/git-diff.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +# +# Used to generate `swc-bump` +set -eu + + +git diff --name-only HEAD upstream/main | grep -E '^crates/' | sed -e "s/^crates\///" | sed 's/\/.*//' | uniq \ No newline at end of file diff --git a/tools/generate-code/src/generators/visitor.rs b/tools/generate-code/src/generators/visitor.rs index 2e0a46d9bec..ecd5b1a7f14 100644 --- a/tools/generate-code/src/generators/visitor.rs +++ b/tools/generate-code/src/generators/visitor.rs @@ -390,7 +390,7 @@ impl Generator { } fn base_trait_attrs(&self) -> Vec { - let mut attrs = vec![]; + let mut attrs = Vec::new(); if self.variant == Variant::AstPath { attrs.push(parse_quote!(#[cfg(any(docsrs, feature = "path"))])); @@ -583,7 +583,7 @@ impl Generator { let visitor_trait_name = self.trait_name(false); let trait_name = self.trait_name(true); let attrs = self.base_trait_attrs(); - let mut visit_with_trait_methods: Vec = vec![]; + let mut visit_with_trait_methods: Vec = Vec::new(); { let lifetime = self.method_lifetime(); @@ -619,7 +619,7 @@ impl Generator { )); } - let mut items: Vec = vec![]; + let mut items: Vec = Vec::new(); items.push(parse_quote!( /// A trait implemented for types that can be visited using a visitor. #(#attrs)* @@ -636,7 +636,7 @@ impl Generator { let trait_name = self.trait_name(true); let attrs = self.base_trait_attrs(); - let mut items: Vec = vec![]; + let mut items: Vec = Vec::new(); for node_type in node_types { let type_name = match node_type { @@ -686,7 +686,7 @@ impl Generator { let default_body: Expr = match node_type { Item::Enum(data) => { let name = &data.ident; - let mut match_arms = vec![]; + let mut match_arms = Vec::new(); for v in &data.variants { let variant_name = &v.ident; @@ -780,8 +780,8 @@ impl Generator { match fields { Fields::Named(n) => { - let mut stmts: Vec = vec![]; - let mut bindings = vec![]; + let mut stmts: Vec = Vec::new(); + let mut bindings = Vec::new(); let mut reconstruct = match self.kind { TraitKind::Visit | TraitKind::VisitAll | TraitKind::VisitMut => None, TraitKind::Fold => Some(Vec::::new()), @@ -874,7 +874,7 @@ impl Generator { } } Fields::Unnamed(u) => { - let mut stmts: Vec = vec![]; + let mut stmts: Vec = Vec::new(); let mut bindings = Vec::::new(); let mut reconstruct = match self.kind { TraitKind::Visit | TraitKind::VisitAll | TraitKind::VisitMut => None, @@ -943,7 +943,7 @@ impl Generator { let receiver = self.parameter_type_token(quote!(self)); - let mut items: Vec = vec![]; + let mut items: Vec = Vec::new(); for node_type in non_leaf_types { let visit_with_name = Ident::new( @@ -1265,8 +1265,8 @@ fn extract_generic<'a>(name: &str, ty: &'a Type) -> Option<&'a Type> { } fn define_fields(crate_name: &Ident, node_types: &[&Item]) -> Vec { let mut items = Vec::::new(); - let mut kind_enum_members = vec![]; - let mut node_ref_enum_members = vec![]; + let mut kind_enum_members = Vec::new(); + let mut node_ref_enum_members = Vec::new(); let mut kind_set_index_arms = Vec::::new(); let mut node_ref_set_index_arms = Vec::::new(); @@ -1288,7 +1288,7 @@ fn define_fields(crate_name: &Ident, node_types: &[&Item]) -> Vec { let fields_enum_name = Ident::new(&format!("{type_name}Field"), Span::call_site()); - let mut variants = vec![]; + let mut variants = Vec::new(); kind_set_index_arms.push(parse_quote!( Self::#type_name(v) => v.set_index(index),