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

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

4
Cargo.lock generated
View File

@ -3866,6 +3866,7 @@ dependencies = [
"serde",
"serde_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",

View File

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

View File

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

View File

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

View File

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

View File

@ -32,7 +32,7 @@ fn derive(
_ => panic!("#[derive(FromVariant)] only works for an enum."),
};
let mut from_impls: Vec<ItemImpl> = vec![];
let mut from_impls: Vec<ItemImpl> = Vec::new();
for v in variants {
let variant_name = v.ident;

View File

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

View File

@ -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);

View File

@ -1548,7 +1548,7 @@ impl GlobalPassOption {
fn expr(cm: &SourceMap, handler: &Handler, src: String) -> Box<Expr> {
let fm = cm.new_source_file(FileName::Anon.into(), src);
let mut errors = vec![];
let mut errors = Vec::new();
let expr = parse_file_as_expr(
&fm,
Syntax::Es(Default::default()),

View File

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

View File

@ -42,6 +42,15 @@ pub mod boxed;
#[cfg(feature = "nightly")]
pub mod vec;
/// Box<T> and Vec<T> depeding on the feature.
pub mod maybe {
#[cfg(not(feature = "nightly"))]
pub use std::{boxed, vec};
#[cfg(feature = "nightly")]
pub use crate::{boxed, vec};
}
/// Fast allocator, effectively working as a cache.
///
/// This type implements [Default] and [Copy]. This type is intended to stored

View File

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

View File

@ -36,7 +36,7 @@ use swc_ecma_visit::VisitMutWith;
fn print_bundles(cm: Lrc<SourceMap>, modules: Vec<Bundle>, minify: bool) {
for bundled in modules {
let code = {
let mut buf = vec![];
let mut buf = Vec::new();
{
let wr = JsWriter::new(cm.clone(), "\n", &mut buf, None);
@ -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 =

View File

@ -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");

View File

@ -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,

View File

@ -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 {

View File

@ -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);

View File

@ -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,

View File

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

View File

@ -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

View File

@ -225,7 +225,7 @@ where
) -> Result<(Exports, Vec<(Source, Lrc<FileName>)>), 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<FileName>)>), 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) => {

View File

@ -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),

View File

@ -266,7 +266,7 @@ impl Modules {
})
.collect::<String>();
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(

View File

@ -30,7 +30,7 @@ impl Modules {
cm: &Lrc<SourceMap>,
) -> Vec<Chunk> {
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::<VecDeque<_>>();
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) {

View File

@ -22,10 +22,10 @@ pub(super) fn sort_stmts(
) -> Vec<ModuleItem> {
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;

View File

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

View File

@ -204,7 +204,7 @@ impl ExportMetadata {
pub fn into_with(self) -> Box<ObjectLit> {
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<Box<ObjectLit>>) {
let mut props = vec![];
let mut props = Vec::new();
if self.injected {
props.push(metadata("__swc_bundler__injected__", "1"));

View File

@ -78,7 +78,7 @@ fn load_url(url: Url) -> Result<String, Error> {
.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 =

View File

@ -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<dyn WriteJs> =
Box::new(JsWriter::new(cm.clone(), "\n", &mut buf, None));

View File

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

View File

@ -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(),
}
}

View File

@ -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
// <EMPTY LINE>
//
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() {

View File

@ -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<Vec<StyledString>> {
let mut output: Vec<Vec<StyledString>> = vec![];
let mut styled_vec: Vec<StyledString> = vec![];
let mut output: Vec<Vec<StyledString>> = Vec::new();
let mut styled_vec: Vec<StyledString> = 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());
}
}

View File

@ -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 {

View File

@ -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<Span>) -> MultiSpan {
MultiSpan {
primary_spans: vec,
span_labels: vec![],
span_labels: Vec::new(),
}
}

View File

@ -21,8 +21,8 @@ pub fn analyze_source_file(
source_file_start_pos: BytePos,
) -> (Vec<BytePos>, Vec<MultiByteChar>, Vec<NonNarrowChar>) {
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(),
);
}

View File

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

View File

@ -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 = [

View File

@ -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<Comment>| -> bool {
let preserve_excl = |_: &BytePos, vc: &mut std::vec::Vec<Comment>| -> bool {
// Preserve license comments.
//
// See https://github.com/terser/terser/blob/798135e04baddd94fea403cfaab4ba8b22b1b524/lib/output.js#L175-L181

View File

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

View File

@ -45,7 +45,7 @@ fn run(input: &Path, minify: bool) {
eprintln!("==== ==== Input ==== ====\n{}\n", fm.src);
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<u8> = vec![];
// let mut source_map_output: Vec<u8> = 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),

View File

@ -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 {

View File

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

View File

@ -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<ComplexSelector>,
) {
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<Rule> {
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 {

View File

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

View File

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

View File

@ -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();

View File

@ -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<CalcNode> = vec![];
let mut operands: Vec<CalcNode> = 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<CalcNode> = vec![];
let mut operands: Vec<CalcNode> = 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<CalcNode> {
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<CalcProductOrOperator> = vec![];
let mut expr: Vec<CalcProductOrOperator> = 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<CalcValueOrOperator> = vec![];
let mut expr: Vec<CalcValueOrOperator> = 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<CalcNode> {
let mut ret: Vec<CalcNode> = vec![];
let mut ret: Vec<CalcNode> = Vec::new();
// If nodes contains a number, remove it from nodes and append it to ret.
let mut numbers: Vec<CalcNode> = nodes

View File

@ -374,7 +374,7 @@ impl Compressor {
pub(super) fn compress_stylesheet(&mut self, stylesheet: &mut Stylesheet) {
let mut names: AHashMap<Name, isize> = 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<Name, isize> = 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() {

View File

@ -6,7 +6,7 @@ pub(crate) fn dedup<T>(v: &mut Vec<T>)
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() {

View File

@ -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<Stylesheet, _> = parse_file(&fm, None, Default::default(), &mut errors);
for err in errors {

View File

@ -61,7 +61,7 @@ pub fn compile<'a>(ss: &mut Stylesheet, config: impl 'a + TransformConfig) -> Tr
ss.visit_mut_with(&mut compiler);
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();

View File

@ -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,

View File

@ -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,

View File

@ -225,7 +225,7 @@ where
self.input.skip_ws();
if is!(self, Ident) {
let mut name_list: Vec<LayerName> = vec![];
let mut name_list: Vec<LayerName> = Vec::new();
name_list.push(self.parse()?);
@ -976,7 +976,7 @@ where
fn parse(&mut self) -> PResult<SupportsCondition> {
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<MediaCondition> {
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<MediaConditionWithoutOr> {
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<LayerName> {
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()?;

View File

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

View File

@ -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<Vec<PseudoClassSelectorChildren>> {
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<Vec<PseudoElementSelectorChildren>> {
let mut children = vec![];
let mut children = Vec::new();
match &*names.0 {
"cue" | "cue-region" => {

View File

@ -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<Vec<StyleBlock>> {
let mut declarations = vec![];
let mut rules = vec![];
let mut declarations = Vec::new();
let mut rules = Vec::new();
loop {
// <EOF-token>
@ -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<Vec<DeclarationOrAtRule>> {
// 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<ListOfComponentValues> {
let span = self.input.cur_span();
let mut children = vec![];
let mut children = Vec::new();
// Repeatedly consume a component value from input until an <EOF-token> is
// returned, appending the returned values (except the final <EOF-token>) into a

View File

@ -287,7 +287,7 @@ where
let locv = self.create_locv(declaration.value);
let 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<Declaration> {
let mut temporary_list = ListOfComponentValues {
span: Default::default(),
children: vec![],
children: Vec::new(),
};
while !is_one_of!(self, ")", EOF) {

View File

@ -13,7 +13,7 @@ where
I: ParserInput,
{
pub(super) fn parse_generic_values(&mut self) -> PResult<Vec<ComponentValue>> {
let mut values = vec![];
let mut values = Vec::new();
loop {
self.input.skip_ws();
@ -119,8 +119,8 @@ where
/// Parse value as <any-value>.
pub(super) fn parse_any_value(&mut self) -> PResult<Vec<TokenAndSpan>> {
let mut tokens = vec![];
let mut balance_stack: Vec<Option<char>> = vec![];
let mut tokens = Vec::new();
let mut balance_stack: Vec<Option<char>> = Vec::new();
// The <any-value> 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<CalcSum> {
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<CalcProduct> {
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 {

View File

@ -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<Stylesheet> =
parse_input(InputType::Tokens(&tokens), config, &mut parser_errors);

View File

@ -125,7 +125,7 @@ impl VisitMut for CrossFadeFunctionReplacerOnLegacyVariant<'_> {
n.visit_mut_children_with(self);
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) {

View File

@ -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,

View File

@ -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<ImportWith> {
let mut values = vec![];
let mut values = Vec::new();
for prop in &self.props {
match prop {
PropOrSpread::Spread(..) => return None,

View File

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

View File

@ -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" }

View File

@ -84,7 +84,6 @@ fn bench_emitter(b: &mut Bencher, s: &str) {
let fm = cm.new_source_file(FileName::Anon.into(), s.into());
let 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(),

View File

@ -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(),

View File

@ -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 {

View File

@ -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 {

View File

@ -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);

View File

@ -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")

View File

@ -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 =

View File

@ -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<Lexer> = Parser::new_from(lexer);
let mut src_map = vec![];
let mut src_map = Vec::new();
{
let mut wr = Box::new(swc_ecma_codegen::text_writer::JsWriter::new(
@ -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()
};

View File

@ -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");

View File

@ -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,

View File

@ -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,

View File

@ -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<Box<Expr>> = vec![];
let mut inits: Vec<Box<Expr>> = 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);

View File

@ -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<Class>,
) -> Vec<Stmt> {
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<Stmt>,
this_mark: Option<Mark>,
) -> Vec<Stmt> {
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<ClassMethod>,
) -> Vec<Stmt> {
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,

View File

@ -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(),
),

View File

@ -494,8 +494,8 @@ impl Destructuring {
ps: &mut Vec<Param>,
body: &mut BlockStmt,
) -> (Vec<Param>, 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,
};

View File

@ -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()],

View File

@ -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<OpArgs>, loc: Option<Span>) {
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];

View File

@ -72,11 +72,11 @@ pub struct Config {
#[swc_trace]
impl Params {
fn visit_mut_fn_like(&mut self, ps: &mut Vec<Param>, 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);
}

View File

@ -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))

View File

@ -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(),

View File

@ -102,8 +102,8 @@ impl<C: Comments + Clone> AsyncToGenerator<C> {
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<C: Comments> VisitMut for Actual<C> {
CallExpr {
span: DUMMY_SP,
callee: expr.as_callee(),
args: vec![],
args: Vec::new(),
..Default::default()
}
.into(),
@ -263,19 +263,19 @@ impl<C: Comments> VisitMut for Actual<C> {
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();

View File

@ -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<Ident> = vec![];
let mut found: Vec<Ident> = 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)

View File

@ -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() {

View File

@ -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 {

View File

@ -74,8 +74,8 @@ impl MemberInitRecord {
}
pub fn into_init(self) -> Vec<Box<Expr>> {
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<Stmt> {
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 {

View File

@ -181,7 +181,7 @@ impl<C: Comments> VisitMut for ClassProperties<C> {
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<C: Comments> ClassProperties<C> {
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<C: Comments> ClassProperties<C> {
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<C: Comments> ClassProperties<C> {
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,

View File

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

View File

@ -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();

View File

@ -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(

View File

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

View File

@ -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),

View File

@ -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;

View File

@ -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(),

View File

@ -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);

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