Unnamed repository; edit this file 'description' to name the repository.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
use hir::{db::HirDatabase, HasSource, HasVisibility, ModuleDef, PathResolution, ScopeDef};
use ide_db::base_db::FileId;
use syntax::{
    ast::{self, HasVisibility as _},
    AstNode, TextRange, TextSize,
};

use crate::{utils::vis_offset, AssistContext, AssistId, AssistKind, Assists};

// FIXME: this really should be a fix for diagnostic, rather than an assist.

// Assist: fix_visibility
//
// Makes inaccessible item public.
//
// ```
// mod m {
//     fn frobnicate() {}
// }
// fn main() {
//     m::frobnicate$0();
// }
// ```
// ->
// ```
// mod m {
//     $0pub(crate) fn frobnicate() {}
// }
// fn main() {
//     m::frobnicate();
// }
// ```
pub(crate) fn fix_visibility(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> {
    add_vis_to_referenced_module_def(acc, ctx)
        .or_else(|| add_vis_to_referenced_record_field(acc, ctx))
}

fn add_vis_to_referenced_module_def(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> {
    let path: ast::Path = ctx.find_node_at_offset()?;
    let qualifier = path.qualifier()?;
    let name_ref = path.segment()?.name_ref()?;
    let qualifier_res = ctx.sema.resolve_path(&qualifier)?;
    let PathResolution::Def(ModuleDef::Module(module)) = qualifier_res else { return None; };
    let (_, def) = module
        .scope(ctx.db(), None)
        .into_iter()
        .find(|(name, _)| name.to_smol_str() == name_ref.text().as_str())?;
    let ScopeDef::ModuleDef(def) = def else { return None; };

    let current_module = ctx.sema.scope(path.syntax())?.module();
    let target_module = def.module(ctx.db())?;

    if def.visibility(ctx.db()).is_visible_from(ctx.db(), current_module.into()) {
        return None;
    };

    let (offset, current_visibility, target, target_file, target_name) =
        target_data_for_def(ctx.db(), def)?;

    let missing_visibility =
        if current_module.krate() == target_module.krate() { "pub(crate)" } else { "pub" };

    let assist_label = match target_name {
        None => format!("Change visibility to {missing_visibility}"),
        Some(name) => format!("Change visibility of {name} to {missing_visibility}"),
    };

    acc.add(AssistId("fix_visibility", AssistKind::QuickFix), assist_label, target, |builder| {
        builder.edit_file(target_file);
        match ctx.config.snippet_cap {
            Some(cap) => match current_visibility {
                Some(current_visibility) => builder.replace_snippet(
                    cap,
                    current_visibility.syntax().text_range(),
                    format!("$0{missing_visibility}"),
                ),
                None => builder.insert_snippet(cap, offset, format!("$0{missing_visibility} ")),
            },
            None => match current_visibility {
                Some(current_visibility) => {
                    builder.replace(current_visibility.syntax().text_range(), missing_visibility)
                }
                None => builder.insert(offset, format!("{missing_visibility} ")),
            },
        }
    })
}

fn add_vis_to_referenced_record_field(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> {
    let record_field: ast::RecordExprField = ctx.find_node_at_offset()?;
    let (record_field_def, _, _) = ctx.sema.resolve_record_field(&record_field)?;

    let current_module = ctx.sema.scope(record_field.syntax())?.module();
    let visibility = record_field_def.visibility(ctx.db());
    if visibility.is_visible_from(ctx.db(), current_module.into()) {
        return None;
    }

    let parent = record_field_def.parent_def(ctx.db());
    let parent_name = parent.name(ctx.db());
    let target_module = parent.module(ctx.db());

    let in_file_source = record_field_def.source(ctx.db())?;
    let (offset, current_visibility, target) = match in_file_source.value {
        hir::FieldSource::Named(it) => {
            let s = it.syntax();
            (vis_offset(s), it.visibility(), s.text_range())
        }
        hir::FieldSource::Pos(it) => {
            let s = it.syntax();
            (vis_offset(s), it.visibility(), s.text_range())
        }
    };

    let missing_visibility =
        if current_module.krate() == target_module.krate() { "pub(crate)" } else { "pub" };
    let target_file = in_file_source.file_id.original_file(ctx.db());

    let target_name = record_field_def.name(ctx.db());
    let assist_label =
        format!("Change visibility of {parent_name}.{target_name} to {missing_visibility}");

    acc.add(AssistId("fix_visibility", AssistKind::QuickFix), assist_label, target, |builder| {
        builder.edit_file(target_file);
        match ctx.config.snippet_cap {
            Some(cap) => match current_visibility {
                Some(current_visibility) => builder.replace_snippet(
                    cap,
                    current_visibility.syntax().text_range(),
                    format!("$0{missing_visibility}"),
                ),
                None => builder.insert_snippet(cap, offset, format!("$0{missing_visibility} ")),
            },
            None => match current_visibility {
                Some(current_visibility) => {
                    builder.replace(current_visibility.syntax().text_range(), missing_visibility)
                }
                None => builder.insert(offset, format!("{missing_visibility} ")),
            },
        }
    })
}

fn target_data_for_def(
    db: &dyn HirDatabase,
    def: hir::ModuleDef,
) -> Option<(TextSize, Option<ast::Visibility>, TextRange, FileId, Option<hir::Name>)> {
    fn offset_target_and_file_id<S, Ast>(
        db: &dyn HirDatabase,
        x: S,
    ) -> Option<(TextSize, Option<ast::Visibility>, TextRange, FileId)>
    where
        S: HasSource<Ast = Ast>,
        Ast: AstNode + ast::HasVisibility,
    {
        let source = x.source(db)?;
        let in_file_syntax = source.syntax();
        let file_id = in_file_syntax.file_id;
        let syntax = in_file_syntax.value;
        let current_visibility = source.value.visibility();
        Some((
            vis_offset(syntax),
            current_visibility,
            syntax.text_range(),
            file_id.original_file(db.upcast()),
        ))
    }

    let target_name;
    let (offset, current_visibility, target, target_file) = match def {
        hir::ModuleDef::Function(f) => {
            target_name = Some(f.name(db));
            offset_target_and_file_id(db, f)?
        }
        hir::ModuleDef::Adt(adt) => {
            target_name = Some(adt.name(db));
            match adt {
                hir::Adt::Struct(s) => offset_target_and_file_id(db, s)?,
                hir::Adt::Union(u) => offset_target_and_file_id(db, u)?,
                hir::Adt::Enum(e) => offset_target_and_file_id(db, e)?,
            }
        }
        hir::ModuleDef::Const(c) => {
            target_name = c.name(db);
            offset_target_and_file_id(db, c)?
        }
        hir::ModuleDef::Static(s) => {
            target_name = Some(s.name(db));
            offset_target_and_file_id(db, s)?
        }
        hir::ModuleDef::Trait(t) => {
            target_name = Some(t.name(db));
            offset_target_and_file_id(db, t)?
        }
        hir::ModuleDef::TypeAlias(t) => {
            target_name = Some(t.name(db));
            offset_target_and_file_id(db, t)?
        }
        hir::ModuleDef::Module(m) => {
            target_name = m.name(db);
            let in_file_source = m.declaration_source(db)?;
            let file_id = in_file_source.file_id.original_file(db.upcast());
            let syntax = in_file_source.value.syntax();
            (vis_offset(syntax), in_file_source.value.visibility(), syntax.text_range(), file_id)
        }
        // FIXME
        hir::ModuleDef::Macro(_) => return None,
        // Enum variants can't be private, we can't modify builtin types
        hir::ModuleDef::Variant(_) | hir::ModuleDef::BuiltinType(_) => return None,
    };

    Some((offset, current_visibility, target, target_file, target_name))
}

#[cfg(test)]
mod tests {
    use crate::tests::{check_assist, check_assist_not_applicable};

    use super::*;

    #[test]
    fn fix_visibility_of_fn() {
        check_assist(
            fix_visibility,
            r"mod foo { fn foo() {} }
              fn main() { foo::foo$0() } ",
            r"mod foo { $0pub(crate) fn foo() {} }
              fn main() { foo::foo() } ",
        );
        check_assist_not_applicable(
            fix_visibility,
            r"mod foo { pub fn foo() {} }
              fn main() { foo::foo$0() } ",
        )
    }

    #[test]
    fn fix_visibility_of_adt_in_submodule() {
        check_assist(
            fix_visibility,
            r"mod foo { struct Foo; }
              fn main() { foo::Foo$0 } ",
            r"mod foo { $0pub(crate) struct Foo; }
              fn main() { foo::Foo } ",
        );
        check_assist_not_applicable(
            fix_visibility,
            r"mod foo { pub struct Foo; }
              fn main() { foo::Foo$0 } ",
        );
        check_assist(
            fix_visibility,
            r"mod foo { enum Foo; }
              fn main() { foo::Foo$0 } ",
            r"mod foo { $0pub(crate) enum Foo; }
              fn main() { foo::Foo } ",
        );
        check_assist_not_applicable(
            fix_visibility,
            r"mod foo { pub enum Foo; }
              fn main() { foo::Foo$0 } ",
        );
        check_assist(
            fix_visibility,
            r"mod foo { union Foo; }
              fn main() { foo::Foo$0 } ",
            r"mod foo { $0pub(crate) union Foo; }
              fn main() { foo::Foo } ",
        );
        check_assist_not_applicable(
            fix_visibility,
            r"mod foo { pub union Foo; }
              fn main() { foo::Foo$0 } ",
        );
    }

    #[test]
    fn fix_visibility_of_adt_in_other_file() {
        check_assist(
            fix_visibility,
            r"
//- /main.rs
mod foo;
fn main() { foo::Foo$0 }

//- /foo.rs
struct Foo;
",
            r"$0pub(crate) struct Foo;
",
        );
    }

    #[test]
    fn fix_visibility_of_struct_field() {
        check_assist(
            fix_visibility,
            r"mod foo { pub struct Foo { bar: (), } }
              fn main() { foo::Foo { $0bar: () }; } ",
            r"mod foo { pub struct Foo { $0pub(crate) bar: (), } }
              fn main() { foo::Foo { bar: () }; } ",
        );
        check_assist(
            fix_visibility,
            r"
//- /lib.rs
mod foo;
fn main() { foo::Foo { $0bar: () }; }
//- /foo.rs
pub struct Foo { bar: () }
",
            r"pub struct Foo { $0pub(crate) bar: () }
",
        );
        check_assist_not_applicable(
            fix_visibility,
            r"mod foo { pub struct Foo { pub bar: (), } }
              fn main() { foo::Foo { $0bar: () }; } ",
        );
        check_assist_not_applicable(
            fix_visibility,
            r"
//- /lib.rs
mod foo;
fn main() { foo::Foo { $0bar: () }; }
//- /foo.rs
pub struct Foo { pub bar: () }
",
        );
    }

    #[test]
    fn fix_visibility_of_enum_variant_field() {
        // Enum variants, as well as their fields, always get the enum's visibility. In fact, rustc
        // rejects any visibility specifiers on them, so this assist should never fire on them.
        check_assist_not_applicable(
            fix_visibility,
            r"mod foo { pub enum Foo { Bar { bar: () } } }
              fn main() { foo::Foo::Bar { $0bar: () }; } ",
        );
        check_assist_not_applicable(
            fix_visibility,
            r"
//- /lib.rs
mod foo;
fn main() { foo::Foo::Bar { $0bar: () }; }
//- /foo.rs
pub enum Foo { Bar { bar: () } }
",
        );
        check_assist_not_applicable(
            fix_visibility,
            r"mod foo { pub struct Foo { pub bar: (), } }
              fn main() { foo::Foo { $0bar: () }; } ",
        );
        check_assist_not_applicable(
            fix_visibility,
            r"
//- /lib.rs
mod foo;
fn main() { foo::Foo { $0bar: () }; }
//- /foo.rs
pub struct Foo { pub bar: () }
",
        );
    }

    #[test]
    fn fix_visibility_of_union_field() {
        check_assist(
            fix_visibility,
            r"mod foo { pub union Foo { bar: (), } }
              fn main() { foo::Foo { $0bar: () }; } ",
            r"mod foo { pub union Foo { $0pub(crate) bar: (), } }
              fn main() { foo::Foo { bar: () }; } ",
        );
        check_assist(
            fix_visibility,
            r"
//- /lib.rs
mod foo;
fn main() { foo::Foo { $0bar: () }; }
//- /foo.rs
pub union Foo { bar: () }
",
            r"pub union Foo { $0pub(crate) bar: () }
",
        );
        check_assist_not_applicable(
            fix_visibility,
            r"mod foo { pub union Foo { pub bar: (), } }
              fn main() { foo::Foo { $0bar: () }; } ",
        );
        check_assist_not_applicable(
            fix_visibility,
            r"
//- /lib.rs
mod foo;
fn main() { foo::Foo { $0bar: () }; }
//- /foo.rs
pub union Foo { pub bar: () }
",
        );
    }

    #[test]
    fn fix_visibility_of_const() {
        check_assist(
            fix_visibility,
            r"mod foo { const FOO: () = (); }
              fn main() { foo::FOO$0 } ",
            r"mod foo { $0pub(crate) const FOO: () = (); }
              fn main() { foo::FOO } ",
        );
        check_assist_not_applicable(
            fix_visibility,
            r"mod foo { pub const FOO: () = (); }
              fn main() { foo::FOO$0 } ",
        );
    }

    #[test]
    fn fix_visibility_of_static() {
        check_assist(
            fix_visibility,
            r"mod foo { static FOO: () = (); }
              fn main() { foo::FOO$0 } ",
            r"mod foo { $0pub(crate) static FOO: () = (); }
              fn main() { foo::FOO } ",
        );
        check_assist_not_applicable(
            fix_visibility,
            r"mod foo { pub static FOO: () = (); }
              fn main() { foo::FOO$0 } ",
        );
    }

    #[test]
    fn fix_visibility_of_trait() {
        check_assist(
            fix_visibility,
            r"mod foo { trait Foo { fn foo(&self) {} } }
              fn main() { let x: &dyn foo::$0Foo; } ",
            r"mod foo { $0pub(crate) trait Foo { fn foo(&self) {} } }
              fn main() { let x: &dyn foo::Foo; } ",
        );
        check_assist_not_applicable(
            fix_visibility,
            r"mod foo { pub trait Foo { fn foo(&self) {} } }
              fn main() { let x: &dyn foo::Foo$0; } ",
        );
    }

    #[test]
    fn fix_visibility_of_type_alias() {
        check_assist(
            fix_visibility,
            r"mod foo { type Foo = (); }
              fn main() { let x: foo::Foo$0; } ",
            r"mod foo { $0pub(crate) type Foo = (); }
              fn main() { let x: foo::Foo; } ",
        );
        check_assist_not_applicable(
            fix_visibility,
            r"mod foo { pub type Foo = (); }
              fn main() { let x: foo::Foo$0; } ",
        );
    }

    #[test]
    fn fix_visibility_of_module() {
        check_assist(
            fix_visibility,
            r"mod foo { mod bar { fn bar() {} } }
              fn main() { foo::bar$0::bar(); } ",
            r"mod foo { $0pub(crate) mod bar { fn bar() {} } }
              fn main() { foo::bar::bar(); } ",
        );

        check_assist(
            fix_visibility,
            r"
//- /main.rs
mod foo;
fn main() { foo::bar$0::baz(); }

//- /foo.rs
mod bar {
    pub fn baz() {}
}
",
            r"$0pub(crate) mod bar {
    pub fn baz() {}
}
",
        );

        check_assist_not_applicable(
            fix_visibility,
            r"mod foo { pub mod bar { pub fn bar() {} } }
              fn main() { foo::bar$0::bar(); } ",
        );
    }

    #[test]
    fn fix_visibility_of_inline_module_in_other_file() {
        check_assist(
            fix_visibility,
            r"
//- /main.rs
mod foo;
fn main() { foo::bar$0::baz(); }

//- /foo.rs
mod bar;
//- /foo/bar.rs
pub fn baz() {}
",
            r"$0pub(crate) mod bar;
",
        );
    }

    #[test]
    fn fix_visibility_of_module_declaration_in_other_file() {
        check_assist(
            fix_visibility,
            r"
//- /main.rs
mod foo;
fn main() { foo::bar$0>::baz(); }

//- /foo.rs
mod bar {
    pub fn baz() {}
}
",
            r"$0pub(crate) mod bar {
    pub fn baz() {}
}
",
        );
    }

    #[test]
    fn adds_pub_when_target_is_in_another_crate() {
        check_assist(
            fix_visibility,
            r"
//- /main.rs crate:a deps:foo
foo::Bar$0
//- /lib.rs crate:foo
struct Bar;
",
            r"$0pub struct Bar;
",
        )
    }

    #[test]
    fn replaces_pub_crate_with_pub() {
        check_assist(
            fix_visibility,
            r"
//- /main.rs crate:a deps:foo
foo::Bar$0
//- /lib.rs crate:foo
pub(crate) struct Bar;
",
            r"$0pub struct Bar;
",
        );
        check_assist(
            fix_visibility,
            r"
//- /main.rs crate:a deps:foo
fn main() {
    foo::Foo { $0bar: () };
}
//- /lib.rs crate:foo
pub struct Foo { pub(crate) bar: () }
",
            r"pub struct Foo { $0pub bar: () }
",
        );
    }

    #[test]
    fn fix_visibility_of_reexport() {
        // FIXME: broken test, this should fix visibility of the re-export
        // rather than the struct.
        check_assist(
            fix_visibility,
            r#"
mod foo {
    use bar::Baz;
    mod bar { pub(super) struct Baz; }
}
foo::Baz$0
"#,
            r#"
mod foo {
    use bar::Baz;
    mod bar { $0pub(crate) struct Baz; }
}
foo::Baz
"#,
        )
    }
}
a id='n1180' href='#n1180'>1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929
use std::ops::Not;

use crate::{
    assist_context::{AssistContext, Assists},
    utils::convert_param_list_to_arg_list,
};
use either::Either;
use hir::{HasVisibility, db::HirDatabase};
use ide_db::{
    FxHashMap, FxHashSet,
    assists::{AssistId, GroupLabel},
    path_transform::PathTransform,
    syntax_helpers::suggest_name,
};
use itertools::Itertools;
use syntax::{
    AstNode, Edition, NodeOrToken, SmolStr, SyntaxKind, ToSmolStr,
    ast::{
        self, AssocItem, GenericArgList, GenericParamList, HasAttrs, HasGenericArgs,
        HasGenericParams, HasName, HasTypeBounds, HasVisibility as astHasVisibility, Path,
        WherePred,
        edit::{self, AstNodeEdit},
        make,
    },
    ted::{self, Position},
};

// Assist: generate_delegate_trait
//
// Generate delegate trait implementation for `StructField`s.
//
// ```
// trait SomeTrait {
//     type T;
//     fn fn_(arg: u32) -> u32;
//     fn method_(&mut self) -> bool;
// }
// struct A;
// impl SomeTrait for A {
//     type T = u32;
//
//     fn fn_(arg: u32) -> u32 {
//         42
//     }
//
//     fn method_(&mut self) -> bool {
//         false
//     }
// }
// struct B {
//     a$0: A,
// }
// ```
// ->
// ```
// trait SomeTrait {
//     type T;
//     fn fn_(arg: u32) -> u32;
//     fn method_(&mut self) -> bool;
// }
// struct A;
// impl SomeTrait for A {
//     type T = u32;
//
//     fn fn_(arg: u32) -> u32 {
//         42
//     }
//
//     fn method_(&mut self) -> bool {
//         false
//     }
// }
// struct B {
//     a: A,
// }
//
// impl SomeTrait for B {
//     type T = <A as SomeTrait>::T;
//
//     fn fn_(arg: u32) -> u32 {
//         <A as SomeTrait>::fn_(arg)
//     }
//
//     fn method_(&mut self) -> bool {
//         <A as SomeTrait>::method_(&mut self.a)
//     }
// }
// ```
pub(crate) fn generate_delegate_trait(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> {
    if !ctx.config.code_action_grouping {
        return None;
    }

    let strukt = Struct::new(ctx.find_node_at_offset::<ast::Struct>()?)?;

    let field: Field = match ctx.find_node_at_offset::<ast::RecordField>() {
        Some(field) => Field::new(ctx, Either::Left(field))?,
        None => {
            let field = ctx.find_node_at_offset::<ast::TupleField>()?;
            let field_list = ctx.find_node_at_offset::<ast::TupleFieldList>()?;
            Field::new(ctx, either::Right((field, field_list)))?
        }
    };

    strukt.delegate(field, acc, ctx);
    Some(())
}

/// A utility object that represents a struct's field.
#[derive(Debug)]
struct Field {
    name: String,
    ty: ast::Type,
    range: syntax::TextRange,
    impls: Vec<Delegee>,
    edition: Edition,
}

impl Field {
    pub(crate) fn new(
        ctx: &AssistContext<'_>,
        f: Either<ast::RecordField, (ast::TupleField, ast::TupleFieldList)>,
    ) -> Option<Field> {
        let db = ctx.sema.db;

        let module = ctx.sema.file_to_module_def(ctx.vfs_file_id())?;
        let edition = module.krate().edition(ctx.db());

        let (name, range, ty) = match f {
            Either::Left(f) => {
                let name = f.name()?.to_string();
                (name, f.syntax().text_range(), f.ty()?)
            }
            Either::Right((f, l)) => {
                let name = l.fields().position(|it| it == f)?.to_string();
                (name, f.syntax().text_range(), f.ty()?)
            }
        };

        let hir_ty = ctx.sema.resolve_type(&ty)?;
        let type_impls = hir::Impl::all_for_type(db, hir_ty.clone());
        let mut impls = Vec::with_capacity(type_impls.len());

        if let Some(tp) = hir_ty.as_type_param(db) {
            for tb in tp.trait_bounds(db) {
                impls.push(Delegee::Bound(tb));
            }
        };

        for imp in type_impls {
            if let Some(tr) = imp.trait_(db).filter(|tr| tr.is_visible_from(db, module)) {
                impls.push(Delegee::Impls(tr, imp))
            }
        }

        Some(Field { name, ty, range, impls, edition })
    }
}

/// A field that we want to delegate can offer the enclosing struct
/// trait to implement in two ways. The first way is when the field
/// actually implements the trait and the second way is when the field
/// has a bound type parameter. We handle these cases in different ways
/// hence the enum.
#[derive(Debug)]
enum Delegee {
    Bound(hir::Trait),
    Impls(hir::Trait, hir::Impl),
}

impl Delegee {
    fn signature(&self, db: &dyn HirDatabase, edition: Edition) -> String {
        let mut s = String::new();

        let (Delegee::Bound(it) | Delegee::Impls(it, _)) = self;

        for m in it.module(db).path_to_root(db).iter().rev() {
            if let Some(name) = m.name(db) {
                s.push_str(&format!("{}::", name.display_no_db(edition).to_smolstr()));
            }
        }

        s.push_str(&it.name(db).display_no_db(edition).to_smolstr());
        s
    }
}

/// A utility struct that is used for the enclosing struct.
struct Struct {
    strukt: ast::Struct,
    name: ast::Name,
}

impl Struct {
    pub(crate) fn new(s: ast::Struct) -> Option<Self> {
        let name = s.name()?;
        Some(Struct { name, strukt: s })
    }

    pub(crate) fn delegate(&self, field: Field, acc: &mut Assists, ctx: &AssistContext<'_>) {
        let db = ctx.db();

        for (index, delegee) in field.impls.iter().enumerate() {
            let trait_ = match delegee {
                Delegee::Bound(b) => b,
                Delegee::Impls(i, _) => i,
            };

            // Skip trait that has `Self` type, which cannot be delegated
            //
            // See [`test_self_ty`]
            if has_self_type(*trait_, ctx).is_some() {
                continue;
            }

            // FIXME :  We can omit already implemented impl_traits
            // But we don't know what the &[hir::Type] argument should look like.
            // if self.hir_ty.impls_trait(db, trait_, &[]) {
            //     continue;
            // }
            let signature = delegee.signature(db, field.edition);

            let Some(delegate) =
                generate_impl(ctx, self, &field.ty, &field.name, delegee, field.edition)
            else {
                continue;
            };

            acc.add_group(
                &GroupLabel(format!("Generate delegate trait impls for field `{}`", field.name)),
                AssistId(
                    "generate_delegate_trait",
                    ide_db::assists::AssistKind::Generate,
                    Some(index),
                ),
                format!("Generate delegate trait impl `{}` for `{}`", signature, field.name),
                field.range,
                |builder| {
                    builder.insert(
                        self.strukt.syntax().text_range().end(),
                        format!("\n\n{}", delegate.syntax()),
                    );
                },
            );
        }
    }
}

fn generate_impl(
    ctx: &AssistContext<'_>,
    strukt: &Struct,
    field_ty: &ast::Type,
    field_name: &str,
    delegee: &Delegee,
    edition: Edition,
) -> Option<ast::Impl> {
    let db = ctx.db();
    let ast_strukt = &strukt.strukt;
    let strukt_ty = make::ty_path(make::ext::ident_path(&strukt.name.to_string()));
    let strukt_params = ast_strukt.generic_param_list();

    match delegee {
        Delegee::Bound(delegee) => {
            let bound_def = ctx.sema.source(delegee.to_owned())?.value;
            let bound_params = bound_def.generic_param_list();

            let delegate = make::impl_trait(
                None,
                delegee.is_unsafe(db),
                bound_params.clone(),
                bound_params.map(|params| params.to_generic_args()),
                strukt_params.clone(),
                strukt_params.map(|params| params.to_generic_args()),
                delegee.is_auto(db),
                make::ty(&delegee.name(db).display_no_db(edition).to_smolstr()),
                strukt_ty,
                bound_def.where_clause(),
                ast_strukt.where_clause(),
                None,
            )
            .clone_for_update();

            // Goto link : https://doc.rust-lang.org/reference/paths.html#qualified-paths
            let qualified_path_type =
                make::path_from_text(&format!("<{} as {}>", field_ty, delegate.trait_()?));

            let delegate_assoc_items = delegate.get_or_create_assoc_item_list();
            if let Some(ai) = bound_def.assoc_item_list() {
                ai.assoc_items()
                    .filter(|item| matches!(item, AssocItem::MacroCall(_)).not())
                    .for_each(|item| {
                        let assoc = process_assoc_item(
                            item.clone_for_update(),
                            qualified_path_type.clone(),
                            field_name,
                        );
                        if let Some(assoc) = assoc {
                            delegate_assoc_items.add_item(assoc);
                        }
                    });
            };

            let target_scope = ctx.sema.scope(strukt.strukt.syntax())?;
            let source_scope = ctx.sema.scope(bound_def.syntax())?;
            let transform = PathTransform::generic_transformation(&target_scope, &source_scope);
            ast::Impl::cast(transform.apply(delegate.syntax()))
        }
        Delegee::Impls(trait_, old_impl) => {
            let old_impl = ctx.sema.source(old_impl.to_owned())?.value;
            let old_impl_params = old_impl.generic_param_list();

            // 1) Resolve conflicts between generic parameters in old_impl and
            // those in strukt.
            //
            // These generics parameters will also be used in `field_ty` and
            // `where_clauses`, so we should substitute arguments in them as well.
            let strukt_params = resolve_name_conflicts(strukt_params, &old_impl_params);
            let (field_ty, ty_where_clause) = match &strukt_params {
                Some(strukt_params) => {
                    let args = strukt_params.to_generic_args();
                    let field_ty = rename_strukt_args(ctx, ast_strukt, field_ty, &args)?;
                    let where_clause = ast_strukt
                        .where_clause()
                        .and_then(|wc| rename_strukt_args(ctx, ast_strukt, &wc, &args));
                    (field_ty, where_clause)
                }
                None => (field_ty.clone_for_update(), None),
            };

            // 2) Handle instantiated generics in `field_ty`.

            // 2.1) Some generics used in `self_ty` may be instantiated, so they
            // are no longer generics, we should remove and instantiate those
            // generics in advance.

            // `old_trait_args` contains names of generic args for trait in `old_impl`
            let old_impl_trait_args = old_impl
                .trait_()?
                .generic_arg_list()
                .map(|l| l.generic_args().map(|arg| arg.to_string()))
                .map_or_else(FxHashSet::default, |it| it.collect());

            let trait_gen_params = remove_instantiated_params(
                &old_impl.self_ty()?,
                old_impl_params.clone(),
                &old_impl_trait_args,
            );

            // 2.2) Generate generic args applied on impl.
            let transform_args = generate_args_for_impl(
                old_impl_params,
                &old_impl.self_ty()?,
                &field_ty,
                &trait_gen_params,
                &old_impl_trait_args,
            );

            // 2.3) Instantiate generics with `transform_impl`, this step also
            // remove unused params.
            let trait_gen_args = old_impl.trait_()?.generic_arg_list().and_then(|trait_args| {
                let trait_args = &mut trait_args.clone_for_update();
                if let Some(new_args) = transform_impl(
                    ctx,
                    ast_strukt,
                    &old_impl,
                    &transform_args,
                    trait_args.clone_subtree(),
                ) {
                    *trait_args = new_args.clone_subtree();
                    Some(new_args)
                } else {
                    None
                }
            });

            let type_gen_args = strukt_params.clone().map(|params| params.to_generic_args());
            let path_type =
                make::ty(&trait_.name(db).display_no_db(edition).to_smolstr()).clone_for_update();
            let path_type = transform_impl(ctx, ast_strukt, &old_impl, &transform_args, path_type)?;
            // 3) Generate delegate trait impl
            let delegate = make::impl_trait(
                None,
                trait_.is_unsafe(db),
                trait_gen_params,
                trait_gen_args,
                strukt_params,
                type_gen_args,
                trait_.is_auto(db),
                path_type,
                strukt_ty,
                old_impl.where_clause().map(|wc| wc.clone_for_update()),
                ty_where_clause,
                None,
            )
            .clone_for_update();
            // Goto link : https://doc.rust-lang.org/reference/paths.html#qualified-paths
            let qualified_path_type =
                make::path_from_text(&format!("<{} as {}>", field_ty, delegate.trait_()?));

            // 4) Transform associated items in delegte trait impl
            let delegate_assoc_items = delegate.get_or_create_assoc_item_list();
            for item in old_impl
                .get_or_create_assoc_item_list()
                .assoc_items()
                .filter(|item| matches!(item, AssocItem::MacroCall(_)).not())
            {
                let item = item.clone_for_update();
                let item = transform_impl(ctx, ast_strukt, &old_impl, &transform_args, item)?;

                let assoc = process_assoc_item(item, qualified_path_type.clone(), field_name)?;
                delegate_assoc_items.add_item(assoc);
            }

            // 5) Remove useless where clauses
            if let Some(wc) = delegate.where_clause() {
                remove_useless_where_clauses(&delegate.trait_()?, &delegate.self_ty()?, wc);
            }
            Some(delegate)
        }
    }
}

fn transform_impl<N: ast::AstNode>(
    ctx: &AssistContext<'_>,
    strukt: &ast::Struct,
    old_impl: &ast::Impl,
    args: &Option<GenericArgList>,
    syntax: N,
) -> Option<N> {
    let source_scope = ctx.sema.scope(old_impl.self_ty()?.syntax())?;
    let target_scope = ctx.sema.scope(strukt.syntax())?;
    let hir_old_impl = ctx.sema.to_impl_def(old_impl)?;

    let transform = args.as_ref().map_or_else(
        || PathTransform::generic_transformation(&target_scope, &source_scope),
        |args| {
            PathTransform::impl_transformation(
                &target_scope,
                &source_scope,
                hir_old_impl,
                args.clone(),
            )
        },
    );

    N::cast(transform.apply(syntax.syntax()))
}

fn remove_instantiated_params(
    self_ty: &ast::Type,
    old_impl_params: Option<GenericParamList>,
    old_trait_args: &FxHashSet<String>,
) -> Option<GenericParamList> {
    match self_ty {
        ast::Type::PathType(path_type) => {
            old_impl_params.and_then(|gpl| {
                // Remove generic parameters in field_ty (which is instantiated).
                let new_gpl = gpl.clone_for_update();

                path_type
                    .path()?
                    .segments()
                    .filter_map(|seg| seg.generic_arg_list())
                    .flat_map(|it| it.generic_args())
                    // However, if the param is also used in the trait arguments,
                    // it shouldn't be removed now, which will be instantiated in
                    // later `path_transform`
                    .filter(|arg| !old_trait_args.contains(&arg.to_string()))
                    .for_each(|arg| new_gpl.remove_generic_arg(&arg));
                (new_gpl.generic_params().count() > 0).then_some(new_gpl)
            })
        }
        _ => old_impl_params,
    }
}

fn remove_useless_where_clauses(trait_ty: &ast::Type, self_ty: &ast::Type, wc: ast::WhereClause) {
    let live_generics = [trait_ty, self_ty]
        .into_iter()
        .flat_map(|ty| ty.generic_arg_list())
        .flat_map(|gal| gal.generic_args())
        .map(|x| x.to_string())
        .collect::<FxHashSet<_>>();

    // Keep where-clauses that have generics after substitution, and remove the
    // rest.
    let has_live_generics = |pred: &WherePred| {
        pred.syntax()
            .descendants_with_tokens()
            .filter_map(|e| e.into_token())
            .any(|e| e.kind() == SyntaxKind::IDENT && live_generics.contains(&e.to_string()))
            .not()
    };
    wc.predicates().filter(has_live_generics).for_each(|pred| wc.remove_predicate(pred));

    if wc.predicates().count() == 0 {
        // Remove useless whitespaces
        [syntax::Direction::Prev, syntax::Direction::Next]
            .into_iter()
            .flat_map(|dir| {
                wc.syntax()
                    .siblings_with_tokens(dir)
                    .skip(1)
                    .take_while(|node_or_tok| node_or_tok.kind() == SyntaxKind::WHITESPACE)
            })
            .for_each(ted::remove);

        ted::insert(
            ted::Position::after(wc.syntax()),
            NodeOrToken::Token(make::token(SyntaxKind::WHITESPACE)),
        );
        // Remove where clause
        ted::remove(wc.syntax());
    }
}

// Generate generic args that should be apply to current impl.
//
// For example, say we have implementation `impl<A, B, C> Trait for B<A>`,
// and `b: B<T>` in struct `S<T>`. Then the `A` should be instantiated to `T`.
// While the last two generic args `B` and `C` doesn't change, it remains
// `<B, C>`. So we apply `<T, B, C>` as generic arguments to impl.
fn generate_args_for_impl(
    old_impl_gpl: Option<GenericParamList>,
    self_ty: &ast::Type,
    field_ty: &ast::Type,
    trait_params: &Option<GenericParamList>,
    old_trait_args: &FxHashSet<String>,
) -> Option<ast::GenericArgList> {
    let old_impl_args = old_impl_gpl.map(|gpl| gpl.to_generic_args().generic_args())?;
    // Create pairs of the args of `self_ty` and corresponding `field_ty` to
    // form the substitution list
    let mut arg_substs = FxHashMap::default();

    if let field_ty @ ast::Type::PathType(_) = field_ty {
        let field_args = field_ty.generic_arg_list().map(|gal| gal.generic_args());
        let self_ty_args = self_ty.generic_arg_list().map(|gal| gal.generic_args());
        if let (Some(field_args), Some(self_ty_args)) = (field_args, self_ty_args) {
            self_ty_args.zip(field_args).for_each(|(self_ty_arg, field_arg)| {
                arg_substs.entry(self_ty_arg.to_string()).or_insert(field_arg);
            })
        }
    }

    let args = old_impl_args
        .map(|old_arg| {
            arg_substs.get(&old_arg.to_string()).map_or_else(
                || old_arg.clone(),
                |replace_with| {
                    // The old_arg will be replaced, so it becomes redundant
                    if trait_params.is_some() && old_trait_args.contains(&old_arg.to_string()) {
                        trait_params.as_ref().unwrap().remove_generic_arg(&old_arg)
                    }
                    replace_with.clone()
                },
            )
        })
        .collect_vec();
    args.is_empty().not().then(|| make::generic_arg_list(args))
}

fn rename_strukt_args<N>(
    ctx: &AssistContext<'_>,
    strukt: &ast::Struct,
    item: &N,
    args: &GenericArgList,
) -> Option<N>
where
    N: ast::AstNode,
{
    let hir_strukt = ctx.sema.to_struct_def(strukt)?;
    let hir_adt = hir::Adt::from(hir_strukt);

    let item = item.clone_for_update();
    let scope = ctx.sema.scope(item.syntax())?;

    let transform = PathTransform::adt_transformation(&scope, &scope, hir_adt, args.clone());
    N::cast(transform.apply(item.syntax()))
}

fn has_self_type(trait_: hir::Trait, ctx: &AssistContext<'_>) -> Option<()> {
    let trait_source = ctx.sema.source(trait_)?.value;
    trait_source
        .syntax()
        .descendants_with_tokens()
        .filter_map(|e| e.into_token())
        .find(|e| e.kind() == SyntaxKind::SELF_TYPE_KW)
        .map(|_| ())
}

fn resolve_name_conflicts(
    strukt_params: Option<ast::GenericParamList>,
    old_impl_params: &Option<ast::GenericParamList>,
) -> Option<ast::GenericParamList> {
    match (strukt_params, old_impl_params) {
        (Some(old_strukt_params), Some(old_impl_params)) => {
            let params = make::generic_param_list(std::iter::empty()).clone_for_update();

            for old_strukt_param in old_strukt_params.generic_params() {
                // Get old name from `strukt`
                let name = SmolStr::from(match &old_strukt_param {
                    ast::GenericParam::ConstParam(c) => c.name()?.to_string(),
                    ast::GenericParam::LifetimeParam(l) => {
                        l.lifetime()?.lifetime_ident_token()?.to_string()
                    }
                    ast::GenericParam::TypeParam(t) => t.name()?.to_string(),
                });

                // The new name cannot be conflicted with generics in trait, and the renamed names.
                let param_list_to_names = |param_list: &GenericParamList| {
                    param_list.generic_params().flat_map(|param| match param {
                        ast::GenericParam::TypeParam(t) => t.name().map(|name| name.to_string()),
                        p => Some(p.to_string()),
                    })
                };
                let existing_names = param_list_to_names(old_impl_params)
                    .chain(param_list_to_names(&params))
                    .collect_vec();
                let mut name_generator = suggest_name::NameGenerator::new_with_names(
                    existing_names.iter().map(|s| s.as_str()),
                );
                let name = name_generator.suggest_name(&name);
                match old_strukt_param {
                    ast::GenericParam::ConstParam(c) => {
                        if let Some(const_ty) = c.ty() {
                            let const_param = make::const_param(make::name(&name), const_ty);
                            params.add_generic_param(ast::GenericParam::ConstParam(
                                const_param.clone_for_update(),
                            ));
                        }
                    }
                    p @ ast::GenericParam::LifetimeParam(_) => {
                        params.add_generic_param(p.clone_for_update());
                    }
                    ast::GenericParam::TypeParam(t) => {
                        let type_bounds = t.type_bound_list();
                        let type_param = make::type_param(make::name(&name), type_bounds);
                        params.add_generic_param(ast::GenericParam::TypeParam(
                            type_param.clone_for_update(),
                        ));
                    }
                }
            }
            Some(params)
        }
        (Some(old_strukt_gpl), None) => Some(old_strukt_gpl),
        _ => None,
    }
}

fn process_assoc_item(
    item: syntax::ast::AssocItem,
    qual_path_ty: ast::Path,
    base_name: &str,
) -> Option<ast::AssocItem> {
    match item {
        AssocItem::Const(c) => const_assoc_item(c, qual_path_ty),
        AssocItem::Fn(f) => func_assoc_item(f, qual_path_ty, base_name),
        AssocItem::MacroCall(_) => {
            // FIXME : Handle MacroCall case.
            // macro_assoc_item(mac, qual_path_ty)
            None
        }
        AssocItem::TypeAlias(ta) => ty_assoc_item(ta, qual_path_ty),
    }
}

fn const_assoc_item(item: syntax::ast::Const, qual_path_ty: ast::Path) -> Option<AssocItem> {
    let path_expr_segment = make::path_from_text(item.name()?.to_string().as_str());

    // We want rhs of the const assignment to be a qualified path
    // The general case for const assignment can be found [here](`https://doc.rust-lang.org/reference/items/constant-items.html`)
    // The qualified will have the following generic syntax :
    // <Base as Trait<GenArgs>>::ConstName;
    // FIXME : We can't rely on `make::path_qualified` for now but it would be nice to replace the following with it.
    // make::path_qualified(qual_path_ty, path_expr_segment.as_single_segment().unwrap());
    let qualified_path = qualified_path(qual_path_ty, path_expr_segment);
    let inner = make::item_const(
        item.attrs(),
        item.visibility(),
        item.name()?,
        item.ty()?,
        make::expr_path(qualified_path),
    )
    .clone_for_update();

    Some(AssocItem::Const(inner))
}

fn func_assoc_item(
    item: syntax::ast::Fn,
    qual_path_ty: Path,
    base_name: &str,
) -> Option<AssocItem> {
    let path_expr_segment = make::path_from_text(item.name()?.to_string().as_str());
    let qualified_path = qualified_path(qual_path_ty, path_expr_segment);

    let call = match item.param_list() {
        // Methods and funcs should be handled separately.
        // We ask if the func has a `self` param.
        Some(l) => match l.self_param() {
            Some(slf) => {
                let mut self_kw = make::expr_path(make::path_from_text("self"));
                self_kw = make::expr_field(self_kw, base_name);

                let tail_expr_self = match slf.kind() {
                    ast::SelfParamKind::Owned => self_kw,
                    ast::SelfParamKind::Ref => make::expr_ref(self_kw, false),
                    ast::SelfParamKind::MutRef => make::expr_ref(self_kw, true),
                };

                let param_count = l.params().count();
                let args = convert_param_list_to_arg_list(l).clone_for_update();
                let pos_after_l_paren = Position::after(args.l_paren_token()?);
                if param_count > 0 {
                    // Add SelfParam and a TOKEN::COMMA
                    ted::insert_all_raw(
                        pos_after_l_paren,
                        vec![
                            NodeOrToken::Node(tail_expr_self.syntax().clone_for_update()),
                            NodeOrToken::Token(make::token(SyntaxKind::COMMA)),
                            NodeOrToken::Token(make::token(SyntaxKind::WHITESPACE)),
                        ],
                    );
                } else {
                    // Add SelfParam only
                    ted::insert_raw(
                        pos_after_l_paren,
                        NodeOrToken::Node(tail_expr_self.syntax().clone_for_update()),
                    );
                }

                make::expr_call(make::expr_path(qualified_path), args)
            }
            None => {
                make::expr_call(make::expr_path(qualified_path), convert_param_list_to_arg_list(l))
            }
        },
        None => make::expr_call(
            make::expr_path(qualified_path),
            convert_param_list_to_arg_list(make::param_list(None, Vec::new())),
        ),
    }
    .clone_for_update();

    let body = make::block_expr(vec![], Some(call.into())).clone_for_update();
    let func = make::fn_(
        item.attrs(),
        item.visibility(),
        item.name()?,
        item.generic_param_list(),
        item.where_clause(),
        item.param_list()?,
        body,
        item.ret_type(),
        item.async_token().is_some(),
        item.const_token().is_some(),
        item.unsafe_token().is_some(),
        item.gen_token().is_some(),
    )
    .clone_for_update();

    Some(AssocItem::Fn(func.indent(edit::IndentLevel(1))))
}

fn ty_assoc_item(item: syntax::ast::TypeAlias, qual_path_ty: Path) -> Option<AssocItem> {
    let path_expr_segment = make::path_from_text(item.name()?.to_string().as_str());
    let qualified_path = qualified_path(qual_path_ty, path_expr_segment);
    let ty = make::ty_path(qualified_path);
    let ident = item.name()?.to_string();

    let alias = make::ty_alias(
        item.attrs(),
        ident.as_str(),
        item.generic_param_list(),
        None,
        item.where_clause(),
        Some((ty, None)),
    )
    .indent(edit::IndentLevel(1));

    Some(AssocItem::TypeAlias(alias))
}

fn qualified_path(qual_path_ty: ast::Path, path_expr_seg: ast::Path) -> ast::Path {
    make::path_from_text(&format!("{qual_path_ty}::{path_expr_seg}"))
}

#[cfg(test)]
mod test {

    use super::*;
    use crate::tests::{
        check_assist, check_assist_not_applicable, check_assist_not_applicable_no_grouping,
    };

    #[test]
    fn test_tuple_struct_basic() {
        check_assist(
            generate_delegate_trait,
            r#"
struct Base;
struct S(B$0ase);
trait Trait {}
impl Trait for Base {}
"#,
            r#"
struct Base;
struct S(Base);

impl Trait for S {}
trait Trait {}
impl Trait for Base {}
"#,
        );
    }

    #[test]
    fn test_self_ty() {
        // trait with `Self` type cannot be delegated
        //
        // See the function `fn f() -> Self`.
        // It should be `fn f() -> Base` in `Base`, and `fn f() -> S` in `S`
        check_assist_not_applicable(
            generate_delegate_trait,
            r#"
struct Base(());
struct S(B$0ase);
trait Trait {
    fn f() -> Self;
}
impl Trait for Base {
    fn f() -> Base {
        Base(())
    }
}
"#,
        );
    }

    #[test]
    fn test_struct_struct_basic() {
        check_assist(
            generate_delegate_trait,
            r#"
struct Base;
struct S {
    ba$0se : Base
}
trait Trait {}
impl Trait for Base {}
"#,
            r#"
struct Base;
struct S {
    base : Base
}

impl Trait for S {}
trait Trait {}
impl Trait for Base {}
"#,
        )
    }

    // Structs need to be by def populated with fields
    // However user can invoke this assist while still editing
    // We therefore assert its non-applicability
    #[test]
    fn test_yet_empty_struct() {
        check_assist_not_applicable(
            generate_delegate_trait,
            r#"
struct Base;
struct S {
    $0
}

impl Trait for S {}
trait Trait {}
impl Trait for Base {}
"#,
        )
    }

    #[test]
    fn test_yet_unspecified_field_type() {
        check_assist_not_applicable(
            generate_delegate_trait,
            r#"
struct Base;
struct S {
    ab$0c
}

impl Trait for S {}
trait Trait {}
impl Trait for Base {}
"#,
        );
    }

    #[test]
    fn test_unsafe_trait() {
        check_assist(
            generate_delegate_trait,
            r#"
struct Base;
struct S {
    ba$0se : Base
}
unsafe trait Trait {}
unsafe impl Trait for Base {}
"#,
            r#"
struct Base;
struct S {
    base : Base
}

unsafe impl Trait for S {}
unsafe trait Trait {}
unsafe impl Trait for Base {}
"#,
        );
    }

    #[test]
    fn test_unsafe_trait_with_unsafe_fn() {
        check_assist(
            generate_delegate_trait,
            r#"
struct Base;
struct S {
    ba$0se: Base,
}

unsafe trait Trait {
    unsafe fn a_func();
    unsafe fn a_method(&self);
}
unsafe impl Trait for Base {
    unsafe fn a_func() {}
    unsafe fn a_method(&self) {}
}
"#,
            r#"
struct Base;
struct S {
    base: Base,
}

unsafe impl Trait for S {
    unsafe fn a_func() {
        <Base as Trait>::a_func()
    }

    unsafe fn a_method(&self) {
        <Base as Trait>::a_method(&self.base)
    }
}

unsafe trait Trait {
    unsafe fn a_func();
    unsafe fn a_method(&self);
}
unsafe impl Trait for Base {
    unsafe fn a_func() {}
    unsafe fn a_method(&self) {}
}
"#,
        );
    }

    #[test]
    fn test_struct_with_where_clause() {
        check_assist(
            generate_delegate_trait,
            r#"
trait AnotherTrait {}
struct S<T>
where
    T: AnotherTrait,
{
    b$0 : T,
}"#,
            r#"
trait AnotherTrait {}
struct S<T>
where
    T: AnotherTrait,
{
    b : T,
}

impl<T> AnotherTrait for S<T>
where
    T: AnotherTrait,
{
}"#,
        );
    }

    #[test]
    fn test_fields_with_generics() {
        check_assist(
            generate_delegate_trait,
            r#"
struct B<T> {
    a: T
}

trait Trait<T> {
    fn f(&self, a: T) -> T;
}

impl<T1, T2> Trait<T1> for B<T2> {
    fn f(&self, a: T1) -> T1 { a }
}

struct A {}
struct S {
    b :$0 B<A>,
}
"#,
            r#"
struct B<T> {
    a: T
}

trait Trait<T> {
    fn f(&self, a: T) -> T;
}

impl<T1, T2> Trait<T1> for B<T2> {
    fn f(&self, a: T1) -> T1 { a }
}

struct A {}
struct S {
    b : B<A>,
}

impl<T1> Trait<T1> for S {
    fn f(&self, a: T1) -> T1 {
        <B<A> as Trait<T1>>::f(&self.b, a)
    }
}
"#,
        );
    }

    #[test]
    fn test_generics_with_conflict_names() {
        check_assist(
            generate_delegate_trait,
            r#"
struct B<T> {
    a: T
}

trait Trait<T> {
    fn f(&self, a: T) -> T;
}

impl<T, T0> Trait<T> for B<T0> {
    fn f(&self, a: T) -> T { a }
}

struct S<T> {
    b : $0B<T>,
}
"#,
            r#"
struct B<T> {
    a: T
}

trait Trait<T> {
    fn f(&self, a: T) -> T;
}

impl<T, T0> Trait<T> for B<T0> {
    fn f(&self, a: T) -> T { a }
}

struct S<T> {
    b : B<T>,
}

impl<T, T1> Trait<T> for S<T1> {
    fn f(&self, a: T) -> T {
        <B<T1> as Trait<T>>::f(&self.b, a)
    }
}
"#,
        );
    }

    #[test]
    fn test_lifetime_with_conflict_names() {
        check_assist(
            generate_delegate_trait,
            r#"
struct B<'a, T> {
    a: &'a T
}

trait Trait<T> {
    fn f(&self, a: T) -> T;
}

impl<'a, T, T0> Trait<T> for B<'a, T0> {
    fn f(&self, a: T) -> T { a }
}

struct S<'a, T> {
    b : $0B<'a, T>,
}
"#,
            r#"
struct B<'a, T> {
    a: &'a T
}

trait Trait<T> {
    fn f(&self, a: T) -> T;
}

impl<'a, T, T0> Trait<T> for B<'a, T0> {
    fn f(&self, a: T) -> T { a }
}

struct S<'a, T> {
    b : B<'a, T>,
}

impl<'a, T, T1> Trait<T> for S<'a, T1> {
    fn f(&self, a: T) -> T {
        <B<'a, T1> as Trait<T>>::f(&self.b, a)
    }
}
"#,
        );
    }

    #[test]
    fn test_multiple_generics() {
        check_assist(
            generate_delegate_trait,
            r#"
struct B<T1, T2> {
    a: T1,
    b: T2
}

trait Trait<T> {
    fn f(&self, a: T) -> T;
}

impl<T, T0> Trait<T> for B<T, T0> {
    fn f(&self, a: T) -> T { a }
}

struct S<T> {
    b :$0 B<i32, T>,
}
"#,
            r#"
struct B<T1, T2> {
    a: T1,
    b: T2
}

trait Trait<T> {
    fn f(&self, a: T) -> T;
}

impl<T, T0> Trait<T> for B<T, T0> {
    fn f(&self, a: T) -> T { a }
}

struct S<T> {
    b : B<i32, T>,
}

impl<T1> Trait<i32> for S<T1> {
    fn f(&self, a: i32) -> i32 {
        <B<i32, T1> as Trait<i32>>::f(&self.b, a)
    }
}
"#,
        );
    }

    #[test]
    fn test_generics_multiplex() {
        check_assist(
            generate_delegate_trait,
            r#"
struct B<T> {
    a: T
}

trait Trait<T> {
    fn f(&self, a: T) -> T;
}

impl<T> Trait<T> for B<T> {
    fn f(&self, a: T) -> T { a }
}

struct S<T> {
    b : $0B<T>,
}
"#,
            r#"
struct B<T> {
    a: T
}

trait Trait<T> {
    fn f(&self, a: T) -> T;
}

impl<T> Trait<T> for B<T> {
    fn f(&self, a: T) -> T { a }
}

struct S<T> {
    b : B<T>,
}

impl<T1> Trait<T1> for S<T1> {
    fn f(&self, a: T1) -> T1 {
        <B<T1> as Trait<T1>>::f(&self.b, a)
    }
}
"#,
        );
    }

    #[test]
    fn test_complex_without_where() {
        check_assist(
            generate_delegate_trait,
            r#"
trait Trait<'a, T, const C: usize> {
    type AssocType;
    const AssocConst: usize;
    fn assoc_fn(p: ());
    fn assoc_method(&self, p: ());
}

struct Base;
struct S {
    field$0: Base
}

impl<'a, T, const C: usize> Trait<'a, T, C> for Base {
    type AssocType = ();
    const AssocConst: usize = 0;
    fn assoc_fn(p: ()) {}
    fn assoc_method(&self, p: ()) {}
}
"#,
            r#"
trait Trait<'a, T, const C: usize> {
    type AssocType;
    const AssocConst: usize;
    fn assoc_fn(p: ());
    fn assoc_method(&self, p: ());
}

struct Base;
struct S {
    field: Base
}

impl<'a, T, const C: usize> Trait<'a, T, C> for S {
    type AssocType = <Base as Trait<'a, T, C>>::AssocType;

    const AssocConst: usize = <Base as Trait<'a, T, C>>::AssocConst;

    fn assoc_fn(p: ()) {
        <Base as Trait<'a, T, C>>::assoc_fn(p)
    }

    fn assoc_method(&self, p: ()) {
        <Base as Trait<'a, T, C>>::assoc_method(&self.field, p)
    }
}

impl<'a, T, const C: usize> Trait<'a, T, C> for Base {
    type AssocType = ();
    const AssocConst: usize = 0;
    fn assoc_fn(p: ()) {}
    fn assoc_method(&self, p: ()) {}
}
"#,
        );
    }

    #[test]
    fn test_complex_two() {
        check_assist(
            generate_delegate_trait,
            r"
trait AnotherTrait {}

trait Trait<'a, T, const C: usize> {
    type AssocType;
    const AssocConst: usize;
    fn assoc_fn(p: ());
    fn assoc_method(&self, p: ());
}

struct Base;
struct S {
    fi$0eld: Base,
}

impl<'b, C, const D: usize> Trait<'b, C, D> for Base
where
    C: AnotherTrait,
{
    type AssocType = ();
    const AssocConst: usize = 0;
    fn assoc_fn(p: ()) {}
    fn assoc_method(&self, p: ()) {}
}",
            r#"
trait AnotherTrait {}

trait Trait<'a, T, const C: usize> {
    type AssocType;
    const AssocConst: usize;
    fn assoc_fn(p: ());
    fn assoc_method(&self, p: ());
}

struct Base;
struct S {
    field: Base,
}

impl<'b, C, const D: usize> Trait<'b, C, D> for S
where
    C: AnotherTrait,
{
    type AssocType = <Base as Trait<'b, C, D>>::AssocType;

    const AssocConst: usize = <Base as Trait<'b, C, D>>::AssocConst;

    fn assoc_fn(p: ()) {
        <Base as Trait<'b, C, D>>::assoc_fn(p)
    }

    fn assoc_method(&self, p: ()) {
        <Base as Trait<'b, C, D>>::assoc_method(&self.field, p)
    }
}

impl<'b, C, const D: usize> Trait<'b, C, D> for Base
where
    C: AnotherTrait,
{
    type AssocType = ();
    const AssocConst: usize = 0;
    fn assoc_fn(p: ()) {}
    fn assoc_method(&self, p: ()) {}
}"#,
        )
    }

    #[test]
    fn test_complex_three() {
        check_assist(
            generate_delegate_trait,
            r#"
trait AnotherTrait {}
trait YetAnotherTrait {}

struct StructImplsAll();
impl AnotherTrait for StructImplsAll {}
impl YetAnotherTrait for StructImplsAll {}

trait Trait<'a, T, const C: usize> {
    type A;
    const ASSOC_CONST: usize = C;
    fn assoc_fn(p: ());
    fn assoc_method(&self, p: ());
}

struct Base;
struct S {
    fi$0eld: Base,
}

impl<'b, A: AnotherTrait + YetAnotherTrait, const B: usize> Trait<'b, A, B> for Base
where
    A: AnotherTrait,
{
    type A = i32;

    const ASSOC_CONST: usize = B;

    fn assoc_fn(p: ()) {}

    fn assoc_method(&self, p: ()) {}
}
"#,
            r#"
trait AnotherTrait {}
trait YetAnotherTrait {}

struct StructImplsAll();
impl AnotherTrait for StructImplsAll {}
impl YetAnotherTrait for StructImplsAll {}

trait Trait<'a, T, const C: usize> {
    type A;
    const ASSOC_CONST: usize = C;
    fn assoc_fn(p: ());
    fn assoc_method(&self, p: ());
}

struct Base;
struct S {
    field: Base,
}

impl<'b, A: AnotherTrait + YetAnotherTrait, const B: usize> Trait<'b, A, B> for S
where
    A: AnotherTrait,
{
    type A = <Base as Trait<'b, A, B>>::A;

    const ASSOC_CONST: usize = <Base as Trait<'b, A, B>>::ASSOC_CONST;

    fn assoc_fn(p: ()) {
        <Base as Trait<'b, A, B>>::assoc_fn(p)
    }

    fn assoc_method(&self, p: ()) {
        <Base as Trait<'b, A, B>>::assoc_method(&self.field, p)
    }
}

impl<'b, A: AnotherTrait + YetAnotherTrait, const B: usize> Trait<'b, A, B> for Base
where
    A: AnotherTrait,
{
    type A = i32;

    const ASSOC_CONST: usize = B;

    fn assoc_fn(p: ()) {}

    fn assoc_method(&self, p: ()) {}
}
"#,
        )
    }

    #[test]
    fn test_type_bound() {
        check_assist(
            generate_delegate_trait,
            r#"
trait AnotherTrait {}
struct S<T>
where
    T: AnotherTrait,
{
    b$0: T,
}"#,
            r#"
trait AnotherTrait {}
struct S<T>
where
    T: AnotherTrait,
{
    b: T,
}

impl<T> AnotherTrait for S<T>
where
    T: AnotherTrait,
{
}"#,
        );
    }

    #[test]
    fn test_type_bound_with_generics_1() {
        check_assist(
            generate_delegate_trait,
            r#"
trait AnotherTrait {}
struct B<T, T1>
where
    T1: AnotherTrait
{
    a: T,
    b: T1
}

trait Trait<T> {
    fn f(&self, a: T) -> T;
}

impl<T, T0, T1: AnotherTrait> Trait<T> for B<T0, T1> {
    fn f(&self, a: T) -> T { a }
}

struct S<T, T1>
where
    T1: AnotherTrait
{
    b : $0B<T, T1>,
}"#,
            r#"
trait AnotherTrait {}
struct B<T, T1>
where
    T1: AnotherTrait
{
    a: T,
    b: T1
}

trait Trait<T> {
    fn f(&self, a: T) -> T;
}

impl<T, T0, T1: AnotherTrait> Trait<T> for B<T0, T1> {
    fn f(&self, a: T) -> T { a }
}

struct S<T, T1>
where
    T1: AnotherTrait
{
    b : B<T, T1>,
}

impl<T, T2, T3> Trait<T> for S<T2, T3>
where
    T3: AnotherTrait
{
    fn f(&self, a: T) -> T {
        <B<T2, T3> as Trait<T>>::f(&self.b, a)
    }
}"#,
        );
    }

    #[test]
    fn test_type_bound_with_generics_2() {
        check_assist(
            generate_delegate_trait,
            r#"
trait AnotherTrait {}
struct B<T1>
where
    T1: AnotherTrait
{
    b: T1
}

trait Trait<T1> {
    fn f(&self, a: T1) -> T1;
}

impl<T, T1: AnotherTrait> Trait<T> for B<T1> {
    fn f(&self, a: T) -> T { a }
}

struct S<T>
where
    T: AnotherTrait
{
    b : $0B<T>,
}"#,
            r#"
trait AnotherTrait {}
struct B<T1>
where
    T1: AnotherTrait
{
    b: T1
}

trait Trait<T1> {
    fn f(&self, a: T1) -> T1;
}

impl<T, T1: AnotherTrait> Trait<T> for B<T1> {
    fn f(&self, a: T) -> T { a }
}

struct S<T>
where
    T: AnotherTrait
{
    b : B<T>,
}

impl<T, T2> Trait<T> for S<T2>
where
    T2: AnotherTrait
{
    fn f(&self, a: T) -> T {
        <B<T2> as Trait<T>>::f(&self.b, a)
    }
}"#,
        );
    }

    #[test]
    fn test_docstring_example() {
        check_assist(
            generate_delegate_trait,
            r#"
trait SomeTrait {
    type T;
    fn fn_(arg: u32) -> u32;
    fn method_(&mut self) -> bool;
}
struct A;
impl SomeTrait for A {
    type T = u32;
    fn fn_(arg: u32) -> u32 {
        42
    }
    fn method_(&mut self) -> bool {
        false
    }
}
struct B {
    a$0: A,
}
"#,
            r#"
trait SomeTrait {
    type T;
    fn fn_(arg: u32) -> u32;
    fn method_(&mut self) -> bool;
}
struct A;
impl SomeTrait for A {
    type T = u32;
    fn fn_(arg: u32) -> u32 {
        42
    }
    fn method_(&mut self) -> bool {
        false
    }
}
struct B {
    a: A,
}

impl SomeTrait for B {
    type T = <A as SomeTrait>::T;

    fn fn_(arg: u32) -> u32 {
        <A as SomeTrait>::fn_(arg)
    }

    fn method_(&mut self) -> bool {
        <A as SomeTrait>::method_(&mut self.a)
    }
}
"#,
        );
    }

    #[test]
    fn import_from_other_mod() {
        check_assist(
            generate_delegate_trait,
            r#"
mod some_module {
    pub trait SomeTrait {
        type T;
        fn fn_(arg: u32) -> u32;
        fn method_(&mut self) -> bool;
    }
    pub struct A;
    impl SomeTrait for A {
        type T = u32;

        fn fn_(arg: u32) -> u32 {
            42
        }

        fn method_(&mut self) -> bool {
            false
        }
    }
}

struct B {
    a$0: some_module::A,
}"#,
            r#"
mod some_module {
    pub trait SomeTrait {
        type T;
        fn fn_(arg: u32) -> u32;
        fn method_(&mut self) -> bool;
    }
    pub struct A;
    impl SomeTrait for A {
        type T = u32;

        fn fn_(arg: u32) -> u32 {
            42
        }

        fn method_(&mut self) -> bool {
            false
        }
    }
}

struct B {
    a: some_module::A,
}

impl some_module::SomeTrait for B {
    type T = <some_module::A as some_module::SomeTrait>::T;

    fn fn_(arg: u32) -> u32 {
        <some_module::A as some_module::SomeTrait>::fn_(arg)
    }

    fn method_(&mut self) -> bool {
        <some_module::A as some_module::SomeTrait>::method_(&mut self.a)
    }
}"#,
        )
    }

    #[test]
    fn test_fn_with_attrs() {
        check_assist(
            generate_delegate_trait,
            r#"
struct A;

trait T {
    #[cfg(test)]
    fn f(&self, a: u32);
    #[cfg(not(test))]
    fn f(&self, a: bool);
}

impl T for A {
    #[cfg(test)]
    fn f(&self, a: u32) {}
    #[cfg(not(test))]
    fn f(&self, a: bool) {}
}

struct B {
    a$0: A,
}
"#,
            r#"
struct A;

trait T {
    #[cfg(test)]
    fn f(&self, a: u32);
    #[cfg(not(test))]
    fn f(&self, a: bool);
}

impl T for A {
    #[cfg(test)]
    fn f(&self, a: u32) {}
    #[cfg(not(test))]
    fn f(&self, a: bool) {}
}

struct B {
    a: A,
}

impl T for B {
    #[cfg(test)]
    fn f(&self, a: u32) {
        <A as T>::f(&self.a, a)
    }

    #[cfg(not(test))]
    fn f(&self, a: bool) {
        <A as T>::f(&self.a, a)
    }
}
"#,
        );
    }

    #[test]
    fn test_ty_alias_attrs() {
        check_assist(
            generate_delegate_trait,
            r#"
struct A;

trait T {
    #[cfg(test)]
    type t;
    #[cfg(not(test))]
    type t;
}

impl T for A {
    #[cfg(test)]
    type t = u32;
    #[cfg(not(test))]
    type t = bool;
}

struct B {
    a$0: A,
}
"#,
            r#"
struct A;

trait T {
    #[cfg(test)]
    type t;
    #[cfg(not(test))]
    type t;
}

impl T for A {
    #[cfg(test)]
    type t = u32;
    #[cfg(not(test))]
    type t = bool;
}

struct B {
    a: A,
}

impl T for B {
    #[cfg(test)]
    type t = <A as T>::t;

    #[cfg(not(test))]
    type t = <A as T>::t;
}
"#,
        );
    }

    #[test]
    fn assoc_items_attributes_mutably_cloned() {
        check_assist(
            generate_delegate_trait,
            r#"
pub struct A;
pub trait C<D> {
    #[allow(clippy::dead_code)]
    fn a_funk(&self) -> &D;
}

pub struct B<T: C<A>> {
    has_dr$0ain: T,
}
"#,
            r#"
pub struct A;
pub trait C<D> {
    #[allow(clippy::dead_code)]
    fn a_funk(&self) -> &D;
}

pub struct B<T: C<A>> {
    has_drain: T,
}

impl<D, T: C<A>> C<D> for B<T> {
    #[allow(clippy::dead_code)]
    fn a_funk(&self) -> &D {
        <T as C<D>>::a_funk(&self.has_drain)
    }
}
"#,
        )
    }

    #[test]
    fn delegate_trait_skipped_when_no_grouping() {
        check_assist_not_applicable_no_grouping(
            generate_delegate_trait,
            r#"
trait SomeTrait {
    type T;
    fn fn_(arg: u32) -> u32;
    fn method_(&mut self) -> bool;
}
struct A;
impl SomeTrait for A {
    type T = u32;

    fn fn_(arg: u32) -> u32 {
        42
    }

    fn method_(&mut self) -> bool {
        false
    }
}
struct B {
    a$0 : A,
}
"#,
        );
    }
}