public virtual ParamBlockAst VisitParamBlock(ParamBlockAst paramBlockAst)
 {
     return(new ParamBlockAst(
                paramBlockAst.Extent,
                paramBlockAst.Attributes.RewriteAll(this, SyntaxKind.Attribute),
                paramBlockAst.Parameters.RewriteAll(this)));
 }
        private bool TryGetParameterAst(
            FunctionDefinitionAst functionDefinitionAst,
            string parameter,
            out int parameterIndex,
            out ParameterAst[] parameters,
            out ParamBlockAst paramBlockAst)
        {
            if (functionDefinitionAst.Parameters != null)
            {
                if (TryGetParameterAst(functionDefinitionAst.Parameters, parameter, out parameterIndex))
                {
                    parameters    = new List <ParameterAst>(functionDefinitionAst.Parameters).ToArray();
                    paramBlockAst = null;
                    functionDefinitionAst.Parameters.CopyTo(parameters, 0);
                    return(true);
                }
            }
            else if (functionDefinitionAst.Body.ParamBlock?.Parameters != null)
            {
                if (TryGetParameterAst(
                        functionDefinitionAst.Body.ParamBlock.Parameters,
                        parameter,
                        out parameterIndex))
                {
                    parameters    = new List <ParameterAst>(functionDefinitionAst.Body.ParamBlock.Parameters).ToArray();
                    paramBlockAst = functionDefinitionAst.Body.ParamBlock;
                    return(true);
                }
            }

            parameterIndex = -1;
            paramBlockAst  = null;
            parameters     = null;
            return(false);
        }
Esempio n. 3
0
        public object VisitParamBlock(ParamBlockAst paramBlockAst)
        {
            var attributes = VisitAst(paramBlockAst.Attributes);
            var parameters = VisitAst(paramBlockAst.Parameters);

            return(new ParamBlockAst(paramBlockAst.Extent, attributes, parameters));
        }
        public object VisitParamBlock(ParamBlockAst paramBlockAst)
        {
            var newAttributes = VisitElements(paramBlockAst.Attributes);
            var newParameters = VisitElements(paramBlockAst.Parameters);

            return(new ParamBlockAst(paramBlockAst.Extent, newAttributes, newParameters));
        }
        private ScriptBlock ConstructScriptBlockWithNewParamBlock(ScriptBlockAst oldScriptBlockAst, HashSet <string> parametersToRedefine)
        {
            var parameterAsts = new List <ParameterAst>(oldScriptBlockAst.ParamBlock.Parameters.Count);

            foreach (ParameterAst parameter in oldScriptBlockAst.ParamBlock.Parameters)
            {
                if (!parametersToRedefine.Contains(parameter.Name.VariablePath.UserPath))
                {
                    parameterAsts.Add(parameter);
                    continue;
                }

                parameterAsts.Add(CreateStrippedParameterAst(parameter));
            }

            var newParamBlock = new ParamBlockAst(
                oldScriptBlockAst.ParamBlock.Extent,
                CopyAstCollection(oldScriptBlockAst.Attributes),
                CopyAstCollection(parameterAsts));

            return(new ScriptBlockAst(
                       oldScriptBlockAst.Extent,
                       newParamBlock,
                       (NamedBlockAst)oldScriptBlockAst.BeginBlock?.Copy(),
                       (NamedBlockAst)oldScriptBlockAst.ProcessBlock?.Copy(),
                       (NamedBlockAst)oldScriptBlockAst.EndBlock?.Copy(),
                       (NamedBlockAst)oldScriptBlockAst.DynamicParamBlock?.Copy()).GetScriptBlock());
        }
Esempio n. 6
0
 public override object VisitParamBlock(ParamBlockAst paramBlockAst)
 {
     VisitElements(paramBlockAst.Attributes, ",");
     script_.Write("Param(");
     VisitElements(paramBlockAst.Parameters, ",");
     script_.Write(")");
     return(paramBlockAst);
 }
        public void ShouldNotHaveParamBlockIfScriptHasNoParametersDefined()
        {
            var           ast        = GenerateAst(scriptWithoutParameters);
            ParamBlockAst paramBlock = null;
            bool          result     = PowerShellParseUtilities.HasParamBlock(ast, out paramBlock);

            Assert.AreEqual <bool>(false, result);
        }
        public static ScriptParameterResult PromptForScriptParameterValues(ParamBlockAst paramBlock)
        {
            string scriptArgs;

            if (ShowParameterEditor(paramBlock, out scriptArgs) == true)
            {
                return(new ScriptParameterResult(scriptArgs, true));
            }
            return(new ScriptParameterResult(null, false));
        }
 public static ParamBlockAst Update(
     this ParamBlockAst ast,
     IEnumerable <ParameterAst> parameters = null,
     IEnumerable <AttributeAst> attributes = null)
 {
     return(new ParamBlockAst(
                ast.Extent,
                attributes?.CloneAll() ?? ast.Attributes?.CloneAll(),
                parameters?.CloneAll() ?? ast.Parameters?.CloneAll()));
 }
Esempio n. 10
0
        public override ParamBlockAst VisitParamBlock(ParamBlockAst paramBlockAst)
        {
            foreach (ParameterAst parameter in paramBlockAst.Parameters)
            {
                _parameters.Add(parameter.Name.VariablePath.UserPath, _parametersIndex);
                _parametersIndex++;
            }

            return(null);
        }
Esempio n. 11
0
        public void ParamBlockWithOneParameterWithDefaultIntegerValueTest()
        {
            ParamBlockAst result = ParseInput("param($first = 2)")
                                   .ParamBlock;

            ParameterAst parameter     = result.Parameters.FirstOrDefault();
            var          constantValue = (ConstantExpressionAst)parameter.DefaultValue;

            Assert.AreEqual(2, constantValue.Value);
        }
Esempio n. 12
0
        public void ParamBlockWithOneParameterTest()
        {
            ParamBlockAst result = ParseInput("param($path)")
                                   .ParamBlock;

            ParameterAst parameter = result.Parameters.FirstOrDefault();

            Assert.AreEqual(1, result.Parameters.Count);
            Assert.AreEqual("path", parameter.Name.VariablePath.UserPath);
        }
        public override void Execute(object sender, EventArgs args)
        {
            ParamBlockAst scriptParameters = ParameterEditorHelper.GetScriptParameters(_adaptersFactory, _textManager);

            ScriptArgs = ParameterEditorHelper.PromptForScriptParameterValues(scriptParameters);

            if (ScriptArgs.ShouldExecute)
            {
                base.Execute(sender, args);
            }
        }
        private ParamBlockAst GenerateParamBlockAst(string script)
        {
            var           ast        = GenerateAst(script);
            ParamBlockAst paramBlock = null;

            if (PowerShellParseUtilities.HasParamBlock(ast, out paramBlock))
            {
                return(paramBlock);
            }
            return(null);
        }
Esempio n. 15
0
        public void ParamBlockWithTwoParametersTest()
        {
            ParamBlockAst result = ParseInput("param($first, $second)")
                                   .ParamBlock;

            ParameterAst firstParameter  = result.Parameters.FirstOrDefault();
            ParameterAst secondParameter = result.Parameters.LastOrDefault();

            Assert.AreEqual(2, result.Parameters.Count);
            Assert.AreEqual("first", firstParameter.Name.VariablePath.UserPath);
            Assert.AreEqual("second", secondParameter.Name.VariablePath.UserPath);
        }
Esempio n. 16
0
    public System.Object VisitScriptBlock(System.Management.Automation.Language.ScriptBlockAst scriptBlockAst)
    {
        IScriptExtent mappedExtent = MapExtent(scriptBlockAst.Extent);

        ParamBlockAst mappedParamBlock = scriptBlockAst.ParamBlock == null ? null : (ParamBlockAst)VisitParamBlock(scriptBlockAst.ParamBlock);

        NamedBlockAst mappedBeginBlock        = scriptBlockAst.BeginBlock == null ? null : (NamedBlockAst)VisitNamedBlock(scriptBlockAst.BeginBlock);
        NamedBlockAst mappedProcessBlock      = scriptBlockAst.ProcessBlock == null ? null : (NamedBlockAst)VisitNamedBlock(scriptBlockAst.ProcessBlock);
        NamedBlockAst mappedEndBlock          = scriptBlockAst.EndBlock == null ? null : (NamedBlockAst)VisitNamedBlock(scriptBlockAst.EndBlock);
        NamedBlockAst mappedDynamicParamBlock = scriptBlockAst.DynamicParamBlock == null ? null : (NamedBlockAst)VisitNamedBlock(scriptBlockAst.DynamicParamBlock);

        return(new ScriptBlockAst(mappedExtent, mappedParamBlock, mappedBeginBlock, mappedProcessBlock, mappedEndBlock, mappedDynamicParamBlock));
    }
 private static CorrectionExtent GetCorrectionToAddAttribute(ParamBlockAst paramBlockAst)
 {
     return(new CorrectionExtent(
                paramBlockAst.Extent.StartLineNumber,
                paramBlockAst.Extent.StartLineNumber,
                1,
                1,
                new String[] {
         new String(whitespace, paramBlockAst.Extent.StartColumnNumber - 1)
         + "[CmdletBinding(SupportsShouldProcess)]",
         String.Empty
     },
                null,
                null));
 }
        private static bool?ShowParameterEditor(ParamBlockAst paramBlockAst, out string scriptArgs)
        {
            scriptArgs = String.Empty;
            var model     = PowerShellParseUtilities.ParseParameters(paramBlockAst);
            var viewModel = new ParameterEditorViewModel(model);
            var view      = new ParameterEditorView(viewModel);

            bool?wasOkClicked = view.ShowModal();

            if (wasOkClicked != true)
            {
                return(wasOkClicked);
            }

            scriptArgs = GenerateScripArgsFromModel(model);
            return(wasOkClicked);
        }
Esempio n. 19
0
        /// <summary>
        /// Get the CmdletBinding attribute ast
        /// </summary>
        /// <param name="attributeAsts"></param>
        /// <returns>Returns CmdletBinding attribute ast if it exists, otherwise returns null</returns>
        public static AttributeAst GetCmdletBindingAttributeAst(this ParamBlockAst paramBlockAst)
        {
            var attributeAsts = paramBlockAst.Attributes;

            if (attributeAsts == null)
            {
                return(null);
            }

            foreach (var attributeAst in attributeAsts)
            {
                if (attributeAst != null && attributeAst.IsCmdletBindingAttributeAst())
                {
                    return(attributeAst);
                }
            }

            return(null);
        }
Esempio n. 20
0
        /// <summary>
        /// Get the parameter Asts from a function definition Ast.
        ///
        /// If not parameters are found, return null.
        /// </summary>
        /// <param name="paramBlockAst">If a parameter block is present, set this argument's value to the parameter block.</param>
        /// <returns></returns>
        public static IEnumerable <ParameterAst> GetParameterAsts(
            this FunctionDefinitionAst functionDefinitionAst,
            out ParamBlockAst paramBlockAst)
        {
            // todo instead of returning null return an empty enumerator if no parameter is found
            // this removes the burden from the user for null checking.
            paramBlockAst = null;
            if (functionDefinitionAst.Parameters != null)
            {
                return(functionDefinitionAst.Parameters);
            }
            else if (functionDefinitionAst.Body.ParamBlock?.Parameters != null)
            {
                paramBlockAst = functionDefinitionAst.Body.ParamBlock;
                return(functionDefinitionAst.Body.ParamBlock.Parameters);
            }

            return(null);
        }
        public static ParamBlockAst GetScriptParameters(IVsEditorAdaptersFactoryService adaptersFactory, IVsTextManager textManager)
        {
            IVsTextView   vsTextView;
            ParamBlockAst paramBlock = null;

            //Returns the active or previously active view.
            //
            // Parameters:
            //   fMustHaveFocus:
            //     [in] If true, then the current UI active view is returned. If false, then
            //     the last active view is returned, regardless of whether this view is currently
            //     UI active.
            //
            //   pBuffer:
            //     [in] Pass null for pBuffer to get the previously active code view, regardless
            //     of the text buffer that it was associated with. If you pass in a valid pointer
            //     to a buffer, then you are returned the last active view for that particular
            //     buffer.
            //
            //   ppView:
            //     [out] Pointer to the Microsoft.VisualStudio.TextManager.Interop.IVsTextView
            //     interface.
            textManager.GetActiveView(1, null, out vsTextView);
            if (vsTextView == null)
            {
                return(null);
            }

            IVsTextLines textLines;

            vsTextView.GetBuffer(out textLines);
            ITextBuffer textBuffer = adaptersFactory.GetDataBuffer(textLines as IVsTextBuffer);
            Ast         scriptAst;

            if (!textBuffer.Properties.TryGetProperty <Ast>(BufferProperties.Ast, out scriptAst))
            {
                return(null);
            }

            PowerShellParseUtilities.HasParamBlock(scriptAst, out paramBlock);
            return(paramBlock);
        }
 public static ScriptBlockAst Update(
     this ScriptBlockAst ast,
     IEnumerable <UsingStatementAst> usingStatements = null,
     IEnumerable <AttributeAst> attributes           = null,
     ParamBlockAst paramBlock        = null,
     NamedBlockAst beginBlock        = null,
     NamedBlockAst processBlock      = null,
     NamedBlockAst endBlock          = null,
     NamedBlockAst dynamicParamBlock = null)
 {
     return(new ScriptBlockAst(
                ast.Extent,
                usingStatements?.CloneAll() ?? ast.UsingStatements?.CloneAll(),
                attributes?.CloneAll() ?? ast.Attributes?.CloneAll(),
                paramBlock?.Clone() ?? ast.ParamBlock?.Clone(),
                beginBlock?.Clone() ?? ast.BeginBlock?.Clone(),
                processBlock?.Clone() ?? ast.ProcessBlock?.Clone(),
                endBlock?.Clone() ?? ast.EndBlock?.Clone(),
                dynamicParamBlock?.Clone() ?? ast.DynamicParamBlock?.Clone()));
 }
 public static ScriptBlockAst Update(
     this ScriptBlockAst ast,
     IEnumerable <StatementAst> statements,
     IEnumerable <UsingStatementAst> usingStatements = null,
     IEnumerable <AttributeAst> attributes           = null,
     ParamBlockAst paramBlock = null,
     bool?isFilter            = null,
     bool?isConfiguration     = null)
 {
     return(new ScriptBlockAst(
                ast.Extent,
                usingStatements?.CloneAll() ?? ast.UsingStatements?.CloneAll(),
                attributes?.CloneAll() ?? ast.Attributes?.CloneAll(),
                paramBlock?.Clone() ?? ast.ParamBlock?.Clone(),
                new StatementBlockAst(
                    ast.EndBlock.Extent,
                    statements?.CloneAll() ?? ast.EndBlock?.Statements?.CloneAll(),
                    ast.EndBlock?.Traps?.CloneAll()),
                isFilter: false,
                isConfiguration: false));
 }
        public void ShouldParseParametersCorrectly()
        {
            ParamBlockAst paramBlock = GenerateParamBlockAst(scriptWithParameters);
            var           model      = PowerShellParseUtilities.ParseParameters(paramBlock);

            var expectedModel = new ParameterEditorModel(
                new ObservableCollection <ScriptParameterViewModel>()
            {
                new ScriptParameterViewModel(new ScriptParameter()
                {
                    Name         = "StringType",
                    Type         = DataTypeConstants.StringType,
                    DefaultValue = null
                }),
                new ScriptParameterViewModel(new ScriptParameter()
                {
                    Name         = "CharType",
                    Type         = DataTypeConstants.CharType,
                    DefaultValue = null
                }),
                new ScriptParameterViewModel(new ScriptParameter()
                {
                    Name         = "ByteType",
                    Type         = DataTypeConstants.ByteType,
                    DefaultValue = null
                }),
                new ScriptParameterViewModel(new ScriptParameter()
                {
                    Name         = "IntType",
                    Type         = DataTypeConstants.Int32Type,
                    DefaultValue = null
                })
            },

                PowerShellParseUtilities.GenerateCommonParameters());

            Assert.AreEqual <bool>(true, CompareParameterEditorModels(expectedModel, model));
        }
Esempio n. 25
0
 public override AstVisitAction VisitParamBlock(ParamBlockAst paramBlockAst)
 {
     Console.WriteLine("Visited an ParamBlockAst.");
     Console.WriteLine("    " + paramBlockAst.ToString().Replace(Environment.NewLine, Environment.NewLine + "    "));
     return(AstVisitAction.Continue);
 }
Esempio n. 26
0
 public object VisitParamBlock(ParamBlockAst paramBlockAst)
 {
     return(false);
 }
Esempio n. 27
0
        /// <summary>
        /// Try to parse a Param block and form them into a model containing parameters related data.
        /// </summary>
        /// <param name="paramBlockAst">The targeting Param block.</param>
        /// <returns>A model containing parameters related data.</returns>
        public static ParameterEditorModel ParseParameters(ParamBlockAst paramBlockAst)
        {
            ObservableCollection <ScriptParameterViewModel>         scriptParameters             = new ObservableCollection <ScriptParameterViewModel>();
            IDictionary <string, IList <ScriptParameterViewModel> > parameterSetToParametersDict = new Dictionary <string, IList <ScriptParameterViewModel> >();
            IList <string> parameterSetNames = new List <string>();

            if (paramBlockAst != null)
            {
                // First, filter all parameter types not supported yet.
                var parametersList = paramBlockAst.Parameters.
                                     Where(p => !DataTypeConstants.UnsupportedDataTypes.Contains(p.StaticType.FullName)).
                                     ToList();

                foreach (var p in parametersList)
                {
                    HashSet <object> allowedValues         = new HashSet <object>();
                    bool             isParameterSetDefined = false;
                    string           parameterSetName      = null;
                    bool             isMandatory           = false;

                    foreach (var a in p.Attributes)
                    {
                        // Find if there defines attribute ValidateSet
                        if (a.TypeName.FullName.Equals(ValidateSetTypeName, StringComparison.OrdinalIgnoreCase))
                        {
                            foreach (StringConstantExpressionAst pa in ((AttributeAst)a).PositionalArguments)
                            {
                                allowedValues.Add(pa.Value);
                            }
                        }

                        // Find if there defines attribute ParameterNameSet
                        // Find if there defines attribute Mandatory
                        if (a is AttributeAst)
                        {
                            foreach (var arg in ((AttributeAst)a).NamedArguments)
                            {
                                if (!isParameterSetDefined)
                                {
                                    isParameterSetDefined = arg.ArgumentName.Equals(ParameterSetArgumentName, StringComparison.OrdinalIgnoreCase);
                                    if (isParameterSetDefined)
                                    {
                                        parameterSetName = ((StringConstantExpressionAst)arg.Argument).Value;
                                    }
                                }

                                if (!isMandatory)
                                {
                                    bool isMandatoryDefined = arg.ArgumentName.Equals(MandatoryArgumentName, StringComparison.OrdinalIgnoreCase);
                                    if (isMandatoryDefined)
                                    {
                                        if (arg.Argument is VariableExpressionAst)
                                        {
                                            isMandatory = ((VariableExpressionAst)arg.Argument).VariablePath.UserPath.Equals("true", StringComparison.OrdinalIgnoreCase);
                                        }

                                        if (arg.Argument is ConstantExpressionAst)
                                        {
                                            isMandatory = Convert.ToBoolean(((ConstantExpressionAst)arg.Argument).Value);
                                        }
                                    }
                                }
                            }
                        }
                    }

                    // Get parameter type
                    string type = p.StaticType.FullName;
                    if (type.EndsWith(DataTypeConstants.ArrayType, StringComparison.OrdinalIgnoreCase))
                    {
                        type = DataTypeConstants.ArrayType;
                    }

                    // Get parameter name
                    string name = p.Name.VariablePath.UserPath;

                    // Get paramter default value, null it is if there is none specified
                    object defaultValue = null;
                    if (p.DefaultValue != null)
                    {
                        if (p.DefaultValue is ConstantExpressionAst)
                        {
                            defaultValue = ((ConstantExpressionAst)p.DefaultValue).Value;
                        }
                        else if (p.DefaultValue is VariableExpressionAst)
                        {
                            defaultValue = ((VariableExpressionAst)p.DefaultValue).VariablePath.UserPath;
                        }
                    }

                    // Construct a ScriptParameterViewModel based on whether a parameter set is found
                    ScriptParameterViewModel newViewModel = null;
                    if (isParameterSetDefined && parameterSetName != null)
                    {
                        newViewModel = new ScriptParameterViewModel(new ScriptParameter(name, type, defaultValue, allowedValues, parameterSetName, isMandatory));
                        IList <ScriptParameterViewModel> existingSets;
                        if (parameterSetToParametersDict.TryGetValue(parameterSetName, out existingSets))
                        {
                            existingSets.Add(newViewModel);
                        }
                        else
                        {
                            parameterSetNames.Add(parameterSetName);
                            parameterSetToParametersDict.Add(parameterSetName, new List <ScriptParameterViewModel>()
                            {
                                newViewModel
                            });
                        }
                    }
                    else
                    {
                        newViewModel = new ScriptParameterViewModel(new ScriptParameter(name, type, defaultValue, allowedValues, isMandatory));
                        scriptParameters.Add(newViewModel);
                    }
                }
            }
            // Construct the actual model
            ParameterEditorModel model = new ParameterEditorModel(scriptParameters,
                                                                  GenerateCommonParameters(),
                                                                  parameterSetToParametersDict.Count > 0 ? parameterSetToParametersDict : null,
                                                                  parameterSetNames.Count > 0 ? parameterSetNames : null,
                                                                  parameterSetNames.FirstOrDefault());

            return(model);
        }
Esempio n. 28
0
        /// <summary>
        /// Try to find a Param block on the top level of an AST.
        /// </summary>
        /// <param name="ast">The targeting AST.</param>
        /// <param name="paramBlockAst">Wanted Param block.</param>
        /// <returns>True if there is one. Otherwise, false.</returns>
        public static bool HasParamBlock(Ast ast, out ParamBlockAst paramBlockAst)
        {
            paramBlockAst = (ParamBlockAst)ast.Find(p => p is ParamBlockAst, false);

            return(paramBlockAst != null);
        }
        public object VisitScriptBlock(ScriptBlockAst scriptBlockAst)
        {
            if (scriptBlockAst.ParamBlock != null)
            {
                return(scriptBlockAst);
            }

            if (scriptBlockAst.BeginBlock != null)
            {
                _errorWriter.ReportNotSupported(
                    scriptBlockAst.BeginBlock.Extent,
                    nameof(CompilerStrings.BeginBlock),
                    CompilerStrings.BeginBlock);
                return(null);
            }

            if (scriptBlockAst.ProcessBlock != null)
            {
                _errorWriter.ReportNotSupported(
                    scriptBlockAst.ProcessBlock.Extent,
                    nameof(CompilerStrings.ProcessBlock),
                    CompilerStrings.ProcessBlock);
                return(null);
            }

            if (scriptBlockAst.EndBlock == null)
            {
                _errorWriter.ReportMissing(
                    scriptBlockAst.Extent,
                    nameof(CompilerStrings.EndBlock),
                    CompilerStrings.EndBlock);
                return(null);
            }

            var body = scriptBlockAst.EndBlock.Visit(this);

            if (_failed)
            {
                return(scriptBlockAst);
            }

            _errorWriter.ThrowIfAnyErrors();
            var parameters = new ParameterAst[_variables.Count];

            for (var i = 0; i < parameters.Length; i++)
            {
                parameters[i] = new ParameterAst(
                    _variables[i].Item2.Extent,
                    (VariableExpressionAst)_variables[i].Item2.Copy(),
                    new[] { new TypeConstraintAst(_variables[i].Item1.Extent, _variables[i].Item1) },
                    null);
            }

            var paramBlock =
                new ParamBlockAst(
                    _paramBlockExtent,
                    Array.Empty <AttributeAst>(),
                    parameters);

            return(new ScriptBlockAst(
                       scriptBlockAst.Extent,
                       paramBlock,
                       null,
                       null,
                       (NamedBlockAst)((Ast)body).Copy(),
                       null));
        }
Esempio n. 30
0
 public object VisitParamBlock(ParamBlockAst paramBlockAst)
 {
     Console.WriteLine("Visited an ParamBlockAst.");
     return(paramBlockAst);
 }