@@ -1316,6 +1316,40 @@ impl<'tcx> LateContext<'tcx> {
13161316 } )
13171317 }
13181318
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+
13191353 /// If the given expression is a local binding, find the initializer expression.
13201354 /// If that initializer expression is another local or **outside** (`const`/`static`)
13211355 /// binding, find its initializer again.
@@ -1338,7 +1372,10 @@ impl<'tcx> LateContext<'tcx> {
13381372 /// dbg!(def);
13391373 /// // ^^^ input
13401374 /// ```
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 > {
13421379 expr = expr. peel_blocks ( ) ;
13431380
13441381 while let hir:: ExprKind :: Path ( ref qpath) = expr. kind
0 commit comments