Exemplo n.º 1
0
 public void Visit(ReturnNode node)
 {
     if (node != null)
     {
         DoesRequire = true;
     }
 }
Exemplo n.º 2
0
        private void Unconcise()
        {
            // Instead of implicitly returning the one expression, we're
            // going to need to turn this into a non-concise block and explicitly return
            // that expression.
            this.IsConcise = false;

            // there should be a single statement that's an expression. Make it the argument of
            // a return statement.
            if (m_list.Count == 1)
            {
                var expression = m_list[0];
                if (expression.IsExpression)
                {
                    m_list[0] = new ReturnNode(expression.Context)
                    {
                        Operand = expression,
                        Parent  = this
                    };
                }
            }
        }
Exemplo n.º 3
0
 public void Visit(ReturnNode node)
 {
     // starts with 'return', so we don't care
 }
Exemplo n.º 4
0
Arquivo: if.cs Projeto: formist/LinkMe
        internal Conditional CanBeReturnOperand(AstNode ultimateOperand, bool isFunctionLevel)
        {
            Conditional conditional = null;

            try
            {
                if (TrueBlock != null && TrueBlock.Count == 1)
                {
                    ReturnNode returnNode = TrueBlock[0] as ReturnNode;
                    if (returnNode != null)
                    {
                        AstNode expr1 = returnNode.Operand;
                        if (FalseBlock == null || FalseBlock.Count == 0)
                        {
                            // no false branch to speak of. Convert to conditional.
                            // if there is an ultimate expression, use it.
                            // if we are not at the function body level, we can't
                            // combine these. But if we are we can
                            // use a false expression of "void 0" (undefined)
                            if (ultimateOperand != null || isFunctionLevel)
                            {
                                conditional = new Conditional(
                                    (Context == null ? null : Context.Clone()),
                                    Parser,
                                    Condition,
                                    expr1 ?? CreateVoidNode(),
                                    ultimateOperand ?? CreateVoidNode());
                            }
                        }
                        else if (FalseBlock.Count == 1)
                        {
                            // there is a false branch with only a single statement
                            // see if it is a return statement
                            returnNode = FalseBlock[0] as ReturnNode;
                            if (returnNode != null)
                            {
                                // it is. so we have if(cond)return expr1;else return expr2
                                // return cond?expr1:expr2
                                AstNode expr2 = returnNode.Operand;
                                conditional = new Conditional(
                                    (Context == null ? null : Context.Clone()),
                                    Parser,
                                    Condition,
                                    expr1 ?? CreateVoidNode(),
                                    expr2 ?? CreateVoidNode());
                            }
                            else
                            {
                                // see if it's another if-statement
                                IfNode elseIf = FalseBlock[0] as IfNode;
                                if (elseIf != null)
                                {
                                    // it's a nested if-statement. See if IT can be a return argument.
                                    Conditional expr2 = elseIf.CanBeReturnOperand(ultimateOperand, isFunctionLevel);
                                    if (expr2 != null)
                                    {
                                        // it can, so we can just nest the conditionals
                                        conditional = new Conditional(
                                            (Context == null ? null : Context.Clone()),
                                            Parser,
                                            Condition,
                                            expr1,
                                            expr2);
                                    }
                                }
                                // else neither return- nor if-statement
                            }
                        }
                        // else false branch has more than one statement
                    }
                    // else the single statement is not a return-statement
                }
                // else no true branch, or not a single statement in the branch
            }
            catch (NotImplementedException)
            {
                // one of the clone calls probably failed.
                // don't say this can be a return argument.
            }
            return(conditional);
        }
 public void Visit(ReturnNode node)
 {
     DebugEx.Fail("shouldn't get here");
 }
Exemplo n.º 6
0
        internal override void AnalyzeNode()
        {
            // javascript doesn't have block scope, so there really is no point
            // in nesting blocks. Unnest any now, before we start combining var statements
            UnnestBlocks();

            // if we want to remove debug statements...
            if (Parser.Settings.StripDebugStatements && Parser.Settings.IsModificationAllowed(TreeModifications.StripDebugStatements))
            {
                // do it now before we try doing other things
                StripDebugStatements();
            }

            // these variables are used to check for combining a particular type of
            // for-statement with preceding var-statements.
            ForNode targetForNode = null;
            string  targetName    = null;

            // check to see if we want to combine adjacent var statements
            bool combineVarStatements = Parser.Settings.IsModificationAllowed(TreeModifications.CombineVarStatements);

            // check to see if we want to combine a preceding var with a for-statement
            bool moveVarIntoFor = Parser.Settings.IsModificationAllowed(TreeModifications.MoveVarIntoFor);

            // look at the statements in the block.
            // if there are multiple var statements adjacent to each other, combine them.
            // walk BACKWARDS down the list because we'll be removing items when we encounter
            // multiple vars.
            // we also don't need to check the first one, since there is nothing before it.
            for (int ndx = m_list.Count - 1; ndx > 0; --ndx)
            {
                // if the previous node is not a Var, then we don't need to try and combine
                // it withthe current node
                Var previousVar = m_list[ndx - 1] as Var;
                if (previousVar != null)
                {
                    // see if THIS item is also a Var...
                    if (m_list[ndx] is Var && combineVarStatements)
                    {
                        // add the items in this VAR to the end of the previous
                        previousVar.Append(m_list[ndx]);

                        // delete this item from the block
                        m_list.RemoveAt(ndx);

                        // if we have a target for-node waiting for another comparison....
                        if (targetForNode != null)
                        {
                            // check to see if the variable we are looking for is in the new list
                            if (previousVar.Contains(targetName))
                            {
                                // IT DOES! we can combine the var statement with the initializer in the for-statement
                                // we already know it's a binaryop, or it wouldn't be a target for-statement
                                BinaryOperator binaryOp = targetForNode.Initializer as BinaryOperator;

                                // create a vardecl that matches our assignment initializer
                                // ignore duplicates because this scope will already have the variable defined.
                                VariableDeclaration varDecl = new VariableDeclaration(
                                    binaryOp.Context.Clone(),
                                    Parser,
                                    targetName,
                                    binaryOp.Operand1.Context.Clone(),
                                    binaryOp.Operand2,
                                    0,
                                    true
                                    );
                                // append it to the preceding var-statement
                                previousVar.Append(varDecl);

                                // move the previous vardecl to our initializer
                                targetForNode.ReplaceChild(targetForNode.Initializer, previousVar);

                                // and remove the previous var from the list.
                                m_list.RemoveAt(ndx - 1);
                                // this will bump the for node up one position in the list, so the next iteration
                                // will be right back on this node, but the initializer will not be null

                                // but now we no longer need the target mechanism -- the for-statement is
                                // not the current node again
                                targetForNode = null;
                            }
                        }
                    }
                    else if (moveVarIntoFor)
                    {
                        // see if this item is a ForNode
                        ForNode forNode = m_list[ndx] as ForNode;
                        if (forNode != null)
                        {
                            // and see if the forNode's initializer is empty
                            if (forNode.Initializer != null)
                            {
                                // not empty -- see if it is a Var node
                                Var varInitializer = forNode.Initializer as Var;
                                if (varInitializer != null)
                                {
                                    // we want to PREPEND the initializers in the previous var statement
                                    // to our for-statement's initializer list
                                    varInitializer.InsertAt(0, previousVar);

                                    // then remove the previous var statement
                                    m_list.RemoveAt(ndx - 1);
                                    // this will bump the for node up one position in the list, so the next iteration
                                    // will be right back on this node in case there are other var statements we need
                                    // to combine
                                }
                                else
                                {
                                    // see if the initializer is a simple assignment
                                    BinaryOperator binaryOp = forNode.Initializer as BinaryOperator;
                                    if (binaryOp != null && binaryOp.OperatorToken == JSToken.Assign)
                                    {
                                        // it is. See if it's a simple lookup
                                        Lookup lookup = binaryOp.Operand1 as Lookup;
                                        if (lookup != null)
                                        {
                                            // it is. see if that variable is in the previous var statement
                                            if (previousVar.Contains(lookup.Name))
                                            {
                                                // create a vardecl that matches our assignment initializer
                                                // ignore duplicates because this scope will already have the variable defined.
                                                VariableDeclaration varDecl = new VariableDeclaration(
                                                    binaryOp.Context.Clone(),
                                                    Parser,
                                                    lookup.Name,
                                                    lookup.Context.Clone(),
                                                    binaryOp.Operand2,
                                                    0,
                                                    true
                                                    );
                                                // append it to the var statement before us
                                                previousVar.Append(varDecl);

                                                // move the previous vardecl to our initializer
                                                forNode.ReplaceChild(forNode.Initializer, previousVar);

                                                // and remove the previous var from the list.
                                                m_list.RemoveAt(ndx - 1);
                                                // this will bump the for node up one position in the list, so the next iteration
                                                // will be right back on this node, but the initializer will not be null
                                            }
                                            else
                                            {
                                                // it's not in the immediately preceding var-statement, but that doesn't mean it won't be in
                                                // a var-statement immediately preceding that one -- in which case they'll get combined and
                                                // then it WILL be in the immediately preceding var-statement. So hold on to this
                                                // for statement and we'll check after we do a combine.
                                                targetForNode = forNode;
                                                targetName    = lookup.Name;
                                            }
                                        }
                                    }
                                }
                            }
                            else
                            {
                                // if it's empty, then we're free to add the previous var statement
                                // to this for statement's initializer. remove it from it's current
                                // position and add it as the initializer
                                m_list.RemoveAt(ndx - 1);
                                forNode.ReplaceChild(forNode.Initializer, previousVar);
                                // this will bump the for node up one position in the list, so the next iteration
                                // will be right back on this node, but the initializer will not be null
                            }
                        }
                    }
                }
                else
                {
                    // not a var statement. make sure the target for-node is cleared.
                    targetForNode = null;

                    ConditionalCompilationComment previousComment = m_list[ndx - 1] as ConditionalCompilationComment;
                    if (previousComment != null)
                    {
                        ConditionalCompilationComment thisComment = m_list[ndx] as ConditionalCompilationComment;
                        if (thisComment != null)
                        {
                            // two adjacent conditional comments -- combine them into the first.
                            // this will actually make the second block a nested block within the first block,
                            // but they'll be flattened when the comment's block gets recursed.
                            previousComment.Statements.Append(thisComment.Statements);

                            // and remove the second one (which is now a duplicate)
                            m_list.RemoveAt(ndx);
                        }
                    }
                }
            }

            if (m_blockScope != null)
            {
                ScopeStack.Push(m_blockScope);
            }
            try
            {
                // call the base class to recurse
                base.AnalyzeNode();
            }
            finally
            {
                if (m_blockScope != null)
                {
                    ScopeStack.Pop();
                }
            }

            // NOW that we've recursively analyzed all the child nodes in this block, let's see
            // if we can further reduce the statements by checking for a couple good opportunities
            if (Parser.Settings.RemoveUnneededCode)
            {
                // Transform: {var foo=expression;return foo;} to: {return expression;}
                if (m_list.Count == 2 && Parser.Settings.IsModificationAllowed(TreeModifications.VarInitializeReturnToReturnInitializer))
                {
                    Var        varStatement    = m_list[0] as Var;
                    ReturnNode returnStatement = m_list[1] as ReturnNode;

                    // see if we have two statements in our block: a var with a single declaration, and a return
                    if (returnStatement != null && varStatement != null &&
                        varStatement.Count == 1 && varStatement[0].Initializer != null)
                    {
                        // now see if the return is returning a lookup for the same var we are declaring in the
                        // previous statement
                        Lookup lookup = returnStatement.Operand as Lookup;
                        if (lookup != null &&
                            string.Compare(lookup.Name, varStatement[0].Identifier, StringComparison.Ordinal) == 0)
                        {
                            // it's a match!
                            // create a combined context starting with the var and adding in the return
                            Context context = varStatement.Context.Clone();
                            context.UpdateWith(returnStatement.Context);

                            // create a new return statement
                            ReturnNode newReturn = new ReturnNode(context, Parser, varStatement[0].Initializer);

                            // clear out the existing statements
                            m_list.Clear();

                            // and add our new one
                            Append(newReturn);
                        }
                    }
                }

                // we do things differently if these statements are the last in a function
                // because we can assume the implicit return
                bool isFunctionLevel = (Parent is FunctionObject);

                // see if we want to change if-statement that forces a return to a return conditional
                if (Parser.Settings.IsModificationAllowed(TreeModifications.IfElseReturnToReturnConditional))
                {
                    // transform: {...; if(cond1)return;} to {...;cond;}
                    // transform: {...; if(cond1)return exp1;else return exp2;} to {...;return cond1?exp1:exp2;}
                    if (m_list.Count >= 1)
                    {
                        // see if the last statement is an if-statement with a true-block containing only one statement
                        IfNode ifStatement = m_list[m_list.Count - 1] as IfNode;
                        if (ifStatement != null &&
                            ifStatement.TrueBlock != null)
                        {
                            // see if this if-statement is structured such that we can convert it to a
                            // Conditional node that is the operand of a return statement
                            Conditional returnOperand = ifStatement.CanBeReturnOperand(null, isFunctionLevel);
                            if (returnOperand != null)
                            {
                                // it can! change it.
                                ReturnNode returnNode = new ReturnNode(
                                    (Context == null ? null : Context.Clone()),
                                    Parser,
                                    returnOperand);

                                // replace the if-statement with the return statement
                                ReplaceChild(ifStatement, returnNode);
                            }
                        }
                        // else last statement is not an if-statement, or true block is not a single statement
                    }

                    // transform: {...; if(cond1)return exp1;return exp2;} to {...; return cond1?exp1:exp2;}
                    // my cascade! changing the two statements to a return may cause us to run this again if the
                    // third statement up becomes the penultimate and is an if-statement
                    while (m_list.Count > 1)
                    {
                        int lastIndex = m_list.Count - 1;
                        // end in a return statement?
                        ReturnNode finalReturn = m_list[lastIndex] as ReturnNode;
                        if (finalReturn != null)
                        {
                            // it does -- see if the penultimate statement is an if-block
                            IfNode ifNode = m_list[lastIndex - 1] as IfNode;
                            if (ifNode != null)
                            {
                                // if followed by return. See if the if statement can be changed to a
                                // return of a conditional, using the operand of the following return
                                // as the ultimate expression
                                Conditional returnConditional = ifNode.CanBeReturnOperand(finalReturn.Operand, isFunctionLevel);
                                if (returnConditional != null)
                                {
                                    // it can! so create the new return statement.
                                    // the context of this new return statement should start with a clone of
                                    // the if-statement and updated with the return statement
                                    Context context = ifNode.Context.Clone();
                                    context.UpdateWith(finalReturn.Context);

                                    // create the new return node
                                    ReturnNode newReturn = new ReturnNode(
                                        context,
                                        Parser,
                                        returnConditional);

                                    // remove the last node (the old return)
                                    m_list.RemoveAt(lastIndex--);

                                    // and replace the if-statement with the new return
                                    m_list[lastIndex] = newReturn;
                                    newReturn.Parent  = this;

                                    // we collapsed the last two statements, and we KNOW the last one is a
                                    // return -- go back up to the top of the loop to see if we can keep going.
                                    continue;
                                }
                            }
                        }

                        // if we get here, then something went wrong, we didn't collapse the last
                        // two statements, so break out of the loop
                        break;
                    }

                    // now we may have converted the last functional statement
                    // from if(cond)return expr to return cond?expr:void 0, which is four
                    // extra bytes. So let's check to see if the last statement in the function
                    // now fits this pattern, and if so, change it back.
                    // We didn't just NOT change it in the first place because changing it could've
                    // enabled even more changes that would save a lot more space. But apparently
                    // those subsequent changes didn't pan out.
                    if (m_list.Count >= 1)
                    {
                        int        lastIndex  = m_list.Count - 1;
                        ReturnNode returnNode = m_list[lastIndex] as ReturnNode;
                        if (returnNode != null)
                        {
                            Conditional conditional = returnNode.Operand as Conditional;
                            if (conditional != null)
                            {
                                VoidNode falseVoid = conditional.FalseExpression as VoidNode;
                                if (falseVoid != null && falseVoid.Operand is ConstantWrapper)
                                {
                                    // we have the required pattern: "return cond?expr:void 0"
                                    // (well, the object of the void is a constant, at least).
                                    // undo it back to "if(cond)return expr" because that takes fewer bytes.

                                    // by default, the operand of the return operator will be the
                                    // true branch of the conditional
                                    AstNode returnOperand = conditional.TrueExpression;

                                    VoidNode trueVoid = conditional.TrueExpression as VoidNode;
                                    if (trueVoid != null && trueVoid.Operand is ConstantWrapper)
                                    {
                                        // the true branch of the conditional is a void operator acting
                                        // on a constant! So really, there is no operand to the return statement
                                        returnOperand = null;

                                        if (Parser.Settings.IsModificationAllowed(TreeModifications.IfConditionReturnToCondition))
                                        {
                                            // actually, we have return cond?void 0:void 0,
                                            // which would get changed back to function{...;if(cond)return}
                                            // BUT we can just shorten it to function{...;cond}
                                            m_list[lastIndex]            = conditional.Condition;
                                            conditional.Condition.Parent = this;
                                            return;
                                        }
                                    }

                                    IfNode ifNode = new IfNode(
                                        returnNode.Context.Clone(),
                                        Parser,
                                        conditional.Condition,
                                        new ReturnNode(returnNode.Context.Clone(), Parser, returnOperand),
                                        null);
                                    m_list[lastIndex] = ifNode;
                                    ifNode.Parent     = this;
                                }
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 7
0
        public override void Visit(ReturnNode node)
        {
            if (node != null)
            {
                // first we want to make sure that we are indeed within a function scope.
                // it makes no sense to have a return outside of a function
                ActivationObject scope = ScopeStack.Peek();
                while (scope != null && !(scope is FunctionScope))
                {
                    scope = scope.Parent;
                }

                if (scope == null)
                {
                    node.Context.HandleError(JSError.BadReturn);
                }

                // now just do the default analyze
                base.Visit(node);
            }
        }
Exemplo n.º 8
0
        public override void Visit(IfNode node)
        {
            if (node != null)
            {
                if (m_parser.Settings.StripDebugStatements
                     && m_parser.Settings.IsModificationAllowed(TreeModifications.StripDebugStatements))
                {
                    if (node.TrueBlock != null && node.TrueBlock.IsDebuggerStatement)
                    {
                        node.ReplaceChild(node.TrueBlock, null);
                    }

                    if (node.FalseBlock != null && node.FalseBlock.IsDebuggerStatement)
                    {
                        node.ReplaceChild(node.FalseBlock, null);
                    }
                }

                // recurse....
                base.Visit(node);

                // now check to see if the two branches are now empty.
                // if they are, null them out.
                if (node.TrueBlock != null && node.TrueBlock.Count == 0)
                {
                    node.ReplaceChild(node.TrueBlock, null);
                }
                if (node.FalseBlock != null && node.FalseBlock.Count == 0)
                {
                    node.ReplaceChild(node.FalseBlock, null);
                }

                // if there is no true branch but a false branch, then
                // put a not on the condition and move the false branch to the true branch.
                if (node.TrueBlock == null && node.FalseBlock != null
                    && m_parser.Settings.IsModificationAllowed(TreeModifications.IfConditionFalseToIfNotConditionTrue))
                {
                    // logical-not the condition
                    var logicalNot = new LogicalNot(node.Condition, m_parser);
                    logicalNot.Apply();

                    // and swap the branches
                    node.SwapBranches();
                }
                else if (node.TrueBlock != null && node.FalseBlock != null)
                {
                    // see if logical-notting the condition produces something smaller
                    var logicalNot = new LogicalNot(node.Condition, m_parser);
                    if (logicalNot.Measure() < 0)
                    {
                        // it does -- not the condition and swap the branches
                        logicalNot.Apply();
                        node.SwapBranches();
                    }

                    // see if the true- and false-branches each contain only a single statement
                    if (node.TrueBlock.Count == 1 && node.FalseBlock.Count == 1)
                    {
                        // they do -- see if the true-branch's statement is a return-statement
                        var trueReturn = node.TrueBlock[0] as ReturnNode;
                        if (trueReturn != null && trueReturn.Operand != null)
                        {
                            // it is -- see if the false-branch is also a return statement
                            var falseReturn = node.FalseBlock[0] as ReturnNode;
                            if (falseReturn != null && falseReturn.Operand != null)
                            {
                                // transform: if(cond)return expr1;else return expr2 to return cond?expr1:expr2
                                var conditional = new Conditional(null, m_parser,
                                    node.Condition,
                                    trueReturn.Operand,
                                    falseReturn.Operand);

                                // create a new return node from the conditional and replace
                                // our if-node with it
                                var returnNode = new ReturnNode(
                                    node.Context,
                                    m_parser,
                                    conditional);

                                node.Parent.ReplaceChild(
                                    node,
                                    returnNode);

                                Optimize(conditional);
                            }
                        }
                    }
                }
                else if (node.TrueBlock == null && node.FalseBlock == null
                    && m_parser.Settings.IsModificationAllowed(TreeModifications.IfEmptyToExpression))
                {
                    // NEITHER branches have anything now!

                    // something we can do in the future: as long as the condition doesn't
                    // contain calls or assignments, we should be able to completely delete
                    // the statement altogether rather than changing it to an expression
                    // statement on the condition.

                    // I'm just not doing it yet because I don't
                    // know what the effect will be on the iteration of block statements.
                    // if we're on item, 5, for instance, and we delete it, will the next
                    // item be item 6, or will it return the NEW item 5 (since the old item
                    // 5 was deleted and everything shifted up)?

                    // We don't know what it is and what the side-effects may be, so
                    // just change this statement into an expression statement by replacing us with
                    // the expression
                    node.Parent.ReplaceChild(node, node.Condition);
                    // no need to analyze -- we already recursed
                }

                // if the true block is not empty, but it's an expression, there are a couple more
                // optimizations we can make
                if (node.TrueBlock != null && node.TrueBlock.IsExpression
                    && m_parser.Settings.IsModificationAllowed(TreeModifications.IfExpressionsToExpression))
                {
                    if (node.FalseBlock != null && node.FalseBlock.IsExpression)
                    {
                        // if this statement has both true and false blocks, and they are both expressions,
                        // then we can simplify this to a conditional expression.
                        // because the blocks are expressions, we know they only have ONE statement in them,
                        // so we can just dereference them directly.
                        Conditional conditional;
                        var logicalNot = new LogicalNot(node.Condition, m_parser);
                        if (logicalNot.Measure() < 0)
                        {
                            // applying a logical-not makes the condition smaller -- reverse the branches
                            logicalNot.Apply();
                            conditional = new Conditional(
                                node.Context,
                                m_parser,
                                node.Condition,
                                node.FalseBlock[0],
                                node.TrueBlock[0]);
                        }
                        else
                        {
                            // regular order
                            conditional = new Conditional(
                                node.Context,
                                m_parser,
                                node.Condition,
                                node.TrueBlock[0],
                                node.FalseBlock[0]);
                        }

                        node.Parent.ReplaceChild(
                            node,
                            conditional);

                        Optimize(conditional);
                    }
                    else if (node.FalseBlock == null
                        && m_parser.Settings.IsModificationAllowed(TreeModifications.IfConditionCallToConditionAndCall))
                    {
                        // but first -- which operator to use? if(a)b --> a&&b, and if(!a)b --> a||b
                        // so determine which one is smaller: a or !a
                        // assume we'll use the logical-and, since that doesn't require changing the condition
                        var newOperator = JSToken.LogicalAnd;
                        var logicalNot = new LogicalNot(node.Condition, m_parser);
                        if (logicalNot.Measure() < 0)
                        {
                            // !a is smaller, so apply it and use the logical-or operator
                            logicalNot.Apply();
                            newOperator = JSToken.LogicalOr;
                        }

                        // because the true block is an expression, we know it must only have
                        // ONE statement in it, so we can just dereference it directly.
                        var binaryOp = new BinaryOperator(
                            node.Context,
                            m_parser,
                            node.Condition,
                            node.TrueBlock[0],
                            newOperator
                            );

                        // we don't need to analyse this new node because we've already analyzed
                        // the pieces parts as part of the if. And this visitor's method for the BinaryOperator
                        // doesn't really do anything else. Just replace our current node with this
                        // new node
                        node.Parent.ReplaceChild(node, binaryOp);
                    }
                }
            }
        }
Exemplo n.º 9
0
 public void Visit(ReturnNode node)
 {
     ReportError(node);
 }
Exemplo n.º 10
0
 public void Visit(ReturnNode node)
 {
     // invalid! ignore
     IsValid = false;
 }