@@ -602,7 +602,10 @@ export default class Astx extends ExtendableProxy implements Iterable<Astx> {
602
602
const { parsePatternToNodes } = backend
603
603
try {
604
604
if ( typeof arg0 === 'function' ) {
605
- for ( const astx of this ) {
605
+ // Always replace in reverse so that if there are matches inside of
606
+ // matches, the inner matches get replaced first (since they come
607
+ // later in the code)
608
+ for ( const astx of [ ...this ] . reverse ( ) ) {
606
609
const replacement = arg0 ( astx , parsePatternToNodes )
607
610
replace (
608
611
astx . match ,
@@ -614,12 +617,12 @@ export default class Astx extends ExtendableProxy implements Iterable<Astx> {
614
617
}
615
618
} else if ( typeof arg0 === 'string' ) {
616
619
const replacement = parsePatternToNodes ( arg0 )
617
- for ( const match of this . _matches ) {
618
- replace ( match , replacement , this . context )
620
+ for ( let i = this . _matches . length - 1 ; i >= 0 ; i -- ) {
621
+ replace ( this . _matches [ i ] , replacement , this . context )
619
622
}
620
623
} else if ( isNode ( arg0 ) || isNodeArray ( arg0 ) ) {
621
- for ( const match of this . _matches ) {
622
- replace ( match , arg0 , this . context )
624
+ for ( let i = this . _matches . length - 1 ; i >= 0 ; i -- ) {
625
+ replace ( this . _matches [ i ] , arg0 , this . context )
623
626
}
624
627
} else {
625
628
const finalPaths = parsePatternToNodes ( arg0 , ...quasis )
0 commit comments