@@ -1316,6 +1316,40 @@ impl<'tcx> LateContext<'tcx> {
1316
1316
} )
1317
1317
}
1318
1318
1319
+ /// If the given expression is a local binding, find the initializer expression.
1320
+ /// If that initializer expression is another local binding, find its initializer again.
1321
+ ///
1322
+ /// This process repeats as long as possible (but usually no more than once).
1323
+ /// Type-check adjustments are not taken in account in this function.
1324
+ ///
1325
+ /// Examples:
1326
+ /// ```
1327
+ /// let abc = 1;
1328
+ /// let def = abc + 2;
1329
+ /// // ^^^^^^^ output
1330
+ /// let def = def;
1331
+ /// dbg!(def);
1332
+ /// // ^^^ input
1333
+ /// ```
1334
+ pub fn expr_or_init < ' a > ( & self , mut expr : & ' a hir:: Expr < ' tcx > ) -> & ' a hir:: Expr < ' tcx > {
1335
+ expr = expr. peel_blocks ( ) ;
1336
+
1337
+ while let hir:: ExprKind :: Path ( ref qpath) = expr. kind
1338
+ && let Some ( parent_node) = match self . qpath_res ( qpath, expr. hir_id ) {
1339
+ Res :: Local ( hir_id) => self . tcx . hir ( ) . find_parent ( hir_id) ,
1340
+ _ => None ,
1341
+ }
1342
+ && let Some ( init) = match parent_node {
1343
+ hir:: Node :: Expr ( expr) => Some ( expr) ,
1344
+ hir:: Node :: Local ( hir:: Local { init, .. } ) => * init,
1345
+ _ => None
1346
+ }
1347
+ {
1348
+ expr = init. peel_blocks ( ) ;
1349
+ }
1350
+ expr
1351
+ }
1352
+
1319
1353
/// If the given expression is a local binding, find the initializer expression.
1320
1354
/// If that initializer expression is another local or **outside** (`const`/`static`)
1321
1355
/// binding, find its initializer again.
@@ -1338,7 +1372,10 @@ impl<'tcx> LateContext<'tcx> {
1338
1372
/// dbg!(def);
1339
1373
/// // ^^^ input
1340
1374
/// ```
1341
- pub fn expr_or_init < ' a > ( & self , mut expr : & ' a hir:: Expr < ' tcx > ) -> & ' a hir:: Expr < ' tcx > {
1375
+ pub fn expr_or_init_with_outside_body < ' a > (
1376
+ & self ,
1377
+ mut expr : & ' a hir:: Expr < ' tcx > ,
1378
+ ) -> & ' a hir:: Expr < ' tcx > {
1342
1379
expr = expr. peel_blocks ( ) ;
1343
1380
1344
1381
while let hir:: ExprKind :: Path ( ref qpath) = expr. kind
0 commit comments