Example #1
0
 public override AstVisitAction VisitSwitchStatement(SwitchStatementAst switchStatementAst)
 {
     if (((switchStatementAst.Flags & SwitchFlags.Parallel) == SwitchFlags.Parallel) && !switchStatementAst.IsInWorkflow())
     {
         this._parser.ReportError(switchStatementAst.Extent, ParserStrings.ParallelNotSupported, new object[0]);
     }
     return(AstVisitAction.Continue);
 }
Example #2
0
        public object VisitSwitchStatement(SwitchStatementAst switchStatementAst)
        {
            VariableAnalysisDetails details = this._variables["switch"];

            if ((details.LocalTupleIndex == -1) && !this._disableOptimizations)
            {
                details.LocalTupleIndex = this._localsAllocated++;
            }
            Action generateCondition = delegate {
                switchStatementAst.Condition.Accept(this);
                this._currentBlock.AddAst(new AssignmentTarget("switch", typeof(IEnumerator)));
            };
            Action generateLoopBody = delegate {
                bool  flag  = switchStatementAst.Default != null;
                Block next  = new Block();
                int   count = switchStatementAst.Clauses.Count;
                for (int j = 0; j < count; j++)
                {
                    Tuple <ExpressionAst, StatementBlockAst> tuple = switchStatementAst.Clauses[j];
                    Block block2 = new Block();
                    bool  flag2  = (j == (count - 1)) && !flag;
                    Block block3 = flag2 ? next : new Block();
                    tuple.Item1.Accept(this);
                    this._currentBlock.FlowsTo(block3);
                    this._currentBlock.FlowsTo(block2);
                    this._currentBlock = block2;
                    tuple.Item2.Accept(this);
                    if (!flag2)
                    {
                        this._currentBlock.FlowsTo(block3);
                        this._currentBlock = block3;
                    }
                }
                if (flag)
                {
                    this._currentBlock.FlowsTo(next);
                    switchStatementAst.Default.Accept(this);
                }
                this._currentBlock.FlowsTo(next);
                this._currentBlock = next;
            };

            this.GenerateWhileLoop(switchStatementAst.Label, generateCondition, generateLoopBody, null);
            return(null);
        }
Example #3
0
    public System.Object VisitSwitchStatement(System.Management.Automation.Language.SwitchStatementAst switchStatementAst)
    {
        IScriptExtent mappedExtent = MapExtent(switchStatementAst.Extent);

        PipelineBaseAst mappedCondition = _VisitPipelineBase(switchStatementAst.Condition);
        LinkedList <Tuple <ExpressionAst, StatementBlockAst> > mappedClauses = new LinkedList <Tuple <ExpressionAst, StatementBlockAst> >();

        foreach (Tuple <ExpressionAst, StatementBlockAst> c in switchStatementAst.Clauses)
        {
            mappedClauses.AddLast(
                new Tuple <ExpressionAst, StatementBlockAst>(
                    _VisitExpression(c.Item1),
                    (StatementBlockAst)VisitStatementBlock(c.Item2)
                    )
                );
        }
        StatementBlockAst mappedDefault = switchStatementAst.Default == null ? null : (StatementBlockAst)VisitStatementBlock(switchStatementAst.Default);

        return(new SwitchStatementAst(mappedExtent, switchStatementAst.Label, mappedCondition, switchStatementAst.Flags, mappedClauses, mappedDefault));
    }
Example #4
0
 public object VisitSwitchStatement(SwitchStatementAst switchStatementAst)
 {
     throw PSTraceSource.NewArgumentException("ast");
 }
Example #5
0
 public object VisitSwitchStatement(SwitchStatementAst switchStatementAst)
 {
     return(false);
 }
Example #6
0
 /// <summary/>
 public virtual object VisitSwitchStatement(SwitchStatementAst switchStatementAst) { return null; }
Example #7
0
 public override AstVisitAction VisitSwitchStatement(SwitchStatementAst ast)
 {
     return(Check(ast));
 }
 /// <summary/>
 public virtual object VisitSwitchStatement(SwitchStatementAst switchStatementAst)
 {
     return _decorated.VisitSwitchStatement(switchStatementAst);
 }
Example #9
0
 public override AstVisitAction VisitSwitchStatement(SwitchStatementAst switchStatementAst)
 {
     if (((switchStatementAst.Flags & SwitchFlags.Parallel) == SwitchFlags.Parallel) && !switchStatementAst.IsInWorkflow())
     {
         this._parser.ReportError(switchStatementAst.Extent, ParserStrings.ParallelNotSupported, new object[0]);
     }
     return AstVisitAction.Continue;
 }
 public object VisitSwitchStatement(SwitchStatementAst switchStatementAst) { throw new UnexpectedElementException(); }
        /// <summary>
        /// Visit switch statement
        /// </summary>
        /// <param name="switchStatementAst"></param>
        /// <returns></returns>
        public object VisitSwitchStatement(SwitchStatementAst switchStatementAst)
        {
            if (switchStatementAst == null) return null;

            Action generateCondition = () =>
            {
                switchStatementAst.Condition.Visit(this.Decorator);

                // $switch is set after evaluating the condition.
                _currentBlock.AddAst(new AssignmentTarget(SpecialVars.@switch, typeof(IEnumerator)));
            };

            Action switchBodyGenerator = () =>
            {
                bool hasDefault = (switchStatementAst.Default != null);
                Block afterStmt = new Block();

                int clauseCount = switchStatementAst.Clauses.Count;
                for (int i = 0; i < clauseCount; i++)
                {
                    var clause = switchStatementAst.Clauses[i];
                    Block clauseBlock = new Block();
                    bool isLastClause = (i == (clauseCount - 1) && !hasDefault);
                    Block nextBlock = isLastClause ? afterStmt : new Block();

                    clause.Item1.Visit(this.Decorator);

                    _currentBlock.FlowsTo(nextBlock);
                    _currentBlock.FlowsTo(clauseBlock);
                    _currentBlock = clauseBlock;

                    clause.Item2.Visit(this.Decorator);

                    if (!isLastClause)
                    {
                        _currentBlock.FlowsTo(nextBlock);
                        _currentBlock = nextBlock;
                    }
                }

                if (hasDefault)
                {
                    // If any clause was executed, we skip the default, so there is always a branch over the default.
                    _currentBlock.FlowsTo(afterStmt);
                    switchStatementAst.Default.Visit(this.Decorator);
                }

                _currentBlock.FlowsTo(afterStmt);
                _currentBlock = afterStmt;
            };

            GenerateWhileLoop(switchStatementAst.Label, generateCondition, switchBodyGenerator);

            return null;
        }
Example #12
0
 /// <summary/>
 public virtual AstVisitAction VisitSwitchStatement(SwitchStatementAst switchStatementAst) => DefaultVisit(switchStatementAst);
Example #13
0
        public override AstVisitAction VisitSwitchStatement(SwitchStatementAst switchStatementAst)
        {
            // Parallel flag not allowed
            if ((switchStatementAst.Flags & SwitchFlags.Parallel) == SwitchFlags.Parallel)
            {
                bool reportError = !switchStatementAst.IsInWorkflow();
                if (reportError)
                {
                    _parser.ReportError(switchStatementAst.Extent, () => ParserStrings.ParallelNotSupported);
                }
            }

            return AstVisitAction.Continue;
        }
Example #14
0
 public object VisitSwitchStatement(SwitchStatementAst switchStatementAst)
 {
     AutomaticVarSaver avs = new AutomaticVarSaver(this, SpecialVariables.UnderbarVarPath, 0);
     List<ParameterExpression> first = new List<ParameterExpression>();
     ParameterExpression item = null;
     if (switchStatementAst.Default != null)
     {
         item = this.NewTemp(typeof(bool), "skipDefault");
         first.Add(item);
     }
     Action<List<Expression>, Expression> switchBodyGenerator = this.GetSwitchBodyGenerator(switchStatementAst, avs, item);
     if ((switchStatementAst.Flags & SwitchFlags.File) != SwitchFlags.None)
     {
         List<Expression> expressions = new List<Expression>();
         ParameterExpression expression2 = this.NewTemp(typeof(string), "path");
         first.Add(expression2);
         expressions.Add(this.UpdatePosition(switchStatementAst.Condition));
         DynamicExpression expression3 = Expression.Dynamic(PSToStringBinder.Get(), typeof(string), this.CaptureStatementResults(switchStatementAst.Condition, CaptureAstContext.Assignment, null), _executionContextParameter);
         expressions.Add(Expression.Assign(expression2, Expression.Call(CachedReflectionInfo.SwitchOps_ResolveFilePath, Expression.Constant(switchStatementAst.Condition.Extent), expression3, _executionContextParameter)));
         List<Expression> list3 = new List<Expression>();
         ParameterExpression expression4 = this.NewTemp(typeof(StreamReader), "streamReader");
         ParameterExpression line = this.NewTemp(typeof(string), "line");
         first.Add(expression4);
         first.Add(line);
         list3.Add(Expression.Assign(expression4, Expression.New(CachedReflectionInfo.StreamReader_ctor, new Expression[] { expression2 })));
         BinaryExpression loopTest = Expression.NotEqual(Expression.Assign(line, Expression.Call(expression4, CachedReflectionInfo.StreamReader_ReadLine)).Cast(typeof(object)), ExpressionCache.NullConstant);
         list3.Add(avs.SaveAutomaticVar());
         list3.Add(this.GenerateWhileLoop(switchStatementAst.Label, () => loopTest, delegate (List<Expression> loopBody, LabelTarget breakTarget, LabelTarget continueTarget) {
             switchBodyGenerator(loopBody, line);
         }, null));
         BlockExpression body = Expression.Block(list3);
         BlockExpression @finally = Expression.Block(Expression.IfThen(Expression.NotEqual(expression4, ExpressionCache.NullConstant), Expression.Call(expression4.Cast(typeof(IDisposable)), CachedReflectionInfo.IDisposable_Dispose)), avs.RestoreAutomaticVar());
         ParameterExpression expression7 = this.NewTemp(typeof(Exception), "exception");
         BlockExpression expression8 = Expression.Block(body.Type, new Expression[] { Expression.Call(CachedReflectionInfo.CommandProcessorBase_CheckForSevereException, expression7), ThrowRuntimeErrorWithInnerException("FileReadError", ParserStrings.FileReadError, expression7, new Expression[] { Expression.Property(expression7, CachedReflectionInfo.Exception_Message) }) });
         expressions.Add(Expression.TryCatchFinally(body, @finally, new CatchBlock[] { Expression.Catch(typeof(FlowControlException), Expression.Rethrow(body.Type)), Expression.Catch(expression7, expression8) }));
         return Expression.Block(first.Concat<ParameterExpression>(avs.GetTemps()), expressions);
     }
     TryExpression expression9 = Expression.TryFinally(Expression.Block(avs.SaveAutomaticVar(), this.GenerateIteratorStatement(SpecialVariables.switchVarPath, () => this.UpdatePosition(switchStatementAst.Condition), this._switchTupleIndex, switchStatementAst, switchBodyGenerator)), avs.RestoreAutomaticVar());
     return Expression.Block(first.Concat<ParameterExpression>(avs.GetTemps()), new Expression[] { expression9 });
 }
Example #15
0
 private Action<List<Expression>, Expression> GetSwitchBodyGenerator(SwitchStatementAst switchStatementAst, AutomaticVarSaver avs, ParameterExpression skipDefault)
 {
     return delegate (List<Expression> exprs, Expression newValue) {
         PSSwitchClauseEvalBinder binder = PSSwitchClauseEvalBinder.Get(switchStatementAst.Flags);
         exprs.Add(avs.SetNewValue(newValue));
         if (skipDefault != null)
         {
             exprs.Add(Expression.Assign(skipDefault, ExpressionCache.Constant(false)));
         }
         IsConstantValueVisitor visitor = new IsConstantValueVisitor();
         ConstantValueVisitor visitor2 = new ConstantValueVisitor();
         int count = switchStatementAst.Clauses.Count;
         for (int j = 0; j < count; j++)
         {
             Expression expression;
             Tuple<ExpressionAst, StatementBlockAst> tuple = switchStatementAst.Clauses[j];
             object obj2 = ((bool) tuple.Item1.Accept(visitor)) ? tuple.Item1.Accept(visitor2) : null;
             if (obj2 is ScriptBlock)
             {
                 MethodCallExpression expression2 = Expression.Call(Expression.Constant(obj2), CachedReflectionInfo.ScriptBlock_DoInvokeReturnAsIs, new Expression[] { ExpressionCache.Constant(true), Expression.Constant(ScriptBlock.ErrorHandlingBehavior.WriteToExternalErrorPipe), this.GetLocal(0).Convert(typeof(object)), ExpressionCache.AutomationNullConstant, ExpressionCache.AutomationNullConstant, ExpressionCache.NullObjectArray });
                 expression = Expression.Dynamic(PSConvertBinder.Get(typeof(bool)), typeof(bool), expression2);
             }
             else if (obj2 != null)
             {
                 SwitchFlags flags = switchStatementAst.Flags;
                 Expression expression3 = Expression.Constant(((obj2 is Regex) || (obj2 is WildcardPattern)) ? obj2 : obj2.ToString());
                 Expression expression4 = Expression.Dynamic(PSToStringBinder.Get(), typeof(string), this.GetLocal(0), _executionContextParameter);
                 if (((flags & SwitchFlags.Regex) != SwitchFlags.None) || (obj2 is Regex))
                 {
                     expression = Expression.Call(CachedReflectionInfo.SwitchOps_ConditionSatisfiedRegex, ExpressionCache.Constant((flags & SwitchFlags.CaseSensitive) != SwitchFlags.None), expression3, Expression.Constant(tuple.Item1.Extent), expression4, _executionContextParameter);
                 }
                 else if (((flags & SwitchFlags.Wildcard) != SwitchFlags.None) || (obj2 is WildcardPattern))
                 {
                     expression = Expression.Call(CachedReflectionInfo.SwitchOps_ConditionSatisfiedWildcard, ExpressionCache.Constant((flags & SwitchFlags.CaseSensitive) != SwitchFlags.None), expression3, expression4, _executionContextParameter);
                 }
                 else
                 {
                     expression = CallStringEquals(expression3, expression4, (flags & SwitchFlags.CaseSensitive) == SwitchFlags.None);
                 }
             }
             else
             {
                 Expression expression5 = this.Compile(tuple.Item1);
                 expression = Expression.Dynamic(binder, typeof(bool), expression5, this.GetLocal(0), _executionContextParameter);
             }
             exprs.Add(this.UpdatePosition(tuple.Item1));
             if (skipDefault != null)
             {
                 exprs.Add(Expression.IfThen(expression, Expression.Block(this.Compile(tuple.Item2), Expression.Assign(skipDefault, ExpressionCache.Constant(true)))));
             }
             else
             {
                 exprs.Add(Expression.IfThen(expression, this.Compile(tuple.Item2)));
             }
         }
         if (skipDefault != null)
         {
             exprs.Add(Expression.IfThen(Expression.Not(skipDefault), this.Compile(switchStatementAst.Default)));
         }
     };
 }
Example #16
0
 public override AstVisitAction VisitSwitchStatement(SwitchStatementAst switchStatementAst) { return AstVisitAction.SkipChildren; }
Example #17
0
 public override AstVisitAction VisitSwitchStatement(SwitchStatementAst ast) { return CheckParent(ast); }
 public override AstVisitAction VisitSwitchStatement(SwitchStatementAst switchStatementAst)
 {
     this.ReportError(switchStatementAst, () => ParserStrings.SwitchStatementNotSupportedInDataSection, new object[0]);
     return(AstVisitAction.Continue);
 }
Example #19
0
 public object VisitSwitchStatement(SwitchStatementAst switchStatementAst)
 {
     VariableAnalysisDetails details = this._variables["switch"];
     if ((details.LocalTupleIndex == -1) && !this._disableOptimizations)
     {
         details.LocalTupleIndex = this._localsAllocated++;
     }
     Action generateCondition = delegate {
         switchStatementAst.Condition.Accept(this);
         this._currentBlock.AddAst(new AssignmentTarget("switch", typeof(IEnumerator)));
     };
     Action generateLoopBody = delegate {
         bool flag = switchStatementAst.Default != null;
         Block next = new Block();
         int count = switchStatementAst.Clauses.Count;
         for (int j = 0; j < count; j++)
         {
             Tuple<ExpressionAst, StatementBlockAst> tuple = switchStatementAst.Clauses[j];
             Block block2 = new Block();
             bool flag2 = (j == (count - 1)) && !flag;
             Block block3 = flag2 ? next : new Block();
             tuple.Item1.Accept(this);
             this._currentBlock.FlowsTo(block3);
             this._currentBlock.FlowsTo(block2);
             this._currentBlock = block2;
             tuple.Item2.Accept(this);
             if (!flag2)
             {
                 this._currentBlock.FlowsTo(block3);
                 this._currentBlock = block3;
             }
         }
         if (flag)
         {
             this._currentBlock.FlowsTo(next);
             switchStatementAst.Default.Accept(this);
         }
         this._currentBlock.FlowsTo(next);
         this._currentBlock = next;
     };
     this.GenerateWhileLoop(switchStatementAst.Label, generateCondition, generateLoopBody, null);
     return null;
 }
Example #20
0
 public override AstVisitAction VisitSwitchStatement(SwitchStatementAst switchStatementAst)
 {
     throw new NotImplementedException(); //VisitSwitchStatement(switchStatementAst);
 }
        /// <summary>
        /// Visit SwitchStatement
        /// </summary>
        /// <param name="switchStatementAst"></param>
        /// <returns></returns>
        public override AstVisitAction VisitSwitchStatement(SwitchStatementAst switchStatementAst)
        {
            NoteVariable(SpecialVars.@switch, typeof(IEnumerator));

            return AstVisitAction.Continue;
        }
 public override AstVisitAction VisitSwitchStatement(SwitchStatementAst switchStatementAst)
 {
     this.NoteVariable("switch", -1, typeof(IEnumerator), false, false);
     return(AstVisitAction.Continue);
 }
Example #23
0
 public override AstVisitAction VisitSwitchStatement(SwitchStatementAst ast)
 {
     return this.Check(ast);
 }
Example #24
0
 public override AstVisitAction VisitSwitchStatement(SwitchStatementAst switchStatementAst)
 {
     this.NoteVariable("switch", -1, typeof(IEnumerator), false, false);
     return AstVisitAction.Continue;
 }
Example #25
0
 public virtual AstVisitAction VisitSwitchStatement(SwitchStatementAst switchStatementAst)
 {
     return AstVisitAction.Continue;
 }
Example #26
0
 public object VisitSwitchStatement(SwitchStatementAst switchStatementAst) { return AutomationNull.Value; }
Example #27
0
 public object VisitSwitchStatement(SwitchStatementAst switchStatementAst) { throw PSTraceSource.NewArgumentException("ast"); }
Example #28
0
        public object VisitSwitchStatement(SwitchStatementAst switchStatementAst)
        {
            var avs = new AutomaticVarSaver(this, SpecialVariables.UnderbarVarPath, (int)AutomaticVariable.Underbar);
            var temps = new List<ParameterExpression>();
            ParameterExpression skipDefault = null;
            if (switchStatementAst.Default != null)
            {
                skipDefault = NewTemp(typeof(bool), "skipDefault");
                temps.Add(skipDefault);
            }

            var switchBodyGenerator = GetSwitchBodyGenerator(switchStatementAst, avs, skipDefault);

            if ((switchStatementAst.Flags & SwitchFlags.File) != 0)
            {
                // Generate:
                //
                //    string path = SwitchOps.ResolveFilePath(cond.Extent, cond, context);
                //    StreamReader sr = null;
                //    try
                //    {
                //        sr = new StreamReader(path);
                //        string line;
                //        while ((line = sr.ReadLine()) != null)
                //        {
                //            $_ = line
                //            test clauses
                //        }
                //    }
                //    catch (FlowControlException) { throw; }
                //    catch (Exception exception)
                //    {
                //        CommandProcessorBase.CheckForSevereException(exception);
                //        // "The file could not be read:" + fne.Message
                //        throw InterpreterError.NewInterpreterExceptionWithInnerException(path, typeof(RuntimeException),
                //            cond.Extent, "FileReadError", ParserStrings.FileReadError, exception, exception.Message);
                //    }
                //    finally
                //    {
                //        if (sr != null) sr.Dispose();
                //    }

                var exprs = new List<Expression>();

                var path = NewTemp(typeof(string), "path");
                temps.Add(path);

                exprs.Add(UpdatePosition(switchStatementAst.Condition));

                // We should not preserve the partial output if exception is thrown when evaluating the condition.
                var cond = DynamicExpression.Dynamic(PSToStringBinder.Get(), typeof(string),
                                                     CaptureStatementResults(switchStatementAst.Condition, CaptureAstContext.AssignmentWithoutResultPreservation),
                                                     _executionContextParameter);
                exprs.Add(
                    Expression.Assign(
                        path,
                        Expression.Call(CachedReflectionInfo.SwitchOps_ResolveFilePath,
                                        Expression.Constant(switchStatementAst.Condition.Extent),
                                        cond,
                                        _executionContextParameter)));

                var tryBodyExprs = new List<Expression>();

                var streamReader = NewTemp(typeof(StreamReader), "streamReader");
                var line = NewTemp(typeof(string), "line");
                temps.Add(streamReader);
                temps.Add(line);

                tryBodyExprs.Add(
                    Expression.Assign(streamReader,
                                      Expression.New(CachedReflectionInfo.StreamReader_ctor, path)));
                var loopTest =
                    Expression.NotEqual(
                        Expression.Assign(line,
                                          Expression.Call(streamReader, CachedReflectionInfo.StreamReader_ReadLine)).Cast(typeof(object)),
                        ExpressionCache.NullConstant);

                tryBodyExprs.Add(avs.SaveAutomaticVar());
                tryBodyExprs.Add(GenerateWhileLoop(switchStatementAst.Label,
                                            () => loopTest,
                                            (loopBody, breakTarget, continueTarget) => switchBodyGenerator(loopBody, line)));
                var tryBlock = Expression.Block(tryBodyExprs);
                var finallyBlock = Expression.Block(
                    Expression.IfThen(
                        Expression.NotEqual(streamReader, ExpressionCache.NullConstant),
                        Expression.Call(streamReader.Cast(typeof(IDisposable)), CachedReflectionInfo.IDisposable_Dispose)),
                    avs.RestoreAutomaticVar());
                var exception = NewTemp(typeof(Exception), "exception");
                var catchAllBlock = Expression.Block(
                    tryBlock.Type,
                    Expression.Call(CachedReflectionInfo.CommandProcessorBase_CheckForSevereException, exception),
                    ThrowRuntimeErrorWithInnerException("FileReadError",
                                                        ParserStrings.FileReadError,
                                                        exception,
                                                        Expression.Property(exception, CachedReflectionInfo.Exception_Message)));

                exprs.Add(Expression.TryCatchFinally(
                    tryBlock, finallyBlock,
                    new[]
                    {
                        Expression.Catch(typeof(FlowControlException), Expression.Rethrow(tryBlock.Type)),
                        Expression.Catch(exception, catchAllBlock)
                    }));

                return Expression.Block(temps.Concat(avs.GetTemps()), exprs);
            }

            // We convert:
            //     switch ($enumerable) {}
            // Into:
            //     $switch = GetEnumerator $enumerable
            //     if ($switch == $null)
            //     {
            //         $switch  = (new object[] { $enumerable }).GetEnumerator()
            //     }
            // REVIEW: should we consider this form of switch a loop for the purposes of deciding
            // to compile or not?  I have a feeling the loop form is uncommon and compiling isn't worth it.

            var tryStmt = Expression.TryFinally(
                Expression.Block(
                    avs.SaveAutomaticVar(),
                    GenerateIteratorStatement(SpecialVariables.switchVarPath, () => UpdatePosition(switchStatementAst.Condition), _switchTupleIndex,
                                              switchStatementAst, switchBodyGenerator)
                    ),
                avs.RestoreAutomaticVar());

            return Expression.Block(temps.Concat(avs.GetTemps()), tryStmt);
        }
Example #29
0
 /// <summary/>
 public virtual object VisitSwitchStatement(SwitchStatementAst switchStatementAst)
 {
     return(null);
 }
Example #30
0
        private Action<List<Expression>, Expression> GetSwitchBodyGenerator(SwitchStatementAst switchStatementAst, AutomaticVarSaver avs, ParameterExpression skipDefault)
        {
            return (exprs, newValue) =>
                   {
                       var clauseEvalBinder = PSSwitchClauseEvalBinder.Get(switchStatementAst.Flags);
                       exprs.Add(avs.SetNewValue(newValue));

                       if (skipDefault != null)
                       {
                           exprs.Add(Expression.Assign(skipDefault, ExpressionCache.Constant(false)));
                       }

                       IsConstantValueVisitor iscvv = new IsConstantValueVisitor();
                       ConstantValueVisitor cvv = new ConstantValueVisitor();

                       int clauseCount = switchStatementAst.Clauses.Count;
                       for (int i = 0; i < clauseCount; i++)
                       {
                           var clause = switchStatementAst.Clauses[i];

                           Expression test;
                           object constValue = ((bool)clause.Item1.Accept(iscvv)) ? clause.Item1.Accept(cvv) : null;
                           if (constValue is ScriptBlock)
                           {
                               var call = Expression.Call(Expression.Constant(constValue),
                                                           CachedReflectionInfo.ScriptBlock_DoInvokeReturnAsIs,
                               /*useLocalScope=*/         ExpressionCache.Constant(true),
                               /*errorHandlingBehavior=*/ Expression.Constant(ScriptBlock.ErrorHandlingBehavior.WriteToExternalErrorPipe),
                               /*dollarUnder=*/           GetLocal((int)AutomaticVariable.Underbar).Convert(typeof(object)),
                               /*input=*/                 ExpressionCache.AutomationNullConstant,
                               /*scriptThis=*/            ExpressionCache.AutomationNullConstant,
                               /*args=*/                  ExpressionCache.NullObjectArray);
                               test = DynamicExpression.Dynamic(PSConvertBinder.Get(typeof(bool)), typeof(bool), call);
                           }
                           else if (constValue != null)
                           {
                               SwitchFlags flags = switchStatementAst.Flags;
                               Expression conditionExpr = constValue is Regex || constValue is WildcardPattern
                                                    ? (Expression)Expression.Constant(constValue)
                                                    : DynamicExpression.Dynamic(PSToStringBinder.Get(), typeof(string),
                                                                                (constValue is Type)
                                                                                    ? Expression.Constant(constValue, typeof(Type))
                                                                                    : Expression.Constant(constValue),
                                                                                _executionContextParameter);
                               Expression currentAsString =
                                   DynamicExpression.Dynamic(PSToStringBinder.Get(), typeof(string), GetLocal((int)AutomaticVariable.Underbar),
                                                             _executionContextParameter);
                               if ((flags & SwitchFlags.Regex) != 0 || constValue is Regex)
                               {
                                   test = Expression.Call(CachedReflectionInfo.SwitchOps_ConditionSatisfiedRegex,
                                       /*caseSensitive=*/ ExpressionCache.Constant((flags & SwitchFlags.CaseSensitive) != 0),
                                       /*condition=*/     conditionExpr,
                                       /*errorPosition=*/ Expression.Constant(clause.Item1.Extent),
                                       /*str=*/           currentAsString,
                                       /*context=*/       _executionContextParameter);
                               }
                               else if ((flags & SwitchFlags.Wildcard) != 0 || constValue is WildcardPattern)
                               {
                                   // It would be a little better to just build the wildcard at compile time, but
                                   // the runtime method must exist when variable cases are involved.
                                   test = Expression.Call(CachedReflectionInfo.SwitchOps_ConditionSatisfiedWildcard,
                                       /*caseSensitive=*/ ExpressionCache.Constant((flags & SwitchFlags.CaseSensitive) != 0),
                                       /*condition=*/     conditionExpr,
                                       /*str=*/           currentAsString,
                                       /*context=*/       _executionContextParameter);
                               }
                               else
                               {
                                   test = CallStringEquals(conditionExpr, currentAsString,
                                                           ((flags & SwitchFlags.CaseSensitive) == 0));
                               }
                           }
                           else
                           {
                               var cond = Compile(clause.Item1);
                               test = DynamicExpression.Dynamic(clauseEvalBinder, typeof(bool),
                                                                cond, GetLocal((int)AutomaticVariable.Underbar), _executionContextParameter);
                           }

                           exprs.Add(UpdatePosition(clause.Item1));
                           if (skipDefault != null)
                           {
                               exprs.Add(Expression.IfThen(
                                   test,
                                   Expression.Block(Compile(clause.Item2),
                                                    Expression.Assign(skipDefault, ExpressionCache.Constant(true)))));
                           }
                           else
                           {
                               exprs.Add(Expression.IfThen(test, Compile(clause.Item2)));
                           }
                       }

                       if (skipDefault != null)
                       {
                           exprs.Add(Expression.IfThen(Expression.Not(skipDefault), Compile(switchStatementAst.Default)));
                       }
                   };
        }
Example #31
0
 public object VisitSwitchStatement(SwitchStatementAst switchStatementAst)
 {
     return false;
 }
Example #32
0
        public object VisitSwitchStatement(SwitchStatementAst switchStatementAst)
        {
            var details = _variables[SpecialVariables.@switch];
            if (details.LocalTupleIndex == VariableAnalysis.Unanalyzed && !_disableOptimizations)
            {
                details.LocalTupleIndex = _localsAllocated++;
            }

            Action generateCondition = () =>
            {
                switchStatementAst.Condition.Accept(this);

                // $switch is set after evaluating the condition.
                _currentBlock.AddAst(new AssignmentTarget(SpecialVariables.@switch, typeof(IEnumerator)));
            };

            Action switchBodyGenerator = () =>
            {
                bool hasDefault = (switchStatementAst.Default != null);
                Block afterStmt = new Block();

                int clauseCount = switchStatementAst.Clauses.Count;
                for (int i = 0; i < clauseCount; i++)
                {
                    var clause = switchStatementAst.Clauses[i];
                    Block clauseBlock = new Block();
                    bool isLastClause = (i == (clauseCount - 1) && !hasDefault);
                    Block nextBlock = isLastClause ? afterStmt : new Block();

                    clause.Item1.Accept(this);

                    _currentBlock.FlowsTo(nextBlock);
                    _currentBlock.FlowsTo(clauseBlock);
                    _currentBlock = clauseBlock;

                    clause.Item2.Accept(this);

                    if (!isLastClause)
                    {
                        _currentBlock.FlowsTo(nextBlock);
                        _currentBlock = nextBlock;
                    }
                }

                if (hasDefault)
                {
                    // If any clause was executed, we skip the default, so there is always a branch over the default.
                    _currentBlock.FlowsTo(afterStmt);
                    switchStatementAst.Default.Accept(this);
                }

                _currentBlock.FlowsTo(afterStmt);
                _currentBlock = afterStmt;
            };

            GenerateWhileLoop(switchStatementAst.Label, generateCondition, switchBodyGenerator);

            return null;
        }
Example #33
0
 /// <summary/>
 public virtual AstVisitAction VisitSwitchStatement(SwitchStatementAst switchStatementAst)
 {
     return(AstVisitAction.Continue);
 }
 public override AstVisitAction VisitSwitchStatement(SwitchStatementAst switchStatementAst)
 {
     this.ReportError(switchStatementAst, () => ParserStrings.SwitchStatementNotSupportedInDataSection, new object[0]);
     return AstVisitAction.Continue;
 }
Example #35
0
 public object VisitSwitchStatement(SwitchStatementAst switchStatementAst)
 {
     return(AutomationNull.Value);
 }
 public object VisitSwitchStatement(SwitchStatementAst switchStatementAst)
 {
     throw new NotImplementedException();
 }