/// <summary>
        /// Condition on the parameter that must be satisfied for the error to be raised.
        /// </summary>
        /// <param name="CmdAst"></param>
        /// <param name="CeAst"></param>
        /// <returns></returns>
        public override bool ParameterCondition(CommandAst CmdAst, CommandElementAst CeAst)
        {
            if (CeAst is CommandParameterAst)
            {
                CommandParameterAst cmdParamAst = CeAst as CommandParameterAst;

                if (String.Equals(cmdParamAst.ParameterName, "computername", StringComparison.OrdinalIgnoreCase))
                {
                    List<string> localhostRepresentations = new List<string> { "localhost", ".", "::1", "127.0.0.1" };
                    Ast computerNameArgument = GetComputerNameArg(CmdAst, cmdParamAst.Extent.StartOffset);                                        

                    if (null != computerNameArgument)
                    {
                        if (!localhostRepresentations.Contains(computerNameArgument.Extent.Text.ToLower()))
                        {
                            return computerNameArgument is ConstantExpressionAst;
                        }

                        return false;
                    }
                    
                    if (null != cmdParamAst.Argument && !localhostRepresentations.Contains(cmdParamAst.Argument.ToString().Replace("\"", "").Replace("'", "").ToLower()))
                    {
                        return cmdParamAst.Argument is ConstantExpressionAst;
                    }
                }
            }

            return false;
        }
        private static string GetTestFixtureName(CommandAst testFixtureAst)
        {
            bool nextElementIsName = false;
            foreach (var element in testFixtureAst.CommandElements)
            {
                if (
                    element is StringConstantExpressionAst &&
                    !(element as StringConstantExpressionAst).Value.Equals("TestFixture", StringComparison.OrdinalIgnoreCase) &&
                    !(element as StringConstantExpressionAst).Value.Equals("Name", StringComparison.OrdinalIgnoreCase))
                {
                    return (element as StringConstantExpressionAst).Value;        
                }

                if (nextElementIsName && element is StringConstantExpressionAst)
                {
                    return (element as StringConstantExpressionAst).Value;
                }

                if (element is CommandParameterAst &&
                    (element as CommandParameterAst).ParameterName.Equals("Name", StringComparison.OrdinalIgnoreCase))
                {
                    nextElementIsName = true;
                }
            }

            throw new Exception("Failed to find test fixture name!");
        }
        public override AstVisitAction VisitCommand(CommandAst ast)
        {
            if (ast == usedAst)
                used = true;

            return AstVisitAction.Continue;
        }
Esempio n. 4
0
        public static AssignmentStatementAst GetLastAssignmentStatementAst(this Ast ast, string varName, CommandAst usedAst)
        {
            var visitor = new FindLastAssignmentStatementVisitor(varName, usedAst);
            ast.Visit(visitor);

            return visitor.LastAssignmentStatementAst;
        }
        public FindLastAssignmentStatementVisitor(string varName, CommandAst usedAst)
        {
            this.varName = varName;
            this.usedAst = usedAst;
            used = false;

            LastAssignmentStatementAst = null;
        }
        /// <summary>
        /// Retrieves the error message
        /// </summary>
        /// <param name="FileName"></param>
        /// <param name="CmdAst"></param>
        /// <returns></returns>
        public override string GetError(string FileName, CommandAst CmdAst)
        {
            if (CmdAst == null)
            {
                return string.Empty;
            }

            return string.Format(CultureInfo.CurrentCulture, Strings.AvoidComputerNameHardcodedError, CmdAst.GetCommandName());
        }
 /// <summary>
 /// Checks to see if the command invocation is a dot
 /// in order to find a dot sourced file
 /// </summary>
 /// <param name="commandAst">A CommandAst object in the script's AST</param>
 /// <returns>A descion to stop searching if the right commandAst was found, 
 /// or a decision to continue if it wasn't found</returns>
 public override AstVisitAction VisitCommand(CommandAst commandAst)
 {
     if (commandAst.InvocationOperator.Equals(TokenKind.Dot))
     {
         string fileName = commandAst.CommandElements[0].Extent.Text;
         DotSourcedFiles.Add(fileName);
     }
     return base.VisitCommand(commandAst);
 }
        /// <summary>
        /// Condition on the cmdlet that must be satisfied for the error to be raised
        /// </summary>
        /// <param name="CmdAst"></param>
        /// <returns></returns>
        public override bool CommandCondition(CommandAst CmdAst)
        {
            if (CTSTCmdlet == null)
            {
                CTSTCmdlet = Helper.Instance.CmdletNameAndAliases("convertto-securestring");
            }

            return CmdAst != null && CmdAst.GetCommandName() != null && CTSTCmdlet.Contains(CmdAst.GetCommandName(), StringComparer.OrdinalIgnoreCase);
        }
Esempio n. 9
0
 private string GetParameterByNameOrPosition(string name, int position, CommandAst commandAst)
 {
     Dictionary<string, string> parameters = this.GetParameters(commandAst.CommandElements);
     string str = null;
     if (!parameters.TryGetValue(name, out str))
     {
         parameters.TryGetValue(position.ToString(CultureInfo.InvariantCulture), out str);
     }
     return str;
 }
 /// <summary>
 /// Retrieves the error message
 /// </summary>
 /// <param name="FileName"></param>
 /// <param name="CmdAst"></param>
 /// <returns></returns>
 public override string GetError(string fileName, CommandAst cmdAst)
 {
     if (String.IsNullOrWhiteSpace(fileName))
     {
         return String.Format(CultureInfo.CurrentCulture, Strings.AvoidUsingConvertToSecureStringWithPlainTextErrorScriptDefinition);
     }
     else
     {
         return String.Format(CultureInfo.CurrentCulture, Strings.AvoidUsingConvertToSecureStringWithPlainTextError, System.IO.Path.GetFileName(fileName));
     }
 }
        /// <summary>
        /// Decides if the current command is a reference of the symbol being searched for.
        /// A reference of the symbol will be a of type SymbolType.Function 
        /// and have the same name as the symbol
        /// </summary>
        /// <param name="commandAst">A CommandAst in the script's AST</param>
        /// <returns>A visit action that continues the search for references</returns>
        public override AstVisitAction VisitCommand(CommandAst commandAst)
        {
            Ast commandNameAst = commandAst.CommandElements[0];
            string commandName = commandNameAst.Extent.Text;

            if(symbolRef.SymbolType.Equals(SymbolType.Function))
            {
                if (needsAliases)
                {
                    // Try to get the commandAst's name and aliases, 
                    // if a command does not exists (if the symbol isn't an alias to a command)
                    // set command to and empty string value string command
                    // if the aliases do not exist (if the symvol isn't a command that has aliases)
                    // set aliases to an empty List<string>
                    string command;
                    List<string> alaises;
                    CmdletToAliasDictionary.TryGetValue(commandName, out alaises);
                    AliasToCmdletDictionary.TryGetValue(commandName, out command);
                    if (alaises == null) { alaises = new List<string>(); }
                    if (command == null) { command = string.Empty; }
                    
                    if (symbolRef.SymbolType.Equals(SymbolType.Function))
                    {
                        // Check if the found symbol's name is the same as the commandAst's name OR
                        // if the symbol's name is an alias for this commandAst's name (commandAst is a cmdlet) OR 
                        // if the symbol's name is the same as the commandAst's cmdlet name (commandAst is a alias)
                        if (commandName.Equals(symbolRef.SymbolName, StringComparison.InvariantCultureIgnoreCase) ||
                        alaises.Contains(symbolRef.ScriptRegion.Text.ToLower()) ||
                        command.Equals(symbolRef.ScriptRegion.Text, StringComparison.InvariantCultureIgnoreCase) ||
                        (!command.Equals(string.Empty) && command.Equals(symbolRefCommandName, StringComparison.InvariantCultureIgnoreCase)))
                        {
                            this.FoundReferences.Add(new SymbolReference(
                                SymbolType.Function,
                                commandNameAst.Extent));
                        }
                    }

                }
                else // search does not include aliases
                {
                    if (commandName.Equals(symbolRef.SymbolName, StringComparison.InvariantCultureIgnoreCase))
                    {
                        this.FoundReferences.Add(new SymbolReference(
                            SymbolType.Function,
                            commandNameAst.Extent));
                    }
                }
                
            }
            return base.VisitCommand(commandAst);
        }
        private static FunctionDefinitionAst FindDefinition(CommandAst ast, Ast parentAst)
        {
            if (ast == null) throw new ArgumentNullException("ast");
            if (parentAst == null) return null;

            var definitions = parentAst.FindAll(
                m => m is FunctionDefinitionAst && ((FunctionDefinitionAst) m).Name.Equals(ast.GetCommandName()), false).ToList();

            if (definitions.Any())
            {
                return definitions.Last() as FunctionDefinitionAst;
            }

            return FindDefinition(ast, parentAst.Parent);
        }
 private static IEnumerable<string> GetLegacyTopLevelParametersFromAst(CommandAst ast, string parameterName)
 {
     var parameters = new List<string>();
     IEnumerable<CommandParameterAst> commandElement =
         ast.CommandElements.Where(x => IsParameterName(x, parameterName)).OfType<CommandParameterAst>();
     foreach (var commandElementAst in commandElement)
     {
         var arrayLiteralAst = commandElementAst.Argument as ArrayLiteralAst;
         if (arrayLiteralAst != null)
         {
             parameters.AddRange(arrayLiteralAst.Elements.OfType<StringConstantExpressionAst>().Select(x => x.Value));
         }
     }
     return parameters;
 }
        private Ast GetComputerNameArg(CommandAst CmdAst, int StartIndex)
        {
            int small = int.MaxValue;
            Ast computerNameArg = null;
            foreach (Ast ast in CmdAst.CommandElements)
            {
                if (ast.Extent.StartOffset > StartIndex && ast.Extent.StartOffset < small)
                {
                    computerNameArg = ast;
                    small = ast.Extent.StartOffset;
                }
            }

            return computerNameArg;
        }
 public override AstVisitAction VisitCommand(CommandAst commandAst)
 {
     if (commandAst.InvocationOperator == TokenKind.Dot)
     {
         ThrowError(new ScriptBlockToPowerShellNotSupportedException("CantConvertWithDotSourcing", null, AutomationExceptions.CantConvertWithDotSourcing, new object[0]), commandAst);
     }
     if (commandAst.Parent.Parent.Parent != this.ScriptBeingConverted)
     {
         ThrowError(new ScriptBlockToPowerShellNotSupportedException("CantConvertWithCommandInvocations", null, AutomationExceptions.CantConvertWithCommandInvocations, new object[0]), commandAst);
     }
     if (commandAst.CommandElements[0] is ScriptBlockExpressionAst)
     {
         ThrowError(new ScriptBlockToPowerShellNotSupportedException("CantConvertWithScriptBlockInvocation", null, AutomationExceptions.CantConvertWithScriptBlockInvocation, new object[0]), commandAst);
     }
     return AstVisitAction.Continue;
 }
        /// <summary>
        /// Checks to see if this command ast is the symbol we are looking for.
        /// </summary>
        /// <param name="commandAst">A CommandAst object in the script's AST</param>
        /// <returns>A descion to stop searching if the right symbol was found, 
        /// or a decision to continue if it wasn't found</returns>
        public override AstVisitAction VisitCommand(CommandAst commandAst)
        {
            Ast commandNameAst = commandAst.CommandElements[0];

            if (this.IsPositionInExtent(commandNameAst.Extent))
            {
                this.FoundSymbolReference =
                    new SymbolReference(
                        SymbolType.Function,
                        commandNameAst.Extent);

                return AstVisitAction.StopVisit;
            }

            return base.VisitCommand(commandAst);
        }
Esempio n. 17
0
    public System.Object VisitCommand(System.Management.Automation.Language.CommandAst commandAst)
    {
        IScriptExtent mappedExtent = MapExtent(commandAst.Extent);

        LinkedList <CommandElementAst> mappedCommandElements = new LinkedList <CommandElementAst>();

        foreach (CommandElementAst ce in commandAst.CommandElements)
        {
            mappedCommandElements.AddLast(_VisitCommandElement(ce));
        }
        LinkedList <RedirectionAst> mappedRedirections = new LinkedList <RedirectionAst>();

        foreach (RedirectionAst r in commandAst.Redirections)
        {
            mappedRedirections.AddLast(_VisitRedirection(r));
        }

        return(new CommandAst(mappedExtent, mappedCommandElements, commandAst.InvocationOperator, mappedRedirections));
    }
        /// <summary>
        /// Checks that write-host command is not used
        /// </summary>
        /// <param name="cmdAst"></param>
        /// <returns></returns>
        public override AstVisitAction VisitCommand(CommandAst cmdAst)
        {
            if (cmdAst == null)
            {
                return AstVisitAction.SkipChildren;
            }

            if (cmdAst.GetCommandName() != null && String.Equals(cmdAst.GetCommandName(), "write-host", StringComparison.OrdinalIgnoreCase))
            {
                if (String.IsNullOrWhiteSpace(fileName))
                {
                    records.Add(new DiagnosticRecord(String.Format(CultureInfo.CurrentCulture, Strings.AvoidUsingWriteHostErrorScriptDefinition),
                        cmdAst.Extent, GetName(), DiagnosticSeverity.Warning, fileName));
                }
                else
                {
                    records.Add(new DiagnosticRecord(String.Format(CultureInfo.CurrentCulture, Strings.AvoidUsingWriteHostError,
                        System.IO.Path.GetFileName(fileName)), cmdAst.Extent, GetName(), DiagnosticSeverity.Warning, fileName));
                }
            }

            return AstVisitAction.Continue;
        }
Esempio n. 19
0
        public override AstVisitAction VisitCommand(CommandAst commandAst)
        {
            if (commandAst.InvocationOperator == TokenKind.Dot)
            {
                ThrowError(
                    new ScriptBlockToPowerShellNotSupportedException(
                        "CantConvertWithDotSourcing", null, AutomationExceptions.CantConvertWithDotSourcing),
                    commandAst);
            }

            // Up front checking ensures that we have a simple script block,
            // so we can safely assume that the parents are:
            //     * a PipelineAst
            //     * a NamedBlockAst (the end block)
            //     * a ScriptBlockAst (the ast we're comparing to)
            // If that isn't the case, the conversion isn't allowed.  It
            // is also safe to assume that we have at least 3 parents, a script block can't be simpler.
            if (commandAst.Parent.Parent.Parent != ScriptBeingConverted)
            {
                ThrowError(
                    new ScriptBlockToPowerShellNotSupportedException(
                        "CantConvertWithCommandInvocations", null, AutomationExceptions.CantConvertWithCommandInvocations),
                    commandAst);
            }

            if (commandAst.CommandElements[0] is ScriptBlockExpressionAst)
            {
                ThrowError(
                    new ScriptBlockToPowerShellNotSupportedException(
                        "CantConvertWithScriptBlockInvocation", null,
                        AutomationExceptions.CantConvertWithScriptBlockInvocation),
                    commandAst);
            }

            return AstVisitAction.Continue;
        }
Esempio n. 20
0
            public override AstVisitAction VisitCommand(CommandAst commandAst)
            {
                var commandName = commandAst.GetCommandName();
                if (commandName != null)
                {
                    if (_singleton._engineIntrinsics != null)
                    {
                        var commandInfo = _singleton._engineIntrinsics.InvokeCommand.GetCommand(commandName, CommandTypes.All);
                        if (commandInfo == null && !_singleton.UnresolvedCommandCouldSucceed(commandName, _rootAst))
                        {
                            _singleton._current = commandAst.CommandElements[0].Extent.EndOffset;
                            detectedError = string.Format(CultureInfo.CurrentCulture, PSReadLineResources.CommandNotFoundError, commandName);
                            return AstVisitAction.StopVisit;
                        }
                    }

                    if (commandAst.CommandElements.Any(e => e is ScriptBlockExpressionAst))
                    {
                        if (_singleton._options.CommandsToValidateScriptBlockArguments == null ||
                            !_singleton._options.CommandsToValidateScriptBlockArguments.Contains(commandName))
                        {
                            return AstVisitAction.SkipChildren;
                        }
                    }
                }

                if (_singleton._options.CommandValidationHandler != null)
                {
                    try
                    {
                        _singleton._options.CommandValidationHandler(commandAst);
                    }
                    catch (Exception e)
                    {
                        detectedError = e.Message;
                    }
                }

                return !string.IsNullOrWhiteSpace(detectedError)
                    ? AstVisitAction.StopVisit
                    : AstVisitAction.Continue;
            }
Esempio n. 21
0
 public override AstVisitAction VisitCommand(CommandAst ast)
 {
     return(this.Check(ast));
 }
Esempio n. 22
0
        Command GetCommand(CommandAst commandAst)
        {
            if (commandAst.CommandElements.First() is ScriptBlockExpressionAst)
            {
                var scriptBlockAst = (commandAst.CommandElements.First() as ScriptBlockExpressionAst).ScriptBlock;
                return new Command(scriptBlockAst);
            }

            else
            {
                return new Command(commandAst.GetCommandName());
            }
        }
Esempio n. 23
0
        public override AstVisitAction VisitCommand(CommandAst commandAst)
        {
            if (commandAst.InvocationOperator == TokenKind.Dot) throw new NotImplementedException(commandAst.ToString());

            Pipeline pipeline = this._context.CurrentRunspace.CreateNestedPipeline();

            pipeline.Input.Write(this._context.inputStreamReader.ReadToEnd(), true);

            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);

            this._context.PushPipeline(pipeline);
            try
            {
                // TODO: develop a rational model for null/singleton/collection
                var result = pipeline.Invoke();
                if (result.Any())
                {
                    this._pipelineCommandRuntime.WriteObject(result, true);
                }
            }
            finally
            {
                this._context.PopPipeline();
            }

            return AstVisitAction.SkipChildren;
        }
Esempio n. 24
0
        public override AstVisitAction VisitCommand(CommandAst commandAst)
        {
            if (commandAst.InvocationOperator == TokenKind.Dot)
                return VisitDotSourceCommand(commandAst);

            // Pipeline uses global execution context, so we should set its WriteSideEffects flag, and restore it to previous value after.
            var pipeLineContext = _context.CurrentRunspace.ExecutionContext;
            bool writeSideEffects = pipeLineContext.WriteSideEffectsToPipeline;
            try
            {
                pipeLineContext.WriteSideEffectsToPipeline = _writeSideEffectsToPipeline;
                var pipeline = _context.CurrentRunspace.CreateNestedPipeline();

                pipeline.Input.Write(_context.inputStreamReader.ReadToEnd(), true);

                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);

                _context.PushPipeline(pipeline);
                try
                {
                    // TODO: develop a rational model for null/singleton/collection
                    var result = pipeline.Invoke();
                    if (result.Any())
                    {
                        _pipelineCommandRuntime.WriteObject(result, true);
                    }
                }
                finally
                {
                    _context.PopPipeline();
                }
            }
            finally
            {
                pipeLineContext.WriteSideEffectsToPipeline = writeSideEffects;
            }

            return AstVisitAction.SkipChildren;
        }
Esempio n. 25
0
        private AstVisitAction VisitDotSourceCommand(CommandAst commandAst)
        {
            object scriptFileName = EvaluateAst(commandAst.Children.First());
            ScriptBlockAst ast = PowerShellGrammar.ParseInteractiveInput(File.ReadAllText(scriptFileName.ToString()));
            ast.Visit(this);

            return AstVisitAction.SkipChildren;
        }
Esempio n. 26
0
 public object VisitCommand(CommandAst commandAst)
 {
     return(AutomationNull.Value);
 }
Esempio n. 27
0
 /// <summary/>
 public virtual AstVisitAction VisitCommand(CommandAst commandAst) => DefaultVisit(commandAst);
Esempio n. 28
0
 /// <summary/>
 public virtual object VisitCommand(CommandAst commandAst)
 {
     return(null);
 }
Esempio n. 29
0
 public object VisitCommand(CommandAst commandAst)
 {
     return false;
 }
 /// <summary>
 /// Condition on the parameter that must be satisfied for the error to be raised.
 /// </summary>
 /// <param name="CmdAst"></param>
 /// <param name="CeAst"></param>
 /// <returns></returns>
 public override bool ParameterCondition(CommandAst CmdAst, CommandElementAst CeAst)
 {
     return CeAst is CommandParameterAst && String.Equals((CeAst as CommandParameterAst).ParameterName, "AsPlainText", StringComparison.OrdinalIgnoreCase);
 }
        /// <summary>
        /// Return true if mandatory parameters are used OR the cmdlet does not exist
        /// </summary>
        /// <param name="cmdAst"></param>
        /// <returns></returns>
        private bool IsMandatoryParameterExisted(CommandAst cmdAst)
        {
            CommandInfo cmdInfo = null;
            List<ParameterMetadata> mandParams = new List<ParameterMetadata>();
            IEnumerable<CommandElementAst> ceAsts = null;
            bool returnValue = false;

            #region Predicates

            // Predicate to find ParameterAsts.
            Func<CommandElementAst, bool> foundParamASTs = delegate(CommandElementAst ceAst)
            {
                if (ceAst is CommandParameterAst) return true;
                return false;
            };

            #endregion

            #region Compares parameter list and mandatory parameter list.

            cmdInfo = Helper.Instance.GetCommandInfo(Helper.Instance.GetCmdletNameFromAlias(cmdAst.GetCommandName()))
                ?? Helper.Instance.GetCommandInfo(cmdAst.GetCommandName());

            if (cmdInfo == null || (cmdInfo.CommandType != System.Management.Automation.CommandTypes.Cmdlet))
            {
                return true;
            }

            // ignores if splatted variable is used
            if (Helper.Instance.HasSplattedVariable(cmdAst))
            {
                return true;
            }

            // Gets parameters from command elements.
            ceAsts = cmdAst.CommandElements.Where<CommandElementAst>(foundParamASTs);

            // Gets mandatory parameters from cmdlet.
            // If cannot find any mandatory parameter, it's not necessary to do a further check for current cmdlet.
            try
            {
                int noOfParamSets = cmdInfo.ParameterSets.Count; 
                foreach (ParameterMetadata pm in cmdInfo.Parameters.Values)
                {
                    int count = 0;

                    if (pm.Attributes.Count < noOfParamSets)
                    {
                        continue;
                    }

                    foreach (Attribute attr in pm.Attributes)
                    {
                        if (!(attr is ParameterAttribute)) continue;
                        if (((ParameterAttribute)attr).Mandatory)
                        {
                            count += 1;
                        }
                    }

                    if (count >= noOfParamSets)
                    {
                        mandParams.Add(pm);
                    }
                }
            }
            catch (Exception)
            {
                // For cases like cmd.exe. Also for runtime exception
                return true;
            }

            if (mandParams.Count() == 0 || Helper.Instance.PositionalParameterUsed(cmdAst))
            {
                returnValue = true;
            }
            else
            {
                // Compares parameter list and mandatory parameter list.
                foreach (CommandElementAst ceAst in ceAsts)
                {
                    CommandParameterAst cpAst = (CommandParameterAst)ceAst;
                    if (mandParams.Count<ParameterMetadata>(item =>
                        item.Name.Equals(cpAst.ParameterName, StringComparison.OrdinalIgnoreCase)) > 0)
                    {
                        returnValue = true;
                        break;
                    }
                }
            }

            #endregion

            return returnValue;
        }
Esempio n. 32
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;
        }
Esempio n. 33
0
 public override AstVisitAction VisitCommand(CommandAst ast)
 {
     return(CheckParent(ast));
 }
Esempio n. 34
0
 public object VisitCommand(CommandAst commandAst)
 {
     return(false);
 }
Esempio n. 35
0
 public virtual AstVisitAction VisitCommand(CommandAst commandAst)
 {
     return AstVisitAction.Continue;
 }
Esempio n. 36
0
 /// <summary/>
 public virtual AstVisitAction VisitCommand(CommandAst commandAst)
 {
     return(AstVisitAction.Continue);
 }
Esempio n. 37
0
        /// <summary>
        /// CompleteArgument
        /// </summary>
        public IEnumerable<CompletionResult> CompleteArgument(string commandName, string parameterName, string wordToComplete, CommandAst commandAst, IDictionary fakeBoundParameters)
        {
            var wordToCompletePattern = WildcardPattern.Get(string.IsNullOrWhiteSpace(wordToComplete) ? "*" : wordToComplete + "*", WildcardOptions.IgnoreCase);

            foreach (var edition in Utils.AllowedEditionValues)
            {
                if (wordToCompletePattern.IsMatch(edition))
                {
                    yield return new CompletionResult(edition, edition, CompletionResultType.Text, edition);
                }
            }
        }
        private static TestCase GetTestCase(CommandAst contextAst, string textFixtureName, string source)
        {
            var contextName = String.Empty;
            var displayName = String.Empty;
            bool nextElementIsName = false;
            foreach (var element in contextAst.CommandElements)
            {
                if (
                    element is StringConstantExpressionAst &&
                    !(element as StringConstantExpressionAst).Value.Equals("TestCase", StringComparison.OrdinalIgnoreCase) &&
                    !(element as StringConstantExpressionAst).Value.Equals("Name", StringComparison.OrdinalIgnoreCase) &&
                    !(element as StringConstantExpressionAst).Value.Equals("ScriptBlock", StringComparison.OrdinalIgnoreCase))
                {
                    contextName = String.Format("PSate||{0}||{1}", textFixtureName, (element as StringConstantExpressionAst).Value);
                    displayName = (element as StringConstantExpressionAst).Value;
                    break;
                }

                if (nextElementIsName && element is StringConstantExpressionAst)
                {
                    contextName = String.Format("PSate||{0}||{1}", textFixtureName, (element as StringConstantExpressionAst).Value);
                    displayName = (element as StringConstantExpressionAst).Value;
                    break;
                }

                if (element is CommandParameterAst &&
                    (element as CommandParameterAst).ParameterName.Equals("Name", StringComparison.OrdinalIgnoreCase))
                {
                    nextElementIsName = true;
                }
            }

            var testcase = new TestCase(contextName, PowerShellTestExecutor.ExecutorUri, source)
            {
                CodeFilePath = source,
                DisplayName = displayName,
                LineNumber = contextAst.Extent.StartLineNumber,
                LocalExtensionData = "PSate"
            };

            return testcase;
        }
Esempio n. 39
0
        private void ConvertCommand(CommandAst commandAst, bool isTrustedInput)
        {
            // First need command name.
            var commandName = GetCommandName(commandAst.CommandElements[0], isTrustedInput);

            var command = new Command(commandName, isScript: false, useLocalScope: _createLocalScope);

            // Handle redirections, if any (there can really be just 0 or 1).
            if (commandAst.Redirections.Count > 0)
            {
                Diagnostics.Assert(commandAst.Redirections.Count == 1, "only 1 kind of redirection is supported");
                Diagnostics.Assert(commandAst.Redirections[0] is MergingRedirectionAst, "unexpected redirection type");

                PipelineResultTypes toType = PipelineResultTypes.Output;
                PipelineResultTypes fromType;
                switch (commandAst.Redirections[0].FromStream)
                {
                    case RedirectionStream.Error:
                        fromType = PipelineResultTypes.Error;
                        break;

                    case RedirectionStream.Warning:
                        fromType = PipelineResultTypes.Warning;
                        break;

                    case RedirectionStream.Verbose:
                        fromType = PipelineResultTypes.Verbose;
                        break;

                    case RedirectionStream.Debug:
                        fromType = PipelineResultTypes.Debug;
                        break;

                    case RedirectionStream.Information:
                        fromType = PipelineResultTypes.Information;
                        break;

                    case RedirectionStream.All:
                        fromType = PipelineResultTypes.All;
                        break;

                    default:
                        // Default to Error->Output to be compatible with V2.
                        fromType = PipelineResultTypes.Error;
                        break;
                }

                command.MergeMyResults(fromType, toType);
            }

            _powershell.AddCommand(command);

            // Now the parameters and arguments.
            foreach (var ast in commandAst.CommandElements.Skip(1))
            {
                var exprAst = ast as ExpressionAst;
                if (exprAst != null)
                {
                    VariableExpressionAst variableAst = null;

                    var usingExprAst = ast as UsingExpressionAst;
                    if (usingExprAst != null)
                    {
                        string usingAstKey = PsUtils.GetUsingExpressionKey(usingExprAst);
                        object usingValue = _usingValueMap[usingAstKey];
                        variableAst = usingExprAst.SubExpression as VariableExpressionAst;
                        if (variableAst != null && variableAst.Splatted)
                        {
                            // Support the splatting of a dictionary
                            var parameters = usingValue as System.Collections.IDictionary;
                            if (parameters != null)
                            {
                                _powershell.AddParameters(parameters);
                            }
                            else
                            {
                                // Support the splatting of an array
                                var arguments = usingValue as System.Collections.IEnumerable;
                                if (arguments != null)
                                {
                                    foreach (Object argument in arguments)
                                    {
                                        _powershell.AddArgument(argument);
                                    }
                                }
                                else
                                {
                                    // Splat the object directly.
                                    _powershell.AddArgument(usingValue);
                                }
                            }
                        }
                        else
                        {
                            _powershell.AddArgument(usingValue);
                        }
                        continue;
                    }

                    variableAst = ast as VariableExpressionAst;
                    if (variableAst != null && variableAst.Splatted)
                    {
                        GetSplattedVariable(variableAst);
                    }
                    else
                    {
                        var constantExprAst = ast as ConstantExpressionAst;
                        object argument;
                        if (constantExprAst != null && LanguagePrimitives.IsNumeric(LanguagePrimitives.GetTypeCode(constantExprAst.StaticType)))
                        {
                            var commandArgumentText = constantExprAst.Extent.Text;
                            argument = constantExprAst.Value;
                            if (!commandArgumentText.Equals(constantExprAst.Value.ToString(), StringComparison.Ordinal))
                            {
                                // The wrapped number will actually return a PSObject which could end holding a reference to
                                // a typetable, making the object runspace specific.  We should find a better way to avoid
                                // any possibility of sharing problems, though this is unlikely to cause problems.
                                argument = ParserOps.WrappedNumber(argument, commandArgumentText);
                            }
                        }
                        else
                        {
                            if (!isTrustedInput)
                            {
                                try
                                {
                                    argument = GetSafeValueVisitor.GetSafeValue(exprAst, _context, GetSafeValueVisitor.SafeValueContext.GetPowerShell);
                                }
                                catch (System.Exception)
                                {
                                    throw new ScriptBlockToPowerShellNotSupportedException(
                                        "CantConvertWithDynamicExpression",
                                        null,
                                        AutomationExceptions.CantConvertWithDynamicExpression,
                                        exprAst.Extent.Text);
                                }
                            }
                            else
                            {
                                argument = GetExpressionValue(exprAst, isTrustedInput);
                            }
                        }
                        _powershell.AddArgument(argument);
                    }
                }
                else
                {
                    AddParameter((CommandParameterAst)ast, isTrustedInput);
                }
            }
        }
Esempio n. 40
0
 public object VisitCommand(CommandAst commandAst)
 {
     throw PSTraceSource.NewArgumentException("ast");
 }