1 //! This module contains functions to generate default trait impl function bodies where possible.
4 ast::{self, edit::AstNodeEdit, make, AstNode, NameOwner},
8 /// Generate custom trait bodies where possible.
10 /// Returns `Option` so that we can use `?` rather than `if let Some`. Returning
11 /// `None` means that generating a custom trait body failed, and the body will remain
12 /// as `todo!` instead.
13 pub(crate) fn gen_trait_fn_body(
15 trait_path: &ast::Path,
18 match trait_path.segment()?.name_ref()?.text().as_str() {
19 "Clone" => gen_clone_impl(adt, func),
20 "Debug" => gen_debug_impl(adt, func),
21 "Default" => gen_default_impl(adt, func),
22 "Hash" => gen_hash_impl(adt, func),
23 "PartialEq" => gen_partial_eq(adt, func),
28 /// Generate a `Clone` impl based on the fields and members of the target type.
29 fn gen_clone_impl(adt: &ast::Adt, func: &ast::Fn) -> Option<()> {
30 fn gen_clone_call(target: ast::Expr) -> ast::Expr {
31 let method = make::name_ref("clone");
32 make::expr_method_call(target, method, make::arg_list(None))
34 let expr = match adt {
35 // `Clone` cannot be derived for unions, so no default impl can be provided.
36 ast::Adt::Union(_) => return None,
37 ast::Adt::Enum(enum_) => {
38 let list = enum_.variant_list()?;
39 let mut arms = vec![];
40 for variant in list.variants() {
41 let name = variant.name()?;
42 let variant_name = make::ext::path_from_idents(["Self", &format!("{}", name)])?;
44 match variant.field_list() {
45 // => match self { Self::Name { x } => Self::Name { x: x.clone() } }
46 Some(ast::FieldList::RecordFieldList(list)) => {
47 let mut pats = vec![];
48 let mut fields = vec![];
49 for field in list.fields() {
50 let field_name = field.name()?;
51 let pat = make::ident_pat(false, false, field_name.clone());
52 pats.push(pat.into());
54 let path = make::ext::ident_path(&field_name.to_string());
55 let method_call = gen_clone_call(make::expr_path(path));
56 let name_ref = make::name_ref(&field_name.to_string());
57 let field = make::record_expr_field(name_ref, Some(method_call));
60 let pat = make::record_pat(variant_name.clone(), pats.into_iter());
61 let fields = make::record_expr_field_list(fields);
62 let record_expr = make::record_expr(variant_name, fields).into();
63 arms.push(make::match_arm(Some(pat.into()), None, record_expr));
66 // => match self { Self::Name(arg1) => Self::Name(arg1.clone()) }
67 Some(ast::FieldList::TupleFieldList(list)) => {
68 let mut pats = vec![];
69 let mut fields = vec![];
70 for (i, _) in list.fields().enumerate() {
71 let field_name = format!("arg{}", i);
72 let pat = make::ident_pat(false, false, make::name(&field_name));
73 pats.push(pat.into());
75 let f_path = make::expr_path(make::ext::ident_path(&field_name));
76 fields.push(gen_clone_call(f_path));
78 let pat = make::tuple_struct_pat(variant_name.clone(), pats.into_iter());
79 let struct_name = make::expr_path(variant_name);
80 let tuple_expr = make::expr_call(struct_name, make::arg_list(fields));
81 arms.push(make::match_arm(Some(pat.into()), None, tuple_expr));
84 // => match self { Self::Name => Self::Name }
86 let pattern = make::path_pat(variant_name.clone());
87 let variant_expr = make::expr_path(variant_name);
88 arms.push(make::match_arm(Some(pattern.into()), None, variant_expr));
93 let match_target = make::expr_path(make::ext::ident_path("self"));
94 let list = make::match_arm_list(arms).indent(ast::edit::IndentLevel(1));
95 make::expr_match(match_target, list)
97 ast::Adt::Struct(strukt) => {
98 match strukt.field_list() {
99 // => Self { name: self.name.clone() }
100 Some(ast::FieldList::RecordFieldList(field_list)) => {
101 let mut fields = vec![];
102 for field in field_list.fields() {
103 let base = make::expr_path(make::ext::ident_path("self"));
104 let target = make::expr_field(base, &field.name()?.to_string());
105 let method_call = gen_clone_call(target);
106 let name_ref = make::name_ref(&field.name()?.to_string());
107 let field = make::record_expr_field(name_ref, Some(method_call));
110 let struct_name = make::ext::ident_path("Self");
111 let fields = make::record_expr_field_list(fields);
112 make::record_expr(struct_name, fields).into()
114 // => Self(self.0.clone(), self.1.clone())
115 Some(ast::FieldList::TupleFieldList(field_list)) => {
116 let mut fields = vec![];
117 for (i, _) in field_list.fields().enumerate() {
118 let f_path = make::expr_path(make::ext::ident_path("self"));
119 let target = make::expr_field(f_path, &format!("{}", i)).into();
120 fields.push(gen_clone_call(target));
122 let struct_name = make::expr_path(make::ext::ident_path("Self"));
123 make::expr_call(struct_name, make::arg_list(fields))
127 let struct_name = make::ext::ident_path("Self");
128 let fields = make::record_expr_field_list(None);
129 make::record_expr(struct_name, fields).into()
134 let body = make::block_expr(None, Some(expr)).indent(ast::edit::IndentLevel(1));
135 ted::replace(func.body()?.syntax(), body.clone_for_update().syntax());
139 /// Generate a `Debug` impl based on the fields and members of the target type.
140 fn gen_debug_impl(adt: &ast::Adt, func: &ast::Fn) -> Option<()> {
141 let annotated_name = adt.name()?;
143 // `Debug` cannot be derived for unions, so no default impl can be provided.
144 ast::Adt::Union(_) => None,
146 // => match self { Self::Variant => write!(f, "Variant") }
147 ast::Adt::Enum(enum_) => {
148 let list = enum_.variant_list()?;
149 let mut arms = vec![];
150 for variant in list.variants() {
151 let name = variant.name()?;
153 make::path_pat(make::ext::path_from_idents(["Self", &format!("{}", name)])?);
155 let target = make::expr_path(make::ext::ident_path("f").into());
156 let fmt_string = make::expr_literal(&(format!("\"{}\"", name))).into();
157 let args = make::arg_list(vec![target, fmt_string]);
158 let macro_name = make::expr_path(make::ext::ident_path("write"));
159 let macro_call = make::expr_macro_call(macro_name, args);
161 arms.push(make::match_arm(Some(variant_name.into()), None, macro_call.into()));
164 let match_target = make::expr_path(make::ext::ident_path("self"));
165 let list = make::match_arm_list(arms).indent(ast::edit::IndentLevel(1));
166 let match_expr = make::expr_match(match_target, list);
168 let body = make::block_expr(None, Some(match_expr));
169 let body = body.indent(ast::edit::IndentLevel(1));
170 ted::replace(func.body()?.syntax(), body.clone_for_update().syntax());
174 ast::Adt::Struct(strukt) => {
175 let name = format!("\"{}\"", annotated_name);
176 let args = make::arg_list(Some(make::expr_literal(&name).into()));
177 let target = make::expr_path(make::ext::ident_path("f"));
179 let expr = match strukt.field_list() {
180 // => f.debug_struct("Name").finish()
181 None => make::expr_method_call(target, make::name_ref("debug_struct"), args),
183 // => f.debug_struct("Name").field("foo", &self.foo).finish()
184 Some(ast::FieldList::RecordFieldList(field_list)) => {
185 let method = make::name_ref("debug_struct");
186 let mut expr = make::expr_method_call(target, method, args);
187 for field in field_list.fields() {
188 let name = field.name()?;
189 let f_name = make::expr_literal(&(format!("\"{}\"", name))).into();
190 let f_path = make::expr_path(make::ext::ident_path("self"));
191 let f_path = make::expr_ref(f_path, false);
192 let f_path = make::expr_field(f_path, &format!("{}", name)).into();
193 let args = make::arg_list(vec![f_name, f_path]);
194 expr = make::expr_method_call(expr, make::name_ref("field"), args);
199 // => f.debug_tuple("Name").field(self.0).finish()
200 Some(ast::FieldList::TupleFieldList(field_list)) => {
201 let method = make::name_ref("debug_tuple");
202 let mut expr = make::expr_method_call(target, method, args);
203 for (i, _) in field_list.fields().enumerate() {
204 let f_path = make::expr_path(make::ext::ident_path("self"));
205 let f_path = make::expr_ref(f_path, false);
206 let f_path = make::expr_field(f_path, &format!("{}", i)).into();
207 let method = make::name_ref("field");
208 expr = make::expr_method_call(expr, method, make::arg_list(Some(f_path)));
214 let method = make::name_ref("finish");
215 let expr = make::expr_method_call(expr, method, make::arg_list(None));
216 let body = make::block_expr(None, Some(expr)).indent(ast::edit::IndentLevel(1));
217 ted::replace(func.body()?.syntax(), body.clone_for_update().syntax());
223 /// Generate a `Debug` impl based on the fields and members of the target type.
224 fn gen_default_impl(adt: &ast::Adt, func: &ast::Fn) -> Option<()> {
225 fn gen_default_call() -> Option<ast::Expr> {
226 let fn_name = make::ext::path_from_idents(["Default", "default"])?;
227 Some(make::expr_call(make::expr_path(fn_name), make::arg_list(None)))
230 // `Debug` cannot be derived for unions, so no default impl can be provided.
231 ast::Adt::Union(_) => None,
232 // Deriving `Debug` for enums is not stable yet.
233 ast::Adt::Enum(_) => None,
234 ast::Adt::Struct(strukt) => {
235 let expr = match strukt.field_list() {
236 Some(ast::FieldList::RecordFieldList(field_list)) => {
237 let mut fields = vec![];
238 for field in field_list.fields() {
239 let method_call = gen_default_call()?;
240 let name_ref = make::name_ref(&field.name()?.to_string());
241 let field = make::record_expr_field(name_ref, Some(method_call));
244 let struct_name = make::ext::ident_path("Self");
245 let fields = make::record_expr_field_list(fields);
246 make::record_expr(struct_name, fields).into()
248 Some(ast::FieldList::TupleFieldList(field_list)) => {
249 let struct_name = make::expr_path(make::ext::ident_path("Self"));
250 let fields = field_list
252 .map(|_| gen_default_call())
253 .collect::<Option<Vec<ast::Expr>>>()?;
254 make::expr_call(struct_name, make::arg_list(fields))
257 let struct_name = make::ext::ident_path("Self");
258 let fields = make::record_expr_field_list(None);
259 make::record_expr(struct_name, fields).into()
262 let body = make::block_expr(None, Some(expr)).indent(ast::edit::IndentLevel(1));
263 ted::replace(func.body()?.syntax(), body.clone_for_update().syntax());
269 /// Generate a `Hash` impl based on the fields and members of the target type.
270 fn gen_hash_impl(adt: &ast::Adt, func: &ast::Fn) -> Option<()> {
271 fn gen_hash_call(target: ast::Expr) -> ast::Stmt {
272 let method = make::name_ref("hash");
273 let arg = make::expr_path(make::ext::ident_path("state"));
274 let expr = make::expr_method_call(target, method, make::arg_list(Some(arg)));
275 make::expr_stmt(expr).into()
278 let body = match adt {
279 // `Hash` cannot be derived for unions, so no default impl can be provided.
280 ast::Adt::Union(_) => return None,
282 // => std::mem::discriminant(self).hash(state);
283 ast::Adt::Enum(_) => {
284 let fn_name = make_discriminant()?;
286 let arg = make::expr_path(make::ext::ident_path("self"));
287 let fn_call = make::expr_call(fn_name, make::arg_list(Some(arg)));
288 let stmt = gen_hash_call(fn_call);
290 make::block_expr(Some(stmt), None).indent(ast::edit::IndentLevel(1))
292 ast::Adt::Struct(strukt) => match strukt.field_list() {
293 // => self.<field>.hash(state);
294 Some(ast::FieldList::RecordFieldList(field_list)) => {
295 let mut stmts = vec![];
296 for field in field_list.fields() {
297 let base = make::expr_path(make::ext::ident_path("self"));
298 let target = make::expr_field(base, &field.name()?.to_string());
299 stmts.push(gen_hash_call(target));
301 make::block_expr(stmts, None).indent(ast::edit::IndentLevel(1))
304 // => self.<field_index>.hash(state);
305 Some(ast::FieldList::TupleFieldList(field_list)) => {
306 let mut stmts = vec![];
307 for (i, _) in field_list.fields().enumerate() {
308 let base = make::expr_path(make::ext::ident_path("self"));
309 let target = make::expr_field(base, &format!("{}", i));
310 stmts.push(gen_hash_call(target));
312 make::block_expr(stmts, None).indent(ast::edit::IndentLevel(1))
315 // No fields in the body means there's nothing to hash.
320 ted::replace(func.body()?.syntax(), body.clone_for_update().syntax());
324 /// Generate a `PartialEq` impl based on the fields and members of the target type.
325 fn gen_partial_eq(adt: &ast::Adt, func: &ast::Fn) -> Option<()> {
326 fn gen_eq_chain(expr: Option<ast::Expr>, cmp: ast::Expr) -> Option<ast::Expr> {
328 Some(expr) => Some(make::expr_op(ast::BinOp::BooleanAnd, expr, cmp)),
333 fn gen_record_pat_field(field_name: &str, pat_name: &str) -> ast::RecordPatField {
334 let pat = make::ext::simple_ident_pat(make::name(&pat_name));
335 let name_ref = make::name_ref(field_name);
336 make::record_pat_field(name_ref, pat.into())
339 fn gen_record_pat(record_name: ast::Path, fields: Vec<ast::RecordPatField>) -> ast::RecordPat {
340 let list = make::record_pat_field_list(fields);
341 make::record_pat_with_fields(record_name, list)
344 fn gen_variant_path(variant: &ast::Variant) -> Option<ast::Path> {
345 make::ext::path_from_idents(["Self", &variant.name()?.to_string()])
348 fn gen_tuple_field(field_name: &String) -> ast::Pat {
349 ast::Pat::IdentPat(make::ident_pat(false, false, make::name(field_name)))
352 // FIXME: return `None` if the trait carries a generic type; we can only
353 // generate this code `Self` for the time being.
355 let body = match adt {
356 // `Hash` cannot be derived for unions, so no default impl can be provided.
357 ast::Adt::Union(_) => return None,
359 ast::Adt::Enum(enum_) => {
360 // => std::mem::discriminant(self) == std::mem::discriminant(other)
361 let lhs_name = make::expr_path(make::ext::ident_path("self"));
362 let lhs = make::expr_call(make_discriminant()?, make::arg_list(Some(lhs_name.clone())));
363 let rhs_name = make::expr_path(make::ext::ident_path("other"));
364 let rhs = make::expr_call(make_discriminant()?, make::arg_list(Some(rhs_name.clone())));
365 let eq_check = make::expr_op(ast::BinOp::EqualityTest, lhs, rhs);
367 let mut case_count = 0;
368 let mut arms = vec![];
369 for variant in enum_.variant_list()?.variants() {
371 match variant.field_list() {
372 // => (Self::Bar { bin: l_bin }, Self::Bar { bin: r_bin }) => l_bin == r_bin,
373 Some(ast::FieldList::RecordFieldList(list)) => {
375 let mut l_fields = vec![];
376 let mut r_fields = vec![];
378 for field in list.fields() {
379 let field_name = field.name()?.to_string();
381 let l_name = &format!("l_{}", field_name);
382 l_fields.push(gen_record_pat_field(&field_name, &l_name));
384 let r_name = &format!("r_{}", field_name);
385 r_fields.push(gen_record_pat_field(&field_name, &r_name));
387 let lhs = make::expr_path(make::ext::ident_path(l_name));
388 let rhs = make::expr_path(make::ext::ident_path(r_name));
389 let cmp = make::expr_op(ast::BinOp::EqualityTest, lhs, rhs);
390 expr = gen_eq_chain(expr, cmp);
393 let left = gen_record_pat(gen_variant_path(&variant)?, l_fields);
394 let right = gen_record_pat(gen_variant_path(&variant)?, r_fields);
395 let tuple = make::tuple_pat(vec![left.into(), right.into()]);
397 if let Some(expr) = expr {
398 arms.push(make::match_arm(Some(tuple.into()), None, expr));
402 Some(ast::FieldList::TupleFieldList(list)) => {
404 let mut l_fields = vec![];
405 let mut r_fields = vec![];
407 for (i, _) in list.fields().enumerate() {
408 let field_name = format!("{}", i);
410 let l_name = format!("l{}", field_name);
411 l_fields.push(gen_tuple_field(&l_name));
413 let r_name = format!("r{}", field_name);
414 r_fields.push(gen_tuple_field(&r_name));
416 let lhs = make::expr_path(make::ext::ident_path(&l_name));
417 let rhs = make::expr_path(make::ext::ident_path(&r_name));
418 let cmp = make::expr_op(ast::BinOp::EqualityTest, lhs, rhs);
419 expr = gen_eq_chain(expr, cmp);
422 let left = make::tuple_struct_pat(gen_variant_path(&variant)?, l_fields);
423 let right = make::tuple_struct_pat(gen_variant_path(&variant)?, r_fields);
424 let tuple = make::tuple_pat(vec![left.into(), right.into()]);
426 if let Some(expr) = expr {
427 arms.push(make::match_arm(Some(tuple.into()), None, expr));
434 let expr = match arms.len() {
437 if case_count > arms.len() {
438 let lhs = make::wildcard_pat().into();
439 arms.push(make::match_arm(Some(lhs), None, eq_check));
442 let match_target = make::expr_tuple(vec![lhs_name, rhs_name]);
443 let list = make::match_arm_list(arms).indent(ast::edit::IndentLevel(1));
444 make::expr_match(match_target, list)
448 make::block_expr(None, Some(expr)).indent(ast::edit::IndentLevel(1))
450 ast::Adt::Struct(strukt) => match strukt.field_list() {
451 Some(ast::FieldList::RecordFieldList(field_list)) => {
453 for field in field_list.fields() {
454 let lhs = make::expr_path(make::ext::ident_path("self"));
455 let lhs = make::expr_field(lhs, &field.name()?.to_string());
456 let rhs = make::expr_path(make::ext::ident_path("other"));
457 let rhs = make::expr_field(rhs, &field.name()?.to_string());
458 let cmp = make::expr_op(ast::BinOp::EqualityTest, lhs, rhs);
459 expr = gen_eq_chain(expr, cmp);
461 make::block_expr(None, expr).indent(ast::edit::IndentLevel(1))
464 Some(ast::FieldList::TupleFieldList(field_list)) => {
466 for (i, _) in field_list.fields().enumerate() {
467 let idx = format!("{}", i);
468 let lhs = make::expr_path(make::ext::ident_path("self"));
469 let lhs = make::expr_field(lhs, &idx);
470 let rhs = make::expr_path(make::ext::ident_path("other"));
471 let rhs = make::expr_field(rhs, &idx);
472 let cmp = make::expr_op(ast::BinOp::EqualityTest, lhs, rhs);
473 expr = gen_eq_chain(expr, cmp);
475 make::block_expr(None, expr).indent(ast::edit::IndentLevel(1))
478 // No fields in the body means there's nothing to hash.
480 let expr = make::expr_literal("true").into();
481 make::block_expr(None, Some(expr)).indent(ast::edit::IndentLevel(1))
486 ted::replace(func.body()?.syntax(), body.clone_for_update().syntax());
490 fn make_discriminant() -> Option<ast::Expr> {
491 Some(make::expr_path(make::ext::path_from_idents(["core", "mem", "discriminant"])?))