internal string GetErrorMessageAndMissingAssemblyIdentities(DiagnosticBag diagnostics, DiagnosticFormatter formatter, CultureInfo preferredUICulture, AssemblyIdentity linqLibrary, out bool useReferencedModulesOnly, out ImmutableArray<AssemblyIdentity> missingAssemblyIdentities)
        {
            var errors = diagnostics.AsEnumerable().Where(d => d.Severity == DiagnosticSeverity.Error);
            foreach (var error in errors)
            {
                missingAssemblyIdentities = this.GetMissingAssemblyIdentities(error, linqLibrary);
                if (!missingAssemblyIdentities.IsDefault)
                {
                    break;
                }
            }

            if (missingAssemblyIdentities.IsDefault)
            {
                missingAssemblyIdentities = ImmutableArray<AssemblyIdentity>.Empty;
            }

            useReferencedModulesOnly = errors.All(HasDuplicateTypesOrAssemblies);

            var firstError = errors.FirstOrDefault();
            Debug.Assert(firstError != null);

            var simpleMessage = firstError as SimpleMessageDiagnostic;
            return (simpleMessage != null) ?
                simpleMessage.GetMessage() :
                formatter.Format(firstError, preferredUICulture ?? CultureInfo.CurrentUICulture);
        }
Beispiel #2
0
        private void CompilationError(DiagnosticBag diagnostics)
        {
            var resolvedLocalDiagnostics = diagnostics.AsEnumerable();
            var firstError = resolvedLocalDiagnostics.FirstOrDefault(d => d.Severity == DiagnosticSeverity.Error);

            if (firstError != null)
            {
                throw new CompilationErrorException(FormatDiagnostic(firstError, CultureInfo.CurrentCulture),
                                                    (resolvedLocalDiagnostics.AsImmutable()));
            }
        }
        public static IEnumerable <Diagnostic> BindAndAnalyze(PhpCompilation compilation, CancellationToken cancellationToken)
        {
            var manager = compilation.GetBoundReferenceManager();   // ensure the references are resolved! (binds ReferenceManager)

            var diagnostics = new DiagnosticBag();
            var compiler    = new SourceCompiler(compilation, null, true, diagnostics, cancellationToken);

            using (compilation.StartMetric("bind"))
            {
                // 1. Bind Syntax & Symbols to Operations (CFG)
                //   a. construct CFG, bind AST to Operation
                //   b. declare table of local variables
                compiler.WalkMethods(compiler.EnqueueRoutine, allowParallel: true);
                compiler.WalkTypes(compiler.EnqueueFieldsInitializer, allowParallel: true);
            }

            // Repeat analysis and transformation until either the limit is met or there are no more changes
            int transformation = 0;

            do
            {
                // 2. Analyze Operations
                //   a. type analysis (converge type - mask), resolve symbols
                //   b. lower semantics, update bound tree, repeat
                using (compilation.StartMetric("analysis"))
                {
                    compiler.AnalyzeMethods();
                }

                // 3. Resolve operators and types
                using (compilation.StartMetric("bind types"))
                {
                    compiler.BindTypes();
                }

                // 4. Transform Semantic Trees for Runtime Optimization
            } while (
                transformation++ < compiler.MaxTransformCount && // limit number of lowering cycles
                !cancellationToken.IsCancellationRequested &&    // user canceled ?
                compiler.RewriteMethods());                      // try lower the semantics

            compilation.TrackMetric("transformations", transformation);

            // 4. Collect diagnostics
            using (compilation.StartMetric("diagnostic"))
            {
                compiler.DiagnoseMethods();
                compiler.DiagnoseTypes();
                compiler.DiagnoseFiles();
            }

            //
            return(diagnostics.AsEnumerable());
        }
 /// <remarks>
 /// Respects the DocumentationMode at the source location.
 /// </remarks>
 private void RecordBindingDiagnostics(DiagnosticBag bindingDiagnostics, Location sourceLocation)
 {
     if (!bindingDiagnostics.IsEmptyWithoutResolution && ((SyntaxTree)sourceLocation.SourceTree).ReportDocumentationCommentDiagnostics())
     {
         foreach (Diagnostic diagnostic in bindingDiagnostics.AsEnumerable())
         {
             // CONSIDER: Dev11 actually uses the originating location plus the offset into the cref/name
             diagnostics.Add(diagnostic.WithLocation(sourceLocation));
         }
     }
 }
        protected static Diagnostic[] GetSortedDiagnostics(DiagnosticAnalyzer analyzer, Document[] documents, TextSpan?[] spans = null)
        {
            var projects = new HashSet <Project>();

            foreach (Document document in documents)
            {
                projects.Add(document.Project);
            }

            DiagnosticBag diagnostics = DiagnosticBag.GetInstance();

            foreach (Project project in projects)
            {
                Compilation compilation = project.GetCompilationAsync().Result;
                compilation = EnableAnalyzer(analyzer, compilation);

                ImmutableArray <Diagnostic> diags = compilation.GetAnalyzerDiagnostics(new[] { analyzer });
                if (spans == null)
                {
                    diagnostics.AddRange(diags);
                }
                else
                {
                    Debug.Assert(spans.Length == documents.Length);
                    foreach (Diagnostic diag in diags)
                    {
                        if (diag.Location == Location.None || diag.Location.IsInMetadata)
                        {
                            diagnostics.Add(diag);
                        }
                        else
                        {
                            for (int i = 0; i < documents.Length; i++)
                            {
                                Document   document = documents[i];
                                SyntaxTree tree     = document.GetSyntaxTreeAsync().Result;
                                if (tree == diag.Location.SourceTree)
                                {
                                    TextSpan?span = spans[i];
                                    if (span == null || span.Value.Contains(diag.Location.SourceSpan))
                                    {
                                        diagnostics.Add(diag);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            Diagnostic[] results = GetSortedDiagnostics(diagnostics.AsEnumerable());
            diagnostics.Free();
            return(results);
        }
Beispiel #6
0
        // Tests just the errors found while binding method M in class C.
        public void TestErrors(string code, params string[] errors)
        {
            var compilation            = CreateCompilationWithMscorlib(code);
            var method                 = (SourceMethodSymbol)compilation.GlobalNamespace.GetTypeMembers("C").Single().GetMembers("M").Single();
            var factory                = compilation.GetBinderFactory(method.SyntaxTree);
            var parameterBinderContext = factory.GetBinder(method.BlockSyntax);
            var binder                 = new ExecutableCodeBinder(method.BlockSyntax.Parent, method, parameterBinderContext);
            var diagnostics            = new DiagnosticBag();
            var block = (BoundBlock)binder.BindStatement(method.BlockSyntax, diagnostics);

            AssertEx.SetEqual(errors, diagnostics.AsEnumerable().Select(DumpDiagnostic));
        }
Beispiel #7
0
 public void TestErrors(string code, params string[] errors)
 {
     var compilation = CreateCompilationWithMscorlib(code);
     var method = (SourceMethodSymbol)compilation.GlobalNamespace.GetTypeMembers("C").Single().GetMembers("M").Single();
     var factory = compilation.GetBinderFactory(method.SyntaxTree);
     var bodyBlock = (BlockSyntax)method.BodySyntax;
     var parameterBinderContext = factory.GetBinder(bodyBlock);
     var binder = new ExecutableCodeBinder(bodyBlock.Parent, method, parameterBinderContext);
     var diagnostics = new DiagnosticBag();
     var block = binder.BindEmbeddedBlock(bodyBlock, diagnostics);
     AssertEx.SetEqual(errors, diagnostics.AsEnumerable().Select(DumpDiagnostic));
 }
Beispiel #8
0
        private static ImmutableArray <Diagnostic> GetDiagnostics(DiagnosticBag diagnostics, bool includeWarnings)
        {
            if (diagnostics.IsEmptyWithoutResolution)
            {
                return(ImmutableArray <Diagnostic> .Empty);
            }

            return(diagnostics.AsEnumerable().Where(d =>
                                                    d.Severity == DiagnosticSeverity.Error ||
                                                    (includeWarnings && d.Severity == DiagnosticSeverity.Warning))
                   .AsImmutable());
        }
Beispiel #9
0
        internal static bool PreventsSuccessfulDelegateConversion(DiagnosticBag diagnostics)
        {
            foreach (Diagnostic diag in diagnostics.AsEnumerable()) // Checking the code would have resolved them anyway.
            {
                if (ErrorFacts.PreventsSuccessfulDelegateConversion((ErrorCode)diag.Code))
                {
                    return(true);
                }
            }

            return(false);
        }
Beispiel #10
0
        public void TestErrors(string code, params string[] errors)
        {
            var compilation            = CreateStandardCompilation(code);
            var method                 = (SourceMemberMethodSymbol)compilation.GlobalNamespace.GetTypeMembers("C").Single().GetMembers("M").Single();
            var factory                = compilation.GetBinderFactory(method.SyntaxTree);
            var bodyBlock              = (BlockSyntax)method.BodySyntax;
            var parameterBinderContext = factory.GetBinder(bodyBlock);
            var binder                 = new ExecutableCodeBinder(bodyBlock.Parent, method, parameterBinderContext);
            var diagnostics            = new DiagnosticBag();
            var block = binder.BindEmbeddedBlock(bodyBlock, diagnostics);

            AssertEx.SetEqual(errors, diagnostics.AsEnumerable().Select(DumpDiagnostic));
        }
Beispiel #11
0
        public void TestWarnings(string code, params string[] expectedWarnings)
        {
            var compilation            = CreateCompilationWithMscorlib(code);
            var method                 = (SourceMethodSymbol)compilation.GlobalNamespace.GetTypeMembers("C").Single().GetMembers("M").Single();
            var factory                = compilation.GetBinderFactory(method.SyntaxTree);
            var bodyBlock              = (BlockSyntax)method.BodySyntax;
            var parameterBinderContext = factory.GetBinder(bodyBlock);
            var binder                 = new ExecutableCodeBinder(bodyBlock.Parent, method, parameterBinderContext);
            var block          = (BoundBlock)binder.BindStatement(bodyBlock, new DiagnosticBag());
            var actualWarnings = new DiagnosticBag();

            DiagnosticsPass.IssueDiagnostics(compilation, block, actualWarnings, method);
            AssertEx.SetEqual(expectedWarnings, actualWarnings.AsEnumerable().Select(DumpDiagnostic));
        }
Beispiel #12
0
        private bool Test(int index)
        {
            bool   result           = false;
            string inputFileName    = string.Format(@"..\..\InputFiles\soal\Xsd{0:00}.soal", index);
            string expectedFileName = string.Format(@"..\..\ExpectedFiles\xsd\Xsd{0:00}.Hello.xsd", index);
            string outputFileName   = string.Format(@"..\..\OutputFiles\xsd\Xsd{0:00}.Hello.xsd", index);
            string outputDirectory  = string.Format(@"..\..\OutputFiles");
            string inputSoal        = null;

            using (StreamReader reader = new StreamReader(inputFileName))
            {
                inputSoal = reader.ReadToEnd();
            }
            SoalSyntaxTree         syntaxTree    = SoalSyntaxTree.ParseText(inputSoal);
            ModelReference         soalReference = ModelReference.CreateFromModel(SoalInstance.Model);
            BinderFlags            binderFlags   = BinderFlags.IgnoreAccessibility;
            SoalCompilationOptions options       = new SoalCompilationOptions(SoalLanguage.Instance, OutputKind.NetModule, topLevelBinderFlags: binderFlags);
            SoalCompilation        compilation   = SoalCompilation.Create("SoalTest").AddReferences(soalReference).AddSyntaxTrees(syntaxTree).WithOptions(options);

            compilation.ForceComplete();
            ImmutableModel model = compilation.Model;

            Assert.IsFalse(compilation.GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error));

            DiagnosticBag generatorDiagnostics = new DiagnosticBag();
            SoalGenerator generator            = new SoalGenerator(model, compilation.BuildModelObjectToSymbolMap(), outputDirectory, generatorDiagnostics, inputFileName);

            generator.SeparateXsdWsdl = true;
            generator.SingleFileWsdl  = false;
            generator.Generate();

            Assert.IsFalse(generatorDiagnostics.AsEnumerable().Any(d => d.Severity == DiagnosticSeverity.Error));

            string expectedXsd = null;

            using (StreamReader reader = new StreamReader(expectedFileName))
            {
                expectedXsd = reader.ReadToEnd();
            }
            string outputXsd = null;

            using (StreamReader reader = new StreamReader(outputFileName))
            {
                outputXsd = reader.ReadToEnd();
            }
            Assert.AreEqual(expectedXsd, outputXsd);
            return(result);
        }
Beispiel #13
0
        private static void ThrowIfAnyCompilationErrors(DiagnosticBag diagnostics, DiagnosticFormatter formatter)
        {
            if (diagnostics.IsEmptyWithoutResolution)
            {
                return;
            }
            var filtered = diagnostics.AsEnumerable().Where(d => d.Severity == DiagnosticSeverity.Error).AsImmutable();

            if (filtered.IsEmpty)
            {
                return;
            }
            throw new CompilationErrorException(
                      formatter.Format(filtered[0], CultureInfo.CurrentCulture),
                      filtered);
        }
        internal Diagnostic GetErrorAndMissingAssemblyIdentities(DiagnosticBag diagnostics, out ImmutableArray<AssemblyIdentity> missingAssemblyIdentities)
        {
            var diagnosticsEnumerable = diagnostics.AsEnumerable();
            foreach (Diagnostic diagnostic in diagnosticsEnumerable)
            {
                missingAssemblyIdentities = GetMissingAssemblyIdentities(diagnostic);
                if (!missingAssemblyIdentities.IsDefault)
                {
                    break;
                }
            }

            if (missingAssemblyIdentities.IsDefault)
            {
                missingAssemblyIdentities = ImmutableArray<AssemblyIdentity>.Empty;
            }

            return diagnosticsEnumerable.FirstOrDefault(d => d.Severity == DiagnosticSeverity.Error);
        }
        internal Diagnostic GetErrorAndMissingAssemblyIdentities(DiagnosticBag diagnostics, out ImmutableArray <AssemblyIdentity> missingAssemblyIdentities)
        {
            var diagnosticsEnumerable = diagnostics.AsEnumerable();

            foreach (Diagnostic diagnostic in diagnosticsEnumerable)
            {
                missingAssemblyIdentities = GetMissingAssemblyIdentities(diagnostic);
                if (!missingAssemblyIdentities.IsDefault)
                {
                    break;
                }
            }

            if (missingAssemblyIdentities.IsDefault)
            {
                missingAssemblyIdentities = ImmutableArray <AssemblyIdentity> .Empty;
            }

            return(diagnosticsEnumerable.FirstOrDefault(d => d.Severity == DiagnosticSeverity.Error));
        }
Beispiel #16
0
        public static IEnumerable <Diagnostic> BindAndAnalyze(PhpCompilation compilation)
        {
            var manager = compilation.GetBoundReferenceManager();   // ensure the references are resolved! (binds ReferenceManager)

            var diagnostics = new DiagnosticBag();
            var compiler    = new SourceCompiler(compilation, null, true, diagnostics, CancellationToken.None);

            using (compilation.StartMetric("bind"))
            {
                // 1. Bind Syntax & Symbols to Operations (CFG)
                //   a. construct CFG, bind AST to Operation
                //   b. declare table of local variables
                compiler.WalkMethods(compiler.EnqueueRoutine, allowParallel: true);
                compiler.WalkTypes(compiler.EnqueueFieldsInitializer, allowParallel: true);
            }

            using (compilation.StartMetric("analysis"))
            {
                // 2. Analyze Operations
                //   a. type analysis (converge type - mask), resolve symbols
                //   b. lower semantics, update bound tree, repeat
                //   c. collect diagnostics
                compiler.AnalyzeMethods();
                compiler.DiagnoseMethods();
                compiler.DiagnoseTypes();
                compiler.DiagnoseFiles();
            }

            // TODO: Enable when the rewriting mechanism is refactored
            //if (!diagnostics.HasAnyErrors() && compilation.Options.OptimizationLevel == OptimizationLevel.Release)
            //{
            //    using (compilation.StartMetric("transform"))
            //    {
            //        // 3. Transform Semantic Trees for Runtime Optimization
            //        compiler.TransformMethods();
            //    }
            //}

            //
            return(diagnostics.AsEnumerable());
        }
Beispiel #17
0
        private static bool HasNonObsoleteError(DiagnosticBag unusedDiagnostics)
        {
            foreach (Diagnostic diag in unusedDiagnostics.AsEnumerable())
            {
                // CONSIDER: If this check is too slow, we could add a helper to DiagnosticBag
                // that checks for unrealized diagnostics without expanding them.
                switch ((ErrorCode)diag.Code)
                {
                case ErrorCode.ERR_DeprecatedSymbolStr:
                case ErrorCode.ERR_DeprecatedCollectionInitAddStr:
                    break;

                default:
                    if (diag.Severity == DiagnosticSeverity.Error)
                    {
                        return(true);
                    }
                    break;
                }
            }
            return(false);
        }
Beispiel #18
0
        private bool Test(int index)
        {
            bool           result            = false;
            string         inputFileName     = string.Format(@"..\..\InputFiles\xsd\Xsd{0:00}.Hello.xsd", index);
            string         expectedFileName  = string.Format(@"..\..\ExpectedFiles\soal\Xsd{0:00}.soal", index);
            string         outputFileName    = string.Format(@"..\..\OutputFiles\soal\Xsd{0:00}.Hello.soal", index);
            string         outputLogFileName = string.Format(@"..\..\OutputFiles\soal\Xsd{0:00}.Hello.log", index);
            string         outputDirectory   = string.Format(@"..\..\OutputFiles\soal", index);
            DiagnosticBag  diagnostics       = new DiagnosticBag();
            ImmutableModel model             = SoalImporter.Import(inputFileName, diagnostics);

            using (StreamWriter writer = new StreamWriter(outputLogFileName))
            {
                foreach (var msg in diagnostics.AsEnumerable())
                {
                    writer.WriteLine(msg);
                }
            }
            Assert.IsFalse(diagnostics.HasAnyErrors());
            Directory.CreateDirectory(outputDirectory);
            string      outputSoal = null;
            SoalPrinter printer    = new SoalPrinter(model.Symbols);

            using (StreamWriter writer = new StreamWriter(outputFileName))
            {
                outputSoal = printer.Generate();
                writer.WriteLine(outputSoal);
            }
            string expectedSoal = null;

            using (StreamReader reader = new StreamReader(expectedFileName))
            {
                expectedSoal = reader.ReadToEnd();
            }
            Assert.AreEqual(expectedSoal, outputSoal);
            return(result);
        }
Beispiel #19
0
        public static IEnumerable <Diagnostic> BindAndAnalyze(PhpCompilation compilation)
        {
            var manager = compilation.GetBoundReferenceManager();   // ensure the references are resolved! (binds ReferenceManager)

            var diagnostics = new DiagnosticBag();
            var compiler    = new SourceCompiler(compilation, null, true, diagnostics, CancellationToken.None);

            // 1.Bind Syntax & Symbols to Operations (CFG)
            //   a.equivalent to building CFG
            //   b.most generic types(and empty type - mask)
            compiler.WalkMethods(compiler.EnqueueRoutine);
            compiler.WalkTypes(compiler.EnqueueFieldsInitializer);

            // 2.Analyze Operations
            //   a.declared variables
            //   b.build global variables/constants table
            //   c.type analysis(converge type - mask), resolve symbols
            //   d.lower semantics, update bound tree, repeat
            compiler.AnalyzeMethods();
            compiler.DiagnoseMethods();

            //
            return(diagnostics.AsEnumerable());
        }
Beispiel #20
0
        public static IEnumerable <Diagnostic> BindAndAnalyze(PhpCompilation compilation)
        {
            var manager = compilation.GetBoundReferenceManager();   // ensure the references are resolved! (binds ReferenceManager)

            var diagnostics = new DiagnosticBag();
            var compiler    = new SourceCompiler(compilation, null, true, diagnostics, CancellationToken.None);

            // 1. Bind Syntax & Symbols to Operations (CFG)
            //   a. construct CFG, bind AST to Operation
            //   b. declare table of local variables
            compiler.WalkMethods(compiler.EnqueueRoutine);
            compiler.WalkTypes(compiler.EnqueueFieldsInitializer);

            // 2. Analyze Operations
            //   a. type analysis (converge type - mask), resolve symbols
            //   b. lower semantics, update bound tree, repeat
            //   c. collect diagnostics
            compiler.AnalyzeMethods();
            compiler.DiagnoseMethods();
            compiler.DiagnoseTypes();

            //
            return(diagnostics.AsEnumerable());
        }
Beispiel #21
0
 private void CompilationError(DiagnosticBag diagnostics)
 {
     var resolvedLocalDiagnostics = diagnostics.AsEnumerable();
     var firstError = resolvedLocalDiagnostics.FirstOrDefault(d => d.Severity == DiagnosticSeverity.Error);
     if (firstError != null)
     {
         throw new CompilationErrorException(FormatDiagnostic(firstError, CultureInfo.CurrentCulture),
             (resolvedLocalDiagnostics.AsImmutable()));
     }
 }
Beispiel #22
0
        static void Main(string[] args)
        {
            string fileName        = null;
            string outputDirectory = null;
            bool   separateXsdWsdl = false;
            bool   singleFileWsdl  = false;

            for (int i = 0; i < args.Length; i++)
            {
                if (args[i].StartsWith("-"))
                {
                    if (args[i] == "-separateXsdWsdl")
                    {
                        separateXsdWsdl = true;
                    }
                    else if (args[i] == "-singleFileWsdl")
                    {
                        singleFileWsdl = true;
                    }
                    else if (i + 1 < args.Length)
                    {
                        if (args[i] == "-o")
                        {
                            outputDirectory = args[++i];
                        }
                        else
                        {
                            Console.WriteLine("Unknown option: '" + args[i] + "'");
                        }
                    }
                    else
                    {
                        Console.WriteLine("Unknown option: '" + args[i] + "'");
                    }
                }
                else
                {
                    fileName = args[i];
                }
            }
            if (fileName == null)
            {
                Console.WriteLine("Usage:");
                Console.WriteLine("  Soal.exe [options] [input.soal]");
                Console.WriteLine("Options:");
                Console.WriteLine("  -o [dir]: output directory");
                Console.WriteLine("  -separateXsdWsdl: separate XSD and WSDL files into different directories");
                Console.WriteLine("  -singleFileWsdl: include XSD code into the WSDL");
                return;
            }
            if (outputDirectory == null)
            {
                outputDirectory = Directory.GetCurrentDirectory();
            }
            if (!File.Exists(fileName))
            {
                Console.WriteLine("Could not find file: " + fileName);
                return;
            }
            if (singleFileWsdl && separateXsdWsdl)
            {
                Console.WriteLine("Warning: conflicting options '-separateXsdWsdl' and '-singleFileWsdl'. '-singleFileWsdl' will be used.");
            }
            string source;

            using (StreamReader reader = new StreamReader(fileName))
            {
                source = reader.ReadToEnd();
            }
            SoalSyntaxTree         syntaxTree    = SoalSyntaxTree.ParseText(source);
            ModelReference         soalReference = ModelReference.CreateFromModel(SoalInstance.Model);
            BinderFlags            binderFlags   = BinderFlags.IgnoreAccessibility;
            SoalCompilationOptions options       = new SoalCompilationOptions(SoalLanguage.Instance, OutputKind.NetModule, topLevelBinderFlags: binderFlags, concurrentBuild: false);
            SoalCompilation        compilation   = SoalCompilation.Create("SoalTest").AddReferences(soalReference).AddSyntaxTrees(syntaxTree).WithOptions(options);

            compilation.ForceComplete();
            ImmutableModel model = compilation.Model;
            DiagnosticBag  generatorDiagnostics = new DiagnosticBag();

            if (!compilation.GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error))
            {
                SoalGenerator generator = new SoalGenerator(model, compilation.BuildModelObjectToSymbolMap(), outputDirectory, generatorDiagnostics, fileName);
                generator.SeparateXsdWsdl = separateXsdWsdl;
                generator.SingleFileWsdl  = singleFileWsdl;
                generator.Generate();
                SoalPrinter printer = new SoalPrinter(model.Symbols);
                using (StreamWriter writer = new StreamWriter(fileName + "0"))
                {
                    writer.WriteLine(printer.Generate());
                }
            }
            DiagnosticFormatter formatter = new DiagnosticFormatter();

            foreach (var diagnostic in compilation.GetDiagnostics())
            {
                string msg = formatter.Format(diagnostic);
                Console.WriteLine(msg);
            }
            foreach (var diagnostic in generatorDiagnostics.AsEnumerable())
            {
                string msg = formatter.Format(diagnostic);
                Console.WriteLine(msg);
            }
        }
Beispiel #23
0
        internal ImmutableArray <Diagnostic> GetDiagnostics(CompilationStage stage, bool includeEarlierStages, CancellationToken cancellationToken)
        {
            var builder = DiagnosticBag.GetInstance();

            // Parse
            if (stage == CompilationStage.Parse || (stage > CompilationStage.Parse && includeEarlierStages))
            {
                var syntaxTrees = this.SyntaxTrees;
                if (this.Options.ConcurrentBuild)
                {
                    Parallel.ForEach(syntaxTrees, UICultureUtilities.WithCurrentUICulture <PhpSyntaxTree>(syntaxTree =>
                    {
                        builder.AddRange(syntaxTree.GetDiagnostics(cancellationToken));
                    }));
                }
                else
                {
                    foreach (var syntaxTree in syntaxTrees)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        builder.AddRange(syntaxTree.GetDiagnostics(cancellationToken));
                    }
                }
            }

            // Declare
            if (stage == CompilationStage.Declare || stage > CompilationStage.Declare && includeEarlierStages)
            {
                // CheckAssemblyName(builder);
                builder.AddRange(Options.Errors);
                builder.AddRange(Options.Diagnostics);

                cancellationToken.ThrowIfCancellationRequested();

                // the set of diagnostics related to establishing references.
                builder.AddRange(GetBoundReferenceManager().Diagnostics);

                //cancellationToken.ThrowIfCancellationRequested();

                try
                {
                    // TODO: cancellationToken
                    builder.AddRange(this.BindAndAnalyseTask().Result.AsImmutable());
                }
                catch (AggregateException e) when(e.InnerException != null)
                {
                    // unwrap the aggregate exception, keep original stacktrace
                    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(e.InnerException).Throw();
                }

                cancellationToken.ThrowIfCancellationRequested();

                // resolve entry point
                this.GetEntryPoint(cancellationToken);

                //
                builder.AddRange(_lazyDeclarationDiagnostics?.AsEnumerable() ?? Enumerable.Empty <Diagnostic>());
            }

            cancellationToken.ThrowIfCancellationRequested();

            // Compile
            if (stage == CompilationStage.Compile || stage > CompilationStage.Compile && includeEarlierStages)
            {
                var methodBodyDiagnostics = DiagnosticBag.GetInstance();
                // TODO: perform compilation and report diagnostics
                // GetDiagnosticsForAllMethodBodies(methodBodyDiagnostics, cancellationToken);
                builder.AddRangeAndFree(methodBodyDiagnostics);
            }

            // Before returning diagnostics, we filter warnings
            // to honor the compiler options (e.g., /nowarn, /warnaserror and /warn) and the pragmas.
            var result = DiagnosticBag.GetInstance();

            FilterAndAppendAndFreeDiagnostics(result, ref builder);
            return(result.ToReadOnlyAndFree <Diagnostic>());
        }
 /// <remarks>
 /// Respects the DocumentationMode at the source location.
 /// </remarks>
 private void RecordBindingDiagnostics(DiagnosticBag bindingDiagnostics, Location sourceLocation)
 {
     if (!bindingDiagnostics.IsEmptyWithoutResolution && ((SyntaxTree)sourceLocation.SourceTree).ReportDocumentationCommentDiagnostics())
     {
         foreach (Diagnostic diagnostic in bindingDiagnostics.AsEnumerable())
         {
             // CONSIDER: Dev11 actually uses the originating location plus the offset into the cref/name,
             // but that just seems silly.
             diagnostics.Add(diagnostic.WithLocation(sourceLocation));
         }
     }
 }
 private static bool HasNonObsoleteError(DiagnosticBag unusedDiagnostics)
 {
     foreach (Diagnostic diag in unusedDiagnostics.AsEnumerable())
     {
         // CONSIDER: If this check is too slow, we could add a helper to DiagnosticBag
         // that checks for unrealized diagnostics without expanding them.
         switch ((ErrorCode)diag.Code)
         {
             case ErrorCode.ERR_DeprecatedSymbolStr:
             case ErrorCode.ERR_DeprecatedCollectionInitAddStr:
                 break;
             default:
                 if (diag.Severity == DiagnosticSeverity.Error)
                 {
                     return true;
                 }
                 break;
         }
     }
     return false;
 }
Beispiel #26
0
 public void TestWarnings(string code, params string[] expectedWarnings)
 {
     var compilation = CreateCompilationWithMscorlib(code);
     var method = (SourceMethodSymbol)compilation.GlobalNamespace.GetTypeMembers("C").Single().GetMembers("M").Single();
     var factory = compilation.GetBinderFactory(method.SyntaxTree);
     var bodyBlock = (BlockSyntax)method.BodySyntax;
     var parameterBinderContext = factory.GetBinder(bodyBlock);
     var binder = new ExecutableCodeBinder(bodyBlock.Parent, method, parameterBinderContext);
     var block = (BoundBlock)binder.BindStatement(bodyBlock, new DiagnosticBag());
     var actualWarnings = new DiagnosticBag();
     DiagnosticsPass.IssueDiagnostics(compilation, block, actualWarnings, method);
     AssertEx.SetEqual(expectedWarnings, actualWarnings.AsEnumerable().Select(DumpDiagnostic));
 }
Beispiel #27
0
 static void Main(string[] args)
 {
     try
     {
         string inputFileName  = null;
         string outputFileName = null;
         for (int i = 0; i < args.Length; i++)
         {
             if (args[i].StartsWith("-"))
             {
                 if (i + 1 < args.Length)
                 {
                     if (args[i] == "-o")
                     {
                         outputFileName = args[++i];
                     }
                     else
                     {
                         Console.WriteLine("Unknown option: '" + args[i] + "'");
                     }
                 }
                 else
                 {
                     Console.WriteLine("Unknown option: '" + args[i] + "'");
                 }
             }
             else
             {
                 inputFileName = args[i];
             }
         }
         if (inputFileName == null)
         {
             Console.WriteLine("Usage:");
             Console.WriteLine("  SoalImport.exe [options] [input.wsdl or input.xsd]");
             Console.WriteLine("Options:");
             Console.WriteLine("  -o [output.soal]: output SOAL file");
             return;
         }
         if (outputFileName == null)
         {
             outputFileName = Path.ChangeExtension(inputFileName, ".soal");
         }
         if (!File.Exists(inputFileName))
         {
             Console.WriteLine("Could not find file: " + inputFileName);
             return;
         }
         DiagnosticBag  importDiagnostics = new DiagnosticBag();
         ImmutableModel model             = SoalImporter.Import(inputFileName, importDiagnostics);
         foreach (var msg in importDiagnostics.AsEnumerable())
         {
             Console.WriteLine(msg);
         }
         //if (!ModelCompilerContext.Current.Diagnostics.HasErrors())
         {
             SoalPrinter printer = new SoalPrinter(model.Symbols);
             using (StreamWriter writer = new StreamWriter(outputFileName))
             {
                 writer.WriteLine(printer.Generate());
             }
         }
     }
     catch (System.Exception ex)
     {
         Console.WriteLine(ex);
     }
 }
Beispiel #28
0
        /// <remarks>
        /// WARNING: will resolve lazy diagnostics - do not call this before the member lists are completed
        /// or you could trigger infinite recursion.
        /// </remarks>
        internal static bool PreventsSuccessfulDelegateConversion(DiagnosticBag diagnostics)
        {
            foreach (Diagnostic diag in diagnostics.AsEnumerable()) // Checking the code would have resolved them anyway.
            {
                if (ErrorFacts.PreventsSuccessfulDelegateConversion((ErrorCode)diag.Code))
                {
                    return true;
                }
            }

            return false;
        }