Ejemplo n.º 1
0
        public string GetCommandName()
        {
            StringConstantExpressionAst ast = this.CommandElements[0] as StringConstantExpressionAst;

            if (ast == null)
            {
                return(null);
            }
            return(ast.Value);
        }
Ejemplo n.º 2
0
        public Expression SetValue(Compiler compiler, Expression rhs)
        {
            StringConstantExpressionAst member = this.MemberExpression.Member as StringConstantExpressionAst;

            if (member != null)
            {
                return(Expression.Dynamic(PSSetMemberBinder.Get(member.Value, this.MemberExpression.Static), typeof(object), this.CachedTarget ?? this.GetTargetExpr(compiler), rhs));
            }
            return(Expression.Dynamic(PSSetDynamicMemberBinder.Get(this.MemberExpression.Static), typeof(object), this.CachedTarget ?? this.GetTargetExpr(compiler), this.CachedPropertyExpr ?? this.GetPropertyExpr(compiler), rhs));
        }
        public Expression SetValue(Compiler compiler, Expression rhs)
        {
            PSMethodInvocationConstraints invokeMemberConstraints = Compiler.GetInvokeMemberConstraints(this.InvokeMemberExpressionAst);
            StringConstantExpressionAst   member = this.InvokeMemberExpressionAst.Member as StringConstantExpressionAst;
            Expression targetExpr = this.GetTargetExpr(compiler);
            IEnumerable <Expression> argumentExprs = this.GetArgumentExprs(compiler);

            if (member == null)
            {
                throw new NotImplementedException("invoke method dynamic name");
            }
            return(Compiler.InvokeMember(member.Value, invokeMemberConstraints, targetExpr, argumentExprs.Append <Expression>(rhs), false, true));
        }
Ejemplo n.º 4
0
        public override AstVisitAction VisitCommand(CommandAst commandAst)
        {
            StringConstantExpressionAst ast = commandAst.CommandElements[0] as StringConstantExpressionAst;

            if ((ast != null) && hashOfPessimizingCmdlets.Contains(ast.Value))
            {
                this._disableOptimizations = true;
            }
            if (commandAst.InvocationOperator == TokenKind.Dot)
            {
                this._disableOptimizations = true;
            }
            return(AstVisitAction.Continue);
        }
Ejemplo n.º 5
0
        private static string GetLabel(ExpressionAst expr)
        {
            if (expr == null)
            {
                return("");
            }
            StringConstantExpressionAst ast = expr as StringConstantExpressionAst;

            if (ast == null)
            {
                return(null);
            }
            return(ast.Value);
        }
Ejemplo n.º 6
0
        public override object VisitStringConstantExpression(StringConstantExpressionAst stringConstantExpressionAst)
        {
            if (stringConstantExpressionAst == ast)
            {
                var newAst = new StringConstantExpressionAst(stringConstantExpressionAst.Extent,
                    code,
                    stringConstantExpressionAst.StringConstantType);

                rootAst.ModifiedAsts.Add(newAst);

                return newAst;
            }
            else
                return base.VisitStringConstantExpression(stringConstantExpressionAst);
        }
Ejemplo n.º 7
0
 public override object VisitInvokeMemberExpression(InvokeMemberExpressionAst invokeMemberExpressionAst)
 {
     var newExpression = VisitElement(invokeMemberExpressionAst.Expression);
     CommandElementAst newMethod;
     if (invokeMemberExpressionAst == ast)
     {
         newMethod = new StringConstantExpressionAst(invokeMemberExpressionAst.Member.Extent, newMethodName,
             ((StringConstantExpressionAst) invokeMemberExpressionAst.Member).StringConstantType);
         rootAst.ModifiedAsts.Add(newMethod);
     }
     else
     {
         newMethod = VisitElement(invokeMemberExpressionAst.Member);
     }
     var newArguments = VisitElements(invokeMemberExpressionAst.Arguments);
     return new InvokeMemberExpressionAst(invokeMemberExpressionAst.Extent, newExpression, newMethod,
         newArguments, invokeMemberExpressionAst.Static);
 }
Ejemplo n.º 8
0
        public Expression GetValue(Compiler compiler, List <Expression> exprs, List <ParameterExpression> temps)
        {
            Expression          targetExpr = this.GetTargetExpr(compiler);
            ParameterExpression item       = Expression.Parameter(targetExpr.Type);

            temps.Add(item);
            this.CachedTarget = item;
            exprs.Add(Expression.Assign(item, targetExpr));
            StringConstantExpressionAst member = this.MemberExpression.Member as StringConstantExpressionAst;

            if (member != null)
            {
                return(Expression.Dynamic(PSGetMemberBinder.Get(member.Value, this.MemberExpression.Static), typeof(object), item));
            }
            ParameterExpression expression4 = Expression.Parameter(this.GetPropertyExpr(compiler).Type);

            temps.Add(expression4);
            exprs.Add(Expression.Assign(expression4, compiler.Compile(this.MemberExpression.Member)));
            this.CachedPropertyExpr = expression4;
            return(Expression.Dynamic(PSGetDynamicMemberBinder.Get(this.MemberExpression.Static), typeof(object), item, expression4));
        }
        public Expression GetValue(Compiler compiler, List <Expression> exprs, List <ParameterExpression> temps)
        {
            PSMethodInvocationConstraints invokeMemberConstraints = Compiler.GetInvokeMemberConstraints(this.InvokeMemberExpressionAst);
            Expression targetExpr = this.GetTargetExpr(compiler);

            this._targetExprTemp = Expression.Variable(targetExpr.Type);
            exprs.Add(Expression.Assign(this._targetExprTemp, targetExpr));
            IEnumerable <Expression> argumentExprs = this.GetArgumentExprs(compiler);

            this._argExprTemps = (from arg in argumentExprs select Expression.Variable(arg.Type)).ToArray <ParameterExpression>();
            exprs.AddRange((IEnumerable <Expression>)argumentExprs.Zip <Expression, ParameterExpression, BinaryExpression>(this._argExprTemps, (arg, temp) => Expression.Assign(temp, arg)));
            temps.Add(this._targetExprTemp);
            temps.AddRange(this._argExprTemps);
            StringConstantExpressionAst member = this.InvokeMemberExpressionAst.Member as StringConstantExpressionAst;

            if (member == null)
            {
                throw new NotImplementedException("invoke method dynamic name");
            }
            return(Compiler.InvokeMember(member.Value, invokeMemberConstraints, this._targetExprTemp, this._argExprTemps, false, false));
        }
Ejemplo n.º 10
0
        private void BreakOrContinue(ExpressionAst label, Func <LoopGotoTargets, Block> fieldSelector)
        {
            Func <LoopGotoTargets, Block> selector = null;
            Block next = null;

            if (label != null)
            {
                label.Accept(this);
                if (this._loopTargets.Any <LoopGotoTargets>())
                {
                    Func <LoopGotoTargets, bool> predicate   = null;
                    StringConstantExpressionAst  labelStrAst = label as StringConstantExpressionAst;
                    if (labelStrAst != null)
                    {
                        if (predicate == null)
                        {
                            predicate = t => t.Label.Equals(labelStrAst.Value, StringComparison.OrdinalIgnoreCase);
                        }
                        if (selector == null)
                        {
                            selector = t => fieldSelector(t);
                        }
                        next = this._loopTargets.Where <LoopGotoTargets>(predicate).Select <LoopGotoTargets, Block>(selector).LastOrDefault <Block>();
                    }
                }
            }
            else if (this._loopTargets.Count > 0)
            {
                next = fieldSelector(this._loopTargets.Last <LoopGotoTargets>());
            }
            if (next != null)
            {
                this._currentBlock.FlowsTo(next);
            }
            this._currentBlock = new Block();
        }
Ejemplo n.º 11
0
 public virtual AstVisitAction VisitStringConstantExpression(StringConstantExpressionAst stringConstantExpressionAst)
 {
     return AstVisitAction.Continue;
 }
Ejemplo n.º 12
0
    public System.Object VisitStringConstantExpression(System.Management.Automation.Language.StringConstantExpressionAst stringConstantExpressionAst)
    {
        IScriptExtent mappedExtent = MapExtent(stringConstantExpressionAst.Extent);

        return(new StringConstantExpressionAst(mappedExtent, stringConstantExpressionAst.Value, stringConstantExpressionAst.StringConstantType));
    }
Ejemplo n.º 13
0
 /// <summary/>
 public virtual object VisitStringConstantExpression(StringConstantExpressionAst stringConstantExpressionAst)
 {
     return _decorated.VisitStringConstantExpression(stringConstantExpressionAst);
 }
Ejemplo n.º 14
0
 public override AstVisitAction VisitStringConstantExpression(StringConstantExpressionAst stringConstantExpressionAst)
 {
     return AstVisitAction.Continue;
 }
Ejemplo n.º 15
0
 public object VisitStringConstantExpression(StringConstantExpressionAst stringConstantExpressionAst)
 {
     return Expression.Constant(stringConstantExpressionAst.Value);
 }
Ejemplo n.º 16
0
 public CSharpPatcher(string code, StringConstantExpressionAst ast, PSScriptAst rootAst)
     : base(rootAst)
 {
     this.code = code;
     this.ast = ast;
 }
Ejemplo n.º 17
0
 public object VisitStringConstantExpression(StringConstantExpressionAst stringConstantExpressionAst)
 {
     return true;
 }
Ejemplo n.º 18
0
 public CSharpClassAst(TypeDeclaration tree, StringConstantExpressionAst ast)
 {
     this.tree = tree;
     Ast = ast;
 }
Ejemplo n.º 19
0
        public override AstVisitAction VisitStringConstantExpression(StringConstantExpressionAst stringConstantExpressionAst)
        {
            // Constants are allowed.

            return AstVisitAction.Continue;
        }
Ejemplo n.º 20
0
 public object VisitStringConstantExpression(StringConstantExpressionAst stringConstantExpressionAst)
 {
     return stringConstantExpressionAst.Value;
 }
Ejemplo n.º 21
0
 /// <summary/>
 public virtual AstVisitAction VisitStringConstantExpression(StringConstantExpressionAst stringConstantExpressionAst) => DefaultVisit(stringConstantExpressionAst);
Ejemplo n.º 22
0
        internal CommandBaseAst CommandRule()
    {
        Token token;
        bool flag;
        bool flag2;
        IScriptExtent extent;
        bool flag3 = false;
        bool flag4 = false;
        RedirectionAst[] redirections = null;
        List<CommandElementAst> elements = new List<CommandElementAst>();
        TokenizerMode mode = this._tokenizer.Mode;
        try
        {
            CommandArgumentContext commandNameAfterInvoationOperator;
            this.SetTokenizerMode(TokenizerMode.Command);
            Token first = this.NextToken();
            token = first;
            extent = first.Extent;
            flag = false;
            flag2 = false;
            if (first.Kind == TokenKind.Dot)
            {
                flag = true;
                first = this.NextToken();
                commandNameAfterInvoationOperator = CommandArgumentContext.CommandNameAfterInvocationOperator;
            }
            else if (first.Kind == TokenKind.Ampersand)
            {
                flag2 = true;
                first = this.NextToken();
                commandNameAfterInvoationOperator = CommandArgumentContext.CommandNameAfterInvocationOperator;
            }
            else
            {
                commandNameAfterInvoationOperator = CommandArgumentContext.CommandName;
            }
            bool flag5 = true;
            while (flag5)
            {
                switch (first.Kind)
                {
                    case TokenKind.Parameter:
                        if (((commandNameAfterInvoationOperator & CommandArgumentContext.CommandName) != 0) || flag3)
                        {
                            extent = first.Extent;
                            first.TokenFlags |= TokenFlags.CommandName;
                            StringConstantExpressionAst item = new StringConstantExpressionAst(first.Extent, first.Text, StringConstantType.BareWord);
                            elements.Add(item);
                        }
                        else
                        {
                            ExpressionAst commandArgument;
                            IScriptExtent extent2;
                            ParameterToken token3 = (ParameterToken) first;
                            if (token3.UsedColon && (this.PeekToken().Kind != TokenKind.Comma))
                            {
                                commandArgument = this.GetCommandArgument(CommandArgumentContext.CommandArgument, this.NextToken());
                                if (commandArgument == null)
                                {
                                    extent2 = token3.Extent;
                                    this.ReportError(After(extent2), ParserStrings.ParameterRequiresArgument, new object[] { token3.Text });
                                }
                                else
                                {
                                    extent2 = ExtentOf(first, commandArgument);
                                }
                            }
                            else
                            {
                                commandArgument = null;
                                extent2 = first.Extent;
                            }
                            extent = extent2;
                            CommandParameterAst ast3 = new CommandParameterAst(extent2, token3.ParameterName, commandArgument, first.Extent);
                            elements.Add(ast3);
                        }
                        goto Label_0404;

                    case TokenKind.NewLine:
                    case TokenKind.RParen:
                    case TokenKind.RCurly:
                    case TokenKind.Semi:
                    case TokenKind.AndAnd:
                    case TokenKind.OrOr:
                    case TokenKind.Pipe:
                    case TokenKind.EndOfInput:
                    {
                        this.UngetToken(first);
                        flag5 = false;
                        continue;
                    }
                    case TokenKind.Ampersand:
                        extent = first.Extent;
                        this.ReportError(first.Extent, ParserStrings.MissingArgument, new object[0]);
                        goto Label_0404;

                    case TokenKind.Comma:
                        extent = first.Extent;
                        this.ReportError(first.Extent, ParserStrings.MissingArgument, new object[0]);
                        this.SkipNewlines();
                        goto Label_0404;

                    case TokenKind.MinusMinus:
                        extent = first.Extent;
                        elements.Add(flag3 ? ((CommandElementAst) new StringConstantExpressionAst(first.Extent, first.Text, StringConstantType.BareWord)) : ((CommandElementAst) new CommandParameterAst(first.Extent, "-", null, first.Extent)));
                        flag3 = true;
                        goto Label_0404;

                    case TokenKind.Redirection:
                    case TokenKind.RedirectInStd:
                        if ((commandNameAfterInvoationOperator & CommandArgumentContext.CommandName) != 0)
                        {
                            break;
                        }
                        if (redirections == null)
                        {
                            redirections = new RedirectionAst[7];
                        }
                        this.RedirectionRule((RedirectionToken) first, redirections, ref extent);
                        goto Label_0404;

                    default:
                    {
                        if ((first.Kind == TokenKind.InlineScript) && (commandNameAfterInvoationOperator == CommandArgumentContext.CommandName))
                        {
                            flag5 = this.InlineScriptRule(first, elements);
                            extent = elements.Last<CommandElementAst>().Extent;
                            if (flag5)
                            {
                                goto Label_0404;
                            }
                            continue;
                        }
                        ExpressionAst ast4 = this.GetCommandArgument(commandNameAfterInvoationOperator, first);
                        StringToken token4 = first as StringToken;
                        if ((token4 != null) && string.Equals(token4.Value, "--%", StringComparison.OrdinalIgnoreCase))
                        {
                            elements.Add(ast4);
                            extent = ast4.Extent;
                            StringToken verbatimCommandArgumentToken = this.GetVerbatimCommandArgumentToken();
                            if (verbatimCommandArgumentToken != null)
                            {
                                flag4 = true;
                                flag5 = false;
                                ast4 = new StringConstantExpressionAst(verbatimCommandArgumentToken.Extent, verbatimCommandArgumentToken.Value, StringConstantType.BareWord);
                                elements.Add(ast4);
                                extent = ast4.Extent;
                            }
                        }
                        else
                        {
                            extent = ast4.Extent;
                            elements.Add(ast4);
                        }
                        goto Label_0404;
                    }
                }
                extent = first.Extent;
                elements.Add(new StringConstantExpressionAst(first.Extent, first.Text, StringConstantType.BareWord));
            Label_0404:
                if (!flag4)
                {
                    commandNameAfterInvoationOperator = CommandArgumentContext.CommandArgument;
                    first = this.NextToken();
                }
            }
        }
        finally
        {
            this.SetTokenizerMode(mode);
        }
        if (elements.Count == 0)
        {
            if (flag || flag2)
            {
                IScriptExtent extent3 = token.Extent;
                this.ReportError(extent3, ParserStrings.MissingExpression, new object[] { token.Text });
                return new CommandExpressionAst(extent3, new ErrorExpressionAst(extent3, null), null);
            }
            return null;
        }
        return new CommandAst(ExtentOf(token, extent), elements, (flag || flag2) ? token.Kind : TokenKind.Unknown, (redirections != null) ? redirections.Where<RedirectionAst>(r => r != null) : null);
    }
Ejemplo n.º 23
0
 private ExpressionAst PrimaryExpressionRule(bool withMemberAccess)
 {
     ExpressionAst constantExpressionAst;
     Token token = this.NextToken();
     TokenKind kind = token.Kind;
     if (kind == TokenKind.Variable || kind == TokenKind.SplattedVariable)
     {
         constantExpressionAst = this.CheckUsingVariable((VariableToken)token, withMemberAccess);
         if (withMemberAccess)
         {
             return this.CheckPostPrimaryExpressionOperators(this.NextMemberAccessToken(true), constantExpressionAst);
         }
         else
         {
             return constantExpressionAst;
         }
         this.UngetToken(token);
         return null;
     }
     else if (kind == TokenKind.Parameter)
     {
         this.UngetToken(token);
         return null;
     }
     else if (kind == TokenKind.Number)
     {
         constantExpressionAst = new ConstantExpressionAst((NumberToken)token);
         if (withMemberAccess)
         {
             return this.CheckPostPrimaryExpressionOperators(this.NextMemberAccessToken(true), constantExpressionAst);
         }
         else
         {
             return constantExpressionAst;
         }
         this.UngetToken(token);
         return null;
     }
     if (kind == TokenKind.StringLiteral || kind == TokenKind.HereStringLiteral)
     {
         constantExpressionAst = new StringConstantExpressionAst((StringToken)token);
     }
     else if (kind == TokenKind.StringExpandable || kind == TokenKind.HereStringExpandable)
     {
         constantExpressionAst = this.ExpandableStringRule((StringExpandableToken)token);
     }
     else if (kind == TokenKind.LParen)
     {
         constantExpressionAst = this.ParenthesizedExpressionRule(token);
     }
     else if (kind == TokenKind.RParen || kind == TokenKind.RCurly || kind == TokenKind.LBracket || kind == TokenKind.RBracket)
     {
         this.UngetToken(token);
         return null;
     }
     else if (kind == TokenKind.LCurly)
     {
         constantExpressionAst = this.ScriptBlockExpressionRule(token);
     }
     else if (kind == TokenKind.AtParen || kind == TokenKind.DollarParen)
     {
         constantExpressionAst = this.SubExpressionRule(token);
     }
     else if (kind == TokenKind.AtCurly)
     {
         constantExpressionAst = this.HashExpressionRule(token);
     }
     else
     {
         this.UngetToken(token);
         return null;
     }
     if (withMemberAccess)
     {
         return this.CheckPostPrimaryExpressionOperators(this.NextMemberAccessToken(true), constantExpressionAst);
     }
     else
     {
         return constantExpressionAst;
     }
     this.UngetToken(token);
     return null;
 }
Ejemplo n.º 24
0
 private bool InlineScriptRule(Token inlineScriptToken, List<CommandElementAst> elements)
 {
     StringConstantExpressionAst stringConstantExpressionAst = new StringConstantExpressionAst(inlineScriptToken.Extent, inlineScriptToken.Text, StringConstantType.BareWord);
     Token tokenFlags = inlineScriptToken;
     tokenFlags.TokenFlags = tokenFlags.TokenFlags | TokenFlags.CommandName;
     elements.Add(stringConstantExpressionAst);
     this.SkipNewlines();
     Token token = this.NextToken();
     if (token.Kind == TokenKind.LCurly)
     {
         ExpressionAst expressionAst = this.ScriptBlockExpressionRule(token);
         elements.Add(expressionAst);
         return true;
     }
     else
     {
         this.UngetToken(token);
         object[] text = new object[1];
         text[0] = inlineScriptToken.Text;
         this.ReportIncompleteInput(Parser.After(inlineScriptToken), ParserStrings.MissingStatementAfterKeyword, text);
         return false;
     }
 }
Ejemplo n.º 25
0
 /// <summary/>
 public virtual object VisitStringConstantExpression(StringConstantExpressionAst stringConstantExpressionAst)
 {
     return(null);
 }
        private AssignmentStatementAst GetAssignmentStatementAst(ExpressionAst leftExpressionAst, TokenKind tokenKind)
        {
            var expressionAst = new StringConstantExpressionAst(extent, "tmp", StringConstantType.BareWord);
            var commandExpressionAst = new CommandExpressionAst(extent, expressionAst, redirections);

            return new AssignmentStatementAst(extent, leftExpressionAst, tokenKind, commandExpressionAst, extent);
        }
Ejemplo n.º 27
0
        private ExpressionAst GetCommandArgument(CommandArgumentContext context, Token token)
        {
            ExpressionAst ast;
            List<ExpressionAst> source = null;
            Token token2 = null;
            bool flag = false;
        Label_0006:
            switch (token.Kind)
            {
                case TokenKind.Variable:
                case TokenKind.SplattedVariable:
                case TokenKind.Number:
                case TokenKind.StringLiteral:
                case TokenKind.StringExpandable:
                case TokenKind.HereStringLiteral:
                case TokenKind.HereStringExpandable:
                case TokenKind.LParen:
                case TokenKind.LCurly:
                case TokenKind.AtParen:
                case TokenKind.AtCurly:
                case TokenKind.DollarParen:
                    this.UngetToken(token);
                    ast = this.PrimaryExpressionRule(true);
                    break;

                case TokenKind.Generic:
                    {
                        if ((context & CommandArgumentContext.CommandName) != 0)
                        {
                            token.TokenFlags |= TokenFlags.CommandName;
                        }
                        StringToken token3 = (StringToken)token;
                        StringExpandableToken expandableStringToken = token3 as StringExpandableToken;
                        if ((expandableStringToken != null) && (context != CommandArgumentContext.CommandName))
                        {
                            List<ExpressionAst> nestedExpressions = this.ParseNestedExpressions(expandableStringToken);
                            ast = new ExpandableStringExpressionAst(expandableStringToken, expandableStringToken.Value, expandableStringToken.FormatString, nestedExpressions);
                        }
                        else
                        {
                            ast = new StringConstantExpressionAst(token3.Extent, token3.Value, StringConstantType.BareWord);
                            if (string.Equals(token3.Value, "--%", StringComparison.OrdinalIgnoreCase))
                            {
                                flag = true;
                            }
                        }
                        break;
                    }
                case TokenKind.NewLine:
                case TokenKind.EndOfInput:
                case TokenKind.RParen:
                case TokenKind.RCurly:
                case TokenKind.Semi:
                case TokenKind.AndAnd:
                case TokenKind.OrOr:
                case TokenKind.Ampersand:
                case TokenKind.Pipe:
                case TokenKind.Comma:
                case TokenKind.MinusMinus:
                case TokenKind.Redirection:
                case TokenKind.RedirectInStd:
                    this.UngetToken(token);
                    if (token2 != null)
                    {
                        this.ReportIncompleteInput(After(token2), ParserStrings.MissingExpression, new object[] { "," });
                        return new ErrorExpressionAst(ExtentOf(source.First<ExpressionAst>(), token2), (IEnumerable<Ast>)source);
                    }
                    return null;

                default:
                    ast = new StringConstantExpressionAst(token.Extent, token.Text, StringConstantType.BareWord);
                    switch (context)
                    {
                        case CommandArgumentContext.CommandName:
                        case CommandArgumentContext.CommandNameAfterInvocationOperator:
                            token.TokenFlags |= TokenFlags.CommandName;
                            break;

                        case CommandArgumentContext.FileName:
                        case CommandArgumentContext.CommandArgument:
                        case CommandArgumentContext.SwitchCondition:
                            token.SetIsCommandArgument();
                            break;
                    }
                    break;
            }
            if ((context == CommandArgumentContext.CommandArgument) && !flag)
            {
                token = this.PeekToken();
                if (token.Kind == TokenKind.Comma)
                {
                    token2 = token;
                    if (source == null)
                    {
                        source = new List<ExpressionAst>();
                    }
                    source.Add(ast);
                    this.SkipToken();
                    this.SkipNewlines();
                    token = this.NextToken();
                    goto Label_0006;
                }
            }
            if (source != null)
            {
                source.Add(ast);
                return new ArrayLiteralAst(ExtentOf(source.First<ExpressionAst>(), source.Last<ExpressionAst>()), source);
            }
            return ast;
        }
        public void LastAssignmentStatementAst_should_be_null_when_not_VariableExpression()
        {
            var leftExpressionAst = new StringConstantExpressionAst(extent, varName, StringConstantType.BareWord);
            var assignmentStatementAst = GetAssignmentStatementAst(leftExpressionAst, TokenKind.Equals);

            visitor.VisitAssignmentStatement(assignmentStatementAst);

            visitor.LastAssignmentStatementAst.Should().BeNull();
        }
Ejemplo n.º 29
0
 public static void PatchCSharpCode(this PSScriptAst psScriptAst, string code, StringConstantExpressionAst ast)
 {
     var patchedAst = psScriptAst.ScriptBlockAst.Visit(new CSharpPatcher(code, ast, psScriptAst)) as ScriptBlockAst;
     psScriptAst.ScriptBlockAst = patchedAst;
 }
Ejemplo n.º 30
0
 public override AstVisitAction VisitStringConstantExpression(StringConstantExpressionAst stringConstantExpressionAst)
 {
     return(AstVisitAction.Continue);
 }
Ejemplo n.º 31
0
        private ExpressionAst ExpandableStringRule(StringExpandableToken strToken)
        {
            //G  value:
            //G      literal

            ExpressionAst expr;
            // We need to scan the nested tokens even if there was some error. This is used by the tab completion: "pshome is $psh<tab>
            if (strToken.NestedTokens != null)
            {
                List<ExpressionAst> nestedExpressions = ParseNestedExpressions(strToken);
                expr = new ExpandableStringExpressionAst(strToken, strToken.Value, strToken.FormatString, nestedExpressions);
            }
            else
            {
                expr = new StringConstantExpressionAst(strToken);
            }
            return expr;
        }
Ejemplo n.º 32
0
 public override AstVisitAction VisitStringConstantExpression(StringConstantExpressionAst ast)
 {
     return this.Check(ast);
 }
Ejemplo n.º 33
0
        private ExpressionAst PrimaryExpressionRule(bool withMemberAccess)
        {
            //G  primary-expression:
            //G      value
            //G      member-access
            //G      element-access
            //G      invocation-expression
            //G      post-increment-expression
            //G      post-decrement-expression
            //G  value:
            //G      parenthesized-expression
            //G      sub-expression
            //G      array-expression
            //G      script-block-expression
            //G      hash-literal-expression
            //G      literal
            //G      type-literal
            //G      variable

            ExpressionAst expr;
            Token token = NextToken();

            switch (token.Kind)
            {
                case TokenKind.SplattedVariable:
                case TokenKind.Variable:
                    expr = CheckUsingVariable((VariableToken)token, withMemberAccess: withMemberAccess);
                    break;

                case TokenKind.Number:
                    expr = new ConstantExpressionAst((NumberToken)token);
                    break;

                case TokenKind.HereStringExpandable:
                case TokenKind.StringExpandable:
                    expr = ExpandableStringRule((StringExpandableToken)token);
                    break;

                case TokenKind.HereStringLiteral:
                case TokenKind.StringLiteral:
                    expr = new StringConstantExpressionAst((StringToken)token);
                    break;

                case TokenKind.LParen:
                    expr = ParenthesizedExpressionRule(token);
                    break;

                case TokenKind.AtParen:
                case TokenKind.DollarParen:
                    expr = SubExpressionRule(token);
                    break;

                case TokenKind.AtCurly:
                    expr = HashExpressionRule(token, false /* parsingSchemaElement */ );
                    break;

                case TokenKind.LCurly:
                    expr = ScriptBlockExpressionRule(token);
                    break;

                default:
                    UngetToken(token);
                    return null;
            }

            if (!withMemberAccess)
            {
                return expr;
            }
            return CheckPostPrimaryExpressionOperators(NextMemberAccessToken(true), expr);
        }
Ejemplo n.º 34
0
 public override AstVisitAction VisitStringConstantExpression(StringConstantExpressionAst stringConstantExpressionAst)
 {
     throw new NotImplementedException(); //VisitStringConstantExpression(stringConstantExpressionAst);
 }
Ejemplo n.º 35
0
        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);
        }
Ejemplo n.º 36
0
 public object VisitStringConstantExpression(StringConstantExpressionAst stringConstantExpressionAst)
 {
     CheckIsConstant(stringConstantExpressionAst, "Caller to verify ast is constant");
     return stringConstantExpressionAst.Value;
 }
Ejemplo n.º 37
0
 public override AstVisitAction VisitStringConstantExpression(StringConstantExpressionAst stringConstantExpressionAst)
 {
     this._pipelineCommandRuntime.outputResults.Write(stringConstantExpressionAst.Value);
     return AstVisitAction.SkipChildren;
 }
Ejemplo n.º 38
0
 /// <summary/>
 public virtual AstVisitAction VisitStringConstantExpression(StringConstantExpressionAst stringConstantExpressionAst)
 {
     return(AstVisitAction.Continue);
 }
Ejemplo n.º 39
0
        internal Ast CommandRule(bool forDynamicKeyword)
        {
            //G  command:
            //G      command-name   command-elements:opt
            //G      command-invocation-operator   command-module:opt  command-name-expr   command-elements:opt
            //G  command-invocation-operator:  one of
            //G      '&'   '.'
            //G  command-module:
            //G      primary-expression
            //G  command-name:
            //G      generic-token
            //G      generic-token-with-subexpr
            //G  generic-token-with-subexpr: No whitespace is allowed between ) and command-name.
            //G      generic-token-with-subexpr-start   statement-list:opt   )   command-name
            //G  command-name-expr:
            //G      command-name
            //G      primary-expression
            //G  command-elements:
            //G      command-element
            //G      command-elements   command-element
            //G  command-element:
            //G      command-parameter
            //G      command-argument
            //G      redirection
            //G  command-argument:
            //G      command-name-expr

            Token firstToken;
            bool dotSource, ampersand;
            bool sawDashDash = false;
            bool foundVerbatimArgument = false;

            RedirectionAst[] redirections = null;
            IScriptExtent endExtent;
            var elements = new List<CommandElementAst>();
            var oldTokenizerMode = _tokenizer.Mode;
            try
            {
                SetTokenizerMode(TokenizerMode.Command);

                Token token = NextToken();
                firstToken = token;
                endExtent = token.Extent;

                dotSource = false;
                ampersand = false;

                CommandArgumentContext context;
                if (token.Kind == TokenKind.Dot)
                {
                    dotSource = true;
                    token = NextToken();
                    context = CommandArgumentContext.CommandNameAfterInvocationOperator;
                }
                else if (token.Kind == TokenKind.Ampersand)
                {
                    ampersand = true;
                    token = NextToken();
                    context = CommandArgumentContext.CommandNameAfterInvocationOperator;
                }
                else
                {
                    context = CommandArgumentContext.CommandName;
                }

                bool scanning = true;
                while (scanning)
                {
                    switch (token.Kind)
                    {
                        case TokenKind.Pipe:
                        case TokenKind.RCurly:
                        case TokenKind.RParen:
                        case TokenKind.EndOfInput:
                        case TokenKind.NewLine:
                        case TokenKind.Semi:
                        case TokenKind.AndAnd:
                        case TokenKind.OrOr:
                            UngetToken(token);
                            scanning = false;
                            continue;

                        case TokenKind.Ampersand:
                            // ErrorRecovery: just ignore the token.
                            endExtent = token.Extent;
                            ReportError(token.Extent, () => ParserStrings.AmpersandNotAllowed);
                            break;

                        case TokenKind.MinusMinus:
                            endExtent = token.Extent;
                            // Add the first -- as a parameter, which is then ignored when constructing the command processor unless it's a native
                            // command.  All subsequent -- are added as arguments.
                            elements.Add(sawDashDash
                                ? (CommandElementAst)new StringConstantExpressionAst(token.Extent, token.Text, StringConstantType.BareWord)
                                : new CommandParameterAst(token.Extent, "-", null, token.Extent));
                            sawDashDash = true;
                            break;

                        case TokenKind.Comma:
                            endExtent = token.Extent;
                            ReportError(token.Extent, () => ParserStrings.MissingArgument);
                            SkipNewlines();
                            break;

                        case TokenKind.Parameter:
                            if ((context & CommandArgumentContext.CommandName) != 0 || sawDashDash)
                            {
                                endExtent = token.Extent;
                                token.TokenFlags |= TokenFlags.CommandName;
                                var commandName = new StringConstantExpressionAst(token.Extent, token.Text, StringConstantType.BareWord);
                                elements.Add(commandName);
                                break;
                            }
                            var parameterToken = (ParameterToken)token;
                            ExpressionAst parameterArgs;
                            IScriptExtent extent;
                            // If the next token is a comma, don't grab it as part of the argument.  The next time through this
                            // loop will issue an error.
                            if (parameterToken.UsedColon && PeekToken().Kind != TokenKind.Comma)
                            {
                                parameterArgs = GetCommandArgument(CommandArgumentContext.CommandArgument, NextToken());
                                if (parameterArgs == null)
                                {
                                    extent = parameterToken.Extent;
                                    ReportError(After(extent), () => ParserStrings.ParameterRequiresArgument, parameterToken.Text);
                                }
                                else
                                {
                                    extent = ExtentOf(token, parameterArgs);
                                }
                            }
                            else
                            {
                                parameterArgs = null;
                                extent = token.Extent;
                            }

                            endExtent = extent;
                            var paramAst = new CommandParameterAst(extent, parameterToken.ParameterName, parameterArgs, token.Extent);
                            elements.Add(paramAst);
                            break;

                        case TokenKind.Redirection:
                        case TokenKind.RedirectInStd:
                            if ((context & CommandArgumentContext.CommandName) == 0)
                            {
                                if (redirections == null)
                                {
                                    redirections = new RedirectionAst[CommandBaseAst.MaxRedirections];
                                }
                                RedirectionRule((RedirectionToken)token, redirections, ref endExtent);
                            }
                            else
                            {
                                // For backwards compatibility, we allow redirection operators as command names.
                                // V2 did not allow:
                                //     & <<
                                // but V3 and on will because it falls out rather naturally here.
                                endExtent = token.Extent;
                                elements.Add(new StringConstantExpressionAst(token.Extent, token.Text, StringConstantType.BareWord));
                            }
                            break;

                        default:
                            if (token.Kind == TokenKind.InlineScript && context == CommandArgumentContext.CommandName)
                            {
                                scanning = InlineScriptRule(token, elements);
                                Diagnostics.Assert(elements.Count >= 1, "We should at least have the command name: inlinescript");
                                endExtent = elements.Last().Extent;

                                if (!scanning) { continue; }
                            }
                            else
                            {
                                var ast = GetCommandArgument(context, token);

                                // If this is the special verbatim argument syntax, look for the next element
                                StringToken argumentToken = token as StringToken;
                                if ((argumentToken != null) && String.Equals(argumentToken.Value, VERBATIM_ARGUMENT, StringComparison.OrdinalIgnoreCase))
                                {
                                    elements.Add(ast);
                                    endExtent = ast.Extent;

                                    var verbatimToken = GetVerbatimCommandArgumentToken();
                                    if (verbatimToken != null)
                                    {
                                        foundVerbatimArgument = true;
                                        scanning = false;
                                        ast = new StringConstantExpressionAst(verbatimToken.Extent, verbatimToken.Value, StringConstantType.BareWord);
                                        elements.Add(ast);
                                        endExtent = ast.Extent;
                                    }

                                    break;
                                }

                                endExtent = ast.Extent;
                                elements.Add(ast);
                            }
                            break;
                    }

                    if (!foundVerbatimArgument)
                    {
                        context = CommandArgumentContext.CommandArgument;
                        token = NextToken();
                    }
                }
            }
            finally
            {
                SetTokenizerMode(oldTokenizerMode);
            }

            if (elements.Count == 0)
            {
                Diagnostics.Assert(!forDynamicKeyword, "DynamicKeyword should have command name at least");

                if (dotSource || ampersand)
                {
                    IScriptExtent extent = firstToken.Extent;
                    ReportError(extent, () => ParserStrings.MissingExpression, firstToken.Text);
                }
                return null;
            }

            if (forDynamicKeyword)
            {
                // TODO: report error if any redirections
                return new DynamicKeywordStatementAst(ExtentOf(firstToken, endExtent), elements);
            }

            return new CommandAst(ExtentOf(firstToken, endExtent), elements,
                                  dotSource || ampersand ? firstToken.Kind : TokenKind.Unknown,
                                  redirections != null ? redirections.Where(r => r != null) : null);
        }
Ejemplo n.º 40
0
 public object VisitStringConstantExpression(StringConstantExpressionAst stringConstantExpressionAst)
 {
     CheckIsConstant(stringConstantExpressionAst, "Caller to verify ast is constant");
     return(stringConstantExpressionAst.Value);
 }
Ejemplo n.º 41
0
        private ExpressionAst GetCommandArgument(CommandArgumentContext context, Token token)
        {
            Diagnostics.Assert(token.Kind != TokenKind.Comma, "A unary comma is an error in command mode, and should have already been reported.");
            ExpressionAst exprAst;
            List<ExpressionAst> commandArgs = null;
            Token commaToken = null;
            bool foundVerbatimArgument = false;

            while (true)
            {
                switch (token.Kind)
                {
                    // The following tokens are never allowed as command arguments.
                    case TokenKind.Pipe:
                    case TokenKind.RCurly:
                    case TokenKind.RParen:
                    case TokenKind.EndOfInput:
                    case TokenKind.NewLine:
                    case TokenKind.Semi:
                    case TokenKind.Redirection:
                    case TokenKind.RedirectInStd:
                    case TokenKind.AndAnd:
                    case TokenKind.OrOr:
                    case TokenKind.Ampersand:
                    case TokenKind.MinusMinus:
                    case TokenKind.Comma:
                        UngetToken(token);

                        // If we haven't seen an argument, the caller must issue an error.  If we've seen at least one
                        // argument, then we will issue the error and return back the arguments seen so far.
                        if (commaToken == null)
                        {
                            return null;
                        }

                        // ErrorRecovery: stop looking for additional arguments, exclude the trailing comma

                        ReportIncompleteInput(After(commaToken), () => ParserStrings.MissingExpression, ",");
                        return new ErrorExpressionAst(ExtentOf(commandArgs.First(), commaToken), commandArgs);

                    case TokenKind.SplattedVariable:
                    case TokenKind.Variable:
                    case TokenKind.Number:
                    case TokenKind.HereStringExpandable:
                    case TokenKind.StringExpandable:
                    case TokenKind.HereStringLiteral:
                    case TokenKind.StringLiteral:
                    case TokenKind.LParen:
                    case TokenKind.DollarParen:
                    case TokenKind.AtParen:
                    case TokenKind.AtCurly:
                    case TokenKind.LCurly:
                        UngetToken(token);
                        exprAst = PrimaryExpressionRule(withMemberAccess: true);
                        Diagnostics.Assert(exprAst != null, "PrimaryExpressionRule should never return null");
                        break;

                    case TokenKind.Generic:
                        if ((context & CommandArgumentContext.CommandName) != 0)
                        {
                            token.TokenFlags |= TokenFlags.CommandName;
                        }

                        var genericToken = (StringToken)token;
                        var expandableToken = genericToken as StringExpandableToken;
                        // A command name w/o invocation operator is not expandable even if the token has expandable parts
                        // If we have seen an invocation operator, the command name is expandable.
                        if (expandableToken != null && context != CommandArgumentContext.CommandName)
                        {
                            var nestedExpressions = ParseNestedExpressions(expandableToken);
                            exprAst = new ExpandableStringExpressionAst(expandableToken, expandableToken.Value,
                                                                        expandableToken.FormatString, nestedExpressions);
                        }
                        else
                        {
                            exprAst = new StringConstantExpressionAst(genericToken.Extent, genericToken.Value, StringConstantType.BareWord);

                            // If this is a verbatim argument, then don't continue peeking
                            if (String.Equals(genericToken.Value, VERBATIM_ARGUMENT, StringComparison.OrdinalIgnoreCase))
                            {
                                foundVerbatimArgument = true;
                            }
                        }
                        break;

                    default:
                        exprAst = new StringConstantExpressionAst(token.Extent, token.Text, StringConstantType.BareWord);

                        // A command/argument that matches a keyword isn't really a keyword, so don't color it that way
                        token.TokenFlags &= ~TokenFlags.Keyword;

                        switch (context)
                        {
                            case CommandArgumentContext.CommandName:
                            case CommandArgumentContext.CommandNameAfterInvocationOperator:
                                token.TokenFlags |= TokenFlags.CommandName;
                                break;
                            case CommandArgumentContext.FileName:
                            case CommandArgumentContext.CommandArgument:
                            case CommandArgumentContext.SwitchCondition:
                                token.SetIsCommandArgument();
                                break;
                        }
                        break;
                }

                if (context != CommandArgumentContext.CommandArgument)
                {
                    break;
                }

                if (foundVerbatimArgument)
                {
                    break;
                }

                token = PeekToken();
                if (token.Kind != TokenKind.Comma)
                {
                    break;
                }
                commaToken = token;
                if (commandArgs == null)
                {
                    commandArgs = new List<ExpressionAst>();
                }
                commandArgs.Add(exprAst);

                SkipToken();
                SkipNewlines();

                token = NextToken();
            }

            Diagnostics.Assert(commandArgs != null || exprAst != null, "How did that happen?");

            if (commandArgs != null)
            {
                commandArgs.Add(exprAst);
                return new ArrayLiteralAst(ExtentOf(commandArgs[0], commandArgs[commandArgs.Count - 1]), commandArgs);
            }

            return exprAst;
        }
Ejemplo n.º 42
0
        private StringConstantExpressionAst ResolveUsingAssembly(StringConstantExpressionAst name)
        {
            var assemblyName = name.Value;
            Uri uri;
            // assemblyName can be invalid, i.e. during typing.
            // We only use uri to check that we don't allow UNC paths.
            if (Uri.TryCreate(assemblyName, UriKind.Absolute, out uri))
            {
                if (uri.IsUnc)
                {
                    ReportError(name.Extent, () => ParserStrings.CannotLoadAssemblyFromUncPath, assemblyName);
                }

                // don't allow things like 'using assembly http://microsoft.com'
                if (uri.Scheme != "file")
                {
                    ReportError(name.Extent, () => ParserStrings.CannotLoadAssemblyWithUriSchema, uri.Scheme);
                }
            }
            else
            {
                string assemblyFileName = assemblyName;
                try
                {
                    var scriptFileName = name.Extent.File;
                    if (!Path.IsPathRooted(assemblyFileName))
                    {
                        string workingDirectory;
                        if (string.IsNullOrEmpty(scriptFileName))
                        {
                            // We are in REPL, or Invoke-Expression, or ScriptBlock.Create, etc.
                            // It's legal to use '.\foo.dll', and we should do lookup in $pwd.
                            // We resolving it in parse time to avoid difference in script behavior, 
                            // when script execution is delayed from parsing, i.e. 
                            // $script = [scriptblock]::Create('using assembly .\foo.dll; [Foo].foo()')
                            // # using assembly behavior should be the same in these two cases:
                            // cd A; $script.Invoke()
                            // cd B; $script.Invoke()
                            if (Runspaces.Runspace.DefaultRunspace != null)
                            {
                                workingDirectory = Runspaces.Runspace.DefaultRunspace.ExecutionContext.EngineIntrinsics.SessionState.Path.CurrentLocation.Path;
                            }
                            else
                            {
                                // In this case, our best guess is process working directory.
                                workingDirectory = Directory.GetCurrentDirectory();
                            }
                        }
                        else
                        {
                            workingDirectory = Path.GetDirectoryName(scriptFileName);
                        }
                        assemblyFileName = workingDirectory + @"\" + assemblyFileName;
                    }

#if !CORECLR
                    if (!File.Exists(assemblyFileName))
                    {
                        GlobalAssemblyCache.ResolvePartialName(assemblyName, out assemblyFileName);
                    }
#endif
                }
                catch
                {
                }

                if (assemblyFileName == null || !File.Exists(assemblyFileName))
                {
                    ReportError(name.Extent, () => ParserStrings.ErrorLoadingAssembly, assemblyName);
                }
                else
                {
                    return new StringConstantExpressionAst(name.Extent, assemblyFileName, name.StringConstantType);
                }
            }

            return name;
        }
Ejemplo n.º 43
0
 public override AstVisitAction VisitStringConstantExpression(StringConstantExpressionAst ast)
 {
     return(Check(ast));
 }
Ejemplo n.º 44
0
 public object VisitStringConstantExpression(StringConstantExpressionAst stringConstantExpressionAst)
 {
     _visitCount++;
     return true;
 }
Ejemplo n.º 45
0
 public object VisitStringConstantExpression(StringConstantExpressionAst stringConstantExpressionAst)
 {
     _visitCount++;
     return(true);
 }
Ejemplo n.º 46
0
 private ExpressionAst ExpandableStringRule(StringExpandableToken strToken)
 {
     ExpressionAst stringConstantExpressionAst;
     if (strToken.NestedTokens == null)
     {
         stringConstantExpressionAst = new StringConstantExpressionAst(strToken);
     }
     else
     {
         List<ExpressionAst> expressionAsts = this.ParseNestedExpressions(strToken);
         stringConstantExpressionAst = new ExpandableStringExpressionAst(strToken, strToken.Value, strToken.FormatString, expressionAsts);
     }
     return stringConstantExpressionAst;
 }
Ejemplo n.º 47
0
 public object VisitStringConstantExpression(StringConstantExpressionAst stringConstantExpressionAst)
 {
     return(true);
 }
Ejemplo n.º 48
0
        internal override IEnumerable <PSTypeName> GetInferredType(CompletionContext context)
        {
            StringConstantExpressionAst member = this.Member as StringConstantExpressionAst;

            if (member != null)
            {
                PSTypeName[] iteratorVariable1;
                if (this.Static)
                {
                    TypeExpressionAst expression = this.Expression as TypeExpressionAst;
                    if (expression == null)
                    {
                        goto Label_064A;
                    }
                    Type type = expression.TypeName.GetReflectionType();
                    if (type == null)
                    {
                        goto Label_064A;
                    }
                    iteratorVariable1 = new PSTypeName[] { new PSTypeName(type) };
                }
                else
                {
                    iteratorVariable1 = this.Expression.GetInferredType(context).ToArray <PSTypeName>();
                    if (iteratorVariable1.Length == 0)
                    {
                        goto Label_064A;
                    }
                }
                List <string> iteratorVariable2 = new List <string> {
                    member.Value
                };
                foreach (PSTypeName iteratorVariable3 in iteratorVariable1)
                {
                    IEnumerable <object> iteratorVariable4 = CompletionCompleters.GetMembersByInferredType(iteratorVariable3, this.Static, context);
                    for (int i = 0; i < iteratorVariable2.Count; i++)
                    {
                        string iteratorVariable6 = iteratorVariable2[i];
                        foreach (object iteratorVariable7 in iteratorVariable4)
                        {
                            PropertyInfo iteratorVariable8 = iteratorVariable7 as PropertyInfo;
                            if (iteratorVariable8 != null)
                            {
                                if (iteratorVariable8.Name.Equals(iteratorVariable6, StringComparison.OrdinalIgnoreCase) && !(this is InvokeMemberExpressionAst))
                                {
                                    yield return(new PSTypeName(iteratorVariable8.PropertyType));

                                    break;
                                }
                            }
                            else
                            {
                                FieldInfo iteratorVariable9 = iteratorVariable7 as FieldInfo;
                                if (iteratorVariable9 != null)
                                {
                                    if (iteratorVariable9.Name.Equals(iteratorVariable6, StringComparison.OrdinalIgnoreCase) && !(this is InvokeMemberExpressionAst))
                                    {
                                        yield return(new PSTypeName(iteratorVariable9.FieldType));

                                        break;
                                    }
                                    continue;
                                }
                                DotNetAdapter.MethodCacheEntry iteratorVariable10 = iteratorVariable7 as DotNetAdapter.MethodCacheEntry;
                                if (iteratorVariable10 != null)
                                {
                                    if (iteratorVariable10[0].method.Name.Equals(iteratorVariable6, StringComparison.OrdinalIgnoreCase))
                                    {
                                        if (!(this is InvokeMemberExpressionAst))
                                        {
                                            yield return(new PSTypeName(typeof(PSMethod)));

                                            break;
                                        }
                                        foreach (MethodInformation iteratorVariable11 in iteratorVariable10.methodInformationStructures)
                                        {
                                            MethodInfo method = iteratorVariable11.method as MethodInfo;
                                            if ((method != null) && !method.ReturnType.ContainsGenericParameters)
                                            {
                                                yield return(new PSTypeName(method.ReturnType));
                                            }
                                        }
                                        break;
                                    }
                                    continue;
                                }
                                PSMemberInfo iteratorVariable13 = iteratorVariable7 as PSMemberInfo;
                                if ((iteratorVariable13 != null) && iteratorVariable13.Name.Equals(iteratorVariable6, StringComparison.OrdinalIgnoreCase))
                                {
                                    PSNoteProperty iteratorVariable14 = iteratorVariable7 as PSNoteProperty;
                                    if (iteratorVariable14 != null)
                                    {
                                        yield return(new PSTypeName(iteratorVariable14.Value.GetType()));

                                        break;
                                    }
                                    PSAliasProperty iteratorVariable15 = iteratorVariable7 as PSAliasProperty;
                                    if (iteratorVariable15 != null)
                                    {
                                        iteratorVariable2.Add(iteratorVariable15.ReferencedMemberName);
                                    }
                                    else
                                    {
                                        PSCodeProperty iteratorVariable16 = iteratorVariable7 as PSCodeProperty;
                                        if (iteratorVariable16 != null)
                                        {
                                            if (iteratorVariable16.GetterCodeReference != null)
                                            {
                                                yield return(new PSTypeName(iteratorVariable16.GetterCodeReference.ReturnType));

                                                break;
                                            }
                                        }
                                        else
                                        {
                                            ScriptBlock      getterScript       = null;
                                            PSScriptProperty iteratorVariable18 = iteratorVariable7 as PSScriptProperty;
                                            if (iteratorVariable18 != null)
                                            {
                                                getterScript = iteratorVariable18.GetterScript;
                                            }
                                            PSScriptMethod iteratorVariable19 = iteratorVariable7 as PSScriptMethod;
                                            if (iteratorVariable19 != null)
                                            {
                                                getterScript = iteratorVariable19.Script;
                                            }
                                            if (getterScript != null)
                                            {
                                                foreach (PSTypeName iteratorVariable20 in getterScript.OutputType)
                                                {
                                                    yield return(iteratorVariable20);
                                                }
                                            }
                                        }
                                    }
                                    break;
                                }
                            }
                        }
                    }
                }
            }
Label_064A:
            yield break;
        }
Ejemplo n.º 49
0
            public void Setup()
            {
                this._commandExpressionAst = ParseStatement("'PS> '")
                    .PipelineElements[0];

                this._stringConstantExpressionAst = (StringConstantExpressionAst)this._commandExpressionAst.Expression;
            }
Ejemplo n.º 50
0
        /// <summary>
        /// Parse a dynamic keyword statement which will be either of the form
        ///     keyword [parameters] [name] { a=1; b=2; } # constructor with properties
        /// or
        ///     keyword [parameters] [name] { ... }  # constructor with a simple body.
        /// or keywordcommand parameters 
        /// This custom keyword does not introduce a new AST node type. Instead it generates a
        /// CommandAst that calls a PowerShell command to implement the keyword's logic.
        /// This command has one of two signatures:
        ///     keywordImplCommand
        /// </summary>
        /// <param name="functionName">The name of the function to invoke</param>
        /// <param name="keywordData">The data for this keyword definition</param>
        /// <returns></returns>
        private StatementAst DynamicKeywordStatementRule(Token functionName, DynamicKeyword keywordData)
        {
            //////////////////////////////////////////////////////////////////////////////////
            // If a custom action was provided. then invoke it
            //////////////////////////////////////////////////////////////////////////////////
            if (keywordData.PreParse != null)
            {
                try
                {
                    ParseError[] errors = keywordData.PreParse(keywordData);
                    if (errors != null && errors.Length > 0)
                    {
                        foreach (var e in errors)
                        {
                            ReportError(e);
                        }
                    }
                }
                catch (Exception e)
                {
                    ReportError(functionName.Extent, () => ParserStrings.DynamicKeywordPreParseException, keywordData.ResourceName, e.ToString());
                    return null;
                }
            }

            if (keywordData.IsReservedKeyword)
            {
                // ErrorRecovery: eat the token
                ReportError(functionName.Extent, () => ParserStrings.UnsupportedReservedKeyword, keywordData.Keyword);
                return null;
            }

            if (keywordData.HasReservedProperties)
            {
                // ErrorRecovery: eat the token
                ReportError(functionName.Extent, () => ParserStrings.UnsupportedReservedProperty, "'Require', 'Trigger', 'Notify', 'Before', 'After' and 'Subscribe'");
                return null;
            }

            string elementName = string.Empty;

            DynamicKeywordStatementAst dynamicKeywordAst;
            if (keywordData.BodyMode == DynamicKeywordBodyMode.Command)
            {
                UngetToken(functionName);
                dynamicKeywordAst = (DynamicKeywordStatementAst)CommandRule(forDynamicKeyword: true);
                dynamicKeywordAst.Keyword = keywordData;
                dynamicKeywordAst.FunctionName = functionName;
            }
            else
            {
                SkipNewlines();

                // The expression that returns the resource name or names.
                ExpressionAst instanceName = null;

                Token nameToken = NextToken();
                if (nameToken.Kind == TokenKind.EndOfInput)
                {
                    UngetToken(nameToken);

                    if (keywordData.NameMode == DynamicKeywordNameMode.NameRequired || keywordData.NameMode == DynamicKeywordNameMode.SimpleNameRequired)
                    {
                        ReportIncompleteInput(After(functionName), () => ParserStrings.RequiredNameOrExpressionMissing);
                    }
                    else
                    {
                        // Name not required so report missing brace
                        ReportIncompleteInput(After(functionName.Extent), () => ParserStrings.MissingBraceInObjectDefinition);
                    }
                    return null;
                }

                // If it's an lcurly, then no name was provided, and we skip to the body processing
                Token lCurly = null;
                if (nameToken.Kind == TokenKind.LCurly)
                {
                    lCurly = nameToken;
                    if (keywordData.NameMode == DynamicKeywordNameMode.NameRequired || keywordData.NameMode == DynamicKeywordNameMode.SimpleNameRequired)
                    {
                        ReportError(After(functionName), () => ParserStrings.RequiredNameOrExpressionMissing);
                        UngetToken(nameToken);
                        return null;
                    }
                }
                else if (nameToken.Kind == TokenKind.Identifier || nameToken.Kind == TokenKind.DynamicKeyword)
                {
                    if (keywordData.NameMode == DynamicKeywordNameMode.NoName)
                    {
                        ReportError(After(functionName), () => ParserStrings.UnexpectedNameForType, functionName.Text, nameToken.Text);
                        UngetToken(nameToken);
                        return null;
                    }

                    // If it's an identifier then this is the name for the data object
                    elementName = nameToken.Text;

                    // If only a simple name is allowed, then the string must be non-null.
                    if ((keywordData.NameMode == DynamicKeywordNameMode.SimpleNameRequired || keywordData.NameMode == DynamicKeywordNameMode.SimpleOptionalName) && string.IsNullOrEmpty(elementName))
                    {
                        ReportIncompleteInput(After(functionName), () => ParserStrings.RequiredNameOrExpressionMissing);
                        UngetToken(nameToken);
                        return null;
                    }
                }
                else
                {
                    // see if an expression was provided instead of a bare word...
                    UngetToken(nameToken);
                    instanceName = GetSingleCommandArgument(CommandArgumentContext.CommandName);

                    if (instanceName == null)
                    {
                        if (keywordData.NameMode == DynamicKeywordNameMode.SimpleNameRequired || keywordData.NameMode == DynamicKeywordNameMode.SimpleOptionalName)
                        {
                            ReportError(After(functionName), () => ParserStrings.RequiredNameOrExpressionMissing);
                        }
                        else
                        {
                            // It wasn't an '{' and it wasn't a name expression so it's a unexpected token.
                            ReportError(After(functionName), () => ParserStrings.UnexpectedToken, nameToken.Text);
                        }
                        return null;
                    }

                    // Ok, we got a name expression, but we're expecting no name, so it's and error.
                    if (keywordData.NameMode == DynamicKeywordNameMode.NoName)
                    {
                        ReportError(After(functionName), () => ParserStrings.UnexpectedNameForType, functionName.Text, instanceName.ToString());
                        return null;
                    }

                    // We were expecting a simple name so report an error
                    if (keywordData.NameMode == DynamicKeywordNameMode.SimpleNameRequired || keywordData.NameMode == DynamicKeywordNameMode.SimpleOptionalName)
                    {
                        // If no match, then this is an incomplete token BUGBUG fix message
                        ReportError(nameToken.Extent, () => ParserStrings.UnexpectedToken, nameToken.Text);
                        return null;
                    }
                }

                // If we didn't get a resource expression AST, then we need to build one out of the
                // name that was specified. It may be the case that we don't have
                // a resource name in which case it will be the empty string. Even in the cases were
                // we aren't expecting a name, we still do this so that the signature of the implementing function remains
                // the same.
                ExpressionAst originalInstanceName = instanceName;
                if (instanceName == null)
                {
                    instanceName = new StringConstantExpressionAst(nameToken.Extent, elementName, StringConstantType.BareWord);
                }

                SkipNewlines();

                //
                // Now look for the body of the data statement.
                //
                if (lCurly == null)
                {
                    lCurly = NextToken();

                    if (lCurly.Kind == TokenKind.EndOfInput)
                    {
                        UngetToken(lCurly);
                        ReportIncompleteInput(After(functionName.Extent), () => ParserStrings.MissingBraceInObjectDefinition);

                        // Preserve the name expression for tab completion
                        return originalInstanceName == null
                                   ? null
                                   : new ErrorStatementAst(ExtentOf(functionName, originalInstanceName),
                                                           GetNestedErrorAsts(originalInstanceName));
                    }

                    if (lCurly.Kind != TokenKind.LCurly)
                    {
                        // We need to generate a reasonable error message for this case:
                        //
                        // Configuration C {
                        //   node $AllNode.NodeName{ # There is no space before curly, and we are converting scriptblock to and argument to call 'NodeName'
                        //     ...
                        //   }
                        // } # we don't want to simple report an unexpected token here, it would be super-confusing.

                        InvokeMemberExpressionAst instanceInvokeMemberExpressionAst = instanceName as InvokeMemberExpressionAst;

                        if (instanceInvokeMemberExpressionAst != null &&
                            instanceInvokeMemberExpressionAst.Arguments.Count == 1 &&
                            instanceInvokeMemberExpressionAst.Arguments[0] is ScriptBlockExpressionAst &&
                            // the last condition checks that there is no space between "method" name and '{'
                            instanceInvokeMemberExpressionAst.Member.Extent.EndOffset == instanceInvokeMemberExpressionAst.Arguments[0].Extent.StartOffset)
                        {
                            ReportError(LastCharacterOf(instanceInvokeMemberExpressionAst.Member.Extent), () => ParserStrings.UnexpectedTokenInDynamicKeyword, functionName.Text);
                        }
                        else
                        {
                            ReportError(lCurly.Extent, () => ParserStrings.UnexpectedToken, lCurly.Text);
                        }

                        if (lCurly.Kind == TokenKind.Dot && originalInstanceName != null && lCurly.Extent.StartOffset == originalInstanceName.Extent.EndOffset)
                        {
                            // Generate more useful ast for tab-completing extension methods on special DSC collection variables
                            // e.g. configuration foo { node $AllNodes.<tab>

                            IScriptExtent errorExtent = ExtentOf(originalInstanceName, lCurly);
                            var errorExpr = new ErrorExpressionAst(errorExtent);
                            var memberExpr = new MemberExpressionAst(originalInstanceName.Extent, originalInstanceName, errorExpr, @static: false);

                            return new ErrorStatementAst(errorExtent, new[] { memberExpr });
                        }

                        UngetToken(lCurly);
                        // Preserve the name expression for tab completion
                        return originalInstanceName == null
                                   ? null
                                   : new ErrorStatementAst(ExtentOf(functionName, originalInstanceName),
                                                           GetNestedErrorAsts(originalInstanceName));
                    }
                }

                //
                // The keyword data is used to see
                // if a scriptblock or a hashtable is expected.
                //
                ExpressionAst body = null;
                if (keywordData.BodyMode == DynamicKeywordBodyMode.ScriptBlock)
                {
                    var oldInConfiguraiton = _inConfiguration;
                    try
                    {
                        _inConfiguration = false;
                        body = ScriptBlockExpressionRule(lCurly);
                    }
                    finally
                    {
                        _inConfiguration = oldInConfiguraiton;
                    }
                }
                else if (keywordData.BodyMode == DynamicKeywordBodyMode.Hashtable)
                {
                    // Resource property value could be set to nested DSC resources except Script resource
                    bool isScriptResource = String.Compare(functionName.Text, @"Script", StringComparison.OrdinalIgnoreCase) == 0;
                    try
                    {
                        if (isScriptResource)
                            DynamicKeyword.Push();
                        body = HashExpressionRule(lCurly, true /* parsingSchemaElement */);
                    }
                    finally
                    {
                        if (isScriptResource)
                            DynamicKeyword.Pop();
                    }
                }
                // commandast
                // elements: instancename/dynamickeyword/hashtable or scripblockexpress
                if (body == null)
                {
                    // Failed to read the statement body
                    ReportIncompleteInput(After(lCurly), () => ParserStrings.MissingStatementAfterKeyword, keywordData.Keyword);

                    // Preserve the name expression for tab completion
                    return originalInstanceName == null
                               ? null
                               : new ErrorStatementAst(ExtentOf(functionName, originalInstanceName),
                                                       GetNestedErrorAsts(originalInstanceName));
                }

                //////////////////////////////////////////////////////////////////////////
                // The statement is now fully parsed
                //////////////////////////////////////////////////////////////////////////

                //
                // Create DynamicKeywordStatementAst
                //
                Collection<CommandElementAst> commandElements = new Collection<CommandElementAst>
                {
                    new StringConstantExpressionAst(functionName.Extent, functionName.Text, StringConstantType.BareWord),
                    (ExpressionAst)instanceName.Copy(),
                    (ExpressionAst)body.Copy()
                };
                Token nextToken = NextToken();
                IScriptExtent dynamicKeywordExtent = ExtentOf(functionName, Before(nextToken));
                UngetToken(nextToken);
                dynamicKeywordAst = new DynamicKeywordStatementAst(dynamicKeywordExtent, commandElements)
                {
                    Keyword = keywordData,
                    LCurly = lCurly,
                    FunctionName = functionName,
                    InstanceName = instanceName,
                    OriginalInstanceName = originalInstanceName,
                    BodyExpression = body,
                    ElementName = elementName,
                };
            }

            //////////////////////////////////////////////////////////////////////////////////
            // If a custom action was provided. then invoke it
            //////////////////////////////////////////////////////////////////////////////////
            if (keywordData.PostParse != null)
            {
                try
                {
                    ParseError[] errors = keywordData.PostParse(dynamicKeywordAst);
                    if (errors != null && errors.Length > 0)
                    {
                        foreach (var e in errors)
                        {
                            ReportError(e);
                        }
                    }
                }
                catch (Exception e)
                {
                    ReportError(functionName.Extent, () => ParserStrings.DynamicKeywordPostParseException, keywordData.Keyword, e.ToString());
                    return null;
                }
            }

            return dynamicKeywordAst;
        }