Merge pull request #19520 from BenjaminBrienen/defaultnew

Align usage of `default` and `new` with style guide
This commit is contained in:
Lukas Wirth 2025-04-04 15:42:16 +00:00 committed by GitHub
commit afcb45e003
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
46 changed files with 100 additions and 127 deletions

View file

@ -34,10 +34,6 @@ impl fmt::Debug for FileChange {
} }
impl FileChange { impl FileChange {
pub fn new() -> Self {
FileChange::default()
}
pub fn set_roots(&mut self, roots: Vec<SourceRoot>) { pub fn set_roots(&mut self, roots: Vec<SourceRoot>) {
self.roots = Some(roots); self.roots = Some(roots);
} }

View file

@ -112,6 +112,10 @@ pub struct Key<K, V, P = (K, V)> {
} }
impl<K, V, P> Key<K, V, P> { impl<K, V, P> Key<K, V, P> {
#[allow(
clippy::new_without_default,
reason = "this a const fn, so it can't be default yet. See <https://github.com/rust-lang/rust/issues/63065>"
)]
pub(crate) const fn new() -> Key<K, V, P> { pub(crate) const fn new() -> Key<K, V, P> {
Key { _phantom: PhantomData } Key { _phantom: PhantomData }
} }
@ -148,16 +152,11 @@ impl<K: Hash + Eq + 'static, V: 'static> Policy for (K, V) {
} }
} }
#[derive(Default)]
pub struct DynMap { pub struct DynMap {
pub(crate) map: Map, pub(crate) map: Map,
} }
impl Default for DynMap {
fn default() -> Self {
DynMap { map: Map::new() }
}
}
#[repr(transparent)] #[repr(transparent)]
pub struct KeyMap<KEY> { pub struct KeyMap<KEY> {
map: DynMap, map: DynMap,

View file

@ -2053,7 +2053,7 @@ impl ExprCollector<'_> {
f: ast::FormatArgsExpr, f: ast::FormatArgsExpr,
syntax_ptr: AstPtr<ast::Expr>, syntax_ptr: AstPtr<ast::Expr>,
) -> ExprId { ) -> ExprId {
let mut args = FormatArgumentsCollector::new(); let mut args = FormatArgumentsCollector::default();
f.args().for_each(|arg| { f.args().for_each(|arg| {
args.add(FormatArgument { args.add(FormatArgument {
kind: match arg.name() { kind: match arg.name() {

View file

@ -460,10 +460,6 @@ impl FormatArgumentsCollector {
} }
} }
pub fn new() -> Self {
Default::default()
}
pub fn add(&mut self, arg: FormatArgument) -> usize { pub fn add(&mut self, arg: FormatArgument) -> usize {
let index = self.arguments.len(); let index = self.arguments.len();
if let Some(name) = arg.kind.ident() { if let Some(name) = arg.kind.ident() {

View file

@ -14,10 +14,6 @@ pub struct ChangeWithProcMacros {
} }
impl ChangeWithProcMacros { impl ChangeWithProcMacros {
pub fn new() -> Self {
Self::default()
}
pub fn apply(self, db: &mut impl ExpandDatabase) { pub fn apply(self, db: &mut impl ExpandDatabase) {
let crates_id_map = self.source_change.apply(db); let crates_id_map = self.source_change.apply(db);
if let Some(proc_macros) = self.proc_macros { if let Some(proc_macros) = self.proc_macros {

View file

@ -39,7 +39,7 @@ pub(crate) fn add_braces(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<(
}, },
expr.syntax().text_range(), expr.syntax().text_range(),
|builder| { |builder| {
let make = SyntaxFactory::new(); let make = SyntaxFactory::with_mappings();
let mut editor = builder.make_editor(expr.syntax()); let mut editor = builder.make_editor(expr.syntax());
let block_expr = make.block_expr(None, Some(expr.clone())); let block_expr = make.block_expr(None, Some(expr.clone()));

View file

@ -77,7 +77,7 @@ pub(crate) fn add_missing_match_arms(acc: &mut Assists, ctx: &AssistContext<'_>)
let cfg = ctx.config.import_path_config(); let cfg = ctx.config.import_path_config();
let make = SyntaxFactory::new(); let make = SyntaxFactory::with_mappings();
let module = ctx.sema.scope(expr.syntax())?.module(); let module = ctx.sema.scope(expr.syntax())?.module();
let (mut missing_pats, is_non_exhaustive, has_hidden_variants): ( let (mut missing_pats, is_non_exhaustive, has_hidden_variants): (
@ -467,7 +467,7 @@ fn build_pat(
let fields = var.fields(db); let fields = var.fields(db);
let pat: ast::Pat = match var.kind(db) { let pat: ast::Pat = match var.kind(db) {
hir::StructKind::Tuple => { hir::StructKind::Tuple => {
let mut name_generator = suggest_name::NameGenerator::new(); let mut name_generator = suggest_name::NameGenerator::default();
let pats = fields.into_iter().map(|f| { let pats = fields.into_iter().map(|f| {
let name = name_generator.for_type(&f.ty(db), db, edition); let name = name_generator.for_type(&f.ty(db), db, edition);
match name { match name {

View file

@ -141,7 +141,7 @@ pub(crate) fn add_turbo_fish(acc: &mut Assists, ctx: &AssistContext<'_>) -> Opti
|builder| { |builder| {
builder.trigger_parameter_hints(); builder.trigger_parameter_hints();
let make = SyntaxFactory::new(); let make = SyntaxFactory::with_mappings();
let mut editor = match &turbofish_target { let mut editor = match &turbofish_target {
Either::Left(it) => builder.make_editor(it.syntax()), Either::Left(it) => builder.make_editor(it.syntax()),
Either::Right(it) => builder.make_editor(it.syntax()), Either::Right(it) => builder.make_editor(it.syntax()),

View file

@ -64,7 +64,7 @@ pub(crate) fn apply_demorgan(acc: &mut Assists, ctx: &AssistContext<'_>) -> Opti
_ => return None, _ => return None,
}; };
let make = SyntaxFactory::new(); let make = SyntaxFactory::with_mappings();
let demorganed = bin_expr.clone_subtree(); let demorganed = bin_expr.clone_subtree();
let mut editor = SyntaxEditor::new(demorganed.syntax().clone()); let mut editor = SyntaxEditor::new(demorganed.syntax().clone());
@ -111,7 +111,7 @@ pub(crate) fn apply_demorgan(acc: &mut Assists, ctx: &AssistContext<'_>) -> Opti
"Apply De Morgan's law", "Apply De Morgan's law",
op_range, op_range,
|builder| { |builder| {
let make = SyntaxFactory::new(); let make = SyntaxFactory::with_mappings();
let paren_expr = bin_expr.syntax().parent().and_then(ast::ParenExpr::cast); let paren_expr = bin_expr.syntax().parent().and_then(ast::ParenExpr::cast);
let neg_expr = paren_expr let neg_expr = paren_expr
.clone() .clone()
@ -194,7 +194,7 @@ pub(crate) fn apply_demorgan_iterator(acc: &mut Assists, ctx: &AssistContext<'_>
label, label,
op_range, op_range,
|builder| { |builder| {
let make = SyntaxFactory::new(); let make = SyntaxFactory::with_mappings();
let mut editor = builder.make_editor(method_call.syntax()); let mut editor = builder.make_editor(method_call.syntax());
// replace the method name // replace the method name
let new_name = match name.text().as_str() { let new_name = match name.text().as_str() {

View file

@ -98,7 +98,7 @@ pub(crate) fn convert_if_to_bool_then(acc: &mut Assists, ctx: &AssistContext<'_>
let closure_body = ast::Expr::cast(edit.new_root().clone()).unwrap(); let closure_body = ast::Expr::cast(edit.new_root().clone()).unwrap();
let mut editor = builder.make_editor(expr.syntax()); let mut editor = builder.make_editor(expr.syntax());
let make = SyntaxFactory::new(); let make = SyntaxFactory::with_mappings();
let closure_body = match closure_body { let closure_body = match closure_body {
ast::Expr::BlockExpr(block) => unwrap_trivial_block(block), ast::Expr::BlockExpr(block) => unwrap_trivial_block(block),
e => e, e => e,
@ -216,7 +216,7 @@ pub(crate) fn convert_bool_then_to_if(acc: &mut Assists, ctx: &AssistContext<'_>
let closure_body = ast::BlockExpr::cast(edit.new_root().clone()).unwrap(); let closure_body = ast::BlockExpr::cast(edit.new_root().clone()).unwrap();
let mut editor = builder.make_editor(mcall.syntax()); let mut editor = builder.make_editor(mcall.syntax());
let make = SyntaxFactory::new(); let make = SyntaxFactory::with_mappings();
let cond = match &receiver { let cond = match &receiver {
ast::Expr::ParenExpr(expr) => expr.expr().unwrap_or(receiver), ast::Expr::ParenExpr(expr) => expr.expr().unwrap_or(receiver),

View file

@ -51,7 +51,7 @@ pub(crate) fn convert_for_loop_to_while_let(
"Replace this for loop with `while let`", "Replace this for loop with `while let`",
for_loop.syntax().text_range(), for_loop.syntax().text_range(),
|builder| { |builder| {
let make = SyntaxFactory::new(); let make = SyntaxFactory::with_mappings();
let mut editor = builder.make_editor(for_loop.syntax()); let mut editor = builder.make_editor(for_loop.syntax());
let (iterable, method) = if impls_core_iter(&ctx.sema, &iterable) { let (iterable, method) = if impls_core_iter(&ctx.sema, &iterable) {

View file

@ -170,7 +170,7 @@ pub(crate) fn extract_variable(acc: &mut Assists, ctx: &AssistContext<'_>) -> Op
|edit| { |edit| {
let (var_name, expr_replace) = kind.get_name_and_expr(ctx, &to_extract); let (var_name, expr_replace) = kind.get_name_and_expr(ctx, &to_extract);
let make = SyntaxFactory::new(); let make = SyntaxFactory::with_mappings();
let mut editor = edit.make_editor(&expr_replace); let mut editor = edit.make_editor(&expr_replace);
let pat_name = make.name(&var_name); let pat_name = make.name(&var_name);

View file

@ -48,7 +48,7 @@ pub(crate) fn flip_binexpr(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option
op_token.text_range(), op_token.text_range(),
|builder| { |builder| {
let mut editor = builder.make_editor(&expr.syntax().parent().unwrap()); let mut editor = builder.make_editor(&expr.syntax().parent().unwrap());
let make = SyntaxFactory::new(); let make = SyntaxFactory::with_mappings();
if let FlipAction::FlipAndReplaceOp(binary_op) = action { if let FlipAction::FlipAndReplaceOp(binary_op) = action {
editor.replace(op_token, make.token(binary_op)) editor.replace(op_token, make.token(binary_op))
}; };

View file

@ -101,7 +101,7 @@ fn flip_tree(tree: ast::TokenTree, comma: SyntaxToken) -> (ast::TokenTree, Synta
] ]
.concat(); .concat();
let make = SyntaxFactory::new(); let make = SyntaxFactory::with_mappings();
let new_token_tree = make.token_tree(tree.left_delimiter_token().unwrap().kind(), result); let new_token_tree = make.token_tree(tree.left_delimiter_token().unwrap().kind(), result);
(new_token_tree, make.finish_with_mappings()) (new_token_tree, make.finish_with_mappings())
} }

View file

@ -60,7 +60,7 @@ pub(crate) fn generate_enum_variant(acc: &mut Assists, ctx: &AssistContext<'_>)
acc.add(AssistId::generate("generate_enum_variant"), "Generate variant", target, |builder| { acc.add(AssistId::generate("generate_enum_variant"), "Generate variant", target, |builder| {
let mut editor = builder.make_editor(enum_node.syntax()); let mut editor = builder.make_editor(enum_node.syntax());
let make = SyntaxFactory::new(); let make = SyntaxFactory::with_mappings();
let field_list = parent.make_field_list(ctx, &make); let field_list = parent.make_field_list(ctx, &make);
let variant = make.variant(None, make.name(&name_ref.text()), field_list, None); let variant = make.variant(None, make.name(&name_ref.text()), field_list, None);
if let Some(it) = enum_node.variant_list() { if let Some(it) = enum_node.variant_list() {

View file

@ -91,7 +91,7 @@ pub(crate) fn inline_local_variable(acc: &mut Assists, ctx: &AssistContext<'_>)
} }
} }
let make = SyntaxFactory::new(); let make = SyntaxFactory::with_mappings();
for (name, should_wrap) in wrap_in_parens { for (name, should_wrap) in wrap_in_parens {
let replacement = if should_wrap { let replacement = if should_wrap {

View file

@ -24,7 +24,7 @@ pub(crate) fn introduce_named_type_parameter(
let fn_ = param.syntax().ancestors().nth(2).and_then(ast::Fn::cast)?; let fn_ = param.syntax().ancestors().nth(2).and_then(ast::Fn::cast)?;
let type_bound_list = impl_trait_type.type_bound_list()?; let type_bound_list = impl_trait_type.type_bound_list()?;
let make = SyntaxFactory::new(); let make = SyntaxFactory::with_mappings();
let target = fn_.syntax().text_range(); let target = fn_.syntax().text_range();
acc.add( acc.add(
AssistId::refactor_rewrite("introduce_named_type_parameter"), AssistId::refactor_rewrite("introduce_named_type_parameter"),

View file

@ -54,7 +54,7 @@ pub(crate) fn remove_parentheses(acc: &mut Assists, ctx: &AssistContext<'_>) ->
None => false, None => false,
}; };
if need_to_add_ws { if need_to_add_ws {
let make = SyntaxFactory::new(); let make = SyntaxFactory::with_mappings();
editor.insert(Position::before(parens.syntax()), make.whitespace(" ")); editor.insert(Position::before(parens.syntax()), make.whitespace(" "));
editor.add_mappings(make.finish_with_mappings()); editor.add_mappings(make.finish_with_mappings());
} }

View file

@ -105,7 +105,7 @@ pub(crate) fn replace_if_let_with_match(acc: &mut Assists, ctx: &AssistContext<'
format!("Replace if{let_} with match"), format!("Replace if{let_} with match"),
available_range, available_range,
move |builder| { move |builder| {
let make = SyntaxFactory::new(); let make = SyntaxFactory::with_mappings();
let match_expr = { let match_expr = {
let else_arm = make_else_arm(ctx, &make, else_block, &cond_bodies); let else_arm = make_else_arm(ctx, &make, else_block, &cond_bodies);
let make_match_arm = |(pat, body): (_, ast::BlockExpr)| { let make_match_arm = |(pat, body): (_, ast::BlockExpr)| {
@ -253,7 +253,7 @@ pub(crate) fn replace_match_with_if_let(acc: &mut Assists, ctx: &AssistContext<'
format!("Replace match with if{let_}"), format!("Replace match with if{let_}"),
match_expr.syntax().text_range(), match_expr.syntax().text_range(),
move |builder| { move |builder| {
let make = SyntaxFactory::new(); let make = SyntaxFactory::with_mappings();
let make_block_expr = |expr: ast::Expr| { let make_block_expr = |expr: ast::Expr| {
// Blocks with modifiers (unsafe, async, etc.) are parsed as BlockExpr, but are // Blocks with modifiers (unsafe, async, etc.) are parsed as BlockExpr, but are
// formatted without enclosing braces. If we encounter such block exprs, // formatted without enclosing braces. If we encounter such block exprs,

View file

@ -43,7 +43,7 @@ pub(crate) fn replace_let_with_if_let(acc: &mut Assists, ctx: &AssistContext<'_>
target, target,
|builder| { |builder| {
let mut editor = builder.make_editor(let_stmt.syntax()); let mut editor = builder.make_editor(let_stmt.syntax());
let make = SyntaxFactory::new(); let make = SyntaxFactory::with_mappings();
let ty = ctx.sema.type_of_expr(&init); let ty = ctx.sema.type_of_expr(&init);
let pat = if let_stmt.let_else().is_some() { let pat = if let_stmt.let_else().is_some() {
// Do not add the wrapper type that implements `Try`, // Do not add the wrapper type that implements `Try`,

View file

@ -67,7 +67,7 @@ pub(crate) fn unwrap_return_type(acc: &mut Assists, ctx: &AssistContext<'_>) ->
acc.add(kind.assist_id(), kind.label(), type_ref.syntax().text_range(), |builder| { acc.add(kind.assist_id(), kind.label(), type_ref.syntax().text_range(), |builder| {
let mut editor = builder.make_editor(&parent); let mut editor = builder.make_editor(&parent);
let make = SyntaxFactory::new(); let make = SyntaxFactory::with_mappings();
let mut exprs_to_unwrap = Vec::new(); let mut exprs_to_unwrap = Vec::new();
let tail_cb = &mut |e: &_| tail_cb_impl(&mut exprs_to_unwrap, e); let tail_cb = &mut |e: &_| tail_cb_impl(&mut exprs_to_unwrap, e);

View file

@ -77,7 +77,7 @@ pub(crate) fn wrap_return_type(acc: &mut Assists, ctx: &AssistContext<'_>) -> Op
type_ref.syntax().text_range(), type_ref.syntax().text_range(),
|builder| { |builder| {
let mut editor = builder.make_editor(&parent); let mut editor = builder.make_editor(&parent);
let make = SyntaxFactory::new(); let make = SyntaxFactory::with_mappings();
let alias = wrapper_alias(ctx, &make, &core_wrapper, type_ref, kind.symbol()); let alias = wrapper_alias(ctx, &make, &core_wrapper, type_ref, kind.symbol());
let new_return_ty = alias.unwrap_or_else(|| match kind { let new_return_ty = alias.unwrap_or_else(|| match kind {
WrapperKind::Option => make.ty_option(type_ref.clone()), WrapperKind::Option => make.ty_option(type_ref.clone()),

View file

@ -48,7 +48,7 @@ pub(crate) fn complete_pattern(
// Suggest name only in let-stmt and fn param // Suggest name only in let-stmt and fn param
if pattern_ctx.should_suggest_name { if pattern_ctx.should_suggest_name {
let mut name_generator = suggest_name::NameGenerator::new(); let mut name_generator = suggest_name::NameGenerator::default();
if let Some(suggested) = ctx if let Some(suggested) = ctx
.expected_type .expected_type
.as_ref() .as_ref()

View file

@ -7,14 +7,20 @@ pub(crate) struct TopologicSortIterBuilder<T> {
nodes: FxHashMap<T, Entry<T>>, nodes: FxHashMap<T, Entry<T>>,
} }
// this implementation has different bounds on T than would be implied by #[derive(Default)]
impl<T> Default for TopologicSortIterBuilder<T>
where
T: Copy + Eq + PartialEq + Hash,
{
fn default() -> Self {
Self { nodes: Default::default() }
}
}
impl<T> TopologicSortIterBuilder<T> impl<T> TopologicSortIterBuilder<T>
where where
T: Copy + Eq + PartialEq + Hash, T: Copy + Eq + PartialEq + Hash,
{ {
fn new() -> Self {
Self { nodes: Default::default() }
}
fn get_or_create_entry(&mut self, item: T) -> &mut Entry<T> { fn get_or_create_entry(&mut self, item: T) -> &mut Entry<T> {
self.nodes.entry(item).or_default() self.nodes.entry(item).or_default()
} }
@ -54,7 +60,7 @@ where
T: Copy + Eq + PartialEq + Hash, T: Copy + Eq + PartialEq + Hash,
{ {
pub(crate) fn builder() -> TopologicSortIterBuilder<T> { pub(crate) fn builder() -> TopologicSortIterBuilder<T> {
TopologicSortIterBuilder::new() TopologicSortIterBuilder::default()
} }
pub(crate) fn pending(&self) -> usize { pub(crate) fn pending(&self) -> usize {

View file

@ -469,7 +469,7 @@ impl SourceChangeBuilder {
} }
fn add_snippet_annotation(&mut self, kind: AnnotationSnippet) -> SyntaxAnnotation { fn add_snippet_annotation(&mut self, kind: AnnotationSnippet) -> SyntaxAnnotation {
let annotation = SyntaxAnnotation::new(); let annotation = SyntaxAnnotation::default();
self.snippet_annotations.push((kind, annotation)); self.snippet_annotations.push((kind, annotation));
self.source_change.is_snippet = true; self.source_change.is_snippet = true;
annotation annotation

View file

@ -96,21 +96,16 @@ pub struct NameGenerator {
} }
impl NameGenerator { impl NameGenerator {
/// Create a new empty generator
pub fn new() -> Self {
Self { pool: FxHashMap::default() }
}
/// Create a new generator with existing names. When suggesting a name, it will /// Create a new generator with existing names. When suggesting a name, it will
/// avoid conflicts with existing names. /// avoid conflicts with existing names.
pub fn new_with_names<'a>(existing_names: impl Iterator<Item = &'a str>) -> Self { pub fn new_with_names<'a>(existing_names: impl Iterator<Item = &'a str>) -> Self {
let mut generator = Self::new(); let mut generator = Self::default();
existing_names.for_each(|name| generator.insert(name)); existing_names.for_each(|name| generator.insert(name));
generator generator
} }
pub fn new_from_scope_locals(scope: Option<SemanticsScope<'_>>) -> Self { pub fn new_from_scope_locals(scope: Option<SemanticsScope<'_>>) -> Self {
let mut generator = Self::new(); let mut generator = Self::default();
if let Some(scope) = scope { if let Some(scope) = scope {
scope.process_all_names(&mut |name, scope| { scope.process_all_names(&mut |name, scope| {
if let hir::ScopeDef::Local(_) = scope { if let hir::ScopeDef::Local(_) = scope {
@ -471,7 +466,7 @@ mod tests {
frange.range, frange.range,
"selection is not an expression(yet contained in one)" "selection is not an expression(yet contained in one)"
); );
let name = NameGenerator::new().for_variable(&expr, &sema); let name = NameGenerator::default().for_variable(&expr, &sema);
assert_eq!(&name, expected); assert_eq!(&name, expected);
} }
@ -1118,7 +1113,7 @@ fn main() {
#[test] #[test]
fn conflicts_with_existing_names() { fn conflicts_with_existing_names() {
let mut generator = NameGenerator::new(); let mut generator = NameGenerator::default();
assert_eq!(generator.suggest_name("a"), "a"); assert_eq!(generator.suggest_name("a"), "a");
assert_eq!(generator.suggest_name("a"), "a1"); assert_eq!(generator.suggest_name("a"), "a1");
assert_eq!(generator.suggest_name("a"), "a2"); assert_eq!(generator.suggest_name("a"), "a2");

View file

@ -231,7 +231,7 @@ fn remove_unnecessary_wrapper(
.and_then(Either::<ast::ReturnExpr, ast::StmtList>::cast)?; .and_then(Either::<ast::ReturnExpr, ast::StmtList>::cast)?;
editor = builder.make_editor(parent.syntax()); editor = builder.make_editor(parent.syntax());
let make = SyntaxFactory::new(); let make = SyntaxFactory::with_mappings();
match parent { match parent {
Either::Left(ret_expr) => { Either::Left(ret_expr) => {

View file

@ -238,7 +238,7 @@ impl Analysis {
file_set.insert(file_id, VfsPath::new_virtual_path("/main.rs".to_owned())); file_set.insert(file_id, VfsPath::new_virtual_path("/main.rs".to_owned()));
let source_root = SourceRoot::new_local(file_set); let source_root = SourceRoot::new_local(file_set);
let mut change = ChangeWithProcMacros::new(); let mut change = ChangeWithProcMacros::default();
change.set_roots(vec![source_root]); change.set_roots(vec![source_root]);
let mut crate_graph = CrateGraphBuilder::default(); let mut crate_graph = CrateGraphBuilder::default();
// FIXME: cfg options // FIXME: cfg options

View file

@ -177,7 +177,10 @@ pub struct InternStorage<T: ?Sized> {
map: OnceLock<InternMap<T>>, map: OnceLock<InternMap<T>>,
} }
#[allow(clippy::new_without_default)] // this a const fn, so it can't be default #[allow(
clippy::new_without_default,
reason = "this a const fn, so it can't be default yet. See <https://github.com/rust-lang/rust/issues/63065>"
)]
impl<T: ?Sized> InternStorage<T> { impl<T: ?Sized> InternStorage<T> {
pub const fn new() -> Self { pub const fn new() -> Self {
Self { map: OnceLock::new() } Self { map: OnceLock::new() }

View file

@ -426,7 +426,7 @@ fn load_crate_graph(
) -> RootDatabase { ) -> RootDatabase {
let lru_cap = std::env::var("RA_LRU_CAP").ok().and_then(|it| it.parse::<u16>().ok()); let lru_cap = std::env::var("RA_LRU_CAP").ok().and_then(|it| it.parse::<u16>().ok());
let mut db = RootDatabase::new(lru_cap); let mut db = RootDatabase::new(lru_cap);
let mut analysis_change = ChangeWithProcMacros::new(); let mut analysis_change = ChangeWithProcMacros::default();
db.enable_proc_attr_macros(); db.enable_proc_attr_macros();

View file

@ -90,7 +90,7 @@ pub fn attr_error(args: TokenStream, item: TokenStream) -> TokenStream {
#[proc_macro_derive(DeriveEmpty)] #[proc_macro_derive(DeriveEmpty)]
pub fn derive_empty(_item: TokenStream) -> TokenStream { pub fn derive_empty(_item: TokenStream) -> TokenStream {
TokenStream::new() TokenStream::default()
} }
#[proc_macro_derive(DerivePanic)] #[proc_macro_derive(DerivePanic)]

View file

@ -26,7 +26,7 @@ impl ProcMacros {
let parsed_body = crate::server_impl::TokenStream::with_subtree(macro_body); let parsed_body = crate::server_impl::TokenStream::with_subtree(macro_body);
let parsed_attributes = attributes let parsed_attributes = attributes
.map_or_else(crate::server_impl::TokenStream::new, |attr| { .map_or_else(crate::server_impl::TokenStream::default, |attr| {
crate::server_impl::TokenStream::with_subtree(attr) crate::server_impl::TokenStream::with_subtree(attr)
}); });

View file

@ -212,7 +212,7 @@ impl server::TokenStream for RaSpanServer {
base: Option<Self::TokenStream>, base: Option<Self::TokenStream>,
trees: Vec<bridge::TokenTree<Self::TokenStream, Self::Span, Self::Symbol>>, trees: Vec<bridge::TokenTree<Self::TokenStream, Self::Span, Self::Symbol>>,
) -> Self::TokenStream { ) -> Self::TokenStream {
let mut builder = TokenStreamBuilder::new(); let mut builder = TokenStreamBuilder::default();
if let Some(base) = base { if let Some(base) = base {
builder.push(base); builder.push(base);
} }
@ -227,7 +227,7 @@ impl server::TokenStream for RaSpanServer {
base: Option<Self::TokenStream>, base: Option<Self::TokenStream>,
streams: Vec<Self::TokenStream>, streams: Vec<Self::TokenStream>,
) -> Self::TokenStream { ) -> Self::TokenStream {
let mut builder = TokenStreamBuilder::new(); let mut builder = TokenStreamBuilder::default();
if let Some(base) = base { if let Some(base) = base {
builder.push(base); builder.push(base);
} }

View file

@ -190,7 +190,7 @@ impl server::TokenStream for TokenIdServer {
base: Option<Self::TokenStream>, base: Option<Self::TokenStream>,
trees: Vec<bridge::TokenTree<Self::TokenStream, Self::Span, Self::Symbol>>, trees: Vec<bridge::TokenTree<Self::TokenStream, Self::Span, Self::Symbol>>,
) -> Self::TokenStream { ) -> Self::TokenStream {
let mut builder = TokenStreamBuilder::new(); let mut builder = TokenStreamBuilder::default();
if let Some(base) = base { if let Some(base) = base {
builder.push(base); builder.push(base);
} }
@ -205,7 +205,7 @@ impl server::TokenStream for TokenIdServer {
base: Option<Self::TokenStream>, base: Option<Self::TokenStream>,
streams: Vec<Self::TokenStream>, streams: Vec<Self::TokenStream>,
) -> Self::TokenStream { ) -> Self::TokenStream {
let mut builder = TokenStreamBuilder::new(); let mut builder = TokenStreamBuilder::default();
if let Some(base) = base { if let Some(base) = base {
builder.push(base); builder.push(base);
} }

View file

@ -9,6 +9,13 @@ pub struct TokenStream<S> {
pub(super) token_trees: Vec<tt::TokenTree<S>>, pub(super) token_trees: Vec<tt::TokenTree<S>>,
} }
// #[derive(Default)] would mean that `S: Default`.
impl<S> Default for TokenStream<S> {
fn default() -> Self {
Self { token_trees: Default::default() }
}
}
impl<S: std::fmt::Debug + Copy> std::fmt::Debug for TokenStream<S> { impl<S: std::fmt::Debug + Copy> std::fmt::Debug for TokenStream<S> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("TokenStream") f.debug_struct("TokenStream")
@ -17,17 +24,7 @@ impl<S: std::fmt::Debug + Copy> std::fmt::Debug for TokenStream<S> {
} }
} }
impl<S> Default for TokenStream<S> {
fn default() -> Self {
Self { token_trees: vec![] }
}
}
impl<S: Copy> TokenStream<S> { impl<S: Copy> TokenStream<S> {
pub(crate) fn new() -> Self {
TokenStream::default()
}
pub(crate) fn with_subtree(subtree: TopSubtree<S>) -> Self { pub(crate) fn with_subtree(subtree: TopSubtree<S>) -> Self {
let delimiter_kind = subtree.top_subtree().delimiter.kind; let delimiter_kind = subtree.top_subtree().delimiter.kind;
let mut token_trees = subtree.0; let mut token_trees = subtree.0;
@ -145,10 +142,6 @@ pub(super) mod token_stream_impls {
} }
impl<S: Copy> TokenStreamBuilder<S> { impl<S: Copy> TokenStreamBuilder<S> {
pub(super) fn new() -> TokenStreamBuilder<S> {
TokenStreamBuilder { acc: TokenStream::new() }
}
pub(super) fn push(&mut self, stream: TokenStream<S>) { pub(super) fn push(&mut self, stream: TokenStream<S>) {
self.acc.token_trees.extend(stream.token_trees) self.acc.token_trees.extend(stream.token_trees)
} }
@ -157,3 +150,9 @@ impl<S: Copy> TokenStreamBuilder<S> {
self.acc self.acc
} }
} }
impl<S: Copy> Default for TokenStreamBuilder<S> {
fn default() -> Self {
Self { acc: TokenStream::default() }
}
}

View file

@ -139,7 +139,7 @@ impl Tester {
FxHashMap::default() FxHashMap::default()
}; };
let text = read_to_string(&p).unwrap(); let text = read_to_string(&p).unwrap();
let mut change = ChangeWithProcMacros::new(); let mut change = ChangeWithProcMacros::default();
// Ignore unstable tests, since they move too fast and we do not intend to support all of them. // Ignore unstable tests, since they move too fast and we do not intend to support all of them.
let mut ignore_test = text.contains("#![feature"); let mut ignore_test = text.contains("#![feature");
// Ignore test with extern crates, as this infra don't support them yet. // Ignore test with extern crates, as this infra don't support them yet.

View file

@ -128,7 +128,7 @@ impl flags::Scip {
}; };
// Generates symbols from token monikers. // Generates symbols from token monikers.
let mut symbol_generator = SymbolGenerator::new(); let mut symbol_generator = SymbolGenerator::default();
for StaticIndexedFile { file_id, tokens, .. } in si.files { for StaticIndexedFile { file_id, tokens, .. } in si.files {
symbol_generator.clear_document_local_state(); symbol_generator.clear_document_local_state();
@ -417,16 +417,13 @@ struct TokenSymbols {
is_inherent_impl: bool, is_inherent_impl: bool,
} }
#[derive(Default)]
struct SymbolGenerator { struct SymbolGenerator {
token_to_symbols: FxHashMap<TokenId, Option<TokenSymbols>>, token_to_symbols: FxHashMap<TokenId, Option<TokenSymbols>>,
local_count: usize, local_count: usize,
} }
impl SymbolGenerator { impl SymbolGenerator {
fn new() -> Self {
SymbolGenerator { token_to_symbols: FxHashMap::default(), local_count: 0 }
}
fn clear_document_local_state(&mut self) { fn clear_document_local_state(&mut self) {
self.local_count = 0; self.local_count = 0;
} }

View file

@ -299,7 +299,7 @@ impl GlobalState {
FxHashMap::default(); FxHashMap::default();
let (change, modified_rust_files, workspace_structure_change) = { let (change, modified_rust_files, workspace_structure_change) = {
let mut change = ChangeWithProcMacros::new(); let mut change = ChangeWithProcMacros::default();
let mut guard = self.vfs.write(); let mut guard = self.vfs.write();
let changed_files = guard.0.take_changes(); let changed_files = guard.0.take_changes();
if changed_files.is_empty() { if changed_files.is_empty() {

View file

@ -86,7 +86,7 @@ fn integrated_highlighting_benchmark() {
"self.data.cargo_buildScripts_rebuildOnSave", "self.data.cargo_buildScripts_rebuildOnSave",
"self. data. cargo_buildScripts_rebuildOnSave", "self. data. cargo_buildScripts_rebuildOnSave",
); );
let mut change = ChangeWithProcMacros::new(); let mut change = ChangeWithProcMacros::default();
change.change_file(file_id, Some(text)); change.change_file(file_id, Some(text));
host.apply_change(change); host.apply_change(change);
} }
@ -149,7 +149,7 @@ fn integrated_completion_benchmark() {
let completion_offset = let completion_offset =
patch(&mut text, "db.struct_data(self.id)", "sel;\ndb.struct_data(self.id)") patch(&mut text, "db.struct_data(self.id)", "sel;\ndb.struct_data(self.id)")
+ "sel".len(); + "sel".len();
let mut change = ChangeWithProcMacros::new(); let mut change = ChangeWithProcMacros::default();
change.change_file(file_id, Some(text)); change.change_file(file_id, Some(text));
host.apply_change(change); host.apply_change(change);
completion_offset completion_offset
@ -200,7 +200,7 @@ fn integrated_completion_benchmark() {
let completion_offset = let completion_offset =
patch(&mut text, "sel;\ndb.struct_data(self.id)", ";sel;\ndb.struct_data(self.id)") patch(&mut text, "sel;\ndb.struct_data(self.id)", ";sel;\ndb.struct_data(self.id)")
+ ";sel".len(); + ";sel".len();
let mut change = ChangeWithProcMacros::new(); let mut change = ChangeWithProcMacros::default();
change.change_file(file_id, Some(text)); change.change_file(file_id, Some(text));
host.apply_change(change); host.apply_change(change);
completion_offset completion_offset
@ -250,7 +250,7 @@ fn integrated_completion_benchmark() {
let completion_offset = let completion_offset =
patch(&mut text, "sel;\ndb.struct_data(self.id)", "self.;\ndb.struct_data(self.id)") patch(&mut text, "sel;\ndb.struct_data(self.id)", "self.;\ndb.struct_data(self.id)")
+ "self.".len(); + "self.".len();
let mut change = ChangeWithProcMacros::new(); let mut change = ChangeWithProcMacros::default();
change.change_file(file_id, Some(text)); change.change_file(file_id, Some(text));
host.apply_change(change); host.apply_change(change);
completion_offset completion_offset
@ -367,7 +367,7 @@ fn integrated_diagnostics_benchmark() {
let _it = stdx::timeit("change"); let _it = stdx::timeit("change");
let mut text = host.analysis().file_text(file_id).unwrap().to_string(); let mut text = host.analysis().file_text(file_id).unwrap().to_string();
patch(&mut text, "db.struct_data(self.id)", "();\ndb.struct_data(self.id)"); patch(&mut text, "db.struct_data(self.id)", "();\ndb.struct_data(self.id)");
let mut change = ChangeWithProcMacros::new(); let mut change = ChangeWithProcMacros::default();
change.change_file(file_id, Some(text)); change.change_file(file_id, Some(text));
host.apply_change(change); host.apply_change(change);
}; };

View file

@ -739,7 +739,7 @@ impl GlobalState {
ws_to_crate_graph(&self.workspaces, self.config.extra_env(None), load) ws_to_crate_graph(&self.workspaces, self.config.extra_env(None), load)
}; };
let mut change = ChangeWithProcMacros::new(); let mut change = ChangeWithProcMacros::default();
if initial_build || !self.config.expand_proc_macros() { if initial_build || !self.config.expand_proc_macros() {
if self.config.expand_proc_macros() { if self.config.expand_proc_macros() {
change.set_proc_macros( change.set_proc_macros(

View file

@ -101,20 +101,15 @@ pub struct Map<A: ?Sized + Downcast = dyn Any> {
/// `Map::new()` doesnt seem to be happy to infer that it should go with the default /// `Map::new()` doesnt seem to be happy to infer that it should go with the default
/// value. Its a bit sad, really. Ah well, I guess this approach will do. /// value. Its a bit sad, really. Ah well, I guess this approach will do.
pub type AnyMap = Map<dyn Any>; pub type AnyMap = Map<dyn Any>;
impl<A: ?Sized + Downcast> Default for Map<A> { impl<A: ?Sized + Downcast> Default for Map<A> {
#[inline] #[inline]
fn default() -> Map<A> { fn default() -> Map<A> {
Map::new() Map { raw: RawMap::with_hasher(Default::default()) }
} }
} }
impl<A: ?Sized + Downcast> Map<A> { impl<A: ?Sized + Downcast> Map<A> {
/// Create an empty collection.
#[inline]
pub fn new() -> Map<A> {
Map { raw: RawMap::with_hasher(Default::default()) }
}
/// Returns a reference to the value stored in the collection for the type `T`, /// Returns a reference to the value stored in the collection for the type `T`,
/// if it exists. /// if it exists.
#[inline] #[inline]

View file

@ -19,8 +19,8 @@ pub struct SyntaxFactory {
impl SyntaxFactory { impl SyntaxFactory {
/// Creates a new [`SyntaxFactory`], generating mappings between input nodes and generated nodes. /// Creates a new [`SyntaxFactory`], generating mappings between input nodes and generated nodes.
pub fn new() -> Self { pub fn with_mappings() -> Self {
Self { mappings: Some(RefCell::new(SyntaxMapping::new())) } Self { mappings: Some(RefCell::new(SyntaxMapping::default())) }
} }
/// Creates a [`SyntaxFactory`] without generating mappings. /// Creates a [`SyntaxFactory`] without generating mappings.

View file

@ -33,7 +33,7 @@ pub struct SyntaxEditor {
impl SyntaxEditor { impl SyntaxEditor {
/// Creates a syntax editor to start editing from `root` /// Creates a syntax editor to start editing from `root`
pub fn new(root: SyntaxNode) -> Self { pub fn new(root: SyntaxNode) -> Self {
Self { root, changes: vec![], mappings: SyntaxMapping::new(), annotations: vec![] } Self { root, changes: vec![], mappings: SyntaxMapping::default(), annotations: vec![] }
} }
pub fn add_annotation(&mut self, element: impl Element, annotation: SyntaxAnnotation) { pub fn add_annotation(&mut self, element: impl Element, annotation: SyntaxAnnotation) {
@ -151,9 +151,8 @@ impl SyntaxEdit {
#[repr(transparent)] #[repr(transparent)]
pub struct SyntaxAnnotation(NonZeroU32); pub struct SyntaxAnnotation(NonZeroU32);
impl SyntaxAnnotation { impl Default for SyntaxAnnotation {
/// Creates a unique syntax annotation to attach data to. fn default() -> Self {
pub fn new() -> Self {
static COUNTER: AtomicU32 = AtomicU32::new(1); static COUNTER: AtomicU32 = AtomicU32::new(1);
// Only consistency within a thread matters, as SyntaxElements are !Send // Only consistency within a thread matters, as SyntaxElements are !Send
@ -163,12 +162,6 @@ impl SyntaxAnnotation {
} }
} }
impl Default for SyntaxAnnotation {
fn default() -> Self {
Self::new()
}
}
/// Position describing where to insert elements /// Position describing where to insert elements
#[derive(Debug)] #[derive(Debug)]
pub struct Position { pub struct Position {
@ -411,12 +404,12 @@ mod tests {
let to_replace = root.syntax().descendants().find_map(ast::BinExpr::cast).unwrap(); let to_replace = root.syntax().descendants().find_map(ast::BinExpr::cast).unwrap();
let mut editor = SyntaxEditor::new(root.syntax().clone()); let mut editor = SyntaxEditor::new(root.syntax().clone());
let make = SyntaxFactory::new(); let make = SyntaxFactory::with_mappings();
let name = make::name("var_name"); let name = make::name("var_name");
let name_ref = make::name_ref("var_name").clone_for_update(); let name_ref = make::name_ref("var_name").clone_for_update();
let placeholder_snippet = SyntaxAnnotation::new(); let placeholder_snippet = SyntaxAnnotation::default();
editor.add_annotation(name.syntax(), placeholder_snippet); editor.add_annotation(name.syntax(), placeholder_snippet);
editor.add_annotation(name_ref.syntax(), placeholder_snippet); editor.add_annotation(name_ref.syntax(), placeholder_snippet);
@ -522,7 +515,7 @@ mod tests {
let second_let = root.syntax().descendants().find_map(ast::LetStmt::cast).unwrap(); let second_let = root.syntax().descendants().find_map(ast::LetStmt::cast).unwrap();
let mut editor = SyntaxEditor::new(root.syntax().clone()); let mut editor = SyntaxEditor::new(root.syntax().clone());
let make = SyntaxFactory::new(); let make = SyntaxFactory::with_mappings();
let new_block_expr = make.block_expr([], Some(ast::Expr::BlockExpr(inner_block.clone()))); let new_block_expr = make.block_expr([], Some(ast::Expr::BlockExpr(inner_block.clone())));
@ -574,7 +567,7 @@ mod tests {
let inner_block = root.clone(); let inner_block = root.clone();
let mut editor = SyntaxEditor::new(root.syntax().clone()); let mut editor = SyntaxEditor::new(root.syntax().clone());
let make = SyntaxFactory::new(); let make = SyntaxFactory::with_mappings();
let new_block_expr = make.block_expr([], Some(ast::Expr::BlockExpr(inner_block.clone()))); let new_block_expr = make.block_expr([], Some(ast::Expr::BlockExpr(inner_block.clone())));

View file

@ -20,10 +20,6 @@ pub struct SyntaxMapping {
} }
impl SyntaxMapping { impl SyntaxMapping {
pub fn new() -> Self {
Self::default()
}
/// Like [`SyntaxMapping::upmap_child`] but for syntax elements. /// Like [`SyntaxMapping::upmap_child`] but for syntax elements.
pub fn upmap_child_element( pub fn upmap_child_element(
&self, &self,

View file

@ -139,7 +139,7 @@ impl ChangeFixture {
let channel = toolchain.as_deref().unwrap_or("stable"); let channel = toolchain.as_deref().unwrap_or("stable");
Version::parse(&format!("1.76.0-{channel}")).unwrap() Version::parse(&format!("1.76.0-{channel}")).unwrap()
}); });
let mut source_change = FileChange::new(); let mut source_change = FileChange::default();
let mut files = Vec::new(); let mut files = Vec::new();
let mut crate_graph = CrateGraphBuilder::default(); let mut crate_graph = CrateGraphBuilder::default();

View file

@ -85,7 +85,7 @@ impl<'a, 'b, R: BufRead> Converter<'a, 'b, R> {
} }
fn process_list(&mut self) -> anyhow::Result<()> { fn process_list(&mut self) -> anyhow::Result<()> {
let mut nesting = ListNesting::new(); let mut nesting = ListNesting::default();
while let Some(line) = self.iter.peek() { while let Some(line) = self.iter.peek() {
let line = line.as_deref().map_err(|e| anyhow!("{e}"))?; let line = line.as_deref().map_err(|e| anyhow!("{e}"))?;
@ -385,10 +385,6 @@ fn parse_media_block<'a>(line: &'a str, prefix: &str) -> Option<(&'a str, &'a st
struct ListNesting(Vec<ListMarker>); struct ListNesting(Vec<ListMarker>);
impl ListNesting { impl ListNesting {
fn new() -> Self {
Self(Vec::<ListMarker>::with_capacity(6))
}
fn current(&mut self) -> Option<&ListMarker> { fn current(&mut self) -> Option<&ListMarker> {
self.0.last() self.0.last()
} }
@ -417,6 +413,12 @@ impl ListNesting {
} }
} }
impl Default for ListNesting {
fn default() -> Self {
Self(Vec::<ListMarker>::with_capacity(6))
}
}
#[derive(Debug, PartialEq, Eq)] #[derive(Debug, PartialEq, Eq)]
enum ListMarker { enum ListMarker {
Asterisk(usize), Asterisk(usize),