@@ -1371,6 +1371,54 @@ impl<'tcx> LateContext<'tcx> {
1371
1371
tcx. try_normalize_erasing_regions ( self . param_env , proj) . ok ( )
1372
1372
} )
1373
1373
}
1374
+
1375
+ /// If the given expression is a local binding, find the initializer expression.
1376
+ /// If that initializer expression is another local or **outside** (`const`/`static`)
1377
+ /// binding, find its initializer again.
1378
+ ///
1379
+ /// This process repeats as long as possible (but usually no more than once).
1380
+ /// Type-check adjustments are not taken in account in this function.
1381
+ ///
1382
+ /// Examples:
1383
+ /// ```
1384
+ /// const ABC: i32 = 1;
1385
+ /// // ^ output
1386
+ /// let def = ABC;
1387
+ /// dbg!(def);
1388
+ /// // ^^^ input
1389
+ ///
1390
+ /// // or...
1391
+ /// let abc = 1;
1392
+ /// let def = abc + 2;
1393
+ /// // ^^^^^^^ output
1394
+ /// dbg!(def);
1395
+ /// // ^^^ input
1396
+ /// ```
1397
+ pub fn expr_or_init < ' a > ( & self , mut expr : & ' a hir:: Expr < ' tcx > ) -> & ' a hir:: Expr < ' tcx > {
1398
+ expr = expr. peel_blocks ( ) ;
1399
+
1400
+ while let hir:: ExprKind :: Path ( ref qpath) = expr. kind
1401
+ && let Some ( parent_node) = match self . qpath_res ( qpath, expr. hir_id ) {
1402
+ Res :: Local ( hir_id) => self . tcx . hir ( ) . find_parent ( hir_id) ,
1403
+ Res :: Def ( _, def_id) => self . tcx . hir ( ) . get_if_local ( def_id) ,
1404
+ _ => None ,
1405
+ }
1406
+ && let Some ( init) = match parent_node {
1407
+ hir:: Node :: Expr ( expr) => Some ( expr) ,
1408
+ hir:: Node :: Local ( hir:: Local { init, .. } ) => * init,
1409
+ hir:: Node :: Item ( item) => match item. kind {
1410
+ hir:: ItemKind :: Const ( .., body_id) | hir:: ItemKind :: Static ( .., body_id) => {
1411
+ Some ( self . tcx . hir ( ) . body ( body_id) . value )
1412
+ }
1413
+ _ => None
1414
+ }
1415
+ _ => None
1416
+ }
1417
+ {
1418
+ expr = init. peel_blocks ( ) ;
1419
+ }
1420
+ expr
1421
+ }
1374
1422
}
1375
1423
1376
1424
impl < ' tcx > abi:: HasDataLayout for LateContext < ' tcx > {
0 commit comments