Inheritance: ISarifNode
        public static bool Include(this Region region, Region location)
        {
            int currentEndLine = region.EndLine == -1 ? region.StartLine : region.EndLine; ;
            int locationEndLine = location.EndLine == -1 ? location.StartLine : location.EndLine; ;

            int currentEndColumn = region.EndColumn == -1 ? region.StartColumn : region.EndColumn; ;
            int locationEndColumn = location.EndColumn == -1 ? location.EndColumn : location.EndColumn; ;

            return region.StartLine <= location.StartLine
                && currentEndLine >= locationEndLine
                && region.StartColumn <= location.StartColumn
                && currentEndColumn >= locationEndColumn;
        }
        public static Region ConvertToRegion(this Location location)
        {
            if (location == Location.None) { return null; }

            var region = new Region();

            FileLinePositionSpan flps = location.GetLineSpan();

            // Roslyn text position numbering is 0-based
            region.StartLine = flps.Span.Start.Line + 1;
            region.StartColumn = flps.Span.Start.Character + 1;
            region.EndLine = flps.Span.End.Line + 1;
            region.EndColumn = flps.Span.End.Character + 1;

            return region;
        }
        /// <summary>
        /// fullFilePath may be null for global issues.
        /// </summary>
        public ResultTextMarker(IServiceProvider serviceProvider, Region region, string fullFilePath)
        {
            if (serviceProvider == null)
            {
                throw new ArgumentNullException(nameof(serviceProvider));
            }

            if (region == null)
            {
                throw new ArgumentNullException(nameof(region));
            }

            m_serviceProvider = serviceProvider;
            m_region = region;
            FullFilePath = fullFilePath;
            Color = DEFAULT_SELECTION_COLOR;
        }
        public void BuildResult_BuildsExpectedResult()
        {
            // Arrange
            const string FormatId = "Default";
            const string RuleId = "TST0001";
            string[] Arguments = new string[] { "42", "54" };

            var context = new TestAnalysisContext
            {
                TargetUri = new System.Uri("file:///c:/src/file.c"),
                Rule = new Rule
                {
                    Id = RuleId,
                    MessageFormats = new Dictionary<string, string>
                    {
                        [FormatId] = "Expected {0} but got {1}."
                    }
                }
            };

            var region = new Region
            {
                StartLine = 42
            };

            // Act.
            Result result = RuleUtilities.BuildResult(
                ResultLevel.Error,
                context,
                region,
                FormatId,
                Arguments);

            // Assert.
            result.RuleId.Should().Be(RuleId);

            result.FormattedRuleMessage.FormatId.Should().Be(FormatId);

            result.FormattedRuleMessage.Arguments.Count.Should().Be(Arguments.Length);
            result.FormattedRuleMessage.Arguments[0].Should().Be(Arguments[0]);
            result.FormattedRuleMessage.Arguments[1].Should().Be(Arguments[1]);

            result.Locations.Count.Should().Be(1);
            result.Locations[0].AnalysisTarget.Region.ValueEquals(region).Should().BeTrue();
        }
Exemple #5
0
        public static Result BuildResult(ResultLevel level, IAnalysisContext context, Region region, string formatId, params string[] arguments)
        {
            //validating parameters
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (arguments == null)
            {
                throw new ArgumentNullException(nameof(arguments));
            }

            formatId = RuleUtilities.NormalizeFormatId(context.Rule.Id, formatId);

            Result result = new Result
            {
                RuleId = context.Rule.Id,

                FormattedRuleMessage = new FormattedRuleMessage()
                {
                    FormatId = formatId,
                    Arguments = arguments
                },

                Level = level
            };

            string targetPath = context.TargetUri?.LocalPath;
            if (targetPath != null)
            {
                result.Locations = new List<Location> {
                    new Sarif.Location {
                        AnalysisTarget = new PhysicalLocation
                        {
                            Uri = new Uri(targetPath),
                            Region = region
                        }
               }};
            }
            return result;
        }
        /// <summary>
        /// Get source location of current marker (tracking code place). 
        /// </summary>
        /// <returns>
        /// This is clone of stored source location with actual source code coordinates.
        /// </returns>
        public Region GetSourceLocation()
        {
            Region sourceLocation = new Region()
            {
                Offset = m_region.Offset,
                StartColumn = m_region.StartColumn,
                EndColumn = m_region.EndColumn,
                StartLine = m_region.StartLine,
                EndLine = m_region.EndLine
            };

            SaveCurrentTrackingData(sourceLocation);
            return sourceLocation;
        }
Exemple #7
0
 public bool ValueEquals(Region other) => ValueComparer.Equals(this, other);
Exemple #8
0
        public static void LogTargetParseError(IAnalysisContext context, Region region, string message)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            // {0}({1}): error {2}: {3}
            context.Logger.LogConfigurationNotification(
                CreateNotification(
                    context.TargetUri,
                    ERR1000_ParseError,
                    NotificationLevel.Error,
                    null,
                    false,
                    context.TargetUri.LocalPath,
                    region.FormatForVisualStudio(),
                    ERR1000_ParseError,
                    message));

            context.RuntimeErrors |= RuntimeConditions.TargetParseError;
        }
Exemple #9
0
        private void WriteToConsole(ResultLevel level, Uri uri, Region region, string ruleId, string message)
        {
            switch (level)
            {
                // These result types are optionally emitted.
                case ResultLevel.Pass:
                case ResultLevel.Note:
                case ResultLevel.NotApplicable:
                    {
                        if (Verbose)
                        {
                            Console.WriteLine(GetMessageText(uri, region, ruleId, message, level));
                        }
                        break;
                    }

                // These result types are always emitted.
                case ResultLevel.Error:
                case ResultLevel.Warning:
                    {
                        Console.WriteLine(GetMessageText(uri, region, ruleId, message, level));
                        break;
                    }

                default:
                    {
                        throw new InvalidOperationException();
                    }
            }
        }
Exemple #10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Region" /> class from the specified instance.
        /// </summary>
        /// <param name="other">
        /// The instance from which the new instance is to be initialized.
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// Thrown if <paramref name="other" /> is null.
        /// </exception>
        public Region(Region other)
        {
            if (other == null)
            {
                throw new ArgumentNullException(nameof(other));
            }

            Init(other.StartLine, other.StartColumn, other.EndLine, other.EndColumn, other.Offset, other.Length);
        }
        private void PopulatePropertiesFromCharOffsetAndLength(NewLineIndex newLineIndex, Region region)
        {
            Assert(!region.IsBinaryRegion);
            Assert(region.StartLine == 0);
            Assert(region.CharLength >= 0 || region.CharOffset >= 0);

            int startLine, startColumn, endLine, endColumn;

            // Retrieve start and end line and column information from the new line index
            OffsetInfo offsetInfo = newLineIndex.GetOffsetInfoForOffset(region.CharOffset);

            startLine   = offsetInfo.LineNumber;
            startColumn = offsetInfo.ColumnNumber;

            offsetInfo = newLineIndex.GetOffsetInfoForOffset(region.CharOffset + region.CharLength);
            endLine    = offsetInfo.LineNumber;

            // The computation above points one past our actual region, because endColumn
            // is exclusive of the region. This allows for length to easily be computed
            // for single line regions: region.EndColumn - region.StartColumn
            endColumn = offsetInfo.ColumnNumber;

            // Only set values if they aren't already specified
            if (region.StartLine == 0)
            {
                region.StartLine = startLine;
            }
            if (region.StartColumn == 0)
            {
                region.StartColumn = startColumn;
            }
            if (region.EndLine == 0)
            {
                region.EndLine = endLine;
            }
            if (region.EndColumn == 0)
            {
                region.EndColumn = endColumn;
            }

            // Validate cases where new line index disagrees with explicit values
            Assert(region.StartLine == startLine);
            Assert(region.StartColumn == startColumn);
            Assert(region.EndLine == endLine);
            Assert(region.EndColumn == endColumn);
        }
Exemple #12
0
        private static string GetMessageText(
            Uri uri,
            Region region,
            string ruleId,
            string message,
            ResultLevel resultLevel)
        {
            string path = null;

            if (uri != null)
            {
                // If a path refers to a URI of form file://blah, we will convert to the local path
                if (uri.IsAbsoluteUri && uri.Scheme == Uri.UriSchemeFile)
                {
                    path = uri.LocalPath;
                }
                else
                {
                    path = uri.ToString();
                }
            }

            string issueType = null;

            switch (resultLevel)
            {
                case ResultLevel.Error:
                    issueType = "error";
                    break;

                case ResultLevel.Warning:
                    issueType = "warning";
                    break;

                case ResultLevel.NotApplicable:
                case ResultLevel.Note:
                case ResultLevel.Pass:
                    issueType = "info";
                    break;

                default:
                    throw new InvalidOperationException("Unknown message kind:" + resultLevel.ToString());
            }

            string detailedDiagnosis = NormalizeMessage(message, enquote: false);

            string location = "";

            if (region != null)
            {
                // TODO
                if (region.Offset > 0 ||
                    region.StartColumn == 0)
                {
                    throw new NotImplementedException();
                }

                if (region.StartLine == 0)
                {
                    throw new InvalidOperationException();
                }

                location = region.FormatForVisualStudio();
            }

            string result = (path != null ? (path + location + ": ") : "") +
                   issueType + (!string.IsNullOrEmpty(ruleId) ? " " : "") +
                   (resultLevel != ResultLevel.Note ? ruleId : "") + ": " +
                   detailedDiagnosis;

            return result;
        }
        private void PopulatePropertiesFromStartAndEndProperties(NewLineIndex lineIndex, Region region, string fileText)
        {
            Assert(region.StartLine > 0);

            // Note: execution order of these helpers is important, as some
            // calls assume that certain preceding helpers have executed,
            // with the result that certain properties are populated

            // Populated at this point: StartLine
            PopulateEndLine(region);

            // Populated at this point: StartLine, EndLine
            PopulateStartColumn(region);

            // Populated at this point: StartLine, EndLine, StartColumn
            PopulateEndColumn(lineIndex, region, fileText);

            // Populated at this point: StartLine, EndLine, StartColumn, EndColumn
            PopulateCharOffset(lineIndex, region);

            // Populated at this point: StartLine, EndLine, StartColumn, EndColumn, CharOffset
            PopulateCharLength(lineIndex, region);

            // Populated at this point: StartLine, EndLine, StartColumn, EndColumn, CharOffset, CharLength
            Assert(region.StartLine > 0);
            Assert(region.EndLine > 0);
            Assert((region.CharOffset + region.CharLength) <= fileText.Length);
            Assert(region.StartColumn > 0);
            Assert(region.CharLength > 0 || (region.StartColumn == region.EndColumn && region.StartLine == region.EndLine));
            Assert(region.EndColumn > 0);
        }
        private void SaveCurrentTrackingData(Region sourceLocation)
        {
            try
            {
                if (!IsTracking())
                {
                    return;
                }

                ITextSnapshot textSnapshot = m_trackingSpan.TextBuffer.CurrentSnapshot;
                SnapshotPoint startPoint = m_trackingSpan.GetStartPoint(textSnapshot);
                SnapshotPoint endPoint = m_trackingSpan.GetEndPoint(textSnapshot);

                var startLine = startPoint.GetContainingLine();
                var endLine = endPoint.GetContainingLine();

                var textLineStart = m_textView.GetTextViewLineContainingBufferPosition(startPoint);
                var textLineEnd = m_textView.GetTextViewLineContainingBufferPosition(endPoint);

                sourceLocation.StartColumn = startLine.Start.Position - textLineStart.Start.Position;
                sourceLocation.EndColumn = endLine.End.Position - textLineEnd.Start.Position;
                sourceLocation.StartLine = startLine.LineNumber + 1;
                sourceLocation.EndLine = endLine.LineNumber + 1;
            }
            catch (InvalidOperationException)
            {
                // Editor throws InvalidOperationException in some cases -
                // We act like tracking isn't turned on if this is thrown to avoid
                // taking all of VS down.
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="PhysicalLocation" /> class from the supplied values.
 /// </summary>
 /// <param name="uri">
 /// An initialization value for the <see cref="P: Uri" /> property.
 /// </param>
 /// <param name="uriBaseId">
 /// An initialization value for the <see cref="P: UriBaseId" /> property.
 /// </param>
 /// <param name="region">
 /// An initialization value for the <see cref="P: Region" /> property.
 /// </param>
 public PhysicalLocation(Uri uri, string uriBaseId, Region region)
 {
     Init(uri, uriBaseId, region);
 }
        private void Init(Uri uri, string uriBaseId, Region region)
        {
            if (uri != null)
            {
                Uri = new Uri(uri.OriginalString, uri.IsAbsoluteUri ? UriKind.Absolute : UriKind.Relative);
            }

            UriBaseId = uriBaseId;
            if (region != null)
            {
                Region = new Region(region);
            }
        }
Exemple #17
0
 public bool ValueEquals(Region other) => ValueComparer.Equals(this, other);