Exemplo n.º 1
0
        private static void PowerShellInvocation_ErrorAdding(object sender, DataAddingEventArgs e, HostSettingCommandMetadata commandMetadata)
        {
            ErrorRecord errorRecord = e.ItemAdded as ErrorRecord;

            if (errorRecord != null)
            {
                if (commandMetadata != null)
                {
                    ScriptPosition scriptStart = new ScriptPosition(
                        commandMetadata.CommandName,
                        commandMetadata.StartLineNumber,
                        commandMetadata.StartColumnNumber,
                        null);
                    ScriptPosition scriptEnd = new ScriptPosition(
                        commandMetadata.CommandName,
                        commandMetadata.EndLineNumber,
                        commandMetadata.EndColumnNumber,
                        null);
                    ScriptExtent extent = new ScriptExtent(scriptStart, scriptEnd);

                    if (errorRecord.InvocationInfo != null)
                    {
                        errorRecord.InvocationInfo.DisplayScriptPosition = extent;
                    }
                }
            }
        }
        /// <summary>
        /// Decides if the current function defintion is the right defition
        /// for the symbol being searched for. The defintion of the symbol will be a of type 
        /// SymbolType.Function and have the same name as the symbol
        /// </summary>
        /// <param name="functionDefinitionAst">A FunctionDefinitionAst in the script's AST</param>
        /// <returns>A descion to stop searching if the right FunctionDefinitionAst was found, 
        /// or a decision to continue if it wasn't found</returns>
        public override AstVisitAction VisitFunctionDefinition(FunctionDefinitionAst functionDefinitionAst)
        {
            // Get the start column number of the function name, 
            // instead of the the start column of 'function' and create new extent for the functionName
            int startColumnNumber =
                functionDefinitionAst.Extent.Text.IndexOf(
                    functionDefinitionAst.Name) + 1;

            IScriptExtent nameExtent = new ScriptExtent()
            {
                Text = functionDefinitionAst.Name,
                StartLineNumber = functionDefinitionAst.Extent.StartLineNumber,
                StartColumnNumber = startColumnNumber,
                EndLineNumber = functionDefinitionAst.Extent.StartLineNumber,
                EndColumnNumber = startColumnNumber + functionDefinitionAst.Name.Length
            };

            if (symbolRef.SymbolType.Equals(SymbolType.Function) &&
                 nameExtent.Text.Equals(symbolRef.ScriptRegion.Text, StringComparison.InvariantCultureIgnoreCase))
            {
                this.FoundDeclartion =
                    new SymbolReference(
                        SymbolType.Function,
                        nameExtent);

                return AstVisitAction.StopVisit;
            }

            return base.VisitFunctionDefinition(functionDefinitionAst);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Adds the information about this informational record to a PSObject as note properties.
        /// The PSObject is used to serialize the record during remote operations.
        /// </summary>
        /// <remarks>
        /// InvocationInfos are usually serialized as part of another object, so we add "InvocationInfo_" to
        /// the note properties to prevent collisions with any properties set by the containing object.
        /// </remarks>
        internal void ToPSObjectForRemoting(PSObject psObject)
        {
            RemotingEncoder.AddNoteProperty <object>(psObject, "InvocationInfo_BoundParameters", () => this.BoundParameters);
            RemotingEncoder.AddNoteProperty <CommandOrigin>(psObject, "InvocationInfo_CommandOrigin", () => this.CommandOrigin);
            RemotingEncoder.AddNoteProperty <bool>(psObject, "InvocationInfo_ExpectingInput", () => this.ExpectingInput);
            RemotingEncoder.AddNoteProperty <string>(psObject, "InvocationInfo_InvocationName", () => this.InvocationName);
            RemotingEncoder.AddNoteProperty <string>(psObject, "InvocationInfo_Line", () => this.Line);
            RemotingEncoder.AddNoteProperty <int>(psObject, "InvocationInfo_OffsetInLine", () => this.OffsetInLine);
            RemotingEncoder.AddNoteProperty <long>(psObject, "InvocationInfo_HistoryId", () => this.HistoryId);
            RemotingEncoder.AddNoteProperty <int[]>(psObject, "InvocationInfo_PipelineIterationInfo", () => this.PipelineIterationInfo);
            RemotingEncoder.AddNoteProperty <int>(psObject, "InvocationInfo_PipelineLength", () => this.PipelineLength);
            RemotingEncoder.AddNoteProperty <int>(psObject, "InvocationInfo_PipelinePosition", () => this.PipelinePosition);
            RemotingEncoder.AddNoteProperty <string>(psObject, "InvocationInfo_PSScriptRoot", () => this.PSScriptRoot);
            RemotingEncoder.AddNoteProperty <string>(psObject, "InvocationInfo_PSCommandPath", () => this.PSCommandPath);
            // PositionMessage is ignored when deserializing because it is synthesized from the other position related fields, but
            // it is serialized for backwards compatibility.
            RemotingEncoder.AddNoteProperty <string>(psObject, "InvocationInfo_PositionMessage", () => this.PositionMessage);
            RemotingEncoder.AddNoteProperty <int>(psObject, "InvocationInfo_ScriptLineNumber", () => this.ScriptLineNumber);
            RemotingEncoder.AddNoteProperty <string>(psObject, "InvocationInfo_ScriptName", () => this.ScriptName);
            RemotingEncoder.AddNoteProperty <object>(psObject, "InvocationInfo_UnboundArguments", () => this.UnboundArguments);

            ScriptExtent extent = DisplayScriptPosition as ScriptExtent;

            if (extent != null)
            {
                extent.ToPSObjectForRemoting(psObject);
                RemotingEncoder.AddNoteProperty(psObject, "SerializeExtent", () => true);
            }
            else
            {
                RemotingEncoder.AddNoteProperty(psObject, "SerializeExtent", () => false);
            }

            RemoteCommandInfo.ToPSObjectForRemoting(this.MyCommand, psObject);
        }
        /// <summary>
        /// Checks to see if this function definition is the symbol we are looking for.
        /// </summary>
        /// <param name="functionDefinitionAst">A functionDefinitionAst object in the script's AST</param>
        /// <returns>A descion to stop searching if the right symbol was found, 
        /// or a decision to continue if it wasn't found</returns>
        public override AstVisitAction VisitFunctionDefinition(FunctionDefinitionAst functionDefinitionAst)
        {
            int startColumnNumber =
                functionDefinitionAst.Extent.Text.IndexOf(
                    functionDefinitionAst.Name) + 1;

            IScriptExtent nameExtent = new ScriptExtent()
            {
                Text = functionDefinitionAst.Name,
                StartLineNumber = functionDefinitionAst.Extent.StartLineNumber,
                EndLineNumber = functionDefinitionAst.Extent.EndLineNumber,
                StartColumnNumber = startColumnNumber,
                EndColumnNumber = startColumnNumber + functionDefinitionAst.Name.Length
            };

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

                return AstVisitAction.StopVisit;
            }

            return base.VisitFunctionDefinition(functionDefinitionAst);
        }
Exemplo n.º 5
0
        internal void ToPSObjectForRemoting(PSObject psObject)
        {
            RemotingEncoder.AddNoteProperty <object>(psObject, "InvocationInfo_BoundParameters", () => this.BoundParameters);
            RemotingEncoder.AddNoteProperty <System.Management.Automation.CommandOrigin>(psObject, "InvocationInfo_CommandOrigin", () => this.CommandOrigin);
            RemotingEncoder.AddNoteProperty <bool>(psObject, "InvocationInfo_ExpectingInput", () => this.ExpectingInput);
            RemotingEncoder.AddNoteProperty <string>(psObject, "InvocationInfo_InvocationName", () => this.InvocationName);
            RemotingEncoder.AddNoteProperty <string>(psObject, "InvocationInfo_Line", () => this.Line);
            RemotingEncoder.AddNoteProperty <int>(psObject, "InvocationInfo_OffsetInLine", () => this.OffsetInLine);
            RemotingEncoder.AddNoteProperty <long>(psObject, "InvocationInfo_HistoryId", () => this.HistoryId);
            RemotingEncoder.AddNoteProperty <int[]>(psObject, "InvocationInfo_PipelineIterationInfo", () => this.PipelineIterationInfo);
            RemotingEncoder.AddNoteProperty <int>(psObject, "InvocationInfo_PipelineLength", () => this.PipelineLength);
            RemotingEncoder.AddNoteProperty <int>(psObject, "InvocationInfo_PipelinePosition", () => this.PipelinePosition);
            RemotingEncoder.AddNoteProperty <string>(psObject, "InvocationInfo_PSScriptRoot", () => this.PSScriptRoot);
            RemotingEncoder.AddNoteProperty <string>(psObject, "InvocationInfo_PSCommandPath", () => this.PSCommandPath);
            RemotingEncoder.AddNoteProperty <string>(psObject, "InvocationInfo_PositionMessage", () => this.PositionMessage);
            RemotingEncoder.AddNoteProperty <int>(psObject, "InvocationInfo_ScriptLineNumber", () => this.ScriptLineNumber);
            RemotingEncoder.AddNoteProperty <string>(psObject, "InvocationInfo_ScriptName", () => this.ScriptName);
            RemotingEncoder.AddNoteProperty <object>(psObject, "InvocationInfo_UnboundArguments", () => this.UnboundArguments);
            ScriptExtent displayScriptPosition = this.DisplayScriptPosition as ScriptExtent;

            if (displayScriptPosition != null)
            {
                displayScriptPosition.ToPSObjectForRemoting(psObject);
                RemotingEncoder.AddNoteProperty <bool>(psObject, "SerializeExtent", () => true);
            }
            else
            {
                RemotingEncoder.AddNoteProperty <bool>(psObject, "SerializeExtent", () => false);
            }
            RemoteCommandInfo.ToPSObjectForRemoting(this.MyCommand, psObject);
        }
        /// <summary>
        /// Analyzes the given ast to find violations.
        /// </summary>
        /// <param name="ast">AST to be analyzed. This should be non-null</param>
        /// <param name="fileName">Name of file that corresponds to the input AST.</param>
        /// <returns>A an enumerable type containing the violations</returns>
        public IEnumerable <DiagnosticRecord> AnalyzeScript(Ast ast, string fileName)
        {
            if (ast == null)
            {
                throw new ArgumentNullException("ast");
            }

            var diagnosticRecords = new List <DiagnosticRecord>();

            string[] lines = Regex.Split(ast.Extent.Text, @"\r?\n");

            for (int lineNumber = 0; lineNumber < lines.Length; lineNumber++)
            {
                var line = lines[lineNumber];

                var match = Regex.Match(line, @"\s+$");
                if (match.Success)
                {
                    var startLine   = lineNumber + 1;
                    var endLine     = startLine;
                    var startColumn = match.Index + 1;
                    var endColumn   = startColumn + match.Length;

                    var violationExtent = new ScriptExtent(
                        new ScriptPosition(
                            ast.Extent.File,
                            startLine,
                            startColumn,
                            line
                            ),
                        new ScriptPosition(
                            ast.Extent.File,
                            endLine,
                            endColumn,
                            line
                            ));

                    var suggestedCorrections = new List <CorrectionExtent>();
                    suggestedCorrections.Add(new CorrectionExtent(
                                                 violationExtent,
                                                 string.Empty,
                                                 ast.Extent.File
                                                 ));

                    diagnosticRecords.Add(
                        new DiagnosticRecord(
                            String.Format(CultureInfo.CurrentCulture, Strings.AvoidTrailingWhitespaceError),
                            violationExtent,
                            GetName(),
                            GetDiagnosticSeverity(),
                            ast.Extent.File,
                            null,
                            suggestedCorrections
                            ));
                }
            }

            return(diagnosticRecords);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Analyzes the given ast to find violations.
        /// </summary>
        /// <param name="ast">AST to be analyzed. This should be non-null</param>
        /// <param name="fileName">Name of file that corresponds to the input AST.</param>
        /// <returns>A an enumerable type containing the violations</returns>
        public override IEnumerable <DiagnosticRecord> AnalyzeScript(Ast ast, string fileName)
        {
            if (ast == null)
            {
                throw new ArgumentNullException(nameof(ast));
            }

            var diagnosticRecords = new List <DiagnosticRecord>();

            string[] lines = ast.Extent.Text.Split(s_lineSeparators, StringSplitOptions.None);

            for (int lineNumber = 0; lineNumber < lines.Length; lineNumber++)
            {
                string line = lines[lineNumber];

                if (line.Length <= MaximumLineLength)
                {
                    continue;
                }

                int startLine   = lineNumber + 1;
                int endLine     = startLine;
                int startColumn = 1;
                int endColumn   = line.Length;

                var violationExtent = new ScriptExtent(
                    new ScriptPosition(
                        ast.Extent.File,
                        startLine,
                        startColumn,
                        line
                        ),
                    new ScriptPosition(
                        ast.Extent.File,
                        endLine,
                        endColumn,
                        line
                        ));

                var record = new DiagnosticRecord(
                    String.Format(CultureInfo.CurrentCulture,
                                  String.Format(Strings.AvoidLongLinesError, MaximumLineLength)),
                    violationExtent,
                    GetName(),
                    GetDiagnosticSeverity(),
                    ast.Extent.File,
                    null
                    );
                diagnosticRecords.Add(record);
            }

            return(diagnosticRecords);
        }
        public override AstVisitAction VisitConfigurationDefinition(ConfigurationDefinitionAst configurationDefinitionAst)
        {
            IScriptExtent nameExtent = new ScriptExtent()
            {
                Text = configurationDefinitionAst.InstanceName.Extent.Text,
                StartLineNumber = configurationDefinitionAst.Extent.StartLineNumber,
                EndLineNumber = configurationDefinitionAst.Extent.EndLineNumber,
                StartColumnNumber = configurationDefinitionAst.Extent.StartColumnNumber,
                EndColumnNumber = configurationDefinitionAst.Extent.EndColumnNumber
            };

            this.findSymbolsVisitor.SymbolReferences.Add(
                new SymbolReference(
                    SymbolType.Configuration,
                    nameExtent));

            return AstVisitAction.Continue;
        }
Exemplo n.º 9
0
        private List <CorrectionExtent> GetCorrections(
            Token prevToken,
            Token token,
            Token nextToken,
            bool hasWhitespaceBefore, // if this is false, then the returned correction extent will add a whitespace before the token
            bool hasWhitespaceAfter   // if this is false, then the returned correction extent will add a whitespace after the token
            )
        {
            var           sb = new StringBuilder();
            IScriptExtent e1 = token.Extent;

            if (!hasWhitespaceBefore)
            {
                sb.Append(whiteSpace);
                e1 = prevToken.Extent;
            }

            var e2 = token.Extent;

            if (!hasWhitespaceAfter)
            {
                if (!hasWhitespaceBefore)
                {
                    sb.Append(token.Text);
                }

                e2 = nextToken.Extent;
                sb.Append(whiteSpace);
            }

            var extent = new ScriptExtent(
                new ScriptPosition(e1.File, e1.EndLineNumber, e1.EndColumnNumber, null),
                new ScriptPosition(e2.File, e2.StartLineNumber, e2.StartColumnNumber, null));

            return(new List <CorrectionExtent>()
            {
                new CorrectionExtent(
                    extent,
                    sb.ToString(),
                    token.Extent.File,
                    GetError(ErrorKind.Operator))
            });
        }
        /// <summary>
        /// Adds each function defintion as a 
        /// </summary>
        /// <param name="functionDefinitionAst">A functionDefinitionAst object in the script's AST</param>
        /// <returns>A decision to stop searching if the right symbol was found, 
        /// or a decision to continue if it wasn't found</returns>
        public override AstVisitAction VisitFunctionDefinition(FunctionDefinitionAst functionDefinitionAst)
        {
            IScriptExtent nameExtent = new ScriptExtent() {
                Text = functionDefinitionAst.Name,
                StartLineNumber = functionDefinitionAst.Extent.StartLineNumber,
                EndLineNumber = functionDefinitionAst.Extent.EndLineNumber,
                StartColumnNumber = functionDefinitionAst.Extent.StartColumnNumber,
                EndColumnNumber = functionDefinitionAst.Extent.EndColumnNumber
            };

            SymbolType symbolType = 
                functionDefinitionAst.IsWorkflow ? 
                    SymbolType.Workflow : SymbolType.Function;

            this.SymbolReferences.Add(
                new SymbolReference(
                    symbolType,
                    nameExtent));

            return AstVisitAction.Continue;
        }
Exemplo n.º 11
0
        /// <summary>
        /// MisleadingBacktick: Checks that lines don't end with a backtick followed by a whitespace
        /// </summary>
        public IEnumerable <DiagnosticRecord> AnalyzeScript(Ast ast, string fileName)
        {
            if (ast == null)
            {
                throw new ArgumentNullException(Strings.NullAstErrorMessage);
            }

            string[] lines = NewlineRegex.Split(ast.Extent.Text);

            if ((ast.Extent.EndLineNumber - ast.Extent.StartLineNumber + 1) != lines.Length)
            {
                // Did not match the number of lines that the extent indicated
                yield break;
            }

            foreach (int i in Enumerable.Range(0, lines.Length))
            {
                string line = lines[i];

                Match match = TrailingEscapedWhitespaceRegex.Match(line);

                if (match.Success)
                {
                    int lineNumber = ast.Extent.StartLineNumber + i;

                    var start  = new ScriptPosition(fileName, lineNumber, match.Index + 1, line);
                    var end    = new ScriptPosition(fileName, lineNumber, match.Index + match.Length + 1, line);
                    var extent = new ScriptExtent(start, end);
                    yield return(new DiagnosticRecord(
                                     string.Format(CultureInfo.CurrentCulture, Strings.MisleadingBacktickError),
                                     extent,
                                     GetName(),
                                     DiagnosticSeverity.Warning,
                                     fileName,
                                     suggestedCorrections: GetCorrectionExtent(extent)));
                }
            }
        }
Exemplo n.º 12
0
 private void AddViolation(
     Token token,
     int expectedIndentationLevel,
     List <DiagnosticRecord> diagnosticRecords,
     ref bool onNewLine,
     bool lineHasPipelineBeforeToken = false)
 {
     if (onNewLine)
     {
         onNewLine = false;
         if (token.Extent.StartColumnNumber - 1 != GetIndentation(expectedIndentationLevel))
         {
             var fileName        = token.Extent.File;
             var extent          = token.Extent;
             var violationExtent = extent = new ScriptExtent(
                 new ScriptPosition(
                     fileName,
                     extent.StartLineNumber,
                     1, // first column in the line
                     extent.StartScriptPosition.Line),
                 new ScriptPosition(
                     fileName,
                     extent.StartLineNumber,
                     extent.StartColumnNumber,
                     extent.StartScriptPosition.Line));
             diagnosticRecords.Add(
                 new DiagnosticRecord(
                     String.Format(CultureInfo.CurrentCulture, Strings.UseConsistentIndentationError),
                     violationExtent,
                     GetName(),
                     GetDiagnosticSeverity(),
                     fileName,
                     null,
                     GetSuggestedCorrections(token, expectedIndentationLevel, lineHasPipelineBeforeToken)));
         }
     }
 }
Exemplo n.º 13
0
        /// <summary>
        /// Creates an InformationalRecord from an instance serialized as a PSObject by ToPSObjectForRemoting.
        /// </summary>
        internal InvocationInfo(PSObject psObject)
        {
            CommandOrigin    = (CommandOrigin)SerializationUtilities.GetPsObjectPropertyBaseObject(psObject, "InvocationInfo_CommandOrigin");
            ExpectingInput   = (bool)SerializationUtilities.GetPropertyValue(psObject, "InvocationInfo_ExpectingInput");
            _invocationName  = (string)SerializationUtilities.GetPropertyValue(psObject, "InvocationInfo_InvocationName");
            HistoryId        = (long)SerializationUtilities.GetPropertyValue(psObject, "InvocationInfo_HistoryId");
            PipelineLength   = (int)SerializationUtilities.GetPropertyValue(psObject, "InvocationInfo_PipelineLength");
            PipelinePosition = (int)SerializationUtilities.GetPropertyValue(psObject, "InvocationInfo_PipelinePosition");

            string scriptName       = (string)SerializationUtilities.GetPropertyValue(psObject, "InvocationInfo_ScriptName");
            int    scriptLineNumber = (int)SerializationUtilities.GetPropertyValue(psObject, "InvocationInfo_ScriptLineNumber");
            int    offsetInLine     = (int)SerializationUtilities.GetPropertyValue(psObject, "InvocationInfo_OffsetInLine");
            string line             = (string)SerializationUtilities.GetPropertyValue(psObject, "InvocationInfo_Line");
            var    scriptPosition   = new ScriptPosition(scriptName, scriptLineNumber, offsetInLine, line);

            ScriptPosition scriptEndPosition;

            if (!string.IsNullOrEmpty(line))
            {
                int endColumn = line.Length + 1;
                scriptEndPosition = new ScriptPosition(scriptName, scriptLineNumber, endColumn, line);
            }
            else
            {
                scriptEndPosition = scriptPosition;
            }
            _scriptPosition = new ScriptExtent(scriptPosition, scriptEndPosition);

            MyCommand = RemoteCommandInfo.FromPSObjectForRemoting(psObject);

            //
            // Arrays are de-serialized as ArrayList so we need to convert the deserialized
            // object into an int[] before assigning to pipelineIterationInfo.
            //
            var list = (ArrayList)SerializationUtilities.GetPsObjectPropertyBaseObject(psObject, "InvocationInfo_PipelineIterationInfo");

            if (list != null)
            {
                PipelineIterationInfo = (int[])list.ToArray(typeof(Int32));
            }
            else
            {
                PipelineIterationInfo = Utils.EmptyArray <int>();
            }

            //
            // Dictionaries are de-serialized as Hashtables so we need to convert the deserialized object into a dictionary
            // before assigning to CommandLineParameters.
            //
            Hashtable hashtable = (Hashtable)SerializationUtilities.GetPsObjectPropertyBaseObject(psObject, "InvocationInfo_BoundParameters");

            Dictionary <string, object> dictionary = new Dictionary <string, object>();

            if (hashtable != null)
            {
                foreach (DictionaryEntry entry in hashtable)
                {
                    dictionary.Add((string)entry.Key, entry.Value);
                }
            }

            _boundParameters = dictionary;

            //
            // The unbound parameters are de-serialized as an ArrayList, which we need to convert to a List
            //
            var unboundArguments = (ArrayList)SerializationUtilities.GetPsObjectPropertyBaseObject(psObject, "InvocationInfo_UnboundArguments");

            _unboundArguments = new List <object>();

            if (unboundArguments != null)
            {
                foreach (object o in unboundArguments)
                {
                    _unboundArguments.Add(o);
                }
            }

            object value           = SerializationUtilities.GetPropertyValue(psObject, "SerializeExtent");
            bool   serializeExtent = false;

            if (value != null)
            {
                serializeExtent = (bool)value;
            }

            if (serializeExtent)
            {
                DisplayScriptPosition = ScriptExtent.FromPSObjectForRemoting(psObject);
            }
        }
Exemplo n.º 14
0
 public JobFailedException(Exception innerException, ScriptExtent displayScriptPosition)
 {
     this.reason = innerException;
     this.displayScriptPosition = displayScriptPosition;
 }
Exemplo n.º 15
0
 protected JobFailedException(SerializationInfo serializationInfo, StreamingContext streamingContext) : base(serializationInfo, streamingContext)
 {
     this.reason = (Exception)serializationInfo.GetValue("Reason", typeof(Exception));
     this.displayScriptPosition = (ScriptExtent)serializationInfo.GetValue("DisplayScriptPosition", typeof(ScriptExtent));
 }
Exemplo n.º 16
0
        ExpressionAst BuildExpandableStringLiteralWithSubexpressionAst(ParseTreeNode parseTreeNode)
        {
            VerifyTerm(parseTreeNode, this._grammar.expandable_string_literal_with_subexpr);

            var toResolve = new List<ExpressionAst>();

            var stmtTreeNode = parseTreeNode.ChildNodes[1];
            var stmtAst = BuildStatementListAst(stmtTreeNode);
            // the child node only covers the stamentent list, but not $( and ), which are part of other child nodes
            // therefore we artifically expand the extent by -2 and 1 to cover the markup.
            // this is important so the replacements work correctly
            var subExpExtent = new ScriptExtent(stmtTreeNode.Span, -2, 1);
            toResolve.Add(new SubExpressionAst(subExpExtent, stmtAst));

            for (int i = 3; i < parseTreeNode.ChildNodes.Count - 1; i++)
            {
                var item = parseTreeNode.ChildNodes[i];

                if (item.Term == this._grammar.expandable_string_with_subexpr_characters)
                {
                    foreach (var item2 in item.ChildNodes)
                    {
                        //sub_expression
                        //expandable_string_part
                        if (item2.Term == this._grammar.expandable_string_with_subexpr_part)
                        {
                            foreach (var item3 in item2.ChildNodes)
                            {
                                if (item3.Term == this._grammar.expandable_string_characters)
                                {
                                    var matches = Regex.Match(item3.FindTokenAndGetText(), this._grammar.expandable_string_characters.Pattern, RegexOptions.IgnoreCase);
                                    string value = matches.Groups[this._grammar.expandable_string_characters.Name].Value;

                                    var ast = new ExpandableStringExpressionAst(new ScriptExtent(item3), value, StringConstantType.DoubleQuoted);
                                    if (ast.NestedExpressions.Any())
                                    {
                                        toResolve.Add(ast);
                                    }
                                }

                                if (item3.Term == this._grammar.sub_expression)
                                {
                                    toResolve.Add(BuildSubExpression(item3));
                                }
                            }
                        }
                    }
                }
            }

            var extent = (IScriptExtent) new ScriptExtent(parseTreeNode);
            // now strip the real text value. +1 and -2 are used to strip the quotes
            var textValue = _parseTree.SourceText.Substring(extent.StartOffset + 1, extent.EndOffset - extent.StartOffset - 2);
            return new ExpandableStringExpressionAst(
                extent, toResolve, textValue,
                StringConstantType.DoubleQuoted);
        }
Exemplo n.º 17
0
        /// <summary>
        /// Analyzes the given ast to find violations.
        /// </summary>
        /// <param name="ast">AST to be analyzed. This should be non-null</param>
        /// <param name="fileName">Name of file that corresponds to the input AST.</param>
        /// <returns>A an enumerable type containing the violations</returns>
        public IEnumerable <DiagnosticRecord> AnalyzeScript(Ast ast, string fileName)
        {
            if (ast == null)
            {
                throw new ArgumentNullException("ast");
            }

            var diagnosticRecords = new List <DiagnosticRecord>();

            string[] lines = ast.Extent.Text.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None);

            for (int lineNumber = 0; lineNumber < lines.Length; lineNumber++)
            {
                var line = lines[lineNumber];

                if (line.Length == 0)
                {
                    continue;
                }

                if (!char.IsWhiteSpace(line[line.Length - 1]) &&
                    line[line.Length - 1] != '\t')
                {
                    continue;
                }

                int startColumnOfTrailingWhitespace = 1;
                for (int i = line.Length - 2; i > 0; i--)
                {
                    if (line[i] != ' ' && line[i] != '\t')
                    {
                        startColumnOfTrailingWhitespace = i + 2;
                        break;
                    }
                }

                int startLine   = lineNumber + 1;
                int endLine     = startLine;
                int startColumn = startColumnOfTrailingWhitespace;
                int endColumn   = line.Length + 1;

                var violationExtent = new ScriptExtent(
                    new ScriptPosition(
                        ast.Extent.File,
                        startLine,
                        startColumn,
                        line
                        ),
                    new ScriptPosition(
                        ast.Extent.File,
                        endLine,
                        endColumn,
                        line
                        ));

                var suggestedCorrections = new List <CorrectionExtent>();
                suggestedCorrections.Add(new CorrectionExtent(
                                             violationExtent,
                                             string.Empty,
                                             ast.Extent.File
                                             ));

                diagnosticRecords.Add(
                    new DiagnosticRecord(
                        String.Format(CultureInfo.CurrentCulture, Strings.AvoidTrailingWhitespaceError),
                        violationExtent,
                        GetName(),
                        GetDiagnosticSeverity(),
                        ast.Extent.File,
                        null,
                        suggestedCorrections
                        ));
            }

            return(diagnosticRecords);
        }
Exemplo n.º 18
0
    public IScriptExtent MapExtent(IScriptExtent extent)
    {
        if (extent == null)
        {
            return(null);
        }

        //Console.WriteLine("StartText: '{0}'", extent.StartScriptPosition.Line);

        int columnCorrection = 0;

        if (extent.StartLineNumber != extent.EndLineNumber)
        {
            columnCorrection = -1;
        }

        ScriptPosition startSourcePosition = null;

        if (extent.StartScriptPosition != null)
        {
            //Console.Write("mapping start {0}:{1} => ", extent.StartLineNumber, extent.StartColumnNumber);
            SourcePosition startGeneratedPosition = GetSourcePosition(extent.StartLineNumber - 1, 0);
            MappingEntry   startMappingEntry      = Map.GetMappingEntryForGeneratedSourcePosition(startGeneratedPosition);
            if (startMappingEntry == null)
            {
                startSourcePosition = new ScriptPosition(
                    extent.File,
                    extent.StartLineNumber,
                    extent.StartColumnNumber + columnCorrection,
                    extent.StartScriptPosition.Line
                    );
            }
            else
            {
                //Console.WriteLine("{0}:{1}", startMappingEntry.OriginalSourcePosition.ZeroBasedLineNumber + 1, extent.StartColumnNumber);
                startSourcePosition = new ScriptPosition(
                    startMappingEntry.OriginalFileName,
                    startMappingEntry.OriginalSourcePosition.ZeroBasedLineNumber + 1,
                    extent.StartColumnNumber + columnCorrection,
                    extent.StartScriptPosition.Line
                    );
            }
        }

        //Console.WriteLine("EndText: '{0}'", extent.EndScriptPosition.Line);

        ScriptPosition endSourcePosition = null;

        if (extent.EndScriptPosition != null)
        {
            //Console.Write("mapping end {0}:{1} => ", extent.EndLineNumber, extent.EndColumnNumber);
            SourcePosition endGeneratedPosition = GetSourcePosition(extent.EndLineNumber - 1, 0);
            MappingEntry   endMappingEntry      = Map.GetMappingEntryForGeneratedSourcePosition(endGeneratedPosition);
            if (endMappingEntry == null)
            {
                endSourcePosition = new ScriptPosition(
                    extent.File,
                    extent.EndLineNumber,
                    extent.EndColumnNumber + columnCorrection,
                    extent.EndScriptPosition.Line
                    );
            }
            else
            {
                //Console.WriteLine("{0}:{1}", endMappingEntry.OriginalSourcePosition.ZeroBasedLineNumber + 1, extent.EndColumnNumber);
                int endColumnNumber = extent.EndColumnNumber;

                /*
                 * if(extent.EndColumnNumber == 1 && extent.EndScriptPosition.Line == String.Empty) {
                 *      endColumnNumber = 0;
                 * }
                 */
                endSourcePosition = new ScriptPosition(
                    endMappingEntry.OriginalFileName,
                    endMappingEntry.OriginalSourcePosition.ZeroBasedLineNumber + 1,
                    endColumnNumber + columnCorrection,
                    extent.EndScriptPosition.Line
                    );
            }
        }

        IScriptExtent newExtent = new ScriptExtent(startSourcePosition, endSourcePosition);

        //Console.WriteLine("Returning mapped extent from {0}:{1} to {2}:{3} - {4}", startSourcePosition.LineNumber, startSourcePosition.ColumnNumber, endSourcePosition.LineNumber, endSourcePosition.ColumnNumber, newExtent.Text);
        return(newExtent);
    }
Exemplo n.º 19
0
        internal InvocationInfo(PSObject psObject)
        {
            this._historyId             = -1L;
            this._pipelineIterationInfo = new int[0];
            this._commandOrigin         = (System.Management.Automation.CommandOrigin)SerializationUtilities.GetPsObjectPropertyBaseObject(psObject, "InvocationInfo_CommandOrigin");
            this._expectingInput        = (bool)SerializationUtilities.GetPropertyValue(psObject, "InvocationInfo_ExpectingInput");
            this._invocationName        = (string)SerializationUtilities.GetPropertyValue(psObject, "InvocationInfo_InvocationName");
            this._historyId             = (long)SerializationUtilities.GetPropertyValue(psObject, "InvocationInfo_HistoryId");
            this._pipelineLength        = (int)SerializationUtilities.GetPropertyValue(psObject, "InvocationInfo_PipelineLength");
            this._pipelinePosition      = (int)SerializationUtilities.GetPropertyValue(psObject, "InvocationInfo_PipelinePosition");
            string propertyValue    = (string)SerializationUtilities.GetPropertyValue(psObject, "InvocationInfo_ScriptName");
            int    scriptLineNumber = (int)SerializationUtilities.GetPropertyValue(psObject, "InvocationInfo_ScriptLineNumber");
            int    offsetInLine     = (int)SerializationUtilities.GetPropertyValue(psObject, "InvocationInfo_OffsetInLine");
            string line             = (string)SerializationUtilities.GetPropertyValue(psObject, "InvocationInfo_Line");

            System.Management.Automation.Language.ScriptPosition startPosition = new System.Management.Automation.Language.ScriptPosition(propertyValue, scriptLineNumber, offsetInLine, line);
            this._scriptPosition = new ScriptExtent(startPosition, startPosition);
            this._commandInfo    = RemoteCommandInfo.FromPSObjectForRemoting(psObject);
            ArrayList psObjectPropertyBaseObject = (ArrayList)SerializationUtilities.GetPsObjectPropertyBaseObject(psObject, "InvocationInfo_PipelineIterationInfo");

            if (psObjectPropertyBaseObject != null)
            {
                this._pipelineIterationInfo = (int[])psObjectPropertyBaseObject.ToArray(Type.GetType("System.Int32"));
            }
            else
            {
                this._pipelineIterationInfo = new int[0];
            }
            Hashtable hashtable = (Hashtable)SerializationUtilities.GetPsObjectPropertyBaseObject(psObject, "InvocationInfo_BoundParameters");
            Dictionary <string, object> dictionary = new Dictionary <string, object>();

            if (hashtable != null)
            {
                foreach (DictionaryEntry entry in hashtable)
                {
                    dictionary.Add((string)entry.Key, entry.Value);
                }
            }
            this._boundParameters = dictionary;
            ArrayList list2 = (ArrayList)SerializationUtilities.GetPsObjectPropertyBaseObject(psObject, "InvocationInfo_UnboundArguments");

            this._unboundArguments = new List <object>();
            if (list2 != null)
            {
                foreach (object obj2 in list2)
                {
                    this._unboundArguments.Add(obj2);
                }
            }
            object obj3 = SerializationUtilities.GetPropertyValue(psObject, "SerializeExtent");
            bool   flag = false;

            if (obj3 != null)
            {
                flag = (bool)obj3;
            }
            if (flag)
            {
                this._displayScriptPosition = ScriptExtent.FromPSObjectForRemoting(psObject);
            }
        }