Exemplo n.º 1
0
        public void ProcessWarningCastsWithInfoLevel()
        {
            const String source = "namespace SomeNamespace\r\n" +
                                  "{\r\n" +
                                  "    public class SomeBaseClass\r\n" +
                                  "    {\r\n" +
                                  "    }\r\n" +
                                  "    public class SomeDerivedClass : SomeBaseClass\r\n" +
                                  "    {\r\n" +
                                  "    }\r\n" +
                                  "    public class SomeClass\r\n" +
                                  "    {\r\n" +
                                  "        public void SomeMethod()\r\n" +
                                  "        {\r\n" +
                                  "            int i1 = 666;\r\n" +
                                  "            int i2 = (int)i1;\r\n" +
                                  "            int i3 = (int)13;\r\n" +
                                  "            double d1 = 3.14;\r\n" +
                                  "            double d2 = (double)d1;\r\n" +
                                  "            object obj1 = new object();\r\n" +
                                  "            object obj2 = (object)obj1;\r\n" +
                                  "            SomeDerivedClass someObj1 = new SomeDerivedClass();\r\n" +
                                  "            SomeDerivedClass someObj2 = (SomeDerivedClass)someObj1;\r\n" +
                                  "        }\r\n" +
                                  "    }\r\n" +
                                  "}\r\n";
            const String filePath = "C:\\SomeFolder\\SomeClass.cs";
            const String expectedOutputTemplate = "Execution of CastToSameTypeAnalyzer started\r\n" +
                                                  "Found 0 casts leading to errors in the ported C++ code\r\n" +
                                                  "Found 5 casts to the same type not leading to errors in the ported C++ code\r\n" +
                                                  "{0}(14): [WARNING]: Found cast to the same type \"int\"\r\n" +
                                                  "{0}(15): [WARNING]: Found cast to the same type \"int\"\r\n" +
                                                  "{0}(17): [WARNING]: Found cast to the same type \"double\"\r\n" +
                                                  "{0}(19): [WARNING]: Found cast to the same type \"object\"\r\n" +
                                                  "{0}(21): [WARNING]: Found cast to the same type \"SomeNamespace.SomeDerivedClass\"\r\n" +
                                                  "Execution of CastToSameTypeAnalyzer finished\r\n";
            String expectedOutput = String.Format(expectedOutputTemplate, filePath);

            AnalyzerHelper.Process(_analyzerFactory, source, "CastToSameType", filePath, OutputLevel.Info, true, expectedOutput);
        }
        public void ProcessAsciiIdentifiers(OutputLevel outputLevel)
        {
            const String source = "namespace SomeNamespace\r\n" +
                                  "{\r\n" +
                                  "    public class OtherClass\r\n" +
                                  "    {\r\n" +
                                  "    }\r\n" +
                                  "    public class SomeClass\r\n" +
                                  "    {\r\n" +
                                  "        public void SomeMethod()\r\n" +
                                  "        {\r\n" +
                                  "            int intVar = 666;\r\n" +
                                  "            string strVar1 = \"IDDQD\";\r\n" +
                                  "            string stringVar2 = \"ИДДКуД\";\r\n" +
                                  "            OtherClass otherObj = new OtherClass();" +
                                  "        }\r\n" +
                                  "    }\r\n" +
                                  "}";
            const String filePath = "C:\\SomeFolder\\SomeClass.cs";

            AnalyzerHelper.Process(_analyzerFactory, source, "NonAsciiIdentifiers", filePath, outputLevel, true, "");
        }
        public void ProcessExactMatchWithWarningsWithErrorLevel()
        {
            const String source = "namespace SomeNamespace\r\n" +
                                  "{\r\n" +
                                  "    public class OtherClass\r\n" +
                                  "    {\r\n" +
                                  "    }\r\n" +
                                  "    public class SomeClass\r\n" +
                                  "    {\r\n" +
                                  "    }\r\n" +
                                  "    public class SOmeClass\r\n" +
                                  "    {\r\n" +
                                  "    }\r\n" +
                                  "    public class Someclass\r\n" +
                                  "    {\r\n" +
                                  "    }\r\n" +
                                  "    public class AnotherClass\r\n" +
                                  "    {\r\n" +
                                  "    }\r\n" +
                                  "}";
            const String filePath = "C:\\SomeFolder\\SomeClass.cs";

            AnalyzerHelper.Process(_analyzerFactory, source, "BadFilenameCase", filePath, OutputLevel.Error, true, "");
        }
        /// <summary>
        /// POST: api/Messages
        /// Receive a message from a user and reply to it
        /// </summary>
        public async Task <HttpResponseMessage> Post([FromBody] Activity activity)
        {
            if (activity.GetActivityType() == ActivityTypes.Message)
            {
                var          connector = new ConnectorClient(new Uri(activity.ServiceUrl));
                const string apiKey    = "&apikey=13ba01ba";

                var ss = activity.Text;

                var r = await AnalyzerHelper.analyze("http://www.omdbapi.com/?t=" + ss + apiKey);

                r


                var rep = activity.CreateReply(r.ToString());
                //   var po = await AnalyzerHelper.poster("http://www.omdbapi.com/?t=" + ss + apiKey);
                //// AnalyzerHelper h = new AnalyzerHelper();
                // rep.Attachments.Add(new Attachment()

                // {
                //     ContentUrl =po,
                //      ContentType = "image/jpg",
                //     Name = "film poster"

                // });

                await connector.Conversations.ReplyToActivityAsync(rep);
            }
            else
            {
                HandleSystemMessage(activity);
            }
            var response = Request.CreateResponse(HttpStatusCode.OK);

            return(response);
        }
 private void Default_OnAnalyzerException_NoTelemetryLogging(Exception e, DiagnosticAnalyzer analyzer, Diagnostic diagnostic)
 {
     AnalyzerHelper.OnAnalyzerException_NoTelemetryLogging(e, analyzer, diagnostic, _hostDiagnosticUpdateSource, _project);
 }
 private static Task <CompilationWithAnalyzers?> CreateCompilationWithAnalyzersAsync(Project project, IEnumerable <StateSet> stateSets, bool includeSuppressedDiagnostics, CancellationToken cancellationToken)
 => AnalyzerHelper.CreateCompilationWithAnalyzersAsync(project, stateSets.Select(s => s.Analyzer), includeSuppressedDiagnostics, cancellationToken);
Exemplo n.º 7
0
 public static void MarkElement(FrameworkElement element)
 {
     AnalyzerHelper.MarkElement(element, MarkBrush, MarkThickness, "Marked");
 }
Exemplo n.º 8
0
        private async Task AnalyzeProjectAsync(
            Project project,
            bool forceAnalyzerRun,
            CancellationToken cancellationToken
            )
        {
            try
            {
                var stateSets = GetStateSetsForFullSolutionAnalysis(
                    _stateManager.GetOrUpdateStateSets(project),
                    project
                    )
                                .ToList();
                var options = project.Solution.Options;

                // PERF: get analyzers that are not suppressed and marked as open file only
                // this is perf optimization. we cache these result since we know the result. (no diagnostics)
                var activeAnalyzers = stateSets
                                      .Select(s => s.Analyzer)
                                      .Where(
                    a =>
                    !DiagnosticAnalyzerInfoCache.IsAnalyzerSuppressed(a, project) &&
                    !a.IsOpenFileOnly(options)
                    );

                // get driver only with active analyzers.
                var compilationWithAnalyzers = await AnalyzerHelper
                                               .CreateCompilationWithAnalyzersAsync(
                    project,
                    activeAnalyzers,
                    includeSuppressedDiagnostics : true,
                    cancellationToken
                    )
                                               .ConfigureAwait(false);

                var result = await GetProjectAnalysisDataAsync(
                    compilationWithAnalyzers,
                    project,
                    stateSets,
                    forceAnalyzerRun,
                    cancellationToken
                    )
                             .ConfigureAwait(false);

                if (result.OldResult == null)
                {
                    RaiseProjectDiagnosticsIfNeeded(project, stateSets, result.Result);
                    return;
                }

                // we might not have compilationWithAnalyzers even if project supports compilation if we are called with no analyzers.
                var compilation =
                    compilationWithAnalyzers?.Compilation
                    ?? (
                        project.SupportsCompilation
                            ? await project
                        .GetCompilationAsync(cancellationToken)
                        .ConfigureAwait(false)
                            : null
                        );

                // no cancellation after this point.
                // any analyzer that doesn't have result will be treated as returned empty set
                // which means we will remove those from error list
                foreach (var stateSet in stateSets)
                {
                    var state = stateSet.GetOrCreateProjectState(project.Id);

                    await state
                    .SaveAsync(
                        PersistentStorageService,
                        project,
                        result.GetResult(stateSet.Analyzer)
                        )
                    .ConfigureAwait(false);
                }

                RaiseProjectDiagnosticsIfNeeded(
                    project,
                    stateSets,
                    result.OldResult,
                    result.Result
                    );
            }
            catch (Exception e)
                when(FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
                {
                    throw ExceptionUtilities.Unreachable;
                }
        }
Exemplo n.º 9
0
 // If you update this method, also consider making updates to CSharpDiagnosticFilter.GetDiagnosticReport and
 // VisualBasicDiagnosticFilter.GetDiagnosticReport.
 internal static ReportDiagnostic GetEffectiveSeverity(string ruleId, IDictionary <string, ReportDiagnostic> specificOptions, ReportDiagnostic generalOption, DiagnosticSeverity defaultSeverity, bool enabledByDefault)
 {
     return(AnalyzerHelper.GetEffectiveSeverity(generalOption, specificOptions, ruleId, defaultSeverity, enabledByDefault));
 }
Exemplo n.º 10
0
 private AnalyzerExecutor GetAnalyzerExecutor(DiagnosticAnalyzer analyzer, Compilation compilation, Action <Diagnostic> addDiagnostic)
 {
     return(AnalyzerHelper.GetAnalyzerExecutor(analyzer, _hostDiagnosticUpdateSource, _project,
                                               compilation, addDiagnostic, _analyzerOptions, CatchAnalyzerException, _cancellationToken));
 }
 private Task <IEnumerable <DiagnosticData> > GetSyntaxDiagnosticsAsync(DiagnosticAnalyzer analyzer, CancellationToken cancellationToken)
 {
     return(AnalyzerHelper.ComputeDiagnosticsAsync(analyzer, _document, AnalysisKind.Syntax, _compilation, _owner.GetOrCreateSkippedAnalyzersInfo, _range, cancellationToken));
 }
Exemplo n.º 12
0
 private AnalyzerExecutor GetAnalyzerExecutorForSupportedDiagnostics(DiagnosticAnalyzer analyzer)
 {
     // Skip telemetry logging if the exception is thrown as we are computing supported diagnostics and
     // we can't determine if any descriptors support getting telemetry without having the descriptors.
     return(AnalyzerHelper.GetAnalyzerExecutorForSupportedDiagnostics(analyzer, _hostDiagnosticUpdateSource, CatchAnalyzerException_NoTelemetryLogging, _cancellationToken));
 }
Exemplo n.º 13
0
 private Action <Diagnostic> GetAddExceptionDiagnosticDelegate(DiagnosticAnalyzer analyzer)
 {
     return(AnalyzerHelper.GetAddExceptionDiagnosticDelegate(analyzer, _hostDiagnosticUpdateSource, _project));
 }
 private void AnalyzerPluginImage(SyntaxNodeAnalysisContext context)
 {
     if (context.Node is AttributeSyntax attribute && attribute?.Name?.ToFullString() == "CrmPluginRegistration")
     {
         attribute.TryFindArgument(0, "message", out var argurment0);
         var message = AnalyzerHelper.RemoveQuote(argurment0?.ToFullString()).Trim().ToLower();
         if (message != "create" && message != "update" && message != "delete")
         {
             return;
         }
         attribute.TryFindArgument(2, "stage", out var argurment2);
         var stage = argurment2?.ToFullString();
         if (message == "create" && stage != null && (stage.EndsWith("StageEnum.PreValidation") || stage.EndsWith("StageEnum.PreOperation")))
         {
             var images = GetImages(attribute.ArgumentList);
             if (images.Count > 0)
             {
                 foreach (var image in images)
                 {
                     if (image.ImageType.EndsWith("ImageTypeEnum.PreImage"))
                     {
                         DiagnosticHelpers.ReportDiagnostic(context, DiagnosticDescriptors.PluginImage_PreCreate_PreImage, image.Location);
                     }
                     if (image.ImageType.EndsWith("ImageTypeEnum.PostImage"))
                     {
                         DiagnosticHelpers.ReportDiagnostic(context, DiagnosticDescriptors.PluginImage_PreCreate_PostImage, image.Location);
                     }
                 }
             }
         }
         else if (message == "create" && stage != null && stage.EndsWith("PostOperation"))
         {
             var images = GetImages(attribute.ArgumentList);
             if (images.Count > 0)
             {
                 foreach (var image in images)
                 {
                     if (image.ImageType.EndsWith("ImageTypeEnum.PreImage"))
                     {
                         DiagnosticHelpers.ReportDiagnostic(context, DiagnosticDescriptors.PluginImage_PostCreate_PreImage, image.Location);
                     }
                 }
             }
         }
         else if (message == "update" && stage != null && (stage.EndsWith("StageEnum.PreValidation") || stage.EndsWith("StageEnum.PreOperation")))
         {
             var images = GetImages(attribute.ArgumentList);
             if (images.Count > 0)
             {
                 foreach (var image in images)
                 {
                     if (image.ImageType.EndsWith("ImageTypeEnum.PostImage"))
                     {
                         DiagnosticHelpers.ReportDiagnostic(context, DiagnosticDescriptors.PluginImage_PreUpdate_PostImage, image.Location);
                     }
                 }
             }
         }
         else if (message == "delete" && stage != null && (stage.EndsWith("StageEnum.PreValidation") || stage.EndsWith("StageEnum.PreOperation")))
         {
             var images = GetImages(attribute.ArgumentList);
             if (images.Count > 0)
             {
                 foreach (var image in images)
                 {
                     if (image.ImageType.EndsWith("ImageTypeEnum.PostImage"))
                     {
                         DiagnosticHelpers.ReportDiagnostic(context, DiagnosticDescriptors.PluginImage_PreDelete_PostImage, image.Location);
                     }
                 }
             }
         }
         else if (message == "delete" && stage != null && stage.EndsWith("PostOperation"))
         {
             var images = GetImages(attribute.ArgumentList);
             if (images.Count > 0)
             {
                 foreach (var image in images)
                 {
                     if (image.ImageType.EndsWith("ImageTypeEnum.PostImage"))
                     {
                         DiagnosticHelpers.ReportDiagnostic(context, DiagnosticDescriptors.PluginImage_PostDelete_PostImage, image.Location);
                     }
                 }
             }
         }
     }
 }
Exemplo n.º 15
0
        private static async Task <ImmutableDictionary <DiagnosticAnalyzer, DiagnosticAnalysisResult> > MergeProjectDiagnosticAnalyzerDiagnosticsAsync(
            Project project,
            ImmutableArray <DiagnosticAnalyzer> ideAnalyzers,
            Compilation?compilation,
            ImmutableDictionary <DiagnosticAnalyzer, DiagnosticAnalysisResult> result,
            CancellationToken cancellationToken)
        {
            try
            {
                var version = await GetDiagnosticVersionAsync(project, cancellationToken).ConfigureAwait(false);

                var(fileLoadAnalysisResult, failedDocuments) = await GetDocumentLoadFailuresAsync(project, version, cancellationToken).ConfigureAwait(false);

                result = result.SetItem(FileContentLoadAnalyzer.Instance, fileLoadAnalysisResult);

                foreach (var analyzer in ideAnalyzers)
                {
                    var builder = new DiagnosticAnalysisResultBuilder(project, version);

                    switch (analyzer)
                    {
                    case DocumentDiagnosticAnalyzer documentAnalyzer:
                        foreach (var document in project.Documents)
                        {
                            // don't analyze documents whose content failed to load
                            if (failedDocuments == null || !failedDocuments.Contains(document))
                            {
                                var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);

                                if (tree != null)
                                {
                                    builder.AddSyntaxDiagnostics(tree, await AnalyzerHelper.ComputeDocumentDiagnosticAnalyzerDiagnosticsAsync(documentAnalyzer, document, AnalysisKind.Syntax, compilation, cancellationToken).ConfigureAwait(false));
                                    builder.AddSemanticDiagnostics(tree, await AnalyzerHelper.ComputeDocumentDiagnosticAnalyzerDiagnosticsAsync(documentAnalyzer, document, AnalysisKind.Semantic, compilation, cancellationToken).ConfigureAwait(false));
                                }
                                else
                                {
                                    builder.AddExternalSyntaxDiagnostics(document.Id, await AnalyzerHelper.ComputeDocumentDiagnosticAnalyzerDiagnosticsAsync(documentAnalyzer, document, AnalysisKind.Syntax, compilation, cancellationToken).ConfigureAwait(false));
                                    builder.AddExternalSemanticDiagnostics(document.Id, await AnalyzerHelper.ComputeDocumentDiagnosticAnalyzerDiagnosticsAsync(documentAnalyzer, document, AnalysisKind.Semantic, compilation, cancellationToken).ConfigureAwait(false));
                                }
                            }
                        }

                        break;

                    case ProjectDiagnosticAnalyzer projectAnalyzer:
                        builder.AddCompilationDiagnostics(await AnalyzerHelper.ComputeProjectDiagnosticAnalyzerDiagnosticsAsync(projectAnalyzer, project, compilation, cancellationToken).ConfigureAwait(false));
                        break;
                    }

                    // merge the result to existing one.
                    // there can be existing one from compiler driver with empty set. overwrite it with
                    // ide one.
                    result = result.SetItem(analyzer, DiagnosticAnalysisResult.CreateFromBuilder(builder));
                }

                return(result);
            }
            catch (Exception e) when(FatalError.ReportUnlessCanceled(e))
            {
                throw ExceptionUtilities.Unreachable;
            }
        }
 private void AnalyzerUpdateMessageShouldHaveFilteringAttributes(SyntaxNodeAnalysisContext context)
 {
     if (
         context.Node is AttributeSyntax attribute &&
         attribute?.Name?.ToFullString() == "CrmPluginRegistration" &&
         attribute.TryFindArgument(0, "message", out var argurment0) &&
         (AnalyzerHelper.RemoveQuote(argurment0?.ToFullString().ToLower()) == "Update".ToLower() || AnalyzerHelper.RemoveQuote(argurment0?.ToFullString().ToLower()) == "OnExternalUpdated".ToLower()) &&
         attribute.TryFindArgument(4, "filteringAttributes", out var argurment4) &&
         AnalyzerHelper.TestIsEmtpy(argurment4?.ToFullString())
         )
     {
         DiagnosticHelpers.ReportDiagnostic(context, DiagnosticDescriptors.UpdateMessageShouldHaveFilteringAttributes, argurment4.GetLocation());
     }
 }
 private Task <IEnumerable <DiagnosticData> > GetSyntaxDiagnosticsAsync(DiagnosticAnalyzer analyzer, CancellationToken cancellationToken)
 => AnalyzerHelper.ComputeDiagnosticsAsync(analyzer, _document, AnalysisKind.Syntax, _owner.DiagnosticAnalyzerInfoCache, _compilation, _range, cancellationToken);
Exemplo n.º 18
0
            > ComputeDiagnosticsAsync(
            CompilationWithAnalyzers?compilationWithAnalyzers,
            Project project,
            IEnumerable <StateSet> stateSets,
            bool forcedAnalysis,
            ImmutableDictionary <DiagnosticAnalyzer, DiagnosticAnalysisResult> existing,
            CancellationToken cancellationToken
            )
        {
            try
            {
                // PERF: check whether we can reduce number of analyzers we need to run.
                //       this can happen since caller could have created the driver with different set of analyzers that are different
                //       than what we used to create the cache.
                var version = await GetDiagnosticVersionAsync(project, cancellationToken)
                              .ConfigureAwait(false);

                var ideAnalyzers = stateSets
                                   .Select(s => s.Analyzer)
                                   .Where(a => a is ProjectDiagnosticAnalyzer || a is DocumentDiagnosticAnalyzer)
                                   .ToImmutableArrayOrEmpty();

                if (
                    compilationWithAnalyzers != null &&
                    TryReduceAnalyzersToRun(
                        compilationWithAnalyzers,
                        project,
                        version,
                        existing,
                        out var analyzersToRun
                        )
                    )
                {
                    // it looks like we can reduce the set. create new CompilationWithAnalyzer.
                    // if we reduced to 0, we just pass in null for analyzer drvier. it could be reduced to 0
                    // since we might have up to date results for analyzers from compiler but not for
                    // workspace analyzers.
                    var compilationWithReducedAnalyzers =
                        (analyzersToRun.Length == 0)
                            ? null
                            : await AnalyzerHelper
                        .CreateCompilationWithAnalyzersAsync(
                            project,
                            analyzersToRun,
                            compilationWithAnalyzers.AnalysisOptions.ReportSuppressedDiagnostics,
                            cancellationToken
                            )
                        .ConfigureAwait(false);

                    var result = await ComputeDiagnosticsAsync(
                        compilationWithReducedAnalyzers,
                        project,
                        ideAnalyzers,
                        forcedAnalysis,
                        cancellationToken
                        )
                                 .ConfigureAwait(false);

                    return(MergeExistingDiagnostics(version, existing, result));
                }

                // we couldn't reduce the set.
                return(await ComputeDiagnosticsAsync(
                           compilationWithAnalyzers,
                           project,
                           ideAnalyzers,
                           forcedAnalysis,
                           cancellationToken
                           )
                       .ConfigureAwait(false));
            }
            catch (Exception e)
                when(FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
                {
                    throw ExceptionUtilities.Unreachable;
                }
        }