@@ -1009,7 +1009,7 @@ export default function (babel) {
10091009 } , null ) ;
10101010 }
10111011
1012- function prependDeclaration ( path , id , init , kind = "const" ) {
1012+ function insertDeclarationBefore ( path , id , init , kind = "const" ) {
10131013 path . insertBefore ( t . variableDeclaration ( kind , [
10141014 t . variableDeclarator ( id , init )
10151015 ] ) ) ;
@@ -1581,19 +1581,23 @@ export default function (babel) {
15811581 const { discriminant } = path . node ;
15821582 const alias = path . node . alias || t . identifier ( "it" ) ;
15831583
1584- let argRef ;
1585- if ( t . isIdentifier ( discriminant ) && ! containsAliasReference ( path , alias ) ) {
1586- argRef = discriminant ;
1587- } else {
1588- argRef = alias ;
1589- if ( path . scope . hasOwnBinding ( argRef . name ) ) {
1590- throw path . buildCodeFrameError ( "Cannot re-use `it` binding in the same scope. Try a new shorthand name (eg; `match foo as x:`)." ) ;
1591- }
1592- prependDeclaration ( path , argRef , discriminant ) ;
1593- }
1594-
1584+ const argRef = t . isIdentifier ( discriminant ) && ! containsAliasReference ( path , alias )
1585+ ? discriminant
1586+ : alias ;
15951587 const matchBody = transformMatchCases ( argRef , path . get ( "cases" ) ) ;
1588+
15961589 path . replaceWith ( matchBody ) ;
1590+
1591+ // insert eg; `const it = foo()` above the body,
1592+ // possibly wrapping both in an anonymous block.
1593+ if ( argRef !== discriminant ) {
1594+ if ( path . scope . hasBinding ( alias . name ) ) {
1595+ // wrap in anonymous block
1596+ path . replaceWith ( t . blockStatement ( [ path . node ] ) ) ;
1597+ path = path . get ( "body.0" ) ;
1598+ }
1599+ insertDeclarationBefore ( path , argRef , discriminant ) ;
1600+ }
15971601 } ,
15981602
15991603 } ) ;
0 commit comments