public PipelineAst(IScriptExtent extent, CommandBaseAst commandAst) : base(extent) { if (commandAst == null) { throw PSTraceSource.NewArgumentNullException("commandAst"); } this.PipelineElements = new ReadOnlyCollection<CommandBaseAst>(new CommandBaseAst[] { commandAst }); base.SetParent(commandAst); }
public PipelineAst(IScriptExtent extent, CommandBaseAst commandAst) : base(extent) { if (commandAst == null) { throw PSTraceSource.NewArgumentNullException("commandAst"); } this.PipelineElements = new ReadOnlyCollection <CommandBaseAst>(new CommandBaseAst[] { commandAst }); base.SetParent(commandAst); }
public PipelineAst(IScriptExtent extent, CommandBaseAst commandAst) : base(extent) { this.PipelineElements = new[] { commandAst }.ToReadOnlyCollection(); }
private bool PrepareCommandElements(ExecutionContext context) { int num = 0; bool dotSource = this._commandAst.InvocationOperator == TokenKind.Dot; CommandProcessorBase base2 = null; string resolvedCommandName = null; bool flag2 = false; try { base2 = this.PrepareFromAst(context, out resolvedCommandName) ?? context.CreateCommand(resolvedCommandName, dotSource); } catch (RuntimeException exception) { CommandProcessorBase.CheckForSevereException(exception); if ((this._commandAst.IsInWorkflow() && (resolvedCommandName != null)) && CompletionCompleters.PseudoWorkflowCommands.Contains <string>(resolvedCommandName, StringComparer.OrdinalIgnoreCase)) { flag2 = true; } else { return(false); } } CommandProcessor commandProcessor = base2 as CommandProcessor; ScriptCommandProcessorBase base3 = base2 as ScriptCommandProcessorBase; bool flag3 = (commandProcessor != null) && commandProcessor.CommandInfo.ImplementsDynamicParameters; List <object> list = flag3 ? new List <object>(this._commandElements.Count) : null; if (((commandProcessor != null) || (base3 != null)) || flag2) { num++; while (num < this._commandElements.Count) { CommandParameterAst parameterAst = this._commandElements[num] as CommandParameterAst; if (parameterAst != null) { if (list != null) { list.Add(parameterAst.Extent.Text); } AstPair item = (parameterAst.Argument != null) ? new AstPair(parameterAst, parameterAst.Argument) : new AstPair(parameterAst); this._arguments.Add(item); } else { StringConstantExpressionAst ast2 = this._commandElements[num] as StringConstantExpressionAst; if ((ast2 == null) || !ast2.Value.Trim().Equals("-", StringComparison.OrdinalIgnoreCase)) { ExpressionAst argumentAst = this._commandElements[num] as ExpressionAst; if (argumentAst != null) { if (list != null) { list.Add(argumentAst.Extent.Text); } this._arguments.Add(new AstPair(null, argumentAst)); } } } num++; } } if (commandProcessor != null) { this._function = false; if (flag3) { ParameterBinderController.AddArgumentsToCommandProcessor(commandProcessor, list.ToArray()); bool flag4 = false; bool flag5 = false; do { CommandProcessorBase currentCommandProcessor = context.CurrentCommandProcessor; try { context.CurrentCommandProcessor = commandProcessor; commandProcessor.SetCurrentScopeToExecutionScope(); if (!flag4) { commandProcessor.CmdletParameterBinderController.BindCommandLineParametersNoValidation(commandProcessor.arguments); } else { flag5 = true; commandProcessor.CmdletParameterBinderController.ClearUnboundArguments(); commandProcessor.CmdletParameterBinderController.BindCommandLineParametersNoValidation(new Collection <CommandParameterInternal>()); } } catch (ParameterBindingException exception2) { if ((exception2.ErrorId == "MissingArgument") || (exception2.ErrorId == "AmbiguousParameter")) { flag4 = true; } } catch (Exception exception3) { CommandProcessorBase.CheckForSevereException(exception3); } finally { context.CurrentCommandProcessor = currentCommandProcessor; commandProcessor.RestorePreviousScope(); } }while (flag4 && !flag5); } this._commandInfo = commandProcessor.CommandInfo; this._commandName = commandProcessor.CommandInfo.Name; this._bindableParameters = commandProcessor.CmdletParameterBinderController.BindableParameters; this._defaultParameterSetFlag = commandProcessor.CommandInfo.CommandMetadata.DefaultParameterSetFlag; } else if (base3 != null) { this._function = true; this._commandInfo = base3.CommandInfo; this._commandName = base3.CommandInfo.Name; this._bindableParameters = base3.ScriptParameterBinderController.BindableParameters; this._defaultParameterSetFlag = 0; } else if (!flag2) { return(false); } if (this._commandAst.IsInWorkflow()) { Type type = Type.GetType("Microsoft.PowerShell.Workflow.AstToWorkflowConverter, Microsoft.PowerShell.Activities, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"); if (type != null) { Dictionary <string, Type> dictionary = (Dictionary <string, Type>)type.GetMethod("GetActivityParameters").Invoke(null, new object[] { this._commandAst }); if (dictionary != null) { bool flag6 = dictionary.ContainsKey("PSComputerName") && !dictionary.ContainsKey("ComputerName"); List <MergedCompiledCommandParameter> source = new List <MergedCompiledCommandParameter>(); Collection <Attribute> attributes = new Collection <Attribute> { new ParameterAttribute() }; foreach (KeyValuePair <string, Type> pair2 in dictionary) { if (flag2 || !this._bindableParameters.BindableParameters.ContainsKey(pair2.Key)) { Type actualActivityParameterType = GetActualActivityParameterType(pair2.Value); RuntimeDefinedParameter runtimeDefinedParameter = new RuntimeDefinedParameter(pair2.Key, actualActivityParameterType, attributes); CompiledCommandParameter parameter = new CompiledCommandParameter(runtimeDefinedParameter, false) { IsInAllSets = true }; MergedCompiledCommandParameter parameter3 = new MergedCompiledCommandParameter(parameter, ParameterBinderAssociation.DeclaredFormalParameters); source.Add(parameter3); } } if (source.Any <MergedCompiledCommandParameter>()) { MergedCommandParameterMetadata metadata = new MergedCommandParameterMetadata(); if (!flag2) { metadata.ReplaceMetadata(this._bindableParameters); } foreach (MergedCompiledCommandParameter parameter5 in source) { metadata.BindableParameters.Add(parameter5.Parameter.Name, parameter5); } this._bindableParameters = metadata; } foreach (string str2 in ignoredWorkflowParameters) { if (this._bindableParameters.BindableParameters.ContainsKey(str2)) { this._bindableParameters.BindableParameters.Remove(str2); } } if (this._bindableParameters.BindableParameters.ContainsKey("ComputerName") && flag6) { this._bindableParameters.BindableParameters.Remove("ComputerName"); string key = (from aliasPair in this._bindableParameters.AliasedParameters where string.Equals("ComputerName", aliasPair.Value.Parameter.Name) select aliasPair.Key).FirstOrDefault <string>(); this._bindableParameters.AliasedParameters.Remove(key); } } } } this._unboundParameters.AddRange(this._bindableParameters.BindableParameters.Values); CommandBaseAst ast4 = null; PipelineAst parent = this._commandAst.Parent as PipelineAst; if (parent.PipelineElements.Count > 1) { foreach (CommandBaseAst ast6 in parent.PipelineElements) { if (ast6.GetHashCode() == this._commandAst.GetHashCode()) { this._isPipelineInputExpected = ast4 != null; if (this._isPipelineInputExpected) { this._pipelineInputType = typeof(object); } break; } ast4 = ast6; } } return(true); }
private void VisitRedirections(CommandBaseAst commandAst) { if (commandAst.Redirections.Count == 0) { return; } foreach (RedirectionAst redirectAst in commandAst.Redirections) { var fileRedirectAst = redirectAst as FileRedirectionAst; if (fileRedirectAst != null) { VisitFileRedirection(fileRedirectAst); } else { throw new NotImplementedException(redirectAst.ToString()); } } }
internal static void InvokePipeline (object input, bool ignoreInput, CommandParameterInternal[][] pipeElements, CommandBaseAst[] pipeElementAsts, CommandRedirection[][] commandRedirections, FunctionContext funcContext) { PipelineProcessor pipelineProcessor = new PipelineProcessor (); System.Management.Automation.ExecutionContext context = funcContext._executionContext; Pipe pipe = funcContext._outputPipe; try { if (context.Events != null) { context.Events.ProcessPendingActions (); } if ((input == AutomationNull.Value) && !ignoreInput) { AddNoopCommandProcessor (pipelineProcessor, context); } CommandProcessorBase commandProcessor = null; CommandRedirection[] redirections = null; for (int i = 0; i < pipeElements.Length; i++) { redirections = (commandRedirections != null) ? commandRedirections [i] : null; commandProcessor = AddCommand (pipelineProcessor, pipeElements [i], pipeElementAsts [i], redirections, context); } if ((commandProcessor != null) && !commandProcessor.CommandRuntime.OutputPipe.IsRedirected) { pipelineProcessor.LinkPipelineSuccessOutput (pipe ?? new Pipe (new ArrayList ())); if (redirections != null) { foreach (CommandRedirection redirection in redirections) { if (redirection is MergingRedirection) { redirection.Bind (pipelineProcessor, commandProcessor, context); } } } } context.PushPipelineProcessor (pipelineProcessor); try { pipelineProcessor.SynchronousExecuteEnumerate (input, null, true); } finally { context.PopPipelineProcessor (false); } } finally { context.QuestionMarkVariableValue = !pipelineProcessor.ExecutionFailed; pipelineProcessor.Dispose(); } }
private static CommandProcessorBase AddCommand(PipelineProcessor pipe, CommandParameterInternal[] commandElements, CommandBaseAst commandBaseAst, CommandRedirection[] redirections, System.Management.Automation.ExecutionContext context) { object parameterText; IScriptExtent parameterExtent; CommandProcessorBase base2; InternalCommand command; string str3; HelpCategory category; CommandAst ast = commandBaseAst as CommandAst; TokenKind kind = (ast != null) ? ast.InvocationOperator : TokenKind.Unknown; bool dotSource = kind == TokenKind.Dot; SessionStateInternal sessionState = null; int index = 0; PSModuleInfo info = PSObject.Base(commandElements[0].ArgumentValue) as PSModuleInfo; if (info != null) { if ((info.ModuleType == ModuleType.Binary) && (info.SessionState == null)) { throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException), null, "CantInvokeInBinaryModule", ParserStrings.CantInvokeInBinaryModule, new object[] { info.Name }); } if (info.SessionState == null) { throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException), null, "CantInvokeInNonImportedModule", ParserStrings.CantInvokeInNonImportedModule, new object[] { info.Name }); } sessionState = info.SessionState.Internal; index++; } CommandParameterInternal internal3 = commandElements[index]; if (internal3.ParameterNameSpecified) { parameterText = internal3.ParameterText; parameterExtent = internal3.ParameterExtent; if (!internal3.ArgumentSpecified) { } } else { parameterText = PSObject.Base(internal3.ArgumentValue); parameterExtent = internal3.ArgumentExtent; } string str = dotSource ? "." : ((kind == TokenKind.Ampersand) ? "&" : null); ScriptBlock scriptblock = parameterText as ScriptBlock; if (scriptblock != null) { base2 = CommandDiscovery.CreateCommandProcessorForScript(scriptblock, context, !dotSource, sessionState); } else { CommandInfo commandInfo = parameterText as CommandInfo; if (commandInfo != null) { base2 = context.CommandDiscovery.LookupCommandProcessor(commandInfo, context.EngineSessionState.CurrentScope.ScopeOrigin, new bool?(!dotSource), sessionState); } else { string str2 = (parameterText as string) ?? PSObject.ToStringParser(context, parameterText); str = str ?? str2; if (string.IsNullOrEmpty(str2)) { throw InterpreterError.NewInterpreterException(parameterText, typeof(RuntimeException), parameterExtent, "BadExpression", ParserStrings.BadExpression, new object[] { dotSource ? "." : "&" }); } try { if (sessionState != null) { SessionStateInternal engineSessionState = context.EngineSessionState; try { context.EngineSessionState = sessionState; base2 = context.CreateCommand(str2, dotSource); goto Label_025D; } finally { context.EngineSessionState = engineSessionState; } } base2 = context.CreateCommand(str2, dotSource); } catch (RuntimeException exception) { if (exception.ErrorRecord.InvocationInfo == null) { InvocationInfo invocationInfo = new InvocationInfo(null, parameterExtent, context) { InvocationName = str }; exception.ErrorRecord.SetInvocationInfo(invocationInfo); } throw; } } } Label_025D: command = base2.Command; base2.UseLocalScope = !dotSource && ((command is ScriptCommand) || (command is PSScriptCmdlet)); bool flag2 = base2 is NativeCommandProcessor; for (int i = index + 1; i < commandElements.Length; i++) { CommandParameterInternal parameter = commandElements[i]; if ((!parameter.ParameterNameSpecified || !parameter.ParameterName.Equals("-", StringComparison.OrdinalIgnoreCase)) || flag2) { if (parameter.ArgumentSplatted) { foreach (CommandParameterInternal internal6 in Splat(parameter.ArgumentValue, parameter.ArgumentExtent)) { base2.AddParameter(internal6); } } else { base2.AddParameter(parameter); } } } if (base2.IsHelpRequested(out str3, out category)) { base2 = CommandProcessorBase.CreateGetHelpCommandProcessor(context, str3, category); } base2.Command.InvocationExtent = commandBaseAst.Extent; base2.Command.MyInvocation.ScriptPosition = commandBaseAst.Extent; base2.Command.MyInvocation.InvocationName = str; pipe.Add(base2); bool flag3 = false; bool flag4 = false; bool flag5 = false; bool flag6 = false; if (redirections != null) { foreach (CommandRedirection redirection in redirections) { redirection.Bind(pipe, base2, context); switch (redirection.FromStream) { case RedirectionStream.All: flag3 = true; flag4 = true; flag5 = true; flag6 = true; break; case RedirectionStream.Error: flag3 = true; break; case RedirectionStream.Warning: flag4 = true; break; case RedirectionStream.Verbose: flag5 = true; break; case RedirectionStream.Debug: flag6 = true; break; } } } if (!flag3) { if (context.ShellFunctionErrorOutputPipe != null) { base2.CommandRuntime.ErrorOutputPipe = context.ShellFunctionErrorOutputPipe; } else { base2.CommandRuntime.ErrorOutputPipe.ExternalWriter = context.ExternalErrorOutput; } } if (!flag4 && (context.ExpressionWarningOutputPipe != null)) { base2.CommandRuntime.WarningOutputPipe = context.ExpressionWarningOutputPipe; flag4 = true; } if (!flag5 && (context.ExpressionVerboseOutputPipe != null)) { base2.CommandRuntime.VerboseOutputPipe = context.ExpressionVerboseOutputPipe; flag5 = true; } if (!flag6 && (context.ExpressionDebugOutputPipe != null)) { base2.CommandRuntime.DebugOutputPipe = context.ExpressionDebugOutputPipe; flag6 = true; } if ((context.CurrentCommandProcessor != null) && (context.CurrentCommandProcessor.CommandRuntime != null)) { if (!flag4 && (context.CurrentCommandProcessor.CommandRuntime.WarningOutputPipe != null)) { base2.CommandRuntime.WarningOutputPipe = context.CurrentCommandProcessor.CommandRuntime.WarningOutputPipe; } if (!flag5 && (context.CurrentCommandProcessor.CommandRuntime.VerboseOutputPipe != null)) { base2.CommandRuntime.VerboseOutputPipe = context.CurrentCommandProcessor.CommandRuntime.VerboseOutputPipe; } if (!flag6 && (context.CurrentCommandProcessor.CommandRuntime.DebugOutputPipe != null)) { base2.CommandRuntime.DebugOutputPipe = context.CurrentCommandProcessor.CommandRuntime.DebugOutputPipe; } } return base2; }
private object GetCommandRedirections(CommandBaseAst command) { int count = command.Redirections.Count; if (count == 0) { return null; } // Most redirections will be instances of CommandRedirection, but non-constant filenames // will generated a Linq.Expression, so we store objects. object[] compiledRedirections = new object[count]; for (int i = 0; i < count; ++i) { compiledRedirections[i] = command.Redirections[i].Accept(this); } // If there were any non-constant expressions, we must generate the array at runtime. if (compiledRedirections.Any(r => r is Expression)) { return Expression.NewArrayInit(typeof(CommandRedirection), compiledRedirections.Select(r => (r as Expression) ?? Expression.Constant(r))); } // Otherwise, we can use a compile time constant array. return compiledRedirections.Map(r => (CommandRedirection)r); }
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); }
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); }
private object GetCommandRedirections(CommandBaseAst command) { int count = command.Redirections.Count; if (count == 0) { return null; } object[] array = new object[count]; for (int i = 0; i < count; i++) { array[i] = command.Redirections[i].Accept(this); } if ((from r in array where r is Expression select r).Any<object>()) { return Expression.NewArrayInit(typeof(CommandRedirection), (IEnumerable<Expression>) (from r in array select (r as Expression) ?? Expression.Constant(r))); } return Array.ConvertAll<object, CommandRedirection>(array, r => (CommandRedirection) r); }