Exemplo n.º 1
0
        public override AstVisitAction VisitPipeline(PipelineAst pipelineAst)
        {
            if (pipelineAst.PipelineElements[0] is CommandExpressionAst)
            {
                // If the first element is a CommandExpression, this pipeline should be the value
                // of a parameter. We want to avoid a scriptblock that contains only a pure expression.
                // The check "pipelineAst.Parent.Parent == ScriptBeingConverted" guarantees we throw
                // error on that kind of scriptblock.

                // Disallow pure expressions at the "top" level, but allow them otherwise.
                // We want to catch:
                //     1 | echo
                // But we don't want to error out on:
                //     echo $(1)
                // See the comment in VisitCommand on why it's safe to check Parent.Parent, we
                // know that we have at least:
                //     * a NamedBlockAst (the end block)
                //     * a ScriptBlockAst (the ast we're comparing to)
                if (pipelineAst.GetPureExpression() == null || pipelineAst.Parent.Parent == ScriptBeingConverted)
                {
                    ThrowError(
                        new ScriptBlockToPowerShellNotSupportedException(
                            "CantConvertPipelineStartsWithExpression", null,
                            AutomationExceptions.CantConvertPipelineStartsWithExpression),
                        pipelineAst);
                }
            }

            return AstVisitAction.Continue;
        }
 public override AstVisitAction VisitPipeline(PipelineAst pipelineAst)
 {
     if ((pipelineAst.PipelineElements[0] is CommandExpressionAst) && ((pipelineAst.GetPureExpression() == null) || (pipelineAst.Parent.Parent == this.ScriptBeingConverted)))
     {
         ThrowError(new ScriptBlockToPowerShellNotSupportedException("CantConvertPipelineStartsWithExpression", null, AutomationExceptions.CantConvertPipelineStartsWithExpression, new object[0]), pipelineAst);
     }
     return AstVisitAction.Continue;
 }
 public object VisitPipeline(PipelineAst pipelineAst)
 {
     var expr = pipelineAst.GetPureExpression();
     if (expr != null)
     {
         return expr.Visit(this);
     }
     throw new UnexpectedElementException();
 }
Exemplo n.º 4
0
    public System.Object VisitPipeline(System.Management.Automation.Language.PipelineAst pipelineAst)
    {
        IScriptExtent mappedExtent = MapExtent(pipelineAst.Extent);

        LinkedList <CommandBaseAst> mappedPipelineElements = new LinkedList <CommandBaseAst>();

        foreach (CommandBaseAst cb in pipelineAst.PipelineElements)
        {
            mappedPipelineElements.AddLast(_VisitCommandBase(cb));
        }

        return(new PipelineAst(mappedExtent, mappedPipelineElements));
    }
        public override AstVisitAction VisitPipeline(PipelineAst pipelineAst)
        {
            if (this.lineNumber == pipelineAst.Extent.StartLineNumber)
            {
                // Which command is the cursor in?
                foreach (var commandAst in pipelineAst.PipelineElements.OfType<CommandAst>())
                {
                    int trueEndColumnNumber = commandAst.Extent.EndColumnNumber;
                    string currentLine = commandAst.Extent.StartScriptPosition.Line;

                    if (currentLine.Length >= trueEndColumnNumber)
                    {
                        // Get the text left in the line after the command's extent
                        string remainingLine = 
                            currentLine.Substring(
                                commandAst.Extent.EndColumnNumber);

                        // Calculate the "true" end column number by finding out how many
                        // whitespace characters are between this command and the next (or
                        // the end of the line).
                        // NOTE: +1 is added to trueEndColumnNumber to account for the position
                        // just after the last character in the command string or script line.
                        int preTrimLength = remainingLine.Length;
                        int postTrimLength = remainingLine.TrimStart().Length;
                        trueEndColumnNumber = 
                            commandAst.Extent.EndColumnNumber + 
                            (preTrimLength - postTrimLength) + 1;
                    }

                    if (commandAst.Extent.StartColumnNumber <= columnNumber &&
                        trueEndColumnNumber >= columnNumber)
                    {
                        this.FoundCommandReference =
                            new SymbolReference(
                                SymbolType.Function,
                                commandAst.CommandElements[0].Extent);

                        return AstVisitAction.StopVisit;
                    }
                }
            }

            return base.VisitPipeline(pipelineAst);
        }
Exemplo n.º 6
0
 public override AstVisitAction VisitPipeline(PipelineAst ast) { return CheckParent(ast); }
Exemplo n.º 7
0
 /// <summary/>
 public virtual object VisitPipeline(PipelineAst pipelineAst)
 {
     return(null);
 }
Exemplo n.º 8
0
 public object VisitPipeline(PipelineAst pipelineAst)
 {
     bool flag = false;
     foreach (CommandBaseAst ast in pipelineAst.PipelineElements)
     {
         ast.Accept(this);
         if (ast is CommandAst)
         {
             flag = true;
         }
         foreach (RedirectionAst ast2 in ast.Redirections)
         {
             ast2.Accept(this);
         }
     }
     if (flag && this._loopTargets.Any<LoopGotoTargets>())
     {
         foreach (LoopGotoTargets targets in this._loopTargets)
         {
             this._currentBlock.FlowsTo(targets.BreakTarget);
             this._currentBlock.FlowsTo(targets.ContinueTarget);
         }
         Block next = new Block();
         this._currentBlock.FlowsTo(next);
         this._currentBlock = next;
     }
     return null;
 }
 /// <summary/>
 public virtual object VisitPipeline(PipelineAst pipelineAst)
 {
     return _decorated.VisitPipeline(pipelineAst);
 }
Exemplo n.º 10
0
        public object VisitPipeline(PipelineAst pipelineAst)
        {
            var temps = new List<ParameterExpression>();
            var exprs = new List<Expression>();

            if (!(pipelineAst.Parent is AssignmentStatementAst || pipelineAst.Parent is ParenExpressionAst))
            {
                // If the parent is an assignment, we've already added a sequence point, don't add another.
                exprs.Add(UpdatePosition(pipelineAst));
            }

            var pipeElements = pipelineAst.PipelineElements;
            var firstCommandExpr = (pipeElements[0] as CommandExpressionAst);
            if (firstCommandExpr != null && pipeElements.Count == 1)
            {
                if (firstCommandExpr.Redirections.Count > 0)
                {
                    exprs.Add(GetRedirectedExpression(firstCommandExpr, captureForInput: false));
                }
                else
                {
                    exprs.Add(Compile(firstCommandExpr));
                }
            }
            else
            {
                Expression input;
                int i, commandsInPipe;

                if (firstCommandExpr != null)
                {
                    if (firstCommandExpr.Redirections.Count > 0)
                    {
                        input = GetRedirectedExpression(firstCommandExpr, captureForInput: true);
                    }
                    else
                    {
                        input = GetRangeEnumerator(firstCommandExpr.Expression) ??
                                Compile(firstCommandExpr.Expression);
                    }
                    i = 1;
                    commandsInPipe = pipeElements.Count - 1;
                }
                else
                {
                    // Compiled code normally never sees AutomationNull.  We use that value
                    // here so that we can tell the difference b/w $null and no input when
                    // starting the pipeline, in other words, PipelineOps.InvokePipe will
                    // not pass this value to the pipe.

                    input = ExpressionCache.AutomationNullConstant;
                    i = 0;
                    commandsInPipe = pipeElements.Count;
                }
                Expression[] pipelineExprs = new Expression[commandsInPipe];
                CommandBaseAst[] pipeElementAsts = new CommandBaseAst[commandsInPipe];
                var commandRedirections = new object[commandsInPipe];

                for (int j = 0; i < pipeElements.Count; ++i, ++j)
                {
                    var pipeElement = pipeElements[i];
                    pipelineExprs[j] = Compile(pipeElement);

                    commandRedirections[j] = GetCommandRedirections(pipeElement);
                    pipeElementAsts[j] = pipeElement;
                }

                // The redirections are passed as a CommandRedirection[][] - one dimension for each command in the pipe,
                // one dimension because each command may have multiple redirections.  Here we create the array for
                // each command in the pipe, either a compile time constant or created at runtime if necessary.
                Expression redirectionExpr;
                if (commandRedirections.Any(r => r is Expression))
                {
                    // If any command redirections are non-constant, commandRedirections will have a Linq.Expression in it,
                    // in which case we must create the array at runtime
                    redirectionExpr =
                        Expression.NewArrayInit(typeof(CommandRedirection[]),
                                                commandRedirections.Select(r => (r as Expression) ?? Expression.Constant(r, typeof(CommandRedirection[]))));
                }
                else if (commandRedirections.Any(r => r != null))
                {
                    // There were redirections, but all were compile time constant, so build the array at compile time.
                    redirectionExpr =
                        Expression.Constant(commandRedirections.Map(r => r as CommandRedirection[]));
                }
                else
                {
                    // No redirections.
                    redirectionExpr = ExpressionCache.NullCommandRedirections;
                }

                if (firstCommandExpr != null)
                {
                    var inputTemp = Expression.Variable(input.Type);
                    temps.Add(inputTemp);
                    exprs.Add(Expression.Assign(inputTemp, input));
                    input = inputTemp;
                }

                Expression invokePipe = Expression.Call(
                    CachedReflectionInfo.PipelineOps_InvokePipeline,
                    input.Cast(typeof(object)),
                    firstCommandExpr != null ? ExpressionCache.FalseConstant : ExpressionCache.TrueConstant,
                    Expression.NewArrayInit(typeof(CommandParameterInternal[]), pipelineExprs),
                    Expression.Constant(pipeElementAsts),
                    redirectionExpr,
                    _functionContext);

                exprs.Add(invokePipe);
            }

            return Expression.Block(temps, exprs);
        }
Exemplo n.º 11
0
 internal static SteppablePipeline GetSteppablePipeline(PipelineAst pipelineAst, CommandOrigin commandOrigin)
 {
     PipelineProcessor pipe = new PipelineProcessor();
     System.Management.Automation.ExecutionContext executionContextFromTLS = LocalPipeline.GetExecutionContextFromTLS();
     foreach (CommandAst ast in pipelineAst.PipelineElements.Cast<CommandAst>())
     {
         List<CommandParameterInternal> list = new List<CommandParameterInternal>();
         foreach (CommandElementAst ast2 in ast.CommandElements)
         {
             CommandParameterAst commandParameterAst = ast2 as CommandParameterAst;
             if (commandParameterAst != null)
             {
                 list.Add(GetCommandParameter(commandParameterAst, executionContextFromTLS));
             }
             else
             {
                 ExpressionAst expressionAst = (ExpressionAst) ast2;
                 object obj2 = Compiler.GetExpressionValue(expressionAst, executionContextFromTLS, (IList)null);
                 bool splatted = (expressionAst is VariableExpressionAst) && ((VariableExpressionAst) expressionAst).Splatted;
                 list.Add(CommandParameterInternal.CreateArgument(expressionAst.Extent, obj2, splatted));
             }
         }
         List<CommandRedirection> list2 = new List<CommandRedirection>();
         foreach (RedirectionAst ast5 in ast.Redirections)
         {
             list2.Add(GetCommandRedirection(ast5, executionContextFromTLS));
         }
         CommandProcessorBase base2 = AddCommand(pipe, list.ToArray(), ast, list2.ToArray(), executionContextFromTLS);
         base2.Command.CommandOriginInternal = commandOrigin;
         base2.CommandScope.ScopeOrigin = commandOrigin;
         base2.Command.MyInvocation.CommandOrigin = commandOrigin;
         CallStackFrame[] frameArray = executionContextFromTLS.Debugger.GetCallStack().ToArray<CallStackFrame>();
         if ((frameArray.Length > 0) && Regex.IsMatch(frameArray[0].Position.Text, "GetSteppablePipeline", RegexOptions.IgnoreCase))
         {
             InvocationInfo myInvocation = base2.Command.MyInvocation;
             myInvocation.InvocationName = frameArray[0].InvocationInfo.InvocationName;
             if (frameArray.Length > 1)
             {
                 IScriptExtent position = frameArray[1].Position;
                 if ((position != null) && (position != PositionUtilities.EmptyExtent))
                 {
                     myInvocation.DisplayScriptPosition = position;
                 }
             }
         }
         if ((executionContextFromTLS.CurrentCommandProcessor != null) && (executionContextFromTLS.CurrentCommandProcessor.CommandRuntime != null))
         {
             base2.CommandRuntime.SetMergeFromRuntime(executionContextFromTLS.CurrentCommandProcessor.CommandRuntime);
         }
     }
     return new SteppablePipeline(executionContextFromTLS, pipe);
 }
Exemplo n.º 12
0
 private StatementAst SwitchStatementRule(LabelToken labelToken, Token switchToken)
 {
     IScriptExtent extent = null;
     Token token;
     string labelText;
     IEnumerable<Ast> nestedErrorAsts;
     LabelToken labelToken1 = labelToken;
     Token token1 = labelToken1;
     if (labelToken1 == null)
     {
         token1 = switchToken;
     }
     IScriptExtent scriptExtent = token1.Extent;
     bool flag = false;
     bool flag1 = false;
     this.SkipNewlines();
     bool flag2 = false;
     PipelineBaseAst pipelineAst = null;
     Dictionary<string, Tuple<Token, Ast>> strs = null;
     Token token2 = this.PeekToken();
     SwitchFlags switchFlag = SwitchFlags.None;
     while (token2.Kind == TokenKind.Parameter)
     {
         this.SkipToken();
         extent = token2.Extent;
         Dictionary<string, Tuple<Token, Ast>> strs1 = strs;
         Dictionary<string, Tuple<Token, Ast>> strs2 = strs1;
         if (strs1 == null)
         {
             strs2 = new Dictionary<string, Tuple<Token, Ast>>();
         }
         strs = strs2;
         if (!Parser.IsSpecificParameter(token2, "regex"))
         {
             if (!Parser.IsSpecificParameter(token2, "wildcard"))
             {
                 if (!Parser.IsSpecificParameter(token2, "exact"))
                 {
                     if (!Parser.IsSpecificParameter(token2, "casesensitive"))
                     {
                         if (!Parser.IsSpecificParameter(token2, "parallel"))
                         {
                             if (!Parser.IsSpecificParameter(token2, "file"))
                             {
                                 flag = true;
                                 object[] parameterName = new object[1];
                                 parameterName[0] = ((ParameterToken)token2).ParameterName;
                                 this.ReportError(token2.Extent, ParserStrings.InvalidSwitchFlag, parameterName);
                             }
                             else
                             {
                                 switchFlag = switchFlag | SwitchFlags.File;
                                 this.SkipNewlines();
                                 ExpressionAst singleCommandArgument = this.GetSingleCommandArgument(Parser.CommandArgumentContext.FileName);
                                 if (singleCommandArgument != null)
                                 {
                                     extent = singleCommandArgument.Extent;
                                     pipelineAst = new PipelineAst(singleCommandArgument.Extent, new CommandExpressionAst(singleCommandArgument.Extent, singleCommandArgument, null));
                                     if (!strs.ContainsKey("file"))
                                     {
                                         strs.Add("file", new Tuple<Token, Ast>(token2, pipelineAst));
                                     }
                                 }
                                 else
                                 {
                                     flag = true;
                                     flag1 = this.ReportIncompleteInput(Parser.After(token2), ParserStrings.MissingFilenameOption, new object[0]);
                                     if (!strs.ContainsKey("file"))
                                     {
                                         strs.Add("file", new Tuple<Token, Ast>(token2, null));
                                     }
                                 }
                             }
                         }
                         else
                         {
                             switchFlag = switchFlag | SwitchFlags.Parallel;
                             if (!strs.ContainsKey("parallel"))
                             {
                                 strs.Add("parallel", new Tuple<Token, Ast>(token2, null));
                             }
                         }
                     }
                     else
                     {
                         switchFlag = switchFlag | SwitchFlags.CaseSensitive;
                         if (!strs.ContainsKey("casesensitive"))
                         {
                             strs.Add("casesensitive", new Tuple<Token, Ast>(token2, null));
                         }
                     }
                 }
                 else
                 {
                     switchFlag = switchFlag & (SwitchFlags.File | SwitchFlags.Wildcard | SwitchFlags.Exact | SwitchFlags.CaseSensitive | SwitchFlags.Parallel);
                     switchFlag = switchFlag & (SwitchFlags.File | SwitchFlags.Regex | SwitchFlags.Exact | SwitchFlags.CaseSensitive | SwitchFlags.Parallel);
                     if (!strs.ContainsKey("exact"))
                     {
                         strs.Add("exact", new Tuple<Token, Ast>(token2, null));
                     }
                 }
             }
             else
             {
                 switchFlag = switchFlag | SwitchFlags.Wildcard;
                 switchFlag = switchFlag & (SwitchFlags.File | SwitchFlags.Wildcard | SwitchFlags.Exact | SwitchFlags.CaseSensitive | SwitchFlags.Parallel);
                 if (!strs.ContainsKey("wildcard"))
                 {
                     strs.Add("wildcard", new Tuple<Token, Ast>(token2, null));
                 }
             }
         }
         else
         {
             switchFlag = switchFlag | SwitchFlags.Regex;
             switchFlag = switchFlag & (SwitchFlags.File | SwitchFlags.Regex | SwitchFlags.Exact | SwitchFlags.CaseSensitive | SwitchFlags.Parallel);
             if (!strs.ContainsKey("regex"))
             {
                 strs.Add("regex", new Tuple<Token, Ast>(token2, null));
             }
         }
         token2 = this.PeekToken();
     }
     if (token2.Kind == TokenKind.Minus)
     {
         Dictionary<string, Tuple<Token, Ast>> strs3 = strs;
         Dictionary<string, Tuple<Token, Ast>> strs4 = strs3;
         if (strs3 == null)
         {
             strs4 = new Dictionary<string, Tuple<Token, Ast>>();
         }
         strs = strs4;
         strs.Add("--%", new Tuple<Token, Ast>(token2, null));
     }
     Token token3 = this.PeekToken();
     if (token3.Kind != TokenKind.LParen)
     {
         if (pipelineAst == null && (switchFlag & SwitchFlags.File) == SwitchFlags.None)
         {
             flag = true;
             flag1 = this.ReportIncompleteInput(Parser.After(extent), ParserStrings.PipelineValueRequired, new object[0]);
         }
     }
     else
     {
         extent = token3.Extent;
         this.SkipToken();
         if ((switchFlag & SwitchFlags.File) == SwitchFlags.File)
         {
             flag = true;
             this.ReportError(token3.Extent, ParserStrings.PipelineValueRequired, new object[0]);
         }
         flag2 = true;
         this.SkipNewlines();
         pipelineAst = this.PipelineRule();
         if (pipelineAst != null)
         {
             extent = pipelineAst.Extent;
         }
         else
         {
             flag = true;
             flag1 = this.ReportIncompleteInput(Parser.After(token3), ParserStrings.PipelineValueRequired, new object[0]);
         }
         this.SkipNewlines();
         Token token4 = this.NextToken();
         if (token4.Kind == TokenKind.RParen)
         {
             extent = token4.Extent;
         }
         else
         {
             this.UngetToken(token4);
             if (!flag1)
             {
                 flag = true;
                 flag1 = this.ReportIncompleteInput(Parser.After(extent), ParserStrings.MissingEndParenthesisInSwitchStatement, new object[0]);
             }
         }
     }
     this.SkipNewlines();
     Token token5 = this.NextToken();
     StatementBlockAst statementBlockAst = null;
     List<Tuple<ExpressionAst, StatementBlockAst>> tuples = new List<Tuple<ExpressionAst, StatementBlockAst>>();
     List<Ast> asts = new List<Ast>();
     Token token6 = null;
     if (token5.Kind == TokenKind.LCurly)
     {
         extent = token5.Extent;
         this.SkipNewlines();
         do
         {
             ExpressionAst expressionAst = this.GetSingleCommandArgument(Parser.CommandArgumentContext.SwitchCondition);
             if (expressionAst != null)
             {
                 asts.Add(expressionAst);
                 extent = expressionAst.Extent;
                 StatementBlockAst statementBlockAst1 = this.StatementBlockRule();
                 if (statementBlockAst1 != null)
                 {
                     asts.Add(statementBlockAst1);
                     extent = statementBlockAst1.Extent;
                     StringConstantExpressionAst stringConstantExpressionAst = expressionAst as StringConstantExpressionAst;
                     if (stringConstantExpressionAst == null || stringConstantExpressionAst.StringConstantType != StringConstantType.BareWord || !stringConstantExpressionAst.Value.Equals("default", StringComparison.OrdinalIgnoreCase))
                     {
                         tuples.Add(new Tuple<ExpressionAst, StatementBlockAst>(expressionAst, statementBlockAst1));
                     }
                     else
                     {
                         if (statementBlockAst != null)
                         {
                             flag = true;
                             this.ReportError(expressionAst.Extent, ParserStrings.MultipleSwitchDefaultClauses, new object[0]);
                         }
                         statementBlockAst = statementBlockAst1;
                     }
                 }
                 else
                 {
                     flag = true;
                     flag1 = this.ReportIncompleteInput(Parser.After(extent), ParserStrings.MissingSwitchStatementClause, new object[0]);
                 }
                 this.SkipNewlinesAndSemicolons();
                 token = this.PeekToken();
                 if (token.Kind != TokenKind.RCurly)
                 {
                     continue;
                 }
                 token6 = token;
                 this.SkipToken();
                 goto Label0;
             }
             else
             {
                 flag = true;
                 this.ReportIncompleteInput(Parser.After(extent), ParserStrings.MissingSwitchConditionExpression, new object[0]);
                 if (this.PeekToken().Kind != TokenKind.RCurly)
                 {
                     goto Label0;
                 }
                 this.SkipToken();
                 goto Label0;
             }
         }
         while (token.Kind != TokenKind.EndOfInput);
         if (!flag1)
         {
             flag = true;
             this.ReportIncompleteInput(token5.Extent, token.Extent, ParserStrings.MissingEndCurlyBrace, new object[0]);
         }
     }
     else
     {
         this.UngetToken(token5);
         if (!flag1)
         {
             flag = true;
             this.ReportIncompleteInput(Parser.After(extent), ParserStrings.MissingCurlyBraceInSwitchStatement, new object[0]);
         }
     }
 Label0:
     if (!flag)
     {
         LabelToken labelToken2 = labelToken;
         Token token7 = labelToken2;
         if (labelToken2 == null)
         {
             token7 = switchToken;
         }
         IScriptExtent scriptExtent1 = Parser.ExtentOf(token7, token6);
         if (labelToken != null)
         {
             labelText = labelToken.LabelText;
         }
         else
         {
             labelText = null;
         }
         return new SwitchStatementAst(scriptExtent1, labelText, pipelineAst, switchFlag, tuples, statementBlockAst);
     }
     else
     {
         IScriptExtent scriptExtent2 = Parser.ExtentOf(scriptExtent, extent);
         Token token8 = switchToken;
         Dictionary<string, Tuple<Token, Ast>> strs5 = strs;
         if (flag2)
         {
             object[] objArray = new object[1];
             objArray[0] = pipelineAst;
             nestedErrorAsts = Parser.GetNestedErrorAsts(objArray);
         }
         else
         {
             nestedErrorAsts = null;
         }
         object[] objArray1 = new object[1];
         objArray1[0] = asts;
         return new ErrorStatementAst(scriptExtent2, token8, strs5, nestedErrorAsts, Parser.GetNestedErrorAsts(objArray1));
     }
 }
Exemplo n.º 13
0
 public object VisitPipeline(PipelineAst pipelineAst)
 {
     var expr = pipelineAst.GetPureExpression();
     if (expr != null)
     {
         return expr.Accept(this);
     }
     throw PSTraceSource.NewArgumentException("ast");
 }
Exemplo n.º 14
0
        public object VisitPipeline(PipelineAst pipelineAst)
        {
            var expr = pipelineAst.GetPureExpression();

            return(expr != null && (bool)expr.Accept(this));
        }
Exemplo n.º 15
0
 public object VisitPipeline(PipelineAst pipelineAst)
 {
     CheckIsConstant(pipelineAst, "Caller to verify ast is constant");
     return(pipelineAst.GetPureExpression().Accept(this));
 }
Exemplo n.º 16
0
 /// <summary/>
 public virtual AstVisitAction VisitPipeline(PipelineAst pipelineAst) => DefaultVisit(pipelineAst);
Exemplo n.º 17
0
        internal override IEnumerable <PSTypeName> GetInferredType(CompletionContext context)
        {
            if (this.VariablePath.IsVariable)
            {
                Ast parent = this.Parent;
                if (this.VariablePath.IsUnqualified && (this.VariablePath.UserPath.Equals("_", StringComparison.Ordinal) || this.VariablePath.UserPath.Equals("PSItem", StringComparison.OrdinalIgnoreCase)))
                {
                    while (parent != null)
                    {
                        if (parent is ScriptBlockExpressionAst)
                        {
                            break;
                        }
                        parent = parent.Parent;
                    }
                    if (parent != null)
                    {
                        if ((parent.Parent is CommandExpressionAst) && (parent.Parent.Parent is PipelineAst))
                        {
                            if (parent.Parent.Parent.Parent is HashtableAst)
                            {
                                parent = parent.Parent.Parent.Parent;
                            }
                            else if ((parent.Parent.Parent.Parent is ArrayLiteralAst) && (parent.Parent.Parent.Parent.Parent is HashtableAst))
                            {
                                parent = parent.Parent.Parent.Parent.Parent;
                            }
                        }
                        if (parent.Parent is CommandParameterAst)
                        {
                            parent = parent.Parent;
                        }
                        CommandAst iteratorVariable1 = parent.Parent as CommandAst;
                        if (iteratorVariable1 != null)
                        {
                            PipelineAst iteratorVariable2 = (PipelineAst)iteratorVariable1.Parent;
                            int         iteratorVariable3 = iteratorVariable2.PipelineElements.IndexOf(iteratorVariable1) - 1;
                            if (iteratorVariable3 >= 0)
                            {
                                foreach (PSTypeName iteratorVariable4 in iteratorVariable2.PipelineElements[0].GetInferredType(context))
                                {
                                    if (iteratorVariable4.Type != null)
                                    {
                                        if (iteratorVariable4.Type.IsArray)
                                        {
                                            yield return(new PSTypeName(iteratorVariable4.Type.GetElementType()));

                                            continue;
                                        }
                                        if (typeof(IEnumerable).IsAssignableFrom(iteratorVariable4.Type))
                                        {
                                            IEnumerable <Type> iteratorVariable5 = from t in iteratorVariable4.Type.GetInterfaces()
                                                                                   where t.IsGenericType && t.GetGenericTypeDefinition().Equals(typeof(IEnumerable <>))
                                                                                   select t;
                                            foreach (Type iteratorVariable6 in iteratorVariable5)
                                            {
                                                yield return(new PSTypeName(iteratorVariable6.GetGenericArguments()[0]));
                                            }
                                            continue;
                                        }
                                    }
                                    yield return(iteratorVariable4);
                                }
                            }
                            goto Label_0833;
                        }
                    }
                }
                if (this.VariablePath.IsUnqualified)
                {
                    for (int i = 0; i < SpecialVariables.AutomaticVariables.Length; i++)
                    {
                        if (this.VariablePath.UserPath.Equals(SpecialVariables.AutomaticVariables[i], StringComparison.OrdinalIgnoreCase))
                        {
                            Type type = SpecialVariables.AutomaticVariableTypes[i];
                            if (!type.Equals(typeof(object)))
                            {
                                yield return(new PSTypeName(type));

                                break;
                            }
                            break;
                        }
                    }
                }
                while (parent.Parent != null)
                {
                    parent = parent.Parent;
                }
                if (parent.Parent is FunctionDefinitionAst)
                {
                    parent = parent.Parent;
                }
                IEnumerable <Ast> source             = AstSearcher.FindAll(parent, ast => (((ast is ParameterAst) || (ast is AssignmentStatementAst)) || (ast is ForEachStatementAst)) && this.AstAssignsToSameVariable(ast), true);
                ParameterAst      iteratorVariable10 = source.OfType <ParameterAst>().FirstOrDefault <ParameterAst>();
                if (iteratorVariable10 != null)
                {
                    PSTypeName[] iteratorVariable11 = iteratorVariable10.GetInferredType(context).ToArray <PSTypeName>();
                    if (iteratorVariable11.Length > 0)
                    {
                        foreach (PSTypeName iteratorVariable12 in iteratorVariable11)
                        {
                            yield return(iteratorVariable12);
                        }
                        goto Label_0833;
                    }
                }
                AssignmentStatementAst[] iteratorVariable13 = source.OfType <AssignmentStatementAst>().ToArray <AssignmentStatementAst>();
                foreach (AssignmentStatementAst iteratorVariable14 in iteratorVariable13)
                {
                    ConvertExpressionAst left = iteratorVariable14.Left as ConvertExpressionAst;
                    if ((left != null) && (left.StaticType != null))
                    {
                        yield return(new PSTypeName(left.StaticType));

                        goto Label_0833;
                    }
                }
                ForEachStatementAst iteratorVariable16 = source.OfType <ForEachStatementAst>().FirstOrDefault <ForEachStatementAst>();
                if (iteratorVariable16 != null)
                {
                    foreach (PSTypeName iteratorVariable17 in iteratorVariable16.Condition.GetInferredType(context))
                    {
                        yield return(iteratorVariable17);
                    }
                }
                else
                {
                    int startOffset        = this.Extent.StartOffset;
                    int iteratorVariable19 = 0x7fffffff;
                    AssignmentStatementAst iteratorVariable20 = null;
                    foreach (AssignmentStatementAst ast in iteratorVariable13)
                    {
                        int endOffset = ast.Extent.EndOffset;
                        if ((endOffset < startOffset) && ((startOffset - endOffset) < iteratorVariable19))
                        {
                            iteratorVariable19 = startOffset - endOffset;
                            iteratorVariable20 = ast;
                        }
                    }
                    if (iteratorVariable20 != null)
                    {
                        foreach (PSTypeName iteratorVariable21 in iteratorVariable20.Right.GetInferredType(context))
                        {
                            yield return(iteratorVariable21);
                        }
                    }
                }
            }
Label_0833:
            yield break;
        }
Exemplo n.º 18
0
 public override AstVisitAction VisitPipeline(PipelineAst ast)
 {
     return(Check(ast));
 }
Exemplo n.º 19
0
 public object VisitPipeline(PipelineAst pipelineAst)
 {
     CheckIsConstant(pipelineAst, "Caller to verify ast is constant");
     return pipelineAst.GetPureExpression().Accept(this);
 }
Exemplo n.º 20
0
 public object VisitPipeline(PipelineAst pipelineAst)
 {
     List<ParameterExpression> list = new List<ParameterExpression>();
     List<Expression> list2 = new List<Expression>();
     if (!(pipelineAst.Parent is AssignmentStatementAst) && !(pipelineAst.Parent is ParenExpressionAst))
     {
         list2.Add(this.UpdatePosition(pipelineAst));
     }
     ReadOnlyCollection<CommandBaseAst> pipelineElements = pipelineAst.PipelineElements;
     CommandExpressionAst commandExpr = pipelineElements[0] as CommandExpressionAst;
     if ((commandExpr != null) && (pipelineElements.Count == 1))
     {
         if (commandExpr.Redirections.Count > 0)
         {
             return this.GetRedirectedExpression(commandExpr, false);
         }
         list2.Add(this.Compile(commandExpr));
     }
     else
     {
         Expression redirectedExpression;
         int num;
         int count;
         Expression nullCommandRedirections;
         if (commandExpr != null)
         {
             if (commandExpr.Redirections.Count > 0)
             {
                 redirectedExpression = this.GetRedirectedExpression(commandExpr, true);
             }
             else
             {
                 redirectedExpression = this.GetRangeEnumerator(commandExpr.Expression) ?? this.Compile(commandExpr.Expression);
             }
             num = 1;
             count = pipelineElements.Count - 1;
         }
         else
         {
             redirectedExpression = ExpressionCache.AutomationNullConstant;
             num = 0;
             count = pipelineElements.Count;
         }
         Expression[] initializers = new Expression[count];
         CommandBaseAst[] astArray = new CommandBaseAst[count];
         object[] array = new object[count];
         for (int i = 0; num < pipelineElements.Count; i++)
         {
             CommandBaseAst ast = pipelineElements[num];
             initializers[i] = this.Compile(ast);
             array[i] = this.GetCommandRedirections(ast);
             astArray[i] = ast;
             num++;
         }
         if ((from r in array
             where r is Expression
             select r).Any<object>())
         {
             nullCommandRedirections = Expression.NewArrayInit(typeof(CommandRedirection[]), (IEnumerable<Expression>) (from r in array select (r as Expression) ?? Expression.Constant(r, typeof(CommandRedirection[]))));
         }
         else if ((from r in array
             where r != null
             select r).Any<object>())
         {
             nullCommandRedirections = Expression.Constant(Array.ConvertAll<object, CommandRedirection[]>(array, r => r as CommandRedirection[]));
         }
         else
         {
             nullCommandRedirections = ExpressionCache.NullCommandRedirections;
         }
         if (commandExpr != null)
         {
             ParameterExpression expression3 = Expression.Variable(redirectedExpression.Type);
             list.Add(expression3);
             list2.Add(Expression.Assign(expression3, redirectedExpression));
             redirectedExpression = expression3;
         }
         Expression item = Expression.Call(CachedReflectionInfo.PipelineOps_InvokePipeline, new Expression[] { redirectedExpression.Cast(typeof(object)), (commandExpr != null) ? ExpressionCache.FalseConstant : ExpressionCache.TrueConstant, Expression.NewArrayInit(typeof(CommandParameterInternal[]), initializers), Expression.Constant(astArray), nullCommandRedirections, _functionContext });
         list2.Add(item);
     }
     return Expression.Block((IEnumerable<ParameterExpression>) list, (IEnumerable<Expression>) list2);
 }
Exemplo n.º 21
0
 public object VisitPipeline(PipelineAst pipelineAst)
 {
     var expr = pipelineAst.GetPureExpression();
     return expr != null && (bool)expr.Accept(this);
 }
Exemplo n.º 22
0
        private StatementAst SwitchStatementRule(LabelToken labelToken, Token switchToken)
        {
            //G  switch-statement:
            //G      'switch'   new-lines:opt   switch-parameters:opt   switch-condition   switch-body
            //G  switch-parameters:
            //G      switch-parameter
            //G      switch-parameters   switch-parameter
            //G  switch-parameter:
            //G      '-regex'
            //G      '-wildcard'
            //G      '-exact'
            //G      '-casesensitive'
            //G      '-parallel'
            //G  switch-condition:
            //G      '('   new-lines:opt   pipeline   new-lines:opt   ')'
            //G      -file   new-lines:opt   switch-filename
            //G  switch-filename:
            //G      command-argument
            //G      primary-expression
            //G  switch-body:
            //G      new-lines:opt   '{'   new-lines:opt   switch-clauses   '}'
            //G  switch-clauses:
            //G      switch-clause
            //G      switch-clauses   switch-clause
            //G  switch-clause:
            //G      switch-clause-condition   statement-block   statement-terminators:opt
            //G  switch-clause-condition:
            //G      command-argument
            //G      primary-expression

            IScriptExtent startExtent = (labelToken ?? switchToken).Extent;
            IScriptExtent endErrorStatement = startExtent;
            bool isError = false;
            bool isIncompleteError = false;

            SkipNewlines();

            bool needErrorCondition = false; // Only used to track if we need to include (condition) ast for the error statement.
            PipelineBaseAst condition = null;
            Dictionary<string, Tuple<Token, Ast>> specifiedFlags = null; // Only used to track all flags specified for the error ast

            Token switchParameterToken = PeekToken();
            SwitchFlags flags = SwitchFlags.None;
            while (switchParameterToken.Kind == TokenKind.Parameter)
            {
                SkipToken();
                endErrorStatement = switchParameterToken.Extent;
                specifiedFlags = specifiedFlags ?? new Dictionary<string, Tuple<Token, Ast>>();

                if (IsSpecificParameter(switchParameterToken, "regex"))
                {
                    flags |= SwitchFlags.Regex;
                    flags &= ~SwitchFlags.Wildcard;

                    if (!specifiedFlags.ContainsKey("regex"))
                    {
                        specifiedFlags.Add("regex", new Tuple<Token, Ast>(switchParameterToken, null));
                    }
                }
                else if (IsSpecificParameter(switchParameterToken, "wildcard"))
                {
                    flags |= SwitchFlags.Wildcard;
                    flags &= ~SwitchFlags.Regex;

                    if (!specifiedFlags.ContainsKey("wildcard"))
                    {
                        specifiedFlags.Add("wildcard", new Tuple<Token, Ast>(switchParameterToken, null));
                    }
                }
                else if (IsSpecificParameter(switchParameterToken, "exact"))
                {
                    flags &= ~SwitchFlags.Regex;
                    flags &= ~SwitchFlags.Wildcard;

                    if (!specifiedFlags.ContainsKey("exact"))
                    {
                        specifiedFlags.Add("exact", new Tuple<Token, Ast>(switchParameterToken, null));
                    }
                }
                else if (IsSpecificParameter(switchParameterToken, "casesensitive"))
                {
                    flags |= SwitchFlags.CaseSensitive;

                    if (!specifiedFlags.ContainsKey("casesensitive"))
                    {
                        specifiedFlags.Add("casesensitive", new Tuple<Token, Ast>(switchParameterToken, null));
                    }
                }
                else if (IsSpecificParameter(switchParameterToken, "parallel"))
                {
                    flags |= SwitchFlags.Parallel;

                    if (!specifiedFlags.ContainsKey("parallel"))
                    {
                        specifiedFlags.Add("parallel", new Tuple<Token, Ast>(switchParameterToken, null));
                    }
                }
                else if (IsSpecificParameter(switchParameterToken, "file"))
                {
                    flags |= SwitchFlags.File;
                    SkipNewlines();
                    ExpressionAst fileNameExpr = GetSingleCommandArgument(CommandArgumentContext.FileName);
                    if (fileNameExpr == null)
                    {
                        // ErrorRecovery: pretend we saw the filename and continue.

                        isError = true;
                        isIncompleteError = ReportIncompleteInput(After(switchParameterToken), () => ParserStrings.MissingFilenameOption);

                        if (!specifiedFlags.ContainsKey("file"))
                        {
                            specifiedFlags.Add("file", new Tuple<Token, Ast>(switchParameterToken, null));
                        }
                    }
                    else
                    {
                        endErrorStatement = fileNameExpr.Extent;
                        condition = new PipelineAst(fileNameExpr.Extent,
                                                    new CommandExpressionAst(fileNameExpr.Extent, fileNameExpr, null));

                        if (!specifiedFlags.ContainsKey("file"))
                        {
                            specifiedFlags.Add("file", new Tuple<Token, Ast>(switchParameterToken, condition));
                        }
                    }
                }
                else
                {
                    // ErrorRecovery: just ignore the token, continue parsing.

                    isError = true;
                    ReportError(switchParameterToken.Extent, () => ParserStrings.InvalidSwitchFlag,
                        ((ParameterToken)switchParameterToken).ParameterName);
                }

                switchParameterToken = PeekToken();
            }

            if (switchParameterToken.Kind == TokenKind.Minus)
            {
                specifiedFlags = specifiedFlags ?? new Dictionary<string, Tuple<Token, Ast>>();
                specifiedFlags.Add(VERBATIM_ARGUMENT, new Tuple<Token, Ast>(switchParameterToken, null));
            }

            Token lParen = PeekToken();
            if (lParen.Kind == TokenKind.LParen)
            {
                endErrorStatement = lParen.Extent;
                SkipToken();

                if ((flags & SwitchFlags.File) == SwitchFlags.File)
                {
                    // ErrorRecovery: nothing special this is a semantic error.

                    isError = true;
                    ReportError(lParen.Extent, () => ParserStrings.PipelineValueRequired);
                }

                needErrorCondition = true; // need to add condition ast to the error statement if the parsing fails
                SkipNewlines();
                condition = PipelineRule();
                if (condition == null)
                {
                    // ErrorRecovery: pretend we saw the condition and keep parsing.

                    isError = true;
                    isIncompleteError = ReportIncompleteInput(After(lParen), () => ParserStrings.PipelineValueRequired);
                }
                else
                {
                    endErrorStatement = condition.Extent;
                }

                SkipNewlines();
                Token rParen = NextToken();
                if (rParen.Kind != TokenKind.RParen)
                {
                    // ErrorRecovery: Try to parse the switch body, if we don't find a body, then bail.

                    UngetToken(rParen);
                    if (!isIncompleteError)
                    {
                        isError = true;
                        isIncompleteError =
                            ReportIncompleteInput(After(endErrorStatement),
                                                  () => ParserStrings.MissingEndParenthesisInSwitchStatement);
                    }
                }
                else
                {
                    endErrorStatement = rParen.Extent;
                }
            }
            else if (condition == null)
            {
                if ((flags & SwitchFlags.File) == 0)
                {
                    isError = true;
                    isIncompleteError = ReportIncompleteInput(After(endErrorStatement),
                                                              () => ParserStrings.PipelineValueRequired);
                }
                else
                {
                    Diagnostics.Assert(isError, "An error should already have been issued");
                }
            }

            SkipNewlines();
            Token lCurly = NextToken();
            StatementBlockAst @default = null;
            List<SwitchClause> clauses = new List<SwitchClause>();
            List<Ast> errorAsts = new List<Ast>();  // in case there is an error, we want the asts parsed up to the error.
            Token rCurly = null;
            if (lCurly.Kind != TokenKind.LCurly)
            {
                // ErrorRecovery: Assume we don't have any switch body to parse.

                UngetToken(lCurly);
                if (!isIncompleteError)
                {
                    isError = true;
                    ReportIncompleteInput(After(endErrorStatement), () => ParserStrings.MissingCurlyBraceInSwitchStatement);
                }
            }
            else
            {
                endErrorStatement = lCurly.Extent;
                SkipNewlines();

                while (true)
                {
                    ExpressionAst clauseCondition = GetSingleCommandArgument(CommandArgumentContext.SwitchCondition);
                    if (clauseCondition == null)
                    {
                        // ErrorRecovery: if we don't have anything that looks like a condition, we won't
                        // find a body (because a body is just a script block, which works as a condition.)
                        // So don't look for a body, hope we find the '}' next.

                        isError = true;
                        ReportIncompleteInput(After(endErrorStatement), () => ParserStrings.MissingSwitchConditionExpression);
                        // Consume a closing curly, if there is one, to avoid an extra error
                        if (PeekToken().Kind == TokenKind.RCurly)
                        {
                            SkipToken();
                        }
                        break;
                    }
                    errorAsts.Add(clauseCondition);
                    endErrorStatement = clauseCondition.Extent;
                    StatementBlockAst clauseBody = StatementBlockRule();
                    if (clauseBody == null)
                    {
                        // ErrorRecovery: We might find another condition/body pair, so keep going.

                        isError = true;
                        isIncompleteError = ReportIncompleteInput(After(endErrorStatement),
                                                                  () => ParserStrings.MissingSwitchStatementClause);
                    }
                    else
                    {
                        errorAsts.Add(clauseBody);
                        endErrorStatement = clauseBody.Extent;

                        var clauseConditionString = clauseCondition as StringConstantExpressionAst;

                        if (clauseConditionString != null &&
                            clauseConditionString.StringConstantType == StringConstantType.BareWord &&
                            clauseConditionString.Value.Equals("default", StringComparison.OrdinalIgnoreCase))
                        {
                            if (@default != null)
                            {
                                // ErrorRecovery: just report the error and continue, forget the previous default clause.

                                isError = true;
                                ReportError(clauseCondition.Extent, () => ParserStrings.MultipleSwitchDefaultClauses);
                            }
                            @default = clauseBody;
                        }
                        else
                        {
                            clauses.Add(new SwitchClause(clauseCondition, clauseBody));
                        }
                    }
                    SkipNewlinesAndSemicolons();

                    Token token = PeekToken();
                    if (token.Kind == TokenKind.RCurly)
                    {
                        rCurly = token;
                        SkipToken();
                        break;
                    }
                    if (token.Kind == TokenKind.EndOfInput)
                    {
                        if (!isIncompleteError)
                        {
                            isError = true;
                            ReportIncompleteInput(lCurly.Extent, token.Extent, () => ParserStrings.MissingEndCurlyBrace);
                        }
                        break;
                    }
                }
            }

            if (isError)
            {
                return new ErrorStatementAst(ExtentOf(startExtent, endErrorStatement), switchToken, specifiedFlags,
                                             needErrorCondition ? GetNestedErrorAsts(condition) : null, GetNestedErrorAsts(errorAsts));
            }

            return new SwitchStatementAst(ExtentOf(labelToken ?? switchToken, rCurly),
                labelToken != null ? labelToken.LabelText : null, condition, flags, clauses, @default);
        }
 private void ConvertPipeline(PipelineAst pipelineAst)
 {
     foreach (CommandBaseAst ast in pipelineAst.PipelineElements)
     {
         this.ConvertCommand((CommandAst) ast);
     }
 }
Exemplo n.º 24
0
 /// <summary/>
 public virtual AstVisitAction VisitPipeline(PipelineAst pipelineAst)
 {
     return(AstVisitAction.Continue);
 }
Exemplo n.º 25
0
 public override AstVisitAction VisitPipeline(PipelineAst pipelineAst)
 {
     return AstVisitAction.Continue;
 }
Exemplo n.º 26
0
        public override AstVisitAction VisitPipeline(PipelineAst pipelineAst)
        {
            // A pipeline is accepted if every command in the pipeline is accepted.

            return AstVisitAction.Continue;
        }
Exemplo n.º 27
0
        public override AstVisitAction VisitPipeline(PipelineAst pipelineAst)
        {
            // shouldn't happen, but anyway
            if (!pipelineAst.PipelineElements.Any())
            {
                return AstVisitAction.SkipChildren;
            }
            // Pipeline uses global execution context, so we should set its WriteSideEffects flag, and restore it after.
            // TODO: I'm not very sure about that changing context and WriteSideEffectsToPipeline stuff
            var pipeLineContext = _context.CurrentRunspace.ExecutionContext;
            bool writeSideEffects = pipeLineContext.WriteSideEffectsToPipeline;
            try
            {
                pipeLineContext.WriteSideEffectsToPipeline = _writeSideEffectsToPipeline;
                var pipeline = _context.CurrentRunspace.CreateNestedPipeline();
                int startAt = 0; // set to 1 if first element is an expression
                int pipelineCommandCount = pipelineAst.PipelineElements.Count;

                // first element of pipeline can be an expression that needs to be evaluated
                var expression = pipelineAst.PipelineElements[0] as CommandExpressionAst;
                if (expression != null)
                {
                    // evaluate it and get results
                    var value = EvaluateAst(expression.Expression, _writeSideEffectsToPipeline);
                    // if we only have that one expression and no commands, write expression to output and return
                    if (pipelineCommandCount == 1)
                    {
                        if (value != null)
                        {
                            _pipelineCommandRuntime.WriteObject(value, true);
                        }
                        return AstVisitAction.SkipChildren;
                    }
                    // otherwise write value to input of pipeline to be processed
                    if (value != null)
                    {
                        pipeline.Input.Write(value, true);
                    }
                    startAt = 1;
                }
                else // if there was no expression we take the input of the context's input stream
                {
                    foreach (var input in _context.InputStream.Read())
                    {
                        pipeline.Input.Write(input);
                    }
                }

                // all other elements *need* to be commands (same in PS). Make that sure and add them to the pipeline
                for (int curCommand = startAt; curCommand < pipelineCommandCount; curCommand++)
                {
                    var commandAst = pipelineAst.PipelineElements[curCommand] as CommandAst;
                    if (commandAst == null)
                    {
                        throw new NotSupportedException("Invalid command in pipeline."
                            + " Only the first element of a pipeline can be an expression.");
                    }
                    var command = GetCommand(commandAst);

                    commandAst.CommandElements
                    // the first CommandElements is the command itself. The rest are parameters/arguments
                    .Skip(1)
                        .Select(ConvertCommandElementToCommandParameter)
                        .ForEach(command.Parameters.Add);

                    pipeline.Commands.Add(command);
                }

                // now execute the pipeline
                _context.PushPipeline(pipeline);
                try
                {
                    var results = pipeline.Invoke();
                    // read output and error and write them as results of the current commandRuntime
                    foreach (var curResult in results)
                    {
                        _pipelineCommandRuntime.WriteObject(curResult);
                    }
                    var errors = pipeline.Error.NonBlockingRead();
                    foreach (var curError in errors)
                    {
                        _pipelineCommandRuntime.ErrorStream.Write(curError);
                    }
                }
                finally
                {
                    _context.PopPipeline();
                }
            }
            finally
            {
                pipeLineContext.WriteSideEffectsToPipeline = writeSideEffects;
            }

            return AstVisitAction.SkipChildren;
        }
Exemplo n.º 28
0
 /// <summary/>
 public virtual object VisitPipeline(PipelineAst pipelineAst) { return null; }
Exemplo n.º 29
0
        /// <summary>
        /// Visit pipeline
        /// </summary>
        /// <param name="pipelineAst"></param>
        /// <returns></returns>
        public object VisitPipeline(PipelineAst pipelineAst)
        {
            if (pipelineAst == null) return null;

            bool invokesCommand = false;
            foreach (var command in pipelineAst.PipelineElements)
            {
                command.Visit(this.Decorator);
                if (command is CommandAst)
                {
                    invokesCommand = true;
                }
                foreach (var redir in command.Redirections)
                {
                    redir.Visit(this.Decorator);
                }
            }

            // Because non-local gotos are supported, we must model them in the flow graph.  We can't detect them
            // in general, so we must be pessimistic and assume any command invocation could result in non-local
            // break or continue, so add the appropriate edges to our graph.  These edges occur after visiting
            // the command elements because command arguments could create new blocks, and we won't have executed
            // the command yet.
            if (invokesCommand && _loopTargets.Any())
            {
                foreach (var loopTarget in _loopTargets)
                {
                    _currentBlock.FlowsTo(loopTarget.BreakTarget);
                    _currentBlock.FlowsTo(loopTarget.ContinueTarget);
                }

                // The rest of the block is potentially unreachable, so split the current block.
                var newBlock = new Block();
                _currentBlock.FlowsTo(newBlock);
                _currentBlock = newBlock;
            }

            return null;
        }
Exemplo n.º 30
0
 public virtual AstVisitAction VisitPipeline(PipelineAst pipelineAst)
 {
     return AstVisitAction.Continue;
 }
Exemplo n.º 31
0
        public override AstVisitAction VisitPipeline(PipelineAst pipelineAst)
        {
            // shouldn't happen, but anyway
            if (!pipelineAst.PipelineElements.Any())
            {
                return AstVisitAction.SkipChildren;
            }
            // Pipeline uses global execution context, so we should set its WriteSideEffects flag, and restore it after.
            // TODO: I'm not very sure about that changing context and WriteSideEffectsToPipeline stuff
            var pipeLineContext = ExecutionContext.CurrentRunspace.ExecutionContext;
            bool writeSideEffects = pipeLineContext.WriteSideEffectsToPipeline;
            try
            {
                pipeLineContext.WriteSideEffectsToPipeline = _writeSideEffectsToPipeline;
                var pipeline = ExecutionContext.CurrentRunspace.CreateNestedPipeline();
                int startAt = 0; // set to 1 if first element is an expression
                int pipelineCommandCount = pipelineAst.PipelineElements.Count;

                // first element of pipeline can be an expression that needs to be evaluated
                var expression = pipelineAst.PipelineElements[0] as CommandExpressionAst;
                if (expression != null)
                {
                    // evaluate it and get results
                    var subVisitor = this.CloneSub(_writeSideEffectsToPipeline);
                    expression.Expression.Visit(subVisitor);
                    var results = subVisitor._pipelineCommandRuntime.OutputStream.Read();
                    // if we only have that one expression and no commands, write expression to output and return
                    if (pipelineCommandCount == 1)
                    {
                        _pipelineCommandRuntime.WriteObject(results, true);
                        VisitRedirections(expression);
                        return AstVisitAction.SkipChildren;
                    }
                    // otherwise write value to input of pipeline to be processed
                    if (results.Count == 1)
                    {
                        // "unroll" an input array: write all enumerated elements seperately to the pipeline
                        pipeline.Input.Write(results[0], true);
                    }
                    else
                    {
                        pipeline.Input.Write(results, true);
                    }
                    startAt = 1;
                }
                else // if there was no expression we take the input of the context's input stream
                {
                    foreach (var input in ExecutionContext.InputStream.Read())
                    {
                        pipeline.Input.Write(input);
                    }
                }

                // all other elements *need* to be commands (same in PS). Make that sure and add them to the pipeline
                for (int curCommand = startAt; curCommand < pipelineCommandCount; curCommand++)
                {
                    var commandAst = pipelineAst.PipelineElements[curCommand] as CommandAst;
                    if (commandAst == null)
                    {
                        throw new NotSupportedException("Invalid command in pipeline."
                            + " Only the first element of a pipeline can be an expression.");
                    }
                    var command = GetCommand(commandAst);

                    commandAst.CommandElements
                    // the first CommandElements is the command itself. The rest are parameters/arguments
                    .Skip(1)
                        .Select(ConvertCommandElementToCommandParameter)
                        .ForEach(command.Parameters.Add);

                    command.RedirectionVisitor = new RedirectionVisitor(this, commandAst.Redirections);

                    pipeline.Commands.Add(command);
                }

                // now execute the pipeline
                ExecutionContext.PushPipeline(pipeline);
                // rerouting the output and error stream would be easier, but Pipeline doesn't
                // have an interface for this. So let's catch the exception for now, read the streams
                // and rethrow it afterwards
                Exception exception = null;
                Collection<PSObject> pipeResults = null;
                try
                {
                    pipeResults = pipeline.Invoke();
                }
                catch (Exception e)
                {
                    exception = e;
                    pipeResults = pipeline.Output.NonBlockingRead();
                }
                // read output and error and write them as results of the current commandRuntime
                foreach (var curResult in pipeResults)
                {
                    _pipelineCommandRuntime.WriteObject(curResult);
                }
                var errors = pipeline.Error.NonBlockingRead();
                foreach (var curError in errors)
                {
                    _pipelineCommandRuntime.ErrorStream.Write(curError);
                }
                ExecutionContext.PopPipeline();
                if (exception != null)
                {
                    throw exception;
                }
            }
            finally
            {
                pipeLineContext.WriteSideEffectsToPipeline = writeSideEffects;
            }

            return AstVisitAction.SkipChildren;
        }
Exemplo n.º 32
0
 public object VisitPipeline(PipelineAst pipelineAst)
 {
     return pipelineAst.GetPureExpression().Accept(this);
 }
Exemplo n.º 33
0
 private void ConvertPipeline(PipelineAst pipelineAst, bool isTrustedInput)
 {
     foreach (var command in pipelineAst.PipelineElements)
     {
         ConvertCommand((CommandAst)command, isTrustedInput);
     }
 }
Exemplo n.º 34
0
        public object VisitPipeline(PipelineAst pipelineAst)
        {
            ExpressionAst pureExpression = pipelineAst.GetPureExpression();

            return((pureExpression == null) ? ((object)false) : ((object)((bool)pureExpression.Accept(this))));
        }
Exemplo n.º 35
0
        public override AstVisitAction VisitPipeline(PipelineAst pipelineAst)
        {
            // TODO: rewrite this - it should expand the commands in the original pipe

            PipelineCommandRuntime subRuntime = null;

            foreach (var pipelineElement in pipelineAst.PipelineElements)
            {
                ExecutionContext subContext = this._context.CreateNestedContext();

                if (subRuntime == null)
                {
                    subContext.inputStreamReader = this._context.inputStreamReader;
                }
                else
                {
                    subContext.inputStreamReader = new PSObjectPipelineReader(subRuntime.outputResults);
                }

                subRuntime = new PipelineCommandRuntime(this._pipelineCommandRuntime.pipelineProcessor);
                subContext.inputStreamReader = subContext.inputStreamReader;

                pipelineElement.Visit(new ExecutionVisitor(subContext, subRuntime, this._writeSideEffectsToPipeline));
            }

            this._pipelineCommandRuntime.WriteObject(subRuntime.outputResults.Read(), true);

            return AstVisitAction.SkipChildren;
        }
Exemplo n.º 36
0
 public override AstVisitAction VisitPipeline(PipelineAst ast)
 {
     return this.Check(ast);
 }
Exemplo n.º 37
0
 public object VisitPipeline(PipelineAst pipelineAst)
 {
     ExpressionAst pureExpression = pipelineAst.GetPureExpression();
     return ((pureExpression == null) ? ((object) false) : ((object) ((bool) pureExpression.Accept(this))));
 }
        public object VisitPipeline(PipelineAst pipelineAst)
        {
            foreach (var element in pipelineAst.PipelineElements)
            {
                return Visit(element);
            }

            return new CodeExpression();
        }