示例#1
0
 internal ErrorStatementAst(IScriptExtent extent, Token kind, IEnumerable<KeyValuePair<string, Tuple<Token, Ast>>> flags, IEnumerable<Ast> conditions, IEnumerable<Ast> bodies) : base(extent)
 {
     if (kind == null)
     {
         throw PSTraceSource.NewArgumentNullException("kind");
     }
     this.Kind = kind;
     if ((flags != null) && flags.Any<KeyValuePair<string, Tuple<Token, Ast>>>())
     {
         this.Flags = new Dictionary<string, Tuple<Token, Ast>>(StringComparer.OrdinalIgnoreCase);
         foreach (KeyValuePair<string, Tuple<Token, Ast>> pair in flags)
         {
             if (!this.Flags.ContainsKey(pair.Key))
             {
                 this.Flags.Add(pair.Key, pair.Value);
                 if (pair.Value.Item2 != null)
                 {
                     base.SetParent(pair.Value.Item2);
                 }
             }
         }
     }
     if ((conditions != null) && conditions.Any<Ast>())
     {
         this.Conditions = new ReadOnlyCollection<Ast>(conditions.ToArray<Ast>());
         base.SetParents(conditions);
     }
     if ((bodies != null) && bodies.Any<Ast>())
     {
         this.Bodies = new ReadOnlyCollection<Ast>(bodies.ToArray<Ast>());
         base.SetParents(bodies);
     }
 }
示例#2
0
 public SwitchStatementAst(IScriptExtent extent, string label, PipelineBaseAst condition, SwitchFlags flags, IEnumerable<Tuple<ExpressionAst, StatementBlockAst>> clauses, StatementBlockAst @default)
     : base(extent, label, condition)
 {
     this.Flags = flags;
     this.Clauses = clauses.ToReadOnlyCollection();
     this.Default = @default;
 }
        public void SetUp()
        {
            extent = Substitute.For<IScriptExtent>();
            argument = new VariableExpressionAst(extent, "other", false);

            visitor = new FindTypeDefinitionVisitor();
        }
示例#4
0
 public TryStatementAst(IScriptExtent extent, StatementBlockAst body, IEnumerable<CatchClauseAst> catchClauses, StatementBlockAst @finally)
     : base(extent)
 {
     this.Body = body;
     this.CatchClauses = catchClauses.ToReadOnlyCollection();
     this.Finally = @finally;
 }
示例#5
0
 public DataStatementAst(IScriptExtent extent, string variableName, IEnumerable<ExpressionAst> commandsAllowed, StatementBlockAst body)
     : base(extent)
 {
     this.Variable = variableName;
     this.CommandsAllowed = commandsAllowed.ToReadOnlyCollection();
     this.Body = body;
 }
示例#6
0
        /// <summary>
        /// Constructor for InvocationInfo object
        /// </summary>
        /// 
        /// <param name="commandInfo">
        /// The command information the invocation info represents.
        /// </param>
        /// 
        /// <param name="scriptPosition">
        /// The position representing the invocation, or the position representing the error.
        /// </param>
        /// 
        /// <param name="context">
        /// The context in which the InvocationInfo is being created.
        /// </param>
        /// 
        internal InvocationInfo(CommandInfo commandInfo, IScriptExtent scriptPosition, ExecutionContext context)
        {
            MyCommand = commandInfo;
            CommandOrigin = CommandOrigin.Internal;
            _scriptPosition = scriptPosition;

            ExecutionContext contextToUse = null;
            if ((commandInfo != null) && (commandInfo.Context != null))
            {
                contextToUse = commandInfo.Context;
            }
            else if (context != null)
            {
                contextToUse = context;
            }

            // Populate the history ID of this command
            if (contextToUse != null)
            {
                Runspaces.LocalRunspace localRunspace = contextToUse.CurrentRunspace as Runspaces.LocalRunspace;
                if (localRunspace != null && localRunspace.History != null)
                {
                    HistoryId = localRunspace.History.GetNextHistoryId();
                }
            }
        }
示例#7
0
 public ScriptBlockAst(IScriptExtent extent, ParamBlockAst paramBlock, NamedBlockAst beginBlock, NamedBlockAst processBlock, NamedBlockAst endBlock, NamedBlockAst dynamicParamBlock) : base(extent)
 {
     if (paramBlock != null)
     {
         this.ParamBlock = paramBlock;
         base.SetParent(paramBlock);
     }
     if (beginBlock != null)
     {
         this.BeginBlock = beginBlock;
         base.SetParent(beginBlock);
     }
     if (processBlock != null)
     {
         this.ProcessBlock = processBlock;
         base.SetParent(processBlock);
     }
     if (endBlock != null)
     {
         this.EndBlock = endBlock;
         base.SetParent(endBlock);
     }
     if (dynamicParamBlock != null)
     {
         this.DynamicParamBlock = dynamicParamBlock;
         base.SetParent(dynamicParamBlock);
     }
 }
示例#8
0
 public CommandParameterAst(IScriptExtent extent, string parameterName, ExpressionAst argument, IScriptExtent errorPosition)
     : base(extent)
 {
     this.ParameterName = parameterName;
     this.Argument = argument;
     this.ErrorPosition = errorPosition;
 }
 public ExpandableStringExpressionAst(IScriptExtent extent, string value, System.Management.Automation.Language.StringConstantType type) : base(extent)
 {
     if (value == null)
     {
         throw PSTraceSource.NewArgumentNullException("value");
     }
     if (((type != System.Management.Automation.Language.StringConstantType.DoubleQuoted) && (type != System.Management.Automation.Language.StringConstantType.DoubleQuotedHereString)) && (type != System.Management.Automation.Language.StringConstantType.BareWord))
     {
         throw PSTraceSource.NewArgumentException("type");
     }
     ExpressionAst ast = Parser.ScanString(value);
     ExpandableStringExpressionAst ast2 = ast as ExpandableStringExpressionAst;
     if (ast2 != null)
     {
         this.FormatExpression = ast2.FormatExpression;
         this.NestedExpressions = ast2.NestedExpressions;
     }
     else
     {
         this.FormatExpression = "{0}";
         this.NestedExpressions = new ReadOnlyCollection<ExpressionAst>(new ExpressionAst[] { ast });
     }
     this.Value = value;
     this.StringConstantType = type;
 }
示例#10
0
 public MemberExpressionAst(IScriptExtent extent, ExpressionAst expression, CommandElementAst member, bool @static)
     : base(extent)
 {
     this.Expression = expression;
     this.Member = member;
     this.Static = @static;
 }
示例#11
0
 public DataStatementAst(IScriptExtent extent, string variableName, IEnumerable<ExpressionAst> commandsAllowed, StatementBlockAst body) : base(extent)
 {
     this._tupleIndex = -1;
     if (body == null)
     {
         throw PSTraceSource.NewArgumentNullException("body");
     }
     if (string.IsNullOrWhiteSpace(variableName))
     {
         variableName = null;
     }
     this.Variable = variableName;
     if ((commandsAllowed != null) && commandsAllowed.Any<ExpressionAst>())
     {
         this.CommandsAllowed = new ReadOnlyCollection<ExpressionAst>(commandsAllowed.ToArray<ExpressionAst>());
         base.SetParents((IEnumerable<Ast>) this.CommandsAllowed);
         this.HasNonConstantAllowedCommand = (from ast in this.CommandsAllowed
             where !(ast is StringConstantExpressionAst)
             select ast).Any<ExpressionAst>();
     }
     else
     {
         this.CommandsAllowed = new ReadOnlyCollection<ExpressionAst>(EmptyCommandsAllowed);
     }
     this.Body = body;
     base.SetParent(body);
 }
示例#12
0
 public FunctionDefinitionAst(IScriptExtent extent, bool isFilter, bool isWorkflow, string name, IEnumerable<ParameterAst> parameters, ScriptBlockAst body) : base(extent)
 {
     if (string.IsNullOrEmpty(name))
     {
         throw PSTraceSource.NewArgumentNullException("name");
     }
     if (body == null)
     {
         throw PSTraceSource.NewArgumentNullException("body");
     }
     if (isFilter && isWorkflow)
     {
         throw PSTraceSource.NewArgumentException("isFilter");
     }
     this.IsFilter = isFilter;
     this.IsWorkflow = isWorkflow;
     this.Name = name;
     if ((parameters != null) && parameters.Any<ParameterAst>())
     {
         this.Parameters = new ReadOnlyCollection<ParameterAst>(parameters.ToArray<ParameterAst>());
         base.SetParents((IEnumerable<Ast>) this.Parameters);
     }
     this.Body = body;
     base.SetParent(body);
 }
示例#13
0
 public UpdatePositionExpr(IScriptExtent extent, int sequencePoint, SymbolDocumentInfo debugSymbolDocument, bool checkBreakpoints)
 {
     this._extent = extent;
     this._checkBreakpoints = checkBreakpoints;
     this._debugSymbolDocument = debugSymbolDocument;
     this._sequencePoint = sequencePoint;
 }
示例#14
0
 public ParameterAst(IScriptExtent extent, VariableExpressionAst name, IEnumerable<AttributeBaseAst> attributes, ExpressionAst defaultValue)
     : base(extent)
 {
     this.Name = name;
     this.Attributes = attributes.ToReadOnlyCollection();
     this.DefaultValue = defaultValue;
 }
示例#15
0
 public AssignmentStatementAst(IScriptExtent extent, ExpressionAst left, TokenKind @operator, StatementAst right, IScriptExtent errorPosition) : base(extent)
 {
     if (((left == null) || (right == null)) || (errorPosition == null))
     {
         throw PSTraceSource.NewArgumentNullException((left == null) ? "left" : ((right == null) ? "right" : "errorPosition"));
     }
     if ((@operator.GetTraits() & TokenFlags.AssignmentOperator) == TokenFlags.None)
     {
         throw PSTraceSource.NewArgumentException("operator");
     }
     PipelineAst ast = right as PipelineAst;
     if ((ast != null) && (ast.PipelineElements.Count == 1))
     {
         CommandExpressionAst ast2 = ast.PipelineElements[0] as CommandExpressionAst;
         if (ast2 != null)
         {
             right = ast2;
             right.ClearParent();
         }
     }
     this.Operator = @operator;
     this.Left = left;
     base.SetParent(left);
     this.Right = right;
     base.SetParent(right);
     this.ErrorPosition = errorPosition;
 }
示例#16
0
 public DoUntilStatementAst(IScriptExtent extent, string label, PipelineBaseAst condition, StatementBlockAst body) : base(extent, label, condition, body)
 {
     if (condition == null)
     {
         throw PSTraceSource.NewArgumentNullException("condition");
     }
 }
示例#17
0
 public TryStatementAst(IScriptExtent extent, StatementBlockAst body, IEnumerable<CatchClauseAst> catchClauses, StatementBlockAst @finally) : base(extent)
 {
     if (body == null)
     {
         throw PSTraceSource.NewArgumentNullException("body");
     }
     if (((catchClauses == null) || !catchClauses.Any<CatchClauseAst>()) && (@finally == null))
     {
         throw PSTraceSource.NewArgumentException("catchClauses");
     }
     this.Body = body;
     base.SetParent(body);
     if ((catchClauses != null) && catchClauses.Any<CatchClauseAst>())
     {
         this.CatchClauses = new ReadOnlyCollection<CatchClauseAst>(catchClauses.ToArray<CatchClauseAst>());
         base.SetParents((IEnumerable<Ast>) this.CatchClauses);
     }
     else
     {
         this.CatchClauses = EmptyCatchClauses;
     }
     if (@finally != null)
     {
         this.Finally = @finally;
         base.SetParent(@finally);
     }
 }
 public NamedAttributeArgumentAst(IScriptExtent extent, string argumentName, ExpressionAst argument, bool expressionOmitted)
     : base(extent)
 {
     this.Argument = argument;
     this.ArgumentName = argumentName;
     this.ExpressionOmitted = expressionOmitted;
 }
示例#19
0
 public ScriptBlockAst(IScriptExtent extent, ParamBlockAst paramBlock, StatementBlockAst statements, bool isFilter)
     : base(extent)
 {
     this.ParamBlock = paramBlock;
     this.EndBlock = new NamedBlockAst(extent, TokenKind.End, statements, true);
     if (isFilter) throw new NotImplementedException(this.ToString());
 }
示例#20
0
 internal ParseError(IScriptExtent extent, string errorId, string message, bool incompleteInput)
 {
     this._extent = extent;
     this._errorId = errorId;
     this._message = message;
     this._incompleteInput = incompleteInput;
 }
示例#21
0
 internal ExpandableStringExpressionAst(IScriptExtent extent, IList<ExpressionAst> expressions,
                                        string value, StringConstantType stringConstantType)
     : base(extent)
 {
     this.StringConstantType = stringConstantType;
     NestedExpressions = new ReadOnlyCollection<ExpressionAst>(expressions);
     Value = value;
 }
示例#22
0
 internal ErrorExpressionAst(IScriptExtent extent, IEnumerable<Ast> nestedAsts = null) : base(extent)
 {
     if ((nestedAsts != null) && nestedAsts.Any<Ast>())
     {
         this.NestedAst = new ReadOnlyCollection<Ast>(nestedAsts.ToArray<Ast>());
         base.SetParents(this.NestedAst);
     }
 }
示例#23
0
 protected AttributeBaseAst(IScriptExtent extent, ITypeName typeName) : base(extent)
 {
     if (typeName == null)
     {
         throw PSTraceSource.NewArgumentNullException("typeName");
     }
     this.TypeName = typeName;
 }
示例#24
0
 public ContinueStatementAst(IScriptExtent extent, ExpressionAst label) : base(extent)
 {
     if (label != null)
     {
         this.Label = label;
         base.SetParent(label);
     }
 }
示例#25
0
 public AssignmentStatementAst(IScriptExtent extent, ExpressionAst left, TokenKind @operator, StatementAst right, IScriptExtent errorPosition)
     : base(extent)
 {
     this.Left = left;
     this.Operator = @operator;
     this.Right = right;
     this.ErrorPosition = errorPosition;
 }
示例#26
0
 public InvokeMemberExpressionAst(IScriptExtent extent, ExpressionAst expression, CommandElementAst method, IEnumerable<ExpressionAst> arguments, bool @static) : base(extent, expression, method, @static)
 {
     if ((arguments != null) && arguments.Any<ExpressionAst>())
     {
         this.Arguments = new ReadOnlyCollection<ExpressionAst>(arguments.ToArray<ExpressionAst>());
         base.SetParents((IEnumerable<Ast>) this.Arguments);
     }
 }
示例#27
0
文件: TypeName.cs 项目: nickchal/pash
 public TypeName(IScriptExtent extent, string name, string assembly) : this(extent, name)
 {
     if (string.IsNullOrEmpty(assembly))
     {
         throw PSTraceSource.NewArgumentNullException("assembly");
     }
     this.AssemblyName = assembly;
 }
        public ExpandableStringExpressionAst(IScriptExtent extent, string value, StringConstantType stringConstantType)
            : base(extent)
        {
            this.Value = value;
            this.StringConstantType = stringConstantType;

            ParseExpandableString(value);
        }
 internal ParameterBindingValidationException(Exception innerException, ErrorCategory errorCategory, InvocationInfo invocationInfo, IScriptExtent errorPosition, string parameterName, Type parameterType, Type typeSpecified, string resourceBaseName, string errorIdAndResourceId, params object[] args) : base(innerException, errorCategory, invocationInfo, errorPosition, parameterName, parameterType, typeSpecified, resourceBaseName, errorIdAndResourceId, args)
 {
     ValidationMetadataException exception = innerException as ValidationMetadataException;
     if ((exception != null) && exception.SwallowException)
     {
         this._swallowException = true;
     }
 }
示例#30
0
 public BinaryExpressionAst(IScriptExtent extent, ExpressionAst left, TokenKind @operator, ExpressionAst right, IScriptExtent errorPosition)
     : base(extent)
 {
     this.Left = left;
     this.Operator = @operator;
     this.Right = @right;
     this.ErrorPosition = errorPosition;
 }
示例#31
0
 private CommandCompatibilityDiagnostic(
     string incompatibleCommand,
     PlatformData targetPlatform,
     string message,
     IScriptExtent extent,
     string ruleName,
     string ruleId,
     string analyzedFileName,
     string parameterName = null,
     IEnumerable <CorrectionExtent> suggestedCorrections = null)
     : base(
         message,
         extent,
         ruleName,
         ruleId,
         analyzedFileName,
         suggestedCorrections)
 {
     Command        = incompatibleCommand;
     TargetPlatform = targetPlatform;
     Parameter      = parameterName;
 }
示例#32
0
 public ScriptBlockAst(IScriptExtent extent, ParamBlockAst paramBlock, StatementBlockAst statements, bool isFilter) : base(extent)
 {
     if (statements == null)
     {
         throw PSTraceSource.NewArgumentNullException("statements");
     }
     if (paramBlock != null)
     {
         this.ParamBlock = paramBlock;
         base.SetParent(paramBlock);
     }
     if (isFilter)
     {
         this.ProcessBlock = new NamedBlockAst(statements.Extent, TokenKind.Process, statements, true);
         base.SetParent(this.ProcessBlock);
     }
     else
     {
         this.EndBlock = new NamedBlockAst(statements.Extent, TokenKind.End, statements, true);
         base.SetParent(this.EndBlock);
     }
 }
        private static CorrectionExtent GetCorrectionToRemoveParam(
            int paramIndex,
            ParameterAst[] parameterAsts)
        {
            IScriptExtent paramExtent = parameterAsts[paramIndex].Extent;
            int           startLineNumber, startColumnNumber, endLineNumber, endColumnNumber;

            startLineNumber   = paramExtent.StartLineNumber;
            startColumnNumber = paramExtent.StartColumnNumber;
            if (paramIndex < parameterAsts.Length - 1)
            {
                endLineNumber   = parameterAsts[paramIndex + 1].Extent.StartLineNumber;
                endColumnNumber = parameterAsts[paramIndex + 1].Extent.StartColumnNumber;
            }
            else
            {
                // if last item in the parameter list then need to remove the
                // trailing comma after the previous parameter.
                if (paramIndex > 0)
                {
                    var lp = parameterAsts[paramIndex - 1];
                    if (!IsWhatIf(lp) && !IsConfirm(lp))
                    {
                        startLineNumber   = lp.Extent.EndLineNumber;
                        startColumnNumber = lp.Extent.EndColumnNumber;
                    }
                }
                endLineNumber   = paramExtent.EndLineNumber;
                endColumnNumber = paramExtent.EndColumnNumber;
            }

            return(new CorrectionExtent(
                       startLineNumber,
                       endLineNumber,
                       startColumnNumber,
                       endColumnNumber,
                       "",
                       paramExtent.File));
        }
示例#34
0
 /// <summary>
 /// Create an named argument, where the parameter name is known.  This can happen when:
 ///     * The user uses the ':' syntax, as in
 ///         foo -bar:val
 ///     * Splatting, as in
 ///         $x = @{ bar = val } ; foo @x
 ///     * Via an API - when converting a CommandParameter to CommandParameterInternal.
 ///     * In the parameter binder when it resolves a positional argument
 ///     * Other random places that manually construct command processors and know their arguments.
 /// </summary>
 /// <param name="parameterExtent">The extent in script of the parameter.</param>
 /// <param name="parameterName">The parameter name (with no leading dash).</param>
 /// <param name="parameterText">The text of the parameter, as it did, or would, appear in script.</param>
 /// <param name="argumentExtent">The extent of the argument value in the script.</param>
 /// <param name="value">The argument value.</param>
 /// <param name="spaceAfterParameter">Used in native commands to correctly handle -foo:bar vs. -foo: bar</param>
 /// <param name="arrayIsSingleArgumentForNativeCommand">If the command is native, pass the string with commas instead of multiple arguments</param>
 internal static CommandParameterInternal CreateParameterWithArgument(
     IScriptExtent parameterExtent,
     string parameterName,
     string parameterText,
     IScriptExtent argumentExtent,
     object value,
     bool spaceAfterParameter,
     bool arrayIsSingleArgumentForNativeCommand = false)
 {
     Diagnostics.Assert(parameterExtent != null, "Caller to verify parameterExtent argument");
     Diagnostics.Assert(argumentExtent != null, "Caller to verify argumentExtent argument");
     return(new CommandParameterInternal
     {
         _parameter = new Parameter {
             extent = parameterExtent, parameterName = parameterName, parameterText = parameterText
         },
         _argument = new Argument {
             extent = argumentExtent, value = value, arrayIsSingleArgumentForNativeCommand = arrayIsSingleArgumentForNativeCommand
         },
         _spaceAfterParameter = spaceAfterParameter
     });
 }
 /// <summary>
 /// Constructs a ParameterBindingArgumentTransformationException
 /// </summary>
 /// <param name="errorCategory">
 /// The category for the error.
 /// </param>
 /// <param name="invocationInfo">
 /// The information about the command that encountered the error.
 ///
 /// InvocationInfo.MyCommand.Name == {0}
 /// </param>
 /// <param name="errorPosition">
 /// The position for the command or parameter that caused the error.
 ///
 /// token.LineNumber == {4}
 /// token.OffsetInLine == {5}
 /// </param>
 /// <param name="parameterName">
 /// The parameter on which binding caused the error.
 ///
 /// parameterName == {1}
 /// </param>
 /// <param name="parameterType">
 /// The Type the parameter was expecting.
 ///
 /// parameterType == {2}
 /// </param>
 /// <param name="typeSpecified">
 /// The Type that was attempted to be bound to the parameter.
 ///
 /// typeSpecified == {3}
 /// </param>
 /// <param name="resourceString">
 /// The format string for the exception message.
 /// </param>
 /// <param name="errorId">
 /// The error ID.
 /// </param>
 /// <param name="args">
 /// Additional arguments to pass to the format string.
 ///
 /// starts at {6}
 /// </param>
 /// <exception cref="ArgumentException">
 /// If <paramref name="resourceString"/> or <paramref name="errorId"/>
 /// is null or empty.
 /// </exception>
 internal ParameterBindingArgumentTransformationException(
     ErrorCategory errorCategory,
     InvocationInfo invocationInfo,
     IScriptExtent errorPosition,
     string parameterName,
     Type parameterType,
     Type typeSpecified,
     string resourceString,
     string errorId,
     params object[] args)
     : base(
         errorCategory,
         invocationInfo,
         errorPosition,
         parameterName,
         parameterType,
         typeSpecified,
         resourceString,
         errorId,
         args)
 {
 }
示例#36
0
    public System.Object VisitStatementBlock(System.Management.Automation.Language.StatementBlockAst statementBlockAst)
    {
        IScriptExtent mappedExtent = MapExtent(statementBlockAst.Extent);

        LinkedList <StatementAst> mappedStatements = new LinkedList <StatementAst>();

        foreach (StatementAst s in statementBlockAst.Statements)
        {
            mappedStatements.AddLast(_VisitStatement(s));
        }
        LinkedList <TrapStatementAst> mappedTraps = new LinkedList <TrapStatementAst>();

        if (statementBlockAst.Traps != null)
        {
            foreach (TrapStatementAst ts in statementBlockAst.Traps)
            {
                mappedTraps.AddLast((TrapStatementAst)VisitTrap(ts));
            }
        }

        return(new StatementBlockAst(mappedExtent, mappedStatements, mappedTraps));
    }
示例#37
0
 public ParameterAst(IScriptExtent extent, VariableExpressionAst name, IEnumerable <AttributeBaseAst> attributes, ExpressionAst defaultValue) : base(extent)
 {
     if (name == null)
     {
         throw PSTraceSource.NewArgumentNullException("name");
     }
     if ((attributes != null) && attributes.Any <AttributeBaseAst>())
     {
         this.Attributes = new ReadOnlyCollection <AttributeBaseAst>(attributes.ToArray <AttributeBaseAst>());
         base.SetParents(attributes);
     }
     else
     {
         this.Attributes = EmptyAttributeList;
     }
     this.Name = name;
     base.SetParent(name);
     if (defaultValue != null)
     {
         this.DefaultValue = defaultValue;
         base.SetParent(defaultValue);
     }
 }
示例#38
0
 public TypeName(IScriptExtent extent, string name)
 {
     if ((extent == null) || string.IsNullOrEmpty(name))
     {
         throw PSTraceSource.NewArgumentNullException((extent == null) ? "extent" : "name");
     }
     if (name.FirstOrDefault <char>(delegate(char c) {
         if ((c != '[') && (c != ']'))
         {
             return(c == ',');
         }
         return(true);
     }) != '\0')
     {
         throw PSTraceSource.NewArgumentException("name");
     }
     if (name.IndexOf('`') != -1)
     {
         name = name.Replace("``", "`");
     }
     this._extent = extent;
     this._name   = name;
 }
示例#39
0
        internal static IScriptExtent NewScriptExtent(IScriptExtent start, IScriptExtent end)
        {
            if (start == end)
            {
                return(start);
            }
            if (start == EmptyExtent)
            {
                return(end);
            }
            if (end == EmptyExtent)
            {
                return(start);
            }

            InternalScriptExtent startExtent = start as InternalScriptExtent;
            InternalScriptExtent endExtent   = end as InternalScriptExtent;

            Diagnostics.Assert(startExtent != null && endExtent != null, "This function only handles internal and empty extents");
            Diagnostics.Assert(startExtent.PositionHelper == endExtent.PositionHelper, "Extents must be from same source");

            return(new InternalScriptExtent(startExtent.PositionHelper, startExtent.StartOffset, endExtent.EndOffset));
        }
示例#40
0
        public override bool Equals(object obj)
        {
            IScriptExtent otherPosition = obj as IScriptExtent;

            if (otherPosition == null)
            {
                return(false);
            }

            if ((String.IsNullOrEmpty(otherPosition.File)) &&
                (otherPosition.StartLineNumber == StartLineNumber) &&
                (otherPosition.StartColumnNumber == StartColumnNumber) &&
                (otherPosition.EndLineNumber == EndLineNumber) &&
                (otherPosition.EndColumnNumber == EndColumnNumber) &&
                (String.IsNullOrEmpty(otherPosition.Text)))
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
示例#41
0
        internal static bool ContainsLineAndColumn(this IScriptExtent extent, int line, int column)
        {
            if (extent.StartLineNumber == line)
            {
                if (column == 0)
                {
                    return(true);
                }
                if (column >= extent.StartColumnNumber)
                {
                    if (extent.EndLineNumber != extent.StartLineNumber)
                    {
                        return(true);
                    }
                    return(column < extent.EndColumnNumber);
                }

                return(false);
            }

            if (extent.StartLineNumber > line)
            {
                return(false);
            }

            if (line > extent.EndLineNumber)
            {
                return(false);
            }

            if (extent.EndLineNumber == line)
            {
                return(column < extent.EndColumnNumber);
            }

            return(true);
        }
 /// <summary>
 /// Constructs a ParameterBindingParameterDefaultValueException.
 /// </summary>
 /// <param name="innerException">
 /// The inner exception.
 /// </param>
 /// <param name="errorCategory">
 /// The category for the error.
 /// </param>
 /// <param name="invocationInfo">
 /// The information about the command that encountered the error.
 ///
 /// InvocationInfo.MyCommand.Name == {0}
 /// </param>
 /// <param name="errorPosition">
 /// The position for the command or parameter that caused the error.
 ///
 /// token.LineNumber == {4}
 /// token.OffsetInLine == {5}
 /// </param>
 /// <param name="parameterName">
 /// The parameter on which binding caused the error.
 ///
 /// parameterName == {1}
 /// </param>
 /// <param name="parameterType">
 /// The Type the parameter was expecting.
 ///
 /// parameterType == {2}
 /// </param>
 /// <param name="typeSpecified">
 /// The Type that was attempted to be bound to the parameter.
 ///
 /// typeSpecified == {3}
 /// </param>
 /// <param name="resourceString">
 /// The format string for the exception message.
 /// </param>
 /// <param name="errorId">
 /// The error ID.
 /// </param>
 /// <param name="args">
 /// Additional arguments to pass to the format string.
 ///
 /// starts at {6}
 /// </param>
 /// <exception cref="ArgumentNullException">
 /// If <paramref name="invocationInfo"/> is null.
 /// </exception>
 /// <exception cref="ArgumentException">
 /// If <paramref name="resourceString"/> or <paramref name="errorId"/>
 /// is null or empty.
 /// </exception>
 internal ParameterBindingParameterDefaultValueException(
     Exception innerException,
     ErrorCategory errorCategory,
     InvocationInfo invocationInfo,
     IScriptExtent errorPosition,
     string parameterName,
     Type parameterType,
     Type typeSpecified,
     string resourceString,
     string errorId,
     params object[] args)
     : base(
         innerException,
         errorCategory,
         invocationInfo,
         errorPosition,
         parameterName,
         parameterType,
         typeSpecified,
         resourceString,
         errorId,
         args)
 {
 }
示例#43
0
    public System.Object VisitNamedBlock(System.Management.Automation.Language.NamedBlockAst namedBlockAst)
    {
        IScriptExtent mappedExtent = MapExtent(namedBlockAst.Extent);

        LinkedList <StatementAst> mappedStatements = new LinkedList <StatementAst>();

        foreach (StatementAst s in namedBlockAst.Statements)
        {
            mappedStatements.AddLast(_VisitStatement(s));
        }
        LinkedList <TrapStatementAst> mappedTraps = new LinkedList <TrapStatementAst>();

        if (namedBlockAst.Traps != null)
        {
            foreach (TrapStatementAst ts in namedBlockAst.Traps)
            {
                mappedTraps.AddLast((TrapStatementAst)VisitTrap(ts));
            }
        }
        // this doesn't really map the statement block
        StatementBlockAst mappedStatementBlock = new StatementBlockAst(mappedExtent, mappedStatements, mappedTraps);

        return(new NamedBlockAst(mappedExtent, namedBlockAst.BlockKind, mappedStatementBlock, namedBlockAst.Unnamed));
    }
        /// <summary>
        /// Creates a new instance of the ScriptRegion class from an
        /// instance of an IScriptExtent implementation.
        /// </summary>
        /// <param name="scriptExtent">
        /// The IScriptExtent to copy into the ScriptRegion.
        /// </param>
        /// <returns>
        /// A new ScriptRegion instance with the same details as the IScriptExtent.
        /// </returns>
        public static ScriptRegion Create(IScriptExtent scriptExtent)
        {
            // IScriptExtent throws an ArgumentOutOfRange exception if Text is null
            string scriptExtentText;

            try
            {
                scriptExtentText = scriptExtent.Text;
            }
            catch (ArgumentOutOfRangeException)
            {
                scriptExtentText = string.Empty;
            }

            return(new ScriptRegion(
                       scriptExtent.File,
                       scriptExtentText,
                       scriptExtent.StartLineNumber,
                       scriptExtent.StartColumnNumber,
                       scriptExtent.StartOffset,
                       scriptExtent.EndLineNumber,
                       scriptExtent.EndColumnNumber,
                       scriptExtent.EndOffset));
        }
示例#45
0
 public MergingRedirectionAst(IScriptExtent extent, RedirectionStream from, RedirectionStream to)
     : base(extent, from)
 {
 }
示例#46
0
 protected AttributeBaseAst(IScriptExtent extent, ITypeName typeName)
     : base(extent)
 {
     this.TypeName = typeName;
 }
示例#47
0
 protected PipelineBaseAst(IScriptExtent extent) : base(extent)
 {
 }
示例#48
0
 private static bool TraceLine(IScriptExtent extent)
 {
     Trace(extent);
     return(false);
 }
示例#49
0
 public TypeConstraintAst(IScriptExtent extent, Type type)
     : base(extent, /* TODO: */ null)
 {
     throw new NotImplementedException(this.ToString());
 }
 /// <summary>
 /// Constructor for InvocationInfo object
 /// </summary>
 /// <param name="commandInfo">
 /// The command information the invocation info represents.
 /// </param>
 /// <param name="scriptPosition">
 /// The position representing the invocation, or the position representing the error.
 /// </param>
 internal InvocationInfo(CommandInfo commandInfo, IScriptExtent scriptPosition)
     : this(commandInfo, scriptPosition, null)
 {
     // nothing to do here
 }
示例#51
0
 public CommandAst(IScriptExtent extent, IEnumerable <CommandElementAst> commandElements, TokenKind invocationOperator, IEnumerable <RedirectionAst> redirections)
     : base(extent, redirections)
 {
     this.CommandElements    = commandElements.ToReadOnlyCollection();
     this.InvocationOperator = invocationOperator;
 }
示例#52
0
 public TypeConstraintAst(IScriptExtent extent, ITypeName typeName)
     : base(extent, typeName)
 {
 }
示例#53
0
        /// <summary>
        /// Return a message that looks like:
        ///
        ///     At {filename}:{line} char:{column}
        ///     + $x + @y
        ///     +    ~
        /// </summary>
        internal static string VerboseMessage(IScriptExtent position)
        {
            if (PositionUtilities.EmptyExtent.Equals(position))
            {
                return("");
            }

            string fileName = position.File;

            if (String.IsNullOrEmpty(fileName))
            {
                fileName = ParserStrings.TextForWordLine;
            }

            string sourceLine = position.StartScriptPosition.Line.TrimEnd();

            string message = "";

            if (!String.IsNullOrEmpty(sourceLine))
            {
                int spacesBeforeError = position.StartColumnNumber - 1;
                int errorLength       = (position.StartLineNumber == position.EndLineNumber)
                                      ? position.EndColumnNumber - position.StartColumnNumber
                                      : sourceLine.TrimEnd().Length - position.StartColumnNumber + 1;

                // Expand tabs before figuring out if we need to truncate the line
                if (sourceLine.IndexOf('\t') != -1)
                {
                    var copyLine = new StringBuilder(sourceLine.Length * 2);

                    var beforeError = sourceLine.Substring(0, spacesBeforeError).Replace("\t", "    ");
                    var error       = sourceLine.Substring(spacesBeforeError, errorLength).Replace("\t", "    ");

                    copyLine.Append(beforeError);
                    copyLine.Append(error);
                    copyLine.Append(sourceLine.Substring(spacesBeforeError + errorLength).Replace("\t", "    "));

                    spacesBeforeError = beforeError.Length;
                    errorLength       = error.Length;
                    sourceLine        = copyLine.ToString();
                }

                // Max width is 69 because:
                //   * sometimes PowerShell is opened with width 80
                //   * we always prepend "+ "
                //   * we sometimes prepend "... "
                //   * we sometimes append " ..."
                //   * wrapping kicks in if we hit the width exactly, so -1 to avoid that.
                const int maxLineLength   = 69;
                bool      needsPrefixDots = false;
                bool      needsSuffixDots = false;

                int lineLength = sourceLine.Length;
                var sb         = new StringBuilder(sourceLine.Length * 2 + 4);
                if (lineLength > maxLineLength)
                {
                    // Need to truncate - include as much of the error as we can, but with
                    // some preceding context if possible.

                    int totalPrefix = spacesBeforeError;
                    int prefix      = Math.Min(totalPrefix, 12);

                    int totalSuffix = lineLength - errorLength - spacesBeforeError;
                    int suffix      = Math.Min(totalSuffix, 8);

                    int candidateLength = prefix + errorLength + suffix;
                    if (candidateLength >= maxLineLength)
                    {
                        // Too long.  The suffix is truncated automatically by
                        // the Substring call, but we might need some of the
                        // squiggles removed as well.
                        if (prefix + errorLength >= maxLineLength)
                        {
                            errorLength = maxLineLength - prefix;
                        }
                        needsSuffixDots = true;
                    }
                    else
                    {
                        // We can shift prefix to suffix or vice versa to fill in
                        // more of the line.  Prefer shifting to prefix.
                        int prefixAvailable = totalPrefix - prefix;
                        if (prefixAvailable > 0)
                        {
                            prefix         += Math.Min(prefixAvailable, maxLineLength - candidateLength);
                            candidateLength = prefix + errorLength + suffix;
                        }

                        if (candidateLength < maxLineLength && totalSuffix > 0)
                        {
                            suffix += Math.Min(totalSuffix, maxLineLength - candidateLength);
                        }
                        needsSuffixDots = (suffix < totalSuffix);
                    }

                    needsPrefixDots = (prefix < totalPrefix);

                    var startIndex = Math.Max(spacesBeforeError - prefix, 0);
                    sourceLine        = sourceLine.Substring(startIndex, maxLineLength);
                    spacesBeforeError = Math.Min(spacesBeforeError, prefix);
                    errorLength       = Math.Min(errorLength, maxLineLength - spacesBeforeError);
                }

                if (needsPrefixDots)
                {
                    sb.Append("... ");
                }
                sb.Append(sourceLine);
                if (needsSuffixDots)
                {
                    sb.Append(" ...");
                }
                sb.Append(Environment.NewLine);
                sb.Append("+ ");
                sb.Append(' ', spacesBeforeError + (needsPrefixDots ? 4 : 0));
                // errorLength of 0 happens at EOF - always write out 1.
                sb.Append('~', errorLength > 0 ? errorLength : 1);
                message = sb.ToString();
            }

            return(StringUtil.Format(ParserStrings.TextForPositionMessage, fileName, position.StartLineNumber,
                                     position.StartColumnNumber, message));
        }
示例#54
0
 public PipelineAst(IScriptExtent extent, CommandBaseAst commandAst)
     : base(extent)
 {
     this.PipelineElements = new[] { commandAst }.ToReadOnlyCollection();
 }
示例#55
0
 internal PSToken(IScriptExtent extent)
 {
     Type    = PSTokenType.Position;
     _extent = extent;
 }
示例#56
0
 internal static void AddKeyValuePair(IDictionary hashtable, object key, object value, IScriptExtent errorExtent)
 {
     key = PSObject.Base(key);
     if (key == null)
     {
         throw InterpreterError.NewInterpreterException(hashtable, typeof(RuntimeException), errorExtent, "InvalidNullKey", ParserStrings.InvalidNullKey, new object[0]);
     }
     if (hashtable.Contains(key))
     {
         string str = PSObject.ToStringParser(null, key);
         if (str.Length > 40)
         {
             str = str.Substring(0, 40) + "...";
         }
         throw InterpreterError.NewInterpreterException(hashtable, typeof(RuntimeException), errorExtent, "DuplicateKeyInHashLiteral", ParserStrings.DuplicateKeyInHashLiteral, new object[] { str });
     }
     hashtable.Add(key, value);
 }
示例#57
0
 public ExpandableStringParser(IScriptExtent extent, string input)
 {
     _extent = extent;
     _input  = input;
 }
示例#58
0
 protected ExpressionAst(IScriptExtent extent) : base(extent)
 {
 }
示例#59
0
        public async Task <CommentHelpRequestResult> Handle(CommentHelpRequestParams request, CancellationToken cancellationToken)
        {
            CommentHelpRequestResult result = new();

            if (!_workspaceService.TryGetFile(request.DocumentUri, out ScriptFile scriptFile))
            {
                return(result);
            }

            int triggerLine = request.TriggerPosition.Line + 1;

            FunctionDefinitionAst functionDefinitionAst = SymbolsService.GetFunctionDefinitionForHelpComment(
                scriptFile,
                triggerLine,
                out string helpLocation);

            if (functionDefinitionAst == null)
            {
                return(result);
            }

            IScriptExtent funcExtent = functionDefinitionAst.Extent;
            string        funcText   = funcExtent.Text;

            if (helpLocation.Equals("begin"))
            {
                // check if the previous character is `<` because it invalidates
                // the param block the follows it.
                IList <string> lines = ScriptFile.GetLinesInternal(funcText);
                int            relativeTriggerLine0b = triggerLine - funcExtent.StartLineNumber;
                if (relativeTriggerLine0b > 0 && lines[relativeTriggerLine0b].IndexOf("<", StringComparison.OrdinalIgnoreCase) > -1)
                {
                    lines[relativeTriggerLine0b] = string.Empty;
                }

                funcText = string.Join("\n", lines);
            }

            string helpText = await _analysisService.GetCommentHelpText(funcText, helpLocation, forBlockComment : request.BlockComment).ConfigureAwait(false);

            if (helpText == null)
            {
                return(result);
            }

            List <string> helpLines = ScriptFile.GetLinesInternal(helpText);

            if (helpLocation != null &&
                !helpLocation.Equals("before", StringComparison.OrdinalIgnoreCase))
            {
                // we need to trim the leading `{` and newline when helpLocation=="begin"
                helpLines.RemoveAt(helpLines.Count - 1);

                // we also need to trim the leading newline when helpLocation=="end"
                helpLines.RemoveAt(0);
            }

            // Trim trailing newline from help text.
            if (string.IsNullOrEmpty(helpLines[helpLines.Count - 1]))
            {
                helpLines.RemoveAt(helpLines.Count - 1);
            }

            result.Content = helpLines.ToArray();
            return(result);
        }
示例#60
0
 public PipelineAst(IScriptExtent extent, IEnumerable <CommandBaseAst> pipelineElements)
     : base(extent)
 {
     this.PipelineElements = pipelineElements.ToReadOnlyCollection();
 }