Example #1
0
        public override void VisitInvocationExpression(InvocationExpressionSyntax node)
        {
            string fileName = Path.GetFileName(node.SyntaxTree.FilePath);
            FileLinePositionSpan lineSpan = node.SyntaxTree.GetLineSpan(node.Span);
            int numLine = lineSpan.StartLinePosition.Line + 1;

            switch (node.Expression.ToString())
            {
            case "Label.Breakpoint":
                string name = node.ArgumentList.Arguments[0].Expression.ToString();
                // "name" -> name
                name = name.Trim(new char[] { '\"' });

                LineBreakpoint lbp = (LineBreakpoint)Activator.CreateInstance(TypeClassBP,
                                                                              name, fileName, numLine);

                TestLabelsInfo.Breakpoints.Add(name, lbp);
                break;

            case "Label.Checkpoint":
                string id      = node.ArgumentList.Arguments[0].Expression.ToString();
                string next_id = node.ArgumentList.Arguments[1].Expression.ToString();
                // "id" -> id
                id      = id.Trim(new char[] { '\"' });
                next_id = next_id.Trim(new char[] { '\"' });

                TestLabelsInfo.CheckPointInvokes.Add(
                    id, new Tuple <string, InvocationExpressionSyntax>(next_id, node));
                break;
            }
        }
Example #2
0
        private DiagnosticResult AppendSpan(FileLinePositionSpan span)
        {
            FileLinePositionSpan[] newSpans;

            if (this.spans != null)
            {
                newSpans = new FileLinePositionSpan[this.spans.Length + 1];
                Array.Copy(this.spans, newSpans, this.spans.Length);
                newSpans[this.spans.Length] = span;
            }
            else
            {
                newSpans = new FileLinePositionSpan[1]
                {
                    span,
                };
            }

            // clone the object, so that the fluent syntax will work on immutable objects.
            return(new DiagnosticResult
            {
                Id = this.Id,
                Message = this.message,
                MessageFormat = this.MessageFormat,
                MessageArguments = this.MessageArguments,
                Severity = this.Severity,
                Spans = newSpans,
            });
        }
Example #3
0
        /// <summary>
        /// Helper method to VerifyDiagnosticResult that checks the location of a diagnostic and compares it with the location in the expected DiagnosticResult.
        /// </summary>
        /// <param name="analyzer">The analyzer that was being run on the sources</param>
        /// <param name="diagnostic">The diagnostic that was found in the code</param>
        /// <param name="actual">The Location of the Diagnostic found in the code</param>
        /// <param name="expected">The DiagnosticResultLocation that should have been found</param>
        private void VerifyDiagnosticLocation(DiagnosticAnalyzer analyzer, Diagnostic diagnostic, Location actual, DiagnosticResultLocation expected)
        {
            FileLinePositionSpan actualSpan = actual.GetLineSpan();

            Assert.IsTrue(actualSpan.Path == expected.Path || (actualSpan.Path != null && actualSpan.Path.Contains("Test0.") && expected.Path.Contains("Test.")),
                          $"Expected diagnostic to be in file \"{expected.Path}\" was actually in file \"{actualSpan.Path}\"\r\n\r\nDiagnostic:\r\n    {FormatDiagnostics(analyzer, diagnostic)}\r\n");

            LinePosition actualLinePosition = actualSpan.StartLinePosition;

            // Only check line position if there is an actual line in the real diagnostic
            if (actualLinePosition.Line > 0)
            {
                if (actualLinePosition.Line + 1 != expected.Line)
                {
                    Assert.IsTrue(false,
                                  $"Expected diagnostic to be on line \"{expected.Line}\" was actually on line \"{actualLinePosition.Line + 1}\"\r\n\r\nDiagnostic:\r\n    {FormatDiagnostics(analyzer, diagnostic)}\r\n");
                }
            }

            // Only check column position if there is an actual column position in the real diagnostic
            if (actualLinePosition.Character > 0)
            {
                if (actualLinePosition.Character + 1 != expected.Column)
                {
                    Assert.IsTrue(false,
                                  $"Expected diagnostic to start at column \"{expected.Column}\" was actually at column \"{actualLinePosition.Character + 1}\"\r\n\r\nDiagnostic:\r\n    {FormatDiagnostics(analyzer, diagnostic)}\r\n");
                }
            }
        }
        public void GetAdjustedDiagnosticSpan(
            DocumentId documentId, Location location,
            out TextSpan sourceSpan, out FileLinePositionSpan originalLineInfo, out FileLinePositionSpan mappedLineInfo)
        {
            sourceSpan = location.SourceSpan;
            originalLineInfo = location.GetLineSpan();
            mappedLineInfo = location.GetMappedLineSpan();

            // Update the original source span, if required.
            LinePositionSpan originalSpan;
            LinePositionSpan mappedSpan;
            if (!TryAdjustSpanIfNeededForVenus(documentId, originalLineInfo, mappedLineInfo, out originalSpan, out mappedSpan))
            {
                return;
            }

            if (originalSpan.Start != originalLineInfo.StartLinePosition || originalSpan.End != originalLineInfo.EndLinePosition)
            {
                originalLineInfo = new FileLinePositionSpan(originalLineInfo.Path, originalSpan.Start, originalSpan.End);

                var textLines = location.SourceTree.GetText().Lines;
                var startPos = textLines.GetPosition(originalSpan.Start);
                var endPos = textLines.GetPosition(originalSpan.End);
                sourceSpan = new TextSpan(startPos, endPos - startPos);
            }

            if (mappedSpan.Start != mappedLineInfo.StartLinePosition || mappedSpan.End != mappedLineInfo.EndLinePosition)
            {
                mappedLineInfo = new FileLinePositionSpan(mappedLineInfo.Path, mappedSpan.Start, mappedSpan.End);
            }
        }
        private bool TryAdjustSpanIfNeededForVenus(
            DocumentId documentId, FileLinePositionSpan originalLineInfo, FileLinePositionSpan mappedLineInfo, out LinePositionSpan originalSpan, out LinePositionSpan mappedSpan)
        {
            var startChanged = true;
            MappedSpan startLineColumn;
            if (!TryAdjustSpanIfNeededForVenus(_workspace, documentId, originalLineInfo.StartLinePosition.Line, originalLineInfo.StartLinePosition.Character, out startLineColumn))
            {
                startChanged = false;
                startLineColumn = new MappedSpan(originalLineInfo.StartLinePosition.Line, originalLineInfo.StartLinePosition.Character, mappedLineInfo.StartLinePosition.Line, mappedLineInfo.StartLinePosition.Character);
            }

            var endChanged = true;
            MappedSpan endLineColumn;
            if (!TryAdjustSpanIfNeededForVenus(_workspace, documentId, originalLineInfo.EndLinePosition.Line, originalLineInfo.EndLinePosition.Character, out endLineColumn))
            {
                endChanged = false;
                endLineColumn = new MappedSpan(originalLineInfo.EndLinePosition.Line, originalLineInfo.EndLinePosition.Character, mappedLineInfo.EndLinePosition.Line, mappedLineInfo.EndLinePosition.Character);
            }

            // start and end position can be swapped when mapped between primary and secondary buffer if start position is within visible span (at the edge)
            // but end position is outside of visible span. in that case, swap start and end position.
            originalSpan = GetLinePositionSpan(startLineColumn.OriginalLinePosition, endLineColumn.OriginalLinePosition);
            mappedSpan = GetLinePositionSpan(startLineColumn.MappedLinePosition, endLineColumn.MappedLinePosition);

            return startChanged || endChanged;
        }
        internal static async Task <long> GetLinesOfCodeAsync(ImmutableArray <SyntaxReference> declarations, ISymbol symbol, CodeMetricsAnalysisContext context)
        {
            long linesOfCode = 0;

            foreach (var decl in declarations)
            {
                SyntaxNode declSyntax = await GetTopmostSyntaxNodeForDeclarationAsync(decl, symbol, context).ConfigureAwait(false);

                // For namespace symbols, don't count lines of code for declarations of child namespaces.
                // For example, "namespace N1.N2 { }" is a declaration reference for N1, but the actual declaration is for N2.
                if (symbol.Kind == SymbolKind.Namespace)
                {
                    var model = context.GetSemanticModel(declSyntax);
                    if (model.GetDeclaredSymbol(declSyntax, context.CancellationToken) != (object)symbol)
                    {
                        continue;
                    }
                }

                FileLinePositionSpan linePosition = declSyntax.SyntaxTree.GetLineSpan(declSyntax.FullSpan, context.CancellationToken);
                long delta = linePosition.EndLinePosition.Line - linePosition.StartLinePosition.Line;
                if (delta == 0)
                {
                    // Declaration on a single line, we count it as a separate line.
                    delta = 1;
                }

                linesOfCode += delta;
            }

            return(linesOfCode);
        }
        public void GetAdjustedDiagnosticSpan(
            DocumentId documentId, Location location,
            out TextSpan sourceSpan, out FileLinePositionSpan originalLineInfo, out FileLinePositionSpan mappedLineInfo)
        {
            sourceSpan = location.SourceSpan;
            originalLineInfo = location.GetLineSpan();
            mappedLineInfo = location.GetMappedLineSpan();

            // check quick bail out case.
            if (location == Location.None)
            {
                return;
            }
            // Update the original source span, if required.
            if (!TryAdjustSpanIfNeededForVenus(documentId, originalLineInfo, mappedLineInfo, out var originalSpan, out var mappedSpan))
            {
                return;
            }

            if (originalSpan.Start != originalLineInfo.StartLinePosition || originalSpan.End != originalLineInfo.EndLinePosition)
            {
                originalLineInfo = new FileLinePositionSpan(originalLineInfo.Path, originalSpan.Start, originalSpan.End);

                var textLines = location.SourceTree.GetText().Lines;
                var startPos = textLines.GetPosition(originalSpan.Start);
                var endPos = textLines.GetPosition(originalSpan.End);

                sourceSpan = TextSpan.FromBounds(startPos, Math.Max(startPos, endPos));
            }

            if (mappedSpan.Start != mappedLineInfo.StartLinePosition || mappedSpan.End != mappedLineInfo.EndLinePosition)
            {
                mappedLineInfo = new FileLinePositionSpan(mappedLineInfo.Path, mappedSpan.Start, mappedSpan.End);
            }
        }
Example #8
0
        /// <summary>
        /// Calculate node comment lines
        /// </summary>
        /// <param name="node"></param>
        /// <returns>Sum of comment lines</returns>
        private static int SumCommentLines(SyntaxNode node)
        {
            int tcloc = 0;
            var list  = node.DescendantTrivia().Where(t => t.IsAcceptableCommentKind()).ToList();

            foreach (var trivia in list)
            {
                SyntaxNode localNode = trivia.Token.Parent;
                if (node.IsAcceptableToInsideNode(localNode))
                {
                    continue;
                }

                FileLinePositionSpan flps = trivia.GetLocation().GetLineSpan();
                switch (trivia.Kind())
                {
                case SyntaxKind.MultiLineCommentTrivia:
                case SyntaxKind.SingleLineCommentTrivia:
                case SyntaxKind.MultiLineDocumentationCommentTrivia:
                    if (localNode.IsParent <BlockSyntax>())
                    {
                        tcloc += flps.EndLinePosition.Line - flps.StartLinePosition.Line + 1;
                    }
                    break;

                case SyntaxKind.SingleLineDocumentationCommentTrivia:
                    if (localNode.IsParent <BlockSyntax>())
                    {
                        tcloc += flps.EndLinePosition.Line - flps.StartLinePosition.Line;
                    }
                    break;
                }
            }
            return(tcloc);
        }
        private IDictionary <int, TextSpan> getLineSpans(SyntaxTree tree, IEnumerable <SyntaxToken> tokens)
        {
            Dictionary <int, TextSpan> dict = new Dictionary <int, TextSpan>();

            foreach (SyntaxToken t in tokens)
            {
                TextSpan span = t.Span;
                if (span.Length == 0)
                {
                    continue;
                }
                FileLinePositionSpan linePos = tree.GetLineSpan(span);
                int line = linePos.StartLinePosition.Line;

                if (dict.ContainsKey(line))
                {
                    if (span.Start < dict[line].Start)
                    {
                        dict[line] = TextSpan.FromBounds(span.Start, dict[line].End);
                    }
                    if (span.End > dict[line].End)
                    {
                        dict[line] = TextSpan.FromBounds(dict[line].Start, span.End);
                    }
                }
                else
                {
                    dict[line] = span;
                }
            }

            return(dict);
        }
Example #10
0
        internal void TraceCompilationDiagnostics(ImmutableArray <Diagnostic> diagnostics, LogTargets logTarget = LogTargets.All, bool isInvocation = false)
        {
            if (logTarget == LogTargets.None)
            {
                return;
            }

            // build the log state based on inputs
            Dictionary <string, object> logState = new Dictionary <string, object>();

            if (!isInvocation)
            {
                // generally we only want to trace compilation diagnostics on the single primary
                // host, to avoid duplicate log statements in the case of file save operations.
                // however if the function is being invoked, we always want to output detailed
                // information.
                logState.Add(ScriptConstants.LogPropertyPrimaryHostKey, true);
            }
            if (!logTarget.HasFlag(LogTargets.User))
            {
                logState.Add(ScriptConstants.LogPropertyIsSystemLogKey, true);
            }
            else if (!logTarget.HasFlag(LogTargets.System))
            {
                logState.Add(ScriptConstants.LogPropertyIsUserLogKey, true);
            }

            // log the diagnostics
            foreach (var diagnostic in diagnostics.Where(d => !d.IsSuppressed))
            {
                FunctionLogger.Log(diagnostic.Severity.ToLogLevel(), 0, logState, null, (s, e) => diagnostic.ToString());
            }

            // log structured logs
            if (Host.InDebugMode && (Host.IsPrimary || isInvocation))
            {
                Host.EventManager.Publish(new StructuredLogEntryEvent(() =>
                {
                    var logEntry = new StructuredLogEntry("codediagnostic");
                    logEntry.AddProperty("functionName", Metadata.Name);
                    logEntry.AddProperty("diagnostics", diagnostics.Select(d =>
                    {
                        FileLinePositionSpan span = d.Location.GetMappedLineSpan();
                        return(new
                        {
                            code = d.Id,
                            message = d.GetMessage(),
                            source = Path.GetFileName(d.Location.SourceTree?.FilePath ?? span.Path ?? string.Empty),
                            severity = d.Severity,
                            startLineNumber = span.StartLinePosition.Line + 1,
                            startColumn = span.StartLinePosition.Character + 1,
                            endLine = span.EndLinePosition.Line + 1,
                            endColumn = span.EndLinePosition.Character + 1,
                        });
                    }));

                    return(logEntry);
                }));
            }
        }
        private bool TryAdjustSpanIfNeededForVenus(
            DocumentId documentId, FileLinePositionSpan originalLineInfo, FileLinePositionSpan mappedLineInfo, out LinePositionSpan originalSpan, out LinePositionSpan mappedSpan)
        {
            var startChanged = true;

            if (!TryAdjustSpanIfNeededForVenus(_workspace, documentId, originalLineInfo.StartLinePosition.Line, originalLineInfo.StartLinePosition.Character, out var startLineColumn))
            {
                startChanged    = false;
                startLineColumn = new MappedSpan(originalLineInfo.StartLinePosition.Line, originalLineInfo.StartLinePosition.Character, mappedLineInfo.StartLinePosition.Line, mappedLineInfo.StartLinePosition.Character);
            }

            var endChanged = true;

            if (!TryAdjustSpanIfNeededForVenus(_workspace, documentId, originalLineInfo.EndLinePosition.Line, originalLineInfo.EndLinePosition.Character, out var endLineColumn))
            {
                endChanged    = false;
                endLineColumn = new MappedSpan(originalLineInfo.EndLinePosition.Line, originalLineInfo.EndLinePosition.Character, mappedLineInfo.EndLinePosition.Line, mappedLineInfo.EndLinePosition.Character);
            }

            // start and end position can be swapped when mapped between primary and secondary buffer if start position is within visible span (at the edge)
            // but end position is outside of visible span. in that case, swap start and end position.
            originalSpan = GetLinePositionSpan(startLineColumn.OriginalLinePosition, endLineColumn.OriginalLinePosition);
            mappedSpan   = GetLinePositionSpan(startLineColumn.MappedLinePosition, endLineColumn.MappedLinePosition);

            return(startChanged || endChanged);
        }
        private static void HandleBlock(SyntaxNodeAnalysisContext context)
        {
            BlockSyntax block = context.Node as BlockSyntax;

            if (block != null && block.Statements.Any())
            {
                var previousStatement = block.Statements[0];
                FileLinePositionSpan previousStatementLocation = previousStatement.GetLineSpan();
                FileLinePositionSpan currentStatementLocation;

                for (int i = 1; i < block.Statements.Count; i++)
                {
                    var currentStatement = block.Statements[i];
                    currentStatementLocation = currentStatement.GetLineSpan();

                    if (previousStatementLocation.EndLinePosition.Line
                        == currentStatementLocation.StartLinePosition.Line &&
                        !IsLastTokenMissing(previousStatement))
                    {
                        context.ReportDiagnostic(Diagnostic.Create(Descriptor, block.Statements[i].GetLocation()));
                    }

                    previousStatementLocation = currentStatementLocation;
                    previousStatement         = currentStatement;
                }
            }
        }
Example #13
0
        void LogException(CompileTaskResult result, System.Exception e, SyntaxNode node, out string logMessage)
        {
            logMessage = "";

            if (node != null)
            {
                FileLinePositionSpan lineSpan = node.GetLocation().GetLineSpan();

                CompileError error = new CompileError();
                error.script   = programAsset.sourceCsScript;
                error.errorStr = $"{e.GetType()}: {e.Message}";
                error.lineIdx  = lineSpan.StartLinePosition.Line;
                error.charIdx  = lineSpan.StartLinePosition.Character;

                result.compileErrors.Add(error);
            }
            else
            {
                logMessage = e.ToString();
                Debug.LogException(e);
            }
#if UDONSHARP_DEBUG
            Debug.LogException(e);
            Debug.LogError(e.StackTrace);
#endif
        }
        /// <summary>
        /// Helper method to VerifyDiagnosticResult that checks the location of a diagnostic and compares it with the location in the expected DiagnosticResult.
        /// </summary>
        /// <param name="analyzer">The analyzer that was being run on the sources</param>
        /// <param name="diagnostic">The diagnostic that was found in the code</param>
        /// <param name="actual">The Location of the Diagnostic found in the code</param>
        /// <param name="expected">The DiagnosticResultLocation that should have been found</param>
        private static void VerifyDiagnosticLocation(DiagnosticAnalyzer analyzer, Diagnostic diagnostic, Location actual, DiagnosticLocation expected)
        {
            FileLinePositionSpan actualSpan = actual.GetLineSpan();

            Assert.True(actualSpan.Path == expected.Span.Path || (actualSpan.Path != null && actualSpan.Path.Contains("Test0.") && expected.Span.Path.Contains("Test.")),
                        string.Format("Expected diagnostic to be in file \"{0}\" was actually in file \"{1}\"\r\n\r\nDiagnostic:\r\n    {2}\r\n",
                                      expected.Span.Path, actualSpan.Path, FormatDiagnostics(analyzer, diagnostic)));

            Microsoft.CodeAnalysis.Text.LinePosition actualLinePosition = actualSpan.StartLinePosition;

            // Only check line position if there is an actual line in the real diagnostic
            if (expected.Span.StartLinePosition.Line > 0)
            {
                if (actualLinePosition.Line + 1 != expected.Span.StartLinePosition.Line)
                {
                    Assert.True(false,
                                string.Format("Expected diagnostic to be on line \"{0}\" was actually on line \"{1}\"\r\n\r\nDiagnostic:\r\n    {2}\r\n",
                                              expected.Span.StartLinePosition.Line, actualLinePosition.Line + 1, FormatDiagnostics(analyzer, diagnostic)));
                }
            }

            // Only check column position if there is an actual column position in the real diagnostic
            if (actualLinePosition.Character > 0)
            {
                if (actualLinePosition.Character + 1 != expected.Span.StartLinePosition.Character)
                {
                    Assert.True(false,
                                string.Format("Expected diagnostic to start at column \"{0}\" was actually at column \"{1}\"\r\n\r\nDiagnostic:\r\n    {2}\r\n",
                                              expected.Span.StartLinePosition.Character, actualLinePosition.Character + 1, FormatDiagnostics(analyzer, diagnostic)));
                }
            }
        }
Example #15
0
        private static XElement SerializeDiagnostic(Diagnostic diagnostic, IFormatProvider formatProvider)
        {
            XElement filePathElement = null;
            XElement locationElement = null;

            FileLinePositionSpan span = diagnostic.Location.GetMappedLineSpan();

            if (span.IsValid)
            {
                filePathElement = new XElement("FilePath", span.Path);

                LinePosition linePosition = span.Span.Start;

                locationElement = new XElement("Location",
                                               new XAttribute("Line", linePosition.Line + 1),
                                               new XAttribute("Character", linePosition.Character + 1));
            }

            return(new XElement(
                       "Diagnostic",
                       new XAttribute("Id", diagnostic.Id),
                       new XElement("Severity", diagnostic.Severity),
                       new XElement("Message", diagnostic.GetMessage(formatProvider)),
                       filePathElement,
                       locationElement));
        }
Example #16
0
 public MethodContext(MethodInfo method, MetaContext context, FileLinePositionSpan methodSpan, string fileName)
 {
     Context    = context;
     Method     = method;
     MethodSpan = methodSpan;
     FileName   = fileName;
 }
        internal void AddMessage(string text, SyntaxNode node, TranslationMessageType type = TranslationMessageType.Error)
        {
            Location             loc  = node.GetLocation();
            FileLinePositionSpan span = loc.GetLineSpan();

            AddMessage(text, span.StartLinePosition.Line, span.StartLinePosition.Character, type);
        }
        public SyntaxNodeOrTokenListItem(SyntaxNodeOrToken syntaxNodeOrToken)
        {
            _lineSpan = syntaxNodeOrToken.GetLocation().GetLineSpan();

            Content = $"{_lineSpan}: {syntaxNodeOrToken.Kind()} {Truncate(syntaxNodeOrToken.ToString())}";
            ToolTip = syntaxNodeOrToken.ToString();
        }
Example #19
0
        protected static bool HasNoBlankLinesAfter(FileLinePositionSpan callLineSpan, StatementSyntax other)
        {
            var otherLineSpan = other.GetLocation().GetLineSpan();

            var differenceAfter = otherLineSpan.StartLinePosition.Line - callLineSpan.EndLinePosition.Line;

            return(differenceAfter == 1);
        }
        public async Task ShouldCreateDiagnosticWithCorrectLocation()
        {
            var diagnostics = await SetupAndGetDiagnosticsAsync();

            var expectedSpan = new FileLinePositionSpan("Class1.cs", new LinePosition(5, 10), new LinePosition(5, 15));

            diagnostics.Should().Contain(d => d.Location.GetLineSpan().Equals(expectedSpan));
        }
Example #21
0
        public static void RegisterRefactoring(RefactoringContext context, MemberDeclarationSyntax member)
        {
            FileLinePositionSpan fileSpan = GetFileLinePositionSpan(member, context.CancellationToken);

            context.RegisterRefactoring(
                $"Comment out {member.GetTitle()}",
                cancellationToken => RefactorAsync(context.Document, fileSpan.StartLine(), fileSpan.EndLine(), cancellationToken));
        }
Example #22
0
        public static void RegisterRefactoring(RefactoringContext context, LocalFunctionStatementSyntax localFunctionStatement)
        {
            FileLinePositionSpan fileSpan = GetFileLinePositionSpan(localFunctionStatement, context.CancellationToken);

            context.RegisterRefactoring(
                $"Comment out {localFunctionStatement.GetTitle()}",
                cancellationToken => RefactorAsync(context.Document, fileSpan.StartLine(), fileSpan.EndLine(), cancellationToken));
        }
Example #23
0
 internal /* for testing */ static TextRange GetTextRange(FileLinePositionSpan lineSpan) =>
 new TextRange
 {
     StartLine   = lineSpan.StartLinePosition.GetLineNumberToReport(),
     EndLine     = lineSpan.EndLinePosition.GetLineNumberToReport(),
     StartOffset = lineSpan.StartLinePosition.Character,
     EndOffset   = lineSpan.EndLinePosition.Character
 };
Example #24
0
        public static void RegisterRefactoring(RefactoringContext context, StatementSyntax statement)
        {
            FileLinePositionSpan fileSpan = statement.SyntaxTree.GetLineSpan(statement.Span, context.CancellationToken);

            context.RegisterRefactoring(
                "Comment out statement",
                ct => RefactorAsync(context.Document, fileSpan.StartLine(), fileSpan.EndLine(), ct));
        }
 private static string GetNotInExpectedFileMessage(
     DiagnosticAnalyzer analyzer,
     Diagnostic diagnostic,
     DiagnosticResultLocation expected,
     FileLinePositionSpan actualSpan)
 {
     return($"Expected diagnostic to be in file \"{expected.Path}\" was actually in file \"{actualSpan.Path}\"{Environment.NewLine}{Environment.NewLine}Diagnostic:{Environment.NewLine}    {FormatDiagnostics(analyzer, new[] { diagnostic })}{Environment.NewLine}");
 }
Example #26
0
        private static string CreateErrorMessage(SyntaxNode node, string message)
        {
            FileLinePositionSpan span = node.SyntaxTree.GetLineSpan(node.Span);
            int lineNumber            = span.StartLinePosition.Line;
            int characterNumber       = span.StartLinePosition.Character;

            return($"({lineNumber}, {characterNumber}): {message}");
        }
        public static void ComputeRefactoring(RefactoringContext context, MemberDeclarationSyntax member)
        {
            MemberDeclarationListInfo info = SyntaxInfo.MemberDeclarationListInfo(member.Parent);

            if (!info.Success)
            {
                return;
            }

            SyntaxList <MemberDeclarationSyntax> members = info.Members;

            if (members.Count <= 1)
            {
                return;
            }

            int index = IndexOfMemberToSwap(member, members, context.Span);

            if (index == -1)
            {
                return;
            }

            SyntaxTree tree = member.SyntaxTree;

            FileLinePositionSpan fileLinePositionSpan = tree.GetLineSpan(context.Span, context.CancellationToken);

            int startLine = fileLinePositionSpan.StartLine();
            int endLine   = fileLinePositionSpan.EndLine();

            if (startLine <= tree.GetEndLine(members[index].TrimmedSpan(), context.CancellationToken))
            {
                return;
            }

            if (endLine >= tree.GetStartLine(members[index + 1].TrimmedSpan(), context.CancellationToken))
            {
                return;
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.RemoveMemberDeclarations))
            {
                context.RegisterRefactoring(
                    "Remove members above",
                    ct => ReplaceMembersAsync(context.Document, info, members.Skip(index + 1), ct));

                context.RegisterRefactoring(
                    "Remove members below",
                    ct => ReplaceMembersAsync(context.Document, info, members.Take(index + 1), ct));
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.SwapMemberDeclarations))
            {
                context.RegisterRefactoring(
                    "Swap members",
                    ct => SwapMembersAsync(context.Document, info, index, ct));
            }
        }
Example #28
0
        public List <Metodo> Construya(SyntaxList <MemberDeclarationSyntax> losNodos, string elIdSolucion)
        {
            List <MethodDeclarationSyntax> losMetodosDeclarados = new List <MethodDeclarationSyntax>();
            List <Metodo> losMetodosConvertidos = new List <Metodo>();

            if (losNodos != null && losNodos.Count != 0)
            {
                Convertidor elConvertidor = new Convertidor();
                losMetodosDeclarados = elConvertidor.Convierta(losNodos, elIdSolucion);
                foreach (MethodDeclarationSyntax elMetodo in losMetodosDeclarados)
                {
                    try
                    {
                        Metodo elMetodoConvertido = new Metodo();
                        elMetodoConvertido.NombreMetodo = elMetodo.Identifier.Text;
                        elMetodoConvertido.Retorno      = elMetodo.ReturnType.ToString();

                        FileLinePositionSpan lineSpan = elMetodo.SyntaxTree.GetLineSpan(elMetodo.Span);
                        elMetodoConvertido.LineaComienzo = lineSpan.StartLinePosition.Line;
                        elMetodoConvertido.LineaFinal    = lineSpan.EndLinePosition.Line;

                        string elModificador;
                        if (elMetodo.Modifiers.Count == 0)
                        {
                            elModificador = "";
                        }
                        else
                        {
                            elModificador = elMetodo.Modifiers.First().ToString();
                        }

                        elMetodoConvertido.Visibilidad = elModificador;
                        Parametros.Constructor elConstructorDeParametros = new Parametros.Constructor();
                        elMetodoConvertido.Parametros = elConstructorDeParametros.Construya(elMetodo.ParameterList.Parameters, elIdSolucion).ToArray();

                        Controles.Constructor elConstructorDeControles = new Controles.Constructor();
                        if (elMetodo.Body != null)
                        {
                            elMetodoConvertido.Controles = elConstructorDeControles.Construya(elMetodo.Body.Statements, elIdSolucion).ToArray();
                        }
                        else
                        {
                            elMetodoConvertido.Controles = new List <Control>().ToArray();
                        }

                        losMetodosConvertidos.Add(elMetodoConvertido);
                    }
                    catch (Exception laExcepcion)
                    {
                        Bitacoras.Registrador elRegistrador = new Bitacoras.Registrador();
                        elRegistrador.Registre(laExcepcion, elIdSolucion, BC.Componentes.AnalizadorCodigoFuente);
                    }
                }
            }


            return(losMetodosConvertidos);
        }
 public ExternalFilePeekableItem(
     FileLinePositionSpan span,
     IPeekRelationship relationship,
     IPeekResultFactory peekResultFactory)
     : base(peekResultFactory)
 {
     _span = span;
     _relationship = relationship;
 }
Example #30
0
        private static void VerifyFileLinePositionSpan(
            FileLinePositionSpan actual,
            FileLinePositionSpan expected)
        {
            actual.Path.Should().Be(expected.Path);
            VerifyLinePosition(actual.StartLinePosition, expected.StartLinePosition, "start");

            VerifyLinePosition(actual.EndLinePosition, expected.EndLinePosition, "end");
        }
Example #31
0
        private static Diff CreateDiff(FileLinePositionSpan fileLinePositionSpan, string text)
        {
            var start = new Position(fileLinePositionSpan.StartLinePosition.Line + 1,
                                     fileLinePositionSpan.StartLinePosition.Character);
            var end = new Position(fileLinePositionSpan.EndLinePosition.Line + 1,
                                   fileLinePositionSpan.EndLinePosition.Character);

            return(new Diff(text, new Gauge.Dotnet.Models.Range(start, end)));
        }
Example #32
0
 public ExternalFilePeekableItem(
     FileLinePositionSpan span,
     IPeekRelationship relationship,
     IPeekResultFactory peekResultFactory)
     : base(peekResultFactory)
 {
     _span         = span;
     _relationship = relationship;
 }
        public static void RegisterRefactoring(RefactoringContext context, LocalFunctionStatementSyntax localFunctionStatement)
        {
            FileLinePositionSpan fileSpan = GetFileLinePositionSpan(localFunctionStatement, context.CancellationToken);

            context.RegisterRefactoring(
                $"Comment out {CSharpFacts.GetTitle(localFunctionStatement)}",
                ct => RefactorAsync(context.Document, fileSpan.StartLine(), fileSpan.EndLine(), ct),
                RefactoringDescriptors.CommentOutMemberDeclaration);
        }
Example #34
0
 /// <summary>
 /// Generates dead checking if statement with injected body block
 /// </summary>
 /// <param name="body"></param>
 /// <param name="resumeLocation"></param>
 /// <returns></returns>
 StatementSyntax DeadCheckIfStatement(StatementSyntax body, FileLinePositionSpan resumeLocation)
 {
     return(SyntaxFactory.IfStatement(
                SyntaxFactory.PrefixUnaryExpression(
                    SyntaxKind.LogicalNotExpression,
                    IsDeadCall()),
                InjectedBlock(body, resumeLocation)
                ));
 }
Example #35
0
        internal AnalysisResult(ISharpenSuggestion suggestion, SingleSyntaxTreeAnalysisContext analysisContext, string filePath, SyntaxToken startingToken, SyntaxNode displayTextNode)
        {
            this.displayTextNode = displayTextNode;

            Suggestion      = suggestion;
            AnalysisContext = analysisContext;
            FilePath        = filePath;
            Position        = startingToken.GetLocation().GetLineSpan();
        }
Example #36
0
 /// <summary>
 /// Gets a document location from a line span.
 /// </summary>
 /// <param name="span">The line span.</param>
 /// <returns>A new document location.</returns>
 internal static DocumentLocation FromSpan(FileLinePositionSpan span)
 {
     return new DocumentLocation
     {
         LineStart = span.StartLinePosition.Line + 1,
         ColumnStart = span.StartLinePosition.Character + 1,
         LineEnd = span.EndLinePosition.Line + 1,
         ColumnEnd = span.EndLinePosition.Character + 1
     };
 }
        public void SaneHashCode()
        {
            var hash1 = new FileLinePositionSpan("C:\\foo.cs", new LinePosition(1, 2), new LinePosition(3, 5)).GetHashCode();
            var hash2 = new FileLinePositionSpan("C:\\foo1.cs", new LinePosition(1, 2), new LinePosition(3, 5)).GetHashCode();
            var hash3 = new FileLinePositionSpan("C:\\foo.cs", new LinePosition(1, 3), new LinePosition(3, 5)).GetHashCode();
            var hash4 = new FileLinePositionSpan("C:\\foo.cs", new LinePosition(1, 1), new LinePosition(6, 5)).GetHashCode();

            Assert.NotEqual(hash1, hash2);
            Assert.NotEqual(hash1, hash3);
            Assert.NotEqual(hash1, hash4);
            Assert.NotEqual(hash2, hash3);
            Assert.NotEqual(hash2, hash4);
            Assert.NotEqual(hash3, hash4);
        }
        private static void Analyze(
            SyntaxNodeAnalysisContext context,
            FileLinePositionSpan declarationLineSpan,
            SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses)
        {
            int currentLine = declarationLineSpan.StartLinePosition.Line;
            foreach (var constraint in constraintClauses)
            {
                int constraintLine = constraint.GetLineSpan().StartLinePosition.Line;
                if (currentLine == constraintLine)
                {
                    context.ReportDiagnostic(Diagnostic.Create(Descriptor, constraint.GetLocation()));
                }

                currentLine = constraintLine;
            }
        }
Example #39
0
        /// <summary>
        /// Initializes a new instance of <see cref="RoslynCompilationMessage"/>.
        /// </summary>
        /// <param name="diagnostic">The <see cref="Diagnostic"/> instance to read
        /// diagnostic details from.</param>
        public RoslynCompilationMessage(Diagnostic diagnostic)
        {
            _diagnostic = diagnostic;
            _mappedLineSpan = _diagnostic.Location.GetMappedLineSpan();

            switch (_diagnostic.Severity)
            {
                case DiagnosticSeverity.Error:
                    Severity = CompilationMessageSeverity.Error;
                    break;
                case DiagnosticSeverity.Warning:
                    Severity = CompilationMessageSeverity.Warning;
                    break;
                default:
                    Severity = CompilationMessageSeverity.Info;
                    break;
            }
        }
Example #40
0
 internal void InspectWithFavoriteCodeEditor(string folder, FileLinePositionSpan? span = null)
 {
     if (span != null)
     {
         FileLinePositionSpan s = (FileLinePositionSpan)span;
         // when working locally on windows we can pop up vs code to see if the code failure.
         if (!StartVsCode(
             folder,
             "-g",
             $"{Path.Combine(folder, s.Path)}:{s.StartLinePosition.Line + 1}:{s.StartLinePosition.Character + 1}"))
         {
             // todo: add code here to try another editor?
         }
     }
     else
     {
         StartVsCode(folder);
     }
 }
        public static void SelectSpanInCodeWindow(FileLinePositionSpan span)
        {
            // If the path is not available we cannot jump to it
            if (string.IsNullOrEmpty(span.Path)) return;

            // Check if the document is opened, if not open it.
            IVsUIHierarchy hierarchy;
            uint itemId;
            IVsWindowFrame windowFrame;
            if (!VsShellUtilities.IsDocumentOpen(ServiceProvider.GlobalProvider, span.Path, VSConstants.LOGVIEWID_Any, out hierarchy, out itemId, out windowFrame))
            {
                VsShellUtilities.OpenDocument(ServiceProvider.GlobalProvider, span.Path, VSConstants.LOGVIEWID_Primary, out hierarchy, out itemId, out windowFrame);
            }

            var window = VsShellUtilities.GetWindowObject(windowFrame);
            window.SetFocus();

            var textView = VsShellUtilities.GetTextView(windowFrame);
            textView.SetSelection(span.StartLinePosition.Line, span.StartLinePosition.Character, span.EndLinePosition.Line, span.EndLinePosition.Character);
        }
        public void Ctor1()
        {
            Assert.Throws(
                typeof(ArgumentNullException),
                () =>
            {
                var notUsed = new FileLinePositionSpan(null, new LinePosition(1, 2), new LinePosition(3, 5));
            });

            Assert.Throws(
                typeof(ArgumentException),
                () =>
            {
                var notUsed = new FileLinePositionSpan("C:\\foo.cs", new LinePosition(3, 2), new LinePosition(2, 4));
            });

            Assert.Throws(
                typeof(ArgumentException),
                () =>
            {
                var notUsed = new FileLinePositionSpan("C:\\foo.cs", new LinePosition(1, 2), new LinePosition(1, 1));
            });
        }
        private bool TryAdjustSpanIfNeededForVenus(
            DocumentId documentId, FileLinePositionSpan originalLineInfo, FileLinePositionSpan mappedLineInfo, out LinePositionSpan originalSpan, out LinePositionSpan mappedSpan)
        {
            var startChanged = true;
            MappedSpan startLineColumn;
            if (!TryAdjustSpanIfNeededForVenus(_workspace, documentId, originalLineInfo.StartLinePosition.Line, originalLineInfo.StartLinePosition.Character, out startLineColumn))
            {
                startChanged = false;
                startLineColumn = new MappedSpan(originalLineInfo.StartLinePosition.Line, originalLineInfo.StartLinePosition.Character, mappedLineInfo.StartLinePosition.Line, mappedLineInfo.StartLinePosition.Character);
            }

            var endChanged = true;
            MappedSpan endLineColumn;
            if (!TryAdjustSpanIfNeededForVenus(_workspace, documentId, originalLineInfo.EndLinePosition.Line, originalLineInfo.EndLinePosition.Character, out endLineColumn))
            {
                endChanged = false;
                endLineColumn = new MappedSpan(originalLineInfo.EndLinePosition.Line, originalLineInfo.EndLinePosition.Character, mappedLineInfo.EndLinePosition.Line, mappedLineInfo.EndLinePosition.Character);
            }

            originalSpan = new LinePositionSpan(startLineColumn.OriginalLinePosition, Max(startLineColumn.OriginalLinePosition, endLineColumn.OriginalLinePosition));
            mappedSpan = new LinePositionSpan(startLineColumn.MappedLinePosition, Max(startLineColumn.MappedLinePosition, endLineColumn.MappedLinePosition));
            return startChanged || endChanged;
        }
Example #44
0
 public CompleterError(SyntaxTree tree, Message message, FileLinePositionSpan span)
 {
     Tree = tree;
     Span = span;
     Message = message;
 }
Example #45
0
        internal WorkItemInfo? GetUpdatedWorkItemInfo(string filePath, FileLinePositionSpan loc, int id, string description)
        {
            if (StringComparer.OrdinalIgnoreCase.Equals("devdiv", description))
            {
                if (_workItemData.IsDevDivTfsBug(id))
                {
                    return new WorkItemInfo(id, string.Format(UrlDevDiv, id));
                }
            }

            if (string.IsNullOrEmpty(description))
            {
                if (_workItemData.IsDevDivTfsBug(id))
                {
                    return new WorkItemInfo(id, string.Format(UrlDevDiv, id));
                }

                if (_workItemData.IsGithubBug(id) && !_workItemData.IsRoslynBug(id))
                {
                    return new WorkItemInfo(id, string.Format(UrlGithub, id));
                }

                if (!_workItemData.IsGithubBug(id) && _workItemData.IsRoslynBug(id))
                {
                    return new WorkItemInfo(id, string.Format(UrlRoslyn, id));
                }

                if (id > 100000 && _workItemData.IsDevDivTfsBug(id, checkAreaPath: false))
                {
                    return new WorkItemInfo(id, string.Format(UrlDevDiv, id));
                }

                _unknownList.Add($"{filePath} line {loc.StartLinePosition.Line} id {id}");
            }

            if (RewriteUrl(id, ref description))
            {
                return new WorkItemInfo(id, description);
            }

            Uri uri;
            if (!Uri.TryCreate(description, UriKind.Absolute, out uri))
            {
                _unknownList.Add($"Bad Url {filePath} {loc.StartLinePosition.Line}");
            }

            return null;
        }
 private Value GetSpanInfoValue(FileLinePositionSpan lineSpan)
 {
     // Note that SARIF region lines and columns are specified to be 1-based, but FileLinePositionSpan.Line and Character are 0-based.
     var builder = ArrayBuilder<KeyValuePair<string, Value>>.GetInstance();
     builder.Add(CreateSimpleKeyValuePair(WellKnownStrings.LocationSpanStartLine, lineSpan.StartLinePosition.Line + 1));
     builder.Add(CreateSimpleKeyValuePair(WellKnownStrings.LocationSpanStartColumn, lineSpan.StartLinePosition.Character + 1));
     builder.Add(CreateSimpleKeyValuePair(WellKnownStrings.LocationSpanEndLine, lineSpan.EndLinePosition.Line + 1));
     builder.Add(CreateSimpleKeyValuePair(WellKnownStrings.LocationSpanEndColumn, lineSpan.EndLinePosition.Character + 1));
     return Value.Create(builder.ToImmutableAndFree(), this);
 }
        /// <summary>
        /// Helper method to <see cref="VerifyDiagnosticResults"/> that checks the location of a
        /// <see cref="Diagnostic"/> and compares it with the location described by a
        /// <see cref="FileLinePositionSpan"/>.
        /// </summary>
        /// <param name="analyzers">The analyzer that have been run on the sources.</param>
        /// <param name="diagnostic">The diagnostic that was found in the code.</param>
        /// <param name="actual">The location of the diagnostic found in the code.</param>
        /// <param name="expected">The <see cref="FileLinePositionSpan"/> describing the expected location of the
        /// diagnostic.</param>
        private static void VerifyDiagnosticLocation(ImmutableArray<DiagnosticAnalyzer> analyzers, Diagnostic diagnostic, Location actual, FileLinePositionSpan expected)
        {
            var actualSpan = actual.GetLineSpan();

            string message =
                string.Format(
                    "Expected diagnostic to be in file \"{0}\" was actually in file \"{1}\"\r\n\r\nDiagnostic:\r\n    {2}\r\n",
                    expected.Path,
                    actualSpan.Path,
                    FormatDiagnostics(analyzers, diagnostic));
            Assert.True(
                actualSpan.Path == expected.Path || (actualSpan.Path != null && actualSpan.Path.Contains("Test0.") && expected.Path.Contains("Test.")),
                message);

            var actualStartLinePosition = actualSpan.StartLinePosition;
            var actualEndLinePosition = actualSpan.EndLinePosition;

            VerifyLinePosition(analyzers, diagnostic, actualSpan.StartLinePosition, expected.StartLinePosition, "start");
            if (expected.StartLinePosition < expected.EndLinePosition)
            {
                VerifyLinePosition(analyzers, diagnostic, actualSpan.EndLinePosition, expected.EndLinePosition, "end");
            }
        }
Example #48
0
 private Value GetSpanInfoValue(FileLinePositionSpan lineSpan)
 {
     var builder = ArrayBuilder<KeyValuePair<string, Value>>.GetInstance();
     builder.Add(CreateSimpleKeyValuePair(WellKnownStrings.LocationSpanStartLine, lineSpan.StartLinePosition.Line));
     builder.Add(CreateSimpleKeyValuePair(WellKnownStrings.LocationSpanStartColumn, lineSpan.StartLinePosition.Character));
     builder.Add(CreateSimpleKeyValuePair(WellKnownStrings.LocationSpanEndLine, lineSpan.EndLinePosition.Line));
     builder.Add(CreateSimpleKeyValuePair(WellKnownStrings.LocationSpanEndColumn, lineSpan.EndLinePosition.Character));
     return Value.Create(builder.ToImmutableAndFree(), this);
 }
Example #49
0
        private Cci.DebugSourceDocument GetSourceDocument(SyntaxNode syntax, FileLinePositionSpan span)
        {
            string path = span.Path;
            // If the path for the syntax node is empty, try the path for the entire syntax tree.
            if (path.Length == 0)
            {
                path = syntax.SyntaxTree.FilePath;
            }

            return _debugDocumentProvider.Invoke(path, basePath: "");
        }
        private static void GetLocationInfo(Document document, Location location, out TextSpan sourceSpan, out FileLinePositionSpan originalLineInfo, out FileLinePositionSpan mappedLineInfo)
        {
            var diagnosticSpanMappingService = document.Project.Solution.Workspace.Services.GetService<IWorkspaceVenusSpanMappingService>();
            if (diagnosticSpanMappingService != null)
            {
                diagnosticSpanMappingService.GetAdjustedDiagnosticSpan(document.Id, location, out sourceSpan, out originalLineInfo, out mappedLineInfo);
                return;
            }

            sourceSpan = location.SourceSpan;
            originalLineInfo = location.GetLineSpan();
            mappedLineInfo = location.GetMappedLineSpan();
        }
        private DiagnosticResult AppendSpan(FileLinePositionSpan span)
        {
            FileLinePositionSpan[] newSpans;

            if (this.spans != null)
            {
                newSpans = new FileLinePositionSpan[this.spans.Length + 1];
                Array.Copy(this.spans, newSpans, this.spans.Length);
                newSpans[this.spans.Length] = span;
            }
            else
            {
                newSpans = new FileLinePositionSpan[1]
                {
                    span,
                };
            }

            // clone the object, so that the fluent syntax will work on immutable objects.
            return new DiagnosticResult
            {
                Id = this.Id,
                Message = this.message,
                MessageFormat = this.MessageFormat,
                MessageArguments = this.MessageArguments,
                Severity = this.Severity,
                Spans = newSpans,
            };
        }
Example #52
0
        private BoundStatement AddAnalysisPoint(SyntaxNode syntaxForSpan, FileLinePositionSpan span, SyntheticBoundNodeFactory statementFactory)
        {
            // Add an entry in the spans array.
            int spansIndex = _spansBuilder.Count;
            _spansBuilder.Add(new SourceSpan(GetSourceDocument(syntaxForSpan, span), span.StartLinePosition.Line, span.StartLinePosition.Character, span.EndLinePosition.Line, span.EndLinePosition.Character));

            // Generate "_payload[pointIndex] = true".
            BoundArrayAccess payloadCell = statementFactory.ArrayAccess(statementFactory.Local(_methodPayload), statementFactory.Literal(spansIndex));
            return statementFactory.Assignment(payloadCell, statementFactory.Literal(true));
        }