Beispiel #1
0
 private static bool IsReportableCSharpError(Diagnostic compilerError)
 {
     return(!compilerError.ToString()
            .Contains(value: "netstandard", comparisonType: StringComparison.Ordinal) && !compilerError.ToString()
            .Contains(value: "static 'Main' method", comparisonType: StringComparison.Ordinal) && !compilerError.ToString()
            .Contains(value: "CS1002",
                      comparisonType: StringComparison.Ordinal) && !compilerError
            .ToString()
            .Contains(value: "CS1702", comparisonType: StringComparison.Ordinal));
 }
Beispiel #2
0
        private static Assembly CompileToAssembly(WebPageRazorHost host, SyntaxTree syntaxTree)
        {
            var compilation = CSharpCompilation.Create(
                "RoslynRazor", // Note: using a fixed assembly name, which doesn't matter as long as we don't expect cross references of generated assemblies
                new[] { syntaxTree },
                BuildManager.GetReferencedAssemblies().OfType <Assembly>().Select(ResolveReference),
                new CSharpCompilationOptions(
                    outputKind: OutputKind.DynamicallyLinkedLibrary,
                    assemblyIdentityComparer: DesktopAssemblyIdentityComparer.Default,
                    optimizationLevel: host.DefaultDebugCompilation ? OptimizationLevel.Debug : OptimizationLevel.Release));

            using (var dllStream = new MemoryStream())
                using (var pdbStream = new MemoryStream())
                {
                    EmitResult emitResult = compilation.Emit(dllStream, pdbStream);

                    if (!emitResult.Success)
                    {
                        Diagnostic   diagnostic   = emitResult.Diagnostics.First(x => x.Severity == DiagnosticSeverity.Error);
                        string       message      = diagnostic.ToString();
                        LinePosition linePosition = diagnostic.Location.GetMappedLineSpan().StartLinePosition;

                        throw new HttpParseException(message, null, host.VirtualPath, null, linePosition.Line + 1);
                    }

                    return(Assembly.Load(dllStream.GetBuffer(), pdbStream.GetBuffer()));
                }
        }
Beispiel #3
0
        public static string GetMessageWithSource(this Diagnostic diagnostic, IOpenApiElementRegistry elementRegistry)
        {
            string?source = diagnostic.GetSource(elementRegistry);

            return(source == null
                ? diagnostic.ToString()
                : $"{source} {diagnostic}");
        }
Beispiel #4
0
 private void AddErrorsToStringBuilder(bool adderrorsonly, ref StringBuilder stringbuilder, Diagnostic diagnostic)
 {
     if (adderrorsonly == false ||
         diagnostic.Severity == DiagnosticSeverity.Error)
     {
         stringbuilder.AppendLine(diagnostic.ToString());
     }
 }
Beispiel #5
0
        /// <summary>
        /// Adds compiler error or warning message with a link that opens the C# file and goes to that position.
        /// </summary>
        /// <param name="d">Error or warning.</param>
        /// <param name="fMain">Main file of the compilation. Used only for failures that are not C# errors, eg when fails to open a metadata reference file.</param>
        /// <remarks>
        /// This and other AddX functions add line like "[C:\path\file.cs(line,column)]: message" or "[C:\path\file.cs]: message".
        /// Then our print.Server.SetNotifications callback will convert the "[...]" part to a link.
        /// </remarks>
        public void AddErrorOrWarning(Diagnostic d, FileNode fMain)
        {
            _StartAdd(isWarning: d.Severity != DiagnosticSeverity.Error);
            var s = d.ToString();
            int i = d.Location.IsInSource ? s.Find("): ") + 1 : 0;

            if (i > 0)
            {
                _b.AppendFormat("[{0}]{1}", s[..i], s[i..]);
Beispiel #6
0
        /// <summary>
        ///   Appends <paramref name="diagnostic" /> to the <paramref name="builder" />.
        /// </summary>
        /// <param name="builder">The builder the diagnostic should be appended to.</param>
        /// <param name="diagnostic">The diagnostic that should be appended.</param>
        public static void Write(StringBuilder builder, Diagnostic diagnostic)
        {
            var lineSpan = diagnostic.Location.GetLineSpan();
            var message  = diagnostic.ToString();

            message = message.Substring(message.IndexOf(":", StringComparison.InvariantCulture) + 1);

            builder.AppendFormat("({1}-{2}) {0}\n\n", message, lineSpan.StartLinePosition, lineSpan.EndLinePosition);
        }
        private static Assembly CompileToAssembly(WebPageRazorHost host, SyntaxTree syntaxTree, ICollection <ICompileModule> compilationModules)
        {
            var strArgs = new List <string>();

            strArgs.Add("/target:library");
            strArgs.Add(host.DefaultDebugCompilation ? "/o-" : "/o+");
            strArgs.Add(host.DefaultDebugCompilation ? "/debug+" : "/debug-");

            var cscArgs = CSharpCommandLineParser.Default.Parse(strArgs, null, null);

            var compilation = CSharpCompilation.Create(
                "RoslynRazor", // Note: using a fixed assembly name, which doesn't matter as long as we don't expect cross references of generated assemblies
                new[] { syntaxTree },
                BuildManager.GetReferencedAssemblies().OfType <Assembly>().Select(ResolveReference),
                cscArgs.CompilationOptions.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default));

            compilation = Hacks.MakeValueTuplesWorkWhenRunningOn47RuntimeAndTargetingNet45Plus(compilation);
            var diagnostics = new List <Diagnostic>();
            var context     = new CompileContext(compilationModules);

            context.Before(new BeforeCompileContext
            {
                Arguments   = cscArgs,
                Compilation = compilation,
                Diagnostics = diagnostics,
            });
            compilation = context.BeforeCompileContext.Compilation;

            using (var dllStream = new MemoryStream())
                using (var pdbStream = new MemoryStream())
                {
                    EmitResult emitResult = compilation.Emit(dllStream, pdbStream);
                    diagnostics.AddRange(emitResult.Diagnostics);

                    if (!emitResult.Success)
                    {
                        Diagnostic   diagnostic   = diagnostics.First(x => x.Severity == DiagnosticSeverity.Error);
                        string       message      = diagnostic.ToString();
                        LinePosition linePosition = diagnostic.Location.GetMappedLineSpan().StartLinePosition;

                        throw new HttpParseException(message, null, host.VirtualPath, null, linePosition.Line + 1);
                    }

                    context.After(new AfterCompileContext
                    {
                        Arguments      = context.BeforeCompileContext.Arguments,
                        AssemblyStream = dllStream,
                        Compilation    = compilation,
                        Diagnostics    = diagnostics,
                        SymbolStream   = pdbStream,
                        XmlDocStream   = null,
                    });

                    return(Assembly.Load(dllStream.GetBuffer(), pdbStream.GetBuffer()));
                }
        }
Beispiel #8
0
        private FormatError ConvertError(Diagnostic diagnostic)
        {
            var lineSpan = diagnostic.Location.SourceTree.GetLineSpan(
                diagnostic.Location.SourceSpan
                );

            return(new FormatError {
                LineSpan = lineSpan, Description = diagnostic.ToString(),
            });
        }
Beispiel #9
0
 public TypeScriptTask(
     FileName fileName,
     Diagnostic diagnostic,
     int column,
     int line)
     : base(
         fileName,
         diagnostic.ToString(),
         column,
         line,
         GetTaskType(diagnostic.category))
 {
 }
Beispiel #10
0
 private static void WriteErrorLine(string path, Diagnostic diagnostic)
 {
     Console.WriteLine(
         "{0}({1},{2},{3},{4}): {5} {6}: {7}",
         path,
         diagnostic.Location.GetLineSpan().StartLinePosition.Line + 1,
         diagnostic.Location.GetLineSpan().StartLinePosition.Character,
         diagnostic.Location.GetLineSpan().EndLinePosition.Line + 1,
         diagnostic.Location.GetLineSpan().EndLinePosition.Character,
         diagnostic.Severity,
         diagnostic.Id,
         diagnostic.ToString());
 }
Beispiel #11
0
        public static void Create()
        {
            var span       = new TextSpan(3, 4);
            var message    = "diagnostic";
            var location   = new TextLocation(SourceText.From("1"), span);
            var diagnostic = new Diagnostic(location, message);

            Assert.Multiple(() =>
            {
                Assert.That(diagnostic.Location, Is.EqualTo(location), nameof(diagnostic.Location));
                Assert.That(diagnostic.Message, Is.EqualTo(message), nameof(diagnostic.Message));
                Assert.That(diagnostic.ToString(), Is.EqualTo(message), nameof(diagnostic.ToString));
            });
        }
Beispiel #12
0
        /// <summary>
        /// Adds compiler error or warning message with a link that opens the C# file and goes to that position.
        /// </summary>
        /// <param name="d">Error or warning.</param>
        /// <param name="fMain">Main file of the compilation. Used only for failures that are not C# errors, eg when fails to open a metadata reference file.</param>
        /// <remarks>
        /// This and other AddX functions add line like "[C:\path\file.cs(line,column)]: message" or "[C:\path\file.cs]: message".
        /// Then our AOutputServer.SetNotifications callback will convert the "[...]" part to a link.
        /// </remarks>
        public void AddErrorOrWarning(Diagnostic d, FileNode fMain)
        {
            _StartAdd(isWarning: d.Severity != DiagnosticSeverity.Error);
            var s = d.ToString();
            int i = d.Location.IsInSource ? s.Find("): ") + 1 : 0;

            if (i > 0)
            {
                _b.AppendFormat("[{0}]{1}", s.Remove(i), s.Substring(i));
            }
            else
            {
                _b.AppendFormat("[{0}]: {1}", fMain.FilePath, s);
            }
        }
Beispiel #13
0
        public void PrintDiagnostic(Diagnostic item)
        {
            switch (item.Severity)
            {
            case DiagnosticSeverity.Hidden: return;

            case DiagnosticSeverity.Error:
                Console.ForegroundColor = ConsoleColor.Red;
                break;

            case DiagnosticSeverity.Warning:
                Console.ForegroundColor = ConsoleColor.Yellow;
                break;
            }
            PrintLine(item.ToString());
            Console.ResetColor();
        }
Beispiel #14
0
        /// <summary>
        /// What we need to do is find a *repeatable* arbitrary way to choose between
        /// two errors; we can for example simply take the one that is lower in alphabetical
        /// order when converted to a string.  As an optimization, we compare error codes
        /// first and skip string comparison if they differ.
        /// </summary>
        private static int CanonicallyCompareDiagnostics(Diagnostic x, Diagnostic y)
        {
            ErrorCode xCode = (ErrorCode)x.Code;
            ErrorCode yCode = (ErrorCode)y.Code;

            int codeCompare = xCode.CompareTo(yCode);

            // ToString fails for a diagnostic with an error code that does not prevernt successful delegate conversion.
            // Also, the order doesn't matter, since all such diagnostics will be dropped.
            if (!ErrorFacts.PreventsSuccessfulDelegateConversion(xCode) || !ErrorFacts.PreventsSuccessfulDelegateConversion(yCode))
            {
                return(codeCompare);
            }

            // Optimization: don't bother
            return(codeCompare == 0 ? string.CompareOrdinal(x.ToString(), y.ToString()) : codeCompare);
        }
Beispiel #15
0
        private static string FormatDiagnostic(Diagnostic diagnostic)
        {
            var builder = new StringBuilder();

            builder.AppendLine(diagnostic.ToString());

            var location = diagnostic.Location;

            if (location == Location.None)
            {
                builder.Append($"Location unknown: ({diagnostic.Id})");
            }
            else
            {
                True(location.IsInSource,
                     $"Test base does not currently handle diagnostics in metadata locations. Diagnostic in metadata: {diagnostic}");

                var linePosition = location.GetLineSpan().StartLinePosition;
                builder.Append($"({(linePosition.Line + 1)}, {(linePosition.Character + 1)}, {diagnostic.Id})");
            }

            return(builder.ToString());
        }
Beispiel #16
0
        public static string GetAssertText(DiagnosticDescription[] expected, IEnumerable <Diagnostic> actual)
        {
            const int CSharp      = 1;
            const int VisualBasic = 2;
            var       language    = actual.Any() && actual.First().Id.StartsWith("CS", StringComparison.Ordinal) ? CSharp : VisualBasic;
            var       includeDiagnosticMessagesAsComments = (language == CSharp);
            int       indentDepth              = (language == CSharp) ? 4 : 1;
            var       includeDefaultSeverity   = expected.Any() && expected.All(d => d.DefaultSeverity != null);
            var       includeEffectiveSeverity = expected.Any() && expected.All(d => d.EffectiveSeverity != null);

            if (IsSortedOrEmpty(expected))
            {
                // If this is a new test (empty expectations) or a test that's already sorted,
                // we sort the actual diagnostics to minimize diff noise as diagnostics change.
                actual = Sort(actual);
            }

            var assertText = new StringBuilder();

            assertText.AppendLine();

            // write out the error baseline as method calls
            int i;

            assertText.AppendLine("Expected:");
            var expectedText = ArrayBuilder <string> .GetInstance();

            foreach (var d in expected)
            {
                expectedText.Add(GetDiagnosticDescription(d, indentDepth));
            }
            GetCommaSeparatedLines(assertText, expectedText);

            // write out the actual results as method calls (copy/paste this to update baseline)
            assertText.AppendLine("Actual:");
            var actualText = ArrayBuilder <string> .GetInstance();

            var e = actual.GetEnumerator();

            for (i = 0; e.MoveNext(); i++)
            {
                Diagnostic d       = e.Current;
                string     message = d.ToString();
                if (Regex.Match(message, @"{\d+}").Success)
                {
                    Assert.True(false, "Diagnostic messages should never contain unsubstituted placeholders.\n    " + message);
                }

                if (i > 0)
                {
                    assertText.AppendLine(",");
                }

                if (includeDiagnosticMessagesAsComments)
                {
                    Indent(assertText, indentDepth);
                    assertText.Append("// ");
                    assertText.AppendLine(d.ToString());
                    var l = d.Location;
                    if (l.IsInSource)
                    {
                        Indent(assertText, indentDepth);
                        assertText.Append("// ");
                        assertText.AppendLine(l.SourceTree.GetText().Lines.GetLineFromPosition(l.SourceSpan.Start).ToString());
                    }
                }

                var description     = new DiagnosticDescription(d, errorCodeOnly: false, includeDefaultSeverity, includeEffectiveSeverity);
                var diffDescription = description;
                var idx             = Array.IndexOf(expected, description);
                if (idx != -1)
                {
                    diffDescription = expected[idx];
                }
                assertText.Append(GetDiagnosticDescription(description, indentDepth));
                actualText.Add(GetDiagnosticDescription(diffDescription, indentDepth));
            }
            if (i > 0)
            {
                assertText.AppendLine();
            }

            assertText.AppendLine("Diff:");
            assertText.Append(DiffUtil.DiffReport(expectedText, actualText, separator: Environment.NewLine));

            actualText.Free();
            expectedText.Free();

            return(assertText.ToString());
        }
Beispiel #17
0
 public MissingPredefinedMember(Diagnostic error) : base(error.ToString())
 {
     this.Diagnostic = error;
 }
 private static void OnDiagnosticProgress(Diagnostic diagnostic)
 {
     Console.WriteLine(diagnostic.ToString());
 }
Beispiel #19
0
        /// <summary>
        /// What we need to do is find a *repeatable* arbitrary way to choose between
        /// two errors; we can for example simply take the one that is lower in alphabetical
        /// order when converted to a string.  As an optimization, we compare error codes
        /// first and skip string comparison if they differ.
        /// </summary>
        private static int CanonicallyCompareDiagnostics(Diagnostic x, Diagnostic y)
        {
            ErrorCode xCode = (ErrorCode)x.Code;
            ErrorCode yCode = (ErrorCode)y.Code;

            int codeCompare = xCode.CompareTo(yCode);

            // ToString fails for a diagnostic with an error code that does not prevent successful delegate conversion.
            // Also, the order doesn't matter, since all such diagnostics will be dropped.
            if (!ErrorFacts.PreventsSuccessfulDelegateConversion(xCode) || !ErrorFacts.PreventsSuccessfulDelegateConversion(yCode))
            {
                return codeCompare;
            }

            // Optimization: don't bother 
            return codeCompare == 0 ? string.CompareOrdinal(x.ToString(), y.ToString()) : codeCompare;
        }
 public DiagnosticItemViewModel(Diagnostic diagnostic)
 {
     Diagnostic = diagnostic;
     Content    = diagnostic.ToString();
 }
Beispiel #21
0
        protected override Type GetTemplateCodeTypeByCode(string Code)
        {
            var tree = SyntaxTree.ParseCompilationUnit(Code);

            var compilation = Compilation.Create(
                "calc.dll",
                options: new CompilationOptions(assemblyKind: AssemblyKind.DynamicallyLinkedLibrary),
                syntaxTrees: new[] { tree },
                references: new[] {
                new AssemblyFileReference(typeof(object).Assembly.Location),
                new AssemblyFileReference(System.Reflection.Assembly.GetAssembly(typeof(TemplateCodeGen)).Location)
            }
                );

            var Errors = String.Join("\n", compilation.GetDiagnostics().Select(Diagnostic => Diagnostic.ToString()));

            if (Errors.Length > 0)
            {
                throw (new Exception(Errors));
            }

            Assembly compiledAssembly;

            using (var stream = new MemoryStream())
            {
                EmitResult compileResult = compilation.Emit(stream);
                compiledAssembly = Assembly.Load(stream.GetBuffer());
            }

            return(compiledAssembly.GetType("CompiledTemplate_TempTemplate"));
        }
 public MissingPredefinedMember(Diagnostic error) : base(error.ToString())
 {
     this.Diagnostic = error;
 }
Beispiel #23
0
        /// <summary>
        /// Writes the diagnostic and the offending code.
        /// </summary>
        /// <returns>A string for use in assert exception</returns>
        internal static async Task <string> ToStringAsync(this Diagnostic diagnostic, Solution solution)
        {
            var sources = await Task.WhenAll(solution.Projects.SelectMany(p => p.Documents).Select(d => CodeReader.GetStringFromDocumentAsync(d, Formatter.Annotation, CancellationToken.None)));

            return(diagnostic.ToString(sources));
        }
 public SerializableDiagnostic(Diagnostic diagnostic)
 {
     _string  = diagnostic.ToString();
     Severity = diagnostic.Severity;
 }
Beispiel #25
0
 public DiagnosticListItem(Diagnostic diagnostic, TextBox codeTextBox)
 {
     _diagnostic  = diagnostic;
     _codeTextBox = codeTextBox;
     Content      = diagnostic.ToString();
 }
 public DiagnosticListItem(Diagnostic diagnostic, TextBox codeTextBox)
 {
     _diagnostic = diagnostic;
     _codeTextBox = codeTextBox;
     Content = diagnostic.ToString();
 }
Beispiel #27
0
		/// <summary>
		///   Appends <paramref name="diagnostic" /> to the <paramref name="builder" />.
		/// </summary>
		/// <param name="builder">The builder the diagnostic should be appended to.</param>
		/// <param name="diagnostic">The diagnostic that should be appended.</param>
		public static void Write(StringBuilder builder, Diagnostic diagnostic)
		{
			var lineSpan = diagnostic.Location.GetLineSpan();
			var message = diagnostic.ToString();
			message = message.Substring(message.IndexOf(":", StringComparison.InvariantCulture) + 1);

			builder.AppendFormat("({1}-{2}) {0}\n\n", message, lineSpan.StartLinePosition, lineSpan.EndLinePosition);
		}
        public static string GetAssertText(DiagnosticDescription[] expected, IEnumerable <Diagnostic> actual)
        {
            var includeCompilerOutput = false;
            var includeDiagnosticMessagesAsComments = false;

            const int CSharp      = 1;
            const int VisualBasic = 2;
            int       language    = actual.Any() && actual.First().Id.StartsWith("CS", StringComparison.Ordinal) ? CSharp : VisualBasic;

            if (language == CSharp)
            {
                includeDiagnosticMessagesAsComments = true;
            }

            StringBuilder assertText = new StringBuilder();

            assertText.AppendLine();

            // Write out the 'command line compiler output' including squiggles (easy to read debugging info in the case of a failure).
            // This will be useful for VB, because we can't do the inline comments.
            if (includeCompilerOutput)
            {
                assertText.AppendLine("Compiler output:");
                foreach (Diagnostic d in actual)
                {
                    Indent(assertText, 1);
                    assertText.AppendLine(d.ToString());
                    Location location = d.Location;
                    string   lineText = location.SourceTree.GetText().Lines.GetLineFromPosition(location.SourceSpan.Start).ToString();
                    assertText.AppendLine(lineText);
                    FileLinePositionSpan span          = location.GetMappedLineSpan();
                    LinePosition         startPosition = span.StartLinePosition;
                    LinePosition         endPosition   = span.EndLinePosition;
                    assertText.Append(' ', startPosition.Character);
                    int endCharacter = (startPosition.Line == endPosition.Line) ? endPosition.Character : lineText.Length;
                    assertText.Append('~', endCharacter - startPosition.Character);
                    assertText.AppendLine();
                }
            }

            // write out the error baseline as method calls
            int i;

            assertText.AppendLine("Expected:");
            var expectedText = new StringBuilder();

            for (i = 0; i < expected.Length; i++)
            {
                DiagnosticDescription d = expected[i];

                AppendDiagnosticDescription(expectedText, d);

                if (i < expected.Length - 1)
                {
                    expectedText.Append(",");
                }

                expectedText.AppendLine();
            }
            assertText.Append(expectedText);

            // write out the actual results as method calls (copy/paste this to update baseline)
            assertText.AppendLine("Actual:");
            var actualText             = new StringBuilder();
            IEnumerator <Diagnostic> e = actual.GetEnumerator();

            for (i = 0; e.MoveNext(); i++)
            {
                Diagnostic d       = e.Current;
                string     message = d.ToString();
                if (Regex.Match(message, @"{\d+}").Success)
                {
                    Assert.True(false, "Diagnostic messages should never contain unsubstituted placeholders.\n    " + message);
                }

                if (i > 0)
                {
                    assertText.AppendLine(",");
                    actualText.AppendLine(",");
                }

                if (includeDiagnosticMessagesAsComments)
                {
                    Indent(assertText, 1);
                    assertText.Append("// ");
                    assertText.AppendLine(d.ToString());
                    Location l = d.Location;
                    if (l.IsInSource)
                    {
                        Indent(assertText, 1);
                        assertText.Append("// ");
                        assertText.AppendLine(l.SourceTree.GetText().Lines.GetLineFromPosition(l.SourceSpan.Start).ToString());
                    }
                }

                var description = new DiagnosticDescription(d, errorCodeOnly: false, showPosition: true);
                AppendDiagnosticDescription(assertText, description);
                AppendDiagnosticDescription(actualText, description);
            }
            if (i > 0)
            {
                assertText.AppendLine();
                actualText.AppendLine();
            }

            assertText.AppendLine("Diff:");
            assertText.Append(DiffUtil.DiffReport(expectedText.ToString(), actualText.ToString()));

            return(assertText.ToString());
        }
Beispiel #29
0
        private static string SkipDirectory(Diagnostic diagnostic)
        {
            var text = diagnostic.ToString();

            return(text.Substring(text.LastIndexOf('\\') + 1));
        }
Beispiel #30
0
 public override string ToString()
 {
     return(_Diagnostic.ToString());
 }