"use strict";

// Removes proxy rules -- that is, rules that only delegate to other rule.
function removeProxyRules( ast, session, options ) {

    function isProxyRule( node ) {

        return node.type === "rule" && node.expression.type === "rule_ref";

    }

    function replaceRuleRefs( ast, from, to ) {

        const replace = session.buildVisitor( {
            rule_ref( node ) {

                if ( node.name === from ) {

                    node.name = to;

                }

            }
        } );

        replace( ast );

    }

    const indices = [];

    ast.rules.forEach( ( rule, i ) => {

        if ( isProxyRule( rule ) ) {

            replaceRuleRefs( ast, rule.name, rule.expression.name );
            if ( options.allowedStartRules.indexOf( rule.name ) === -1 ) {

                indices.push( i );

            }

        }

    } );

    indices.reverse();

    indices.forEach( i => {

        ast.rules.splice( i, 1 );

    } );

}

module.exports = removeProxyRules;

@@ -261,24 +261,21 @@
  %7D%0A%0A    
-function
+const
  replace
@@ -286,50 +286,8 @@
 Refs
-( ast, from, to ) %7B%0A%0A        const replace
  = s
@@ -309,20 +309,17 @@
 itor( %7B%0A
-    
+%0A
         
@@ -328,34 +328,43 @@
 le_ref( node
+, proxy, real
  ) %7B%0A%0A
-    
             
@@ -386,133 +386,112 @@
 === 
-from ) %7B%0A%0A                    node.name = to;%0A%0A                %7D%0A%0A            %7D%0A        %7D );%0A%0A        replace( ast );%0A%0A    %7D%0A
+proxy ) node.name = real;%0A%0A        %7D%0A%0A    %7D );%0A%0A    const allowedStartRules = options.allowedStartRules;
 %0A   
@@ -497,21 +497,19 @@
   const 
-indic
+rul
 es = %5B%5D;
@@ -518,41 +518,39 @@
     
-ast.
+for ( const 
 rule
-s.forEach( ( rule, i ) =%3E
+ of ast.rules )
  %7B%0A%0A
@@ -673,24 +673,16 @@
    if ( 
-options.
 allowedS
@@ -716,18 +716,23 @@
 e ) 
-=== -1 ) %7B
+%3C 0 ) continue;
 %0A%0A  
@@ -737,24 +737,27 @@
         
+%7D%0A%0A
         
 indices.
@@ -748,21 +748,19 @@
         
-indic
+rul
 es.push(
@@ -764,22 +764,17 @@
 sh( 
-i
+rule
  );%0A%0A
-        
     
@@ -784,120 +784,25 @@
     
-    %7D%0A%0A    %7D );%0A%0A    indices.reverse();%0A%0A    indices.forEach( i =%3E %7B%0A%0A        ast.rules.splice( i, 1 );%0A%0A    %7D )
+ast.rules = rules
 ;%0A%0A%7D

Refactor removeProxyRules