private void AnalyzeCompilation(CompilationAnalysisContext context)
        {
            if (AssemblyHasPublicTypes(context.Compilation.Assembly))
            {
                var comVisibleAttributeSymbol = WellKnownTypes.ComVisibleAttribute(context.Compilation);
                if (comVisibleAttributeSymbol == null)
                {
                    return;
                }

                var attributeInstance = context.Compilation.Assembly.GetAttributes().FirstOrDefault(a => a.AttributeClass.Equals(comVisibleAttributeSymbol));

                if (attributeInstance != null)
                {
                    if (attributeInstance.ConstructorArguments.Length > 0 &&
                        attributeInstance.ConstructorArguments[0].Kind == TypedConstantKind.Primitive &&
                        attributeInstance.ConstructorArguments[0].Value != null &
                        attributeInstance.ConstructorArguments[0].Value.Equals(true))
                    {
                        // Has the attribute, with the value 'true'.
                        context.ReportDiagnostic(Diagnostic.Create(Rule, Location.None, string.Format(SystemRuntimeAnalyzersResources.CA1017_AttributeTrue, context.Compilation.Assembly.Name)));
                    }
                }
                else
                {
                    // No ComVisible attribute at all.
                    context.ReportDiagnostic(Diagnostic.Create(Rule, Location.None, string.Format(SystemRuntimeAnalyzersResources.CA1017_NoAttribute, context.Compilation.Assembly.Name)));
                }
            }

            return;
        }
        private static void AnalyzeCompilation(CompilationAnalysisContext context)
        {
            if (AssemblyHasPublicTypes(context.Compilation.Assembly))
            {
                INamedTypeSymbol comVisibleAttributeSymbol = WellKnownTypes.ComVisibleAttribute(context.Compilation);
                if (comVisibleAttributeSymbol == null)
                {
                    return;
                }

                AttributeData attributeInstance = context.Compilation.Assembly.GetAttributes().FirstOrDefault(a => a.AttributeClass.Equals(comVisibleAttributeSymbol));

                if (attributeInstance != null)
                {
                    if (attributeInstance.ConstructorArguments.Length > 0 &&
                        attributeInstance.ConstructorArguments[0].Kind == TypedConstantKind.Primitive &&
                        attributeInstance.ConstructorArguments[0].Value != null &
                        attributeInstance.ConstructorArguments[0].Value.Equals(true))
                    {
                        // Has the attribute, with the value 'true'.
                        context.ReportDiagnostic(Diagnostic.Create(RuleA, Location.None, context.Compilation.Assembly.Name));
                    }
                }
                else
                {
                    // No ComVisible attribute at all.
                    context.ReportDiagnostic(Diagnostic.Create(RuleB, Location.None, context.Compilation.Assembly.Name));
                }
            }

            return;
        }
        private void AnalyzeCompilation(CompilationAnalysisContext context)
        {
            Trace.WriteLine("AnalyzeCompilation");

            try
            {
                INamedTypeSymbol dbContextTypeSymbol;
                IEnumerable<INamedTypeSymbol> entityTypeSymbols = SymbolHelper.GetAllEntityTypesFromDbContext(context.Compilation, out dbContextTypeSymbol);
                if (!entityTypeSymbols.Any())
                {
                    return;
                }

                var allTypeSymbols = context.Compilation.GetSymbolsWithName(s => !s.EndsWith("DbContext"), SymbolFilter.Type).Cast<INamedTypeSymbol>();
                var allMemberSymbols = allTypeSymbols.SelectMany(t => t.GetMembers().Where(m => m.Kind == SymbolKind.Property));
                Trace.WriteLine("Class count: " + allTypeSymbols.Count());
                Trace.WriteLine("Property count: " + allMemberSymbols.Count());

                var efRoslynTheorem = new EFRoslynTheorem();
                var result = efRoslynTheorem.Solve(entityTypeSymbols);
                if (result.Status == Status.Unsatisfiable)
                {
                    var classAssumptions = efRoslynTheorem.ClassAssumptions.ToList();
                    var propertyAssumptions = efRoslynTheorem.PropertyAssumptions.OrderBy(pa => pa.Rank).ToList();

                    do
                    {
                        result = TryToRemoveWrongAssumption(efRoslynTheorem, result, classAssumptions, propertyAssumptions);
                    } while (result != null && result.Status != Status.Satisfiable);

                    if (result == null || result.Status != Status.Satisfiable)
                    {
                        var diagnostic2 = Diagnostic.Create(UnsatisfiableRule, dbContextTypeSymbol.Locations[0], dbContextTypeSymbol.Name);
                        Trace.WriteLine("ReportDiagnostic " + diagnostic2.Descriptor.Id);
                        context.ReportDiagnostic(diagnostic2);
                        return;
                    }

                    var cacheId = EFRoslynTheoremCache.Add(context.Compilation, efRoslynTheorem, result);

                    var props = ImmutableDictionary.Create<string, string>();
                    props = props.Add("CacheId", cacheId);

                    var diagnostic = Diagnostic.Create(SatisfiableRule, dbContextTypeSymbol.Locations[0], props, dbContextTypeSymbol.Name);
                    Trace.WriteLine("ReportDiagnostic " + diagnostic.Descriptor.Id);
                    context.ReportDiagnostic(diagnostic);
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.ToString());
                throw;
            }
        }
        private static bool AnalyzeIdentifierTaskContinueWith(SyntaxNode method, CompilationAnalysisContext context, SemanticModel semanticModel)
        {
            var diagnosedIssue = false;

            foreach (SyntaxNode descendant in method.DescendantNodes())
            {
                if (descendant is IdentifierNameSyntax identifierName)
                {
                    var identifierText = identifierName.Identifier.ValueText;
                    if (identifierText == "ContinueWith")
                    {
                        if (!HasExecuteSynchronously(identifierName))
                        {
                            var memberAccessExpression = identifierName.Parent;

                            var diagnostic = Diagnostic.Create(Rule, memberAccessExpression.GetLocation(), "Task.ContinueWith");

                            context.ReportDiagnostic(diagnostic);

                            diagnosedIssue = true;
                        }
                    }
                }
            }

            return(diagnosedIssue);
        }
        public static BuildServiceProviderValidator CreateAndInitialize(CompilationAnalysisContext context, ConcurrentBag <StartupComputedAnalysis> analyses)
        {
            if (analyses == null)
            {
                throw new ArgumentNullException(nameof(analyses));
            }

            var validator = new BuildServiceProviderValidator();

            foreach (var serviceAnalysis in analyses.OfType <ServicesAnalysis>())
            {
                foreach (var serviceItem in serviceAnalysis.Services)
                {
                    if (serviceItem.UseMethod.Name == "BuildServiceProvider")
                    {
                        context.ReportDiagnostic(Diagnostic.Create(
                                                     StartupAnalzyer.BuildServiceProviderShouldNotCalledInConfigureServicesMethod,
                                                     serviceItem.Operation.Syntax.GetLocation(),
                                                     serviceItem.UseMethod.Name,
                                                     serviceAnalysis.ConfigureServicesMethod.Name));
                    }
                }
            }

            return(validator);
        }
Ejemplo n.º 6
0
 /// <summary>
 /// Uses the supplied <paramref name="compilationEndContext"/> to report any file-parsing-related diagnostics.
 /// </summary>
 /// <param name="compilationEndContext">A context provided from a compilation end action.</param>
 public void ReportAnyParsingDiagnostics(CompilationAnalysisContext compilationEndContext)
 {
     foreach (Diagnostic diagnostic in ParsingDiagnostics)
     {
         compilationEndContext.ReportDiagnostic(diagnostic);
     }
 }
Ejemplo n.º 7
0
        public static void ReportProblems(
            CompilationAnalysisContext context,
            SemanticModel semanticModel,
            IEnumerable <ActivityFunctionDefinition> availableFunctions,
            IEnumerable <ActivityFunctionCall> calledFunctions)
        {
            foreach (var activityInvocation in calledFunctions)
            {
                var functionDefinition = availableFunctions.Where(x => x.FunctionName == activityInvocation.Name).FirstOrDefault();
                if (functionDefinition != null && activityInvocation.ReturnTypeNode != null)
                {
                    TryGetInvocationReturnType(semanticModel, activityInvocation, out ITypeSymbol invocationReturnType);
                    TryGetDefinitionReturnType(semanticModel, functionDefinition, out ITypeSymbol definitionReturnType);

                    if (!InputMatchesOrTaskOrCompatibleType(invocationReturnType, definitionReturnType))
                    {
                        var invocationTypeName = SyntaxNodeUtils.GetQualifiedTypeName(invocationReturnType);
                        var functionTypeName   = SyntaxNodeUtils.GetQualifiedTypeName(definitionReturnType);

                        var diagnostic = Diagnostic.Create(Rule, activityInvocation.InvocationExpression.GetLocation(), activityInvocation.Name, functionTypeName, invocationTypeName);

                        context.ReportDiagnostic(diagnostic);
                    }
                }
            }
        }
Ejemplo n.º 8
0
        internal static bool RegisterDiagnostic(SyntaxNode method, CompilationAnalysisContext context, SemanticModel semanticModel)
        {
            var diagnosedIssue = false;

            foreach (SyntaxNode descendant in method.DescendantNodes())
            {
                if (descendant is IdentifierNameSyntax identifierName)
                {
                    var identifierText = identifierName.Identifier.ValueText;
                    if (identifierText == "GetEnvironmentVariable" || identifierText == "GetEnvironmentVariables" || identifierText == "ExpandEnvironmentVariables")
                    {
                        var memberAccessExpression = identifierName.Parent;
                        var invocationExpression   = memberAccessExpression.Parent;
                        if (SyntaxNodeUtils.TryGetISymbol(semanticModel, memberAccessExpression, out ISymbol memberSymbol))
                        {
                            if (memberSymbol.ToString().StartsWith("System.Environment"))
                            {
                                var diagnostic = Diagnostic.Create(Rule, invocationExpression.GetLocation(), memberAccessExpression);

                                context.ReportDiagnostic(diagnostic);

                                diagnosedIssue = true;
                            }
                        }
                    }
                }
            }

            return(diagnosedIssue);
        }
Ejemplo n.º 9
0
 public static void ReportDiagnosticIfNonGenerated(this CompilationAnalysisContext context, Diagnostic diagnostic)
 {
     if (!diagnostic.Location.SourceTree.IsGenerated())
     {
         context.ReportDiagnostic(diagnostic);
     }
 }
        internal static bool RegisterDiagnostic(SyntaxNode method, CompilationAnalysisContext context, SemanticModel semanticModel)
        {
            var diagnosedIssue = false;

            foreach (SyntaxNode descendant in method.DescendantNodes())
            {
                if (descendant is IdentifierNameSyntax identifierName)
                {
                    var typeInfo = SyntaxNodeUtils.GetSyntaxTreeSemanticModel(semanticModel, identifierName).GetTypeInfo(identifierName);
                    if (typeInfo.Type != null)
                    {
                        var type = typeInfo.Type.ToString();
                        if (IsIOClass(type))
                        {
                            var diagnostic = Diagnostic.Create(Rule, identifierName.Identifier.GetLocation(), type);

                            context.ReportDiagnostic(diagnostic);

                            diagnosedIssue = true;
                        }
                    }
                }
            }

            return(diagnosedIssue);
        }
 public void HandleCompilation(CompilationAnalysisContext context)
 {
     if (Volatile.Read(ref this.documentationAnalysisDisabled))
     {
         context.ReportDiagnostic(Diagnostic.Create(Descriptor, Location.None));
     }
 }
Ejemplo n.º 12
0
            public void CompilationEndAction(CompilationAnalysisContext context)
            {
                if (_interfacesWithUnsecureMethods.Count == 0 || _secureTypes.Count == 0)
                {
                    // No violating types.
                    return;
                }

                // Report diagnostic for violating named types.
                foreach (INamedTypeSymbol secureType in _secureTypes)
                {
                    foreach (INamedTypeSymbol unsecureInterface in _interfacesWithUnsecureMethods)
                    {
                        if (secureType.AllInterfaces.Contains(unsecureInterface))
                        {
                            context.ReportDiagnostic(
                                Diagnostic.Create(
                                    Rule,
                                    secureType.Locations[0],
                                    secureType.Name,
                                    SecureTypeInterfaceName,
                                    unsecureInterface.Name));
                            break;
                        }
                    }
                }
            }
Ejemplo n.º 13
0
 public void EndCompilationAction(CompilationAnalysisContext context)
 {
     foreach (Diagnostic diagnostic in _diagnostics)
     {
         context.ReportDiagnostic(diagnostic);
     }
 }
        private static void AnalyzeCompilation(CompilationAnalysisContext context)
        {
            var compilation = context.Compilation;
            var allPlugins  = compilation.SyntaxTrees
                              .Select(x => x.GetCompilationUnitRoot())
                              .SelectMany(x => x.FindSyntax <ClassDeclarationSyntax>())
                              .Where(x => x.IsPluginClass())
                              .ToArray();
            var plugins = allPlugins.Where(x => x.IsExportIPlugin()).ToArray();

            foreach (var p in allPlugins)
            {
                var guidVaue = p.GetGuidMetadataValue();
                if (guidVaue == null)
                {
                    continue;                                   //GUID な Metadata がない場合はスルー
                }
                // GUID として解釈できない値か、IPlugin で未定義の GUID が指定されてたらアウト
                Guid guid;
                if (!Guid.TryParse(guidVaue, out guid) ||
                    plugins.All(x => x.GetGuidMetadataValue().ToUpper() != guidVaue.ToUpper()))
                {
                    context.ReportDiagnostic(Diagnostic.Create(InvalidGuidMetadataRule, p.GetLocation()));
                }
            }
        }
        private static void AnalyzeCompilation(CompilationAnalysisContext context)
        {
            var compilation = context.Compilation;
            var plugins     = compilation.SyntaxTrees
                              .Select(x => x.GetCompilationUnitRoot())
                              .SelectMany(x => x.FindSyntax <ClassDeclarationSyntax>())
                              .Where(x => x.IsExportIPlugin())
                              .ToArray();

            var dupe = plugins
                       .GroupBy(x => x.GetGuidMetadataValue(compilation.GetSemanticModel(x.SyntaxTree)))
                       .Where(x => 1 < x.Count())
                       .ToArray();

            if (!dupe.Any())
            {
                return;
            }

            foreach (var group in dupe)
            {
                foreach (var c in group)
                {
                    var other = group.Except(new[] { c }).ToArray();
                    context.ReportDiagnostic(Diagnostic.Create(
                                                 DuplicateGuidRule,
                                                 c.GetLocation(),
                                                 string.Join(", ", other.Select(x => x.Identifier))));
                }
            }
        }
Ejemplo n.º 16
0
        private void AnalyzeDbContext(CompilationAnalysisContext context)
        {
            var visitor = new DbContextSymbolsVisitor();

            visitor.Visit(context.Compilation.GlobalNamespace);

            var entities = visitor.EntityExtensions.Select(s => s.Name).ToArray();

            foreach (var dbContext in visitor.DbContextExtensions)
            {
                var dbSets = dbContext
                             .GetMembers()
                             .OfType <IPropertySymbol>()
                             .Select(p => p.Type)
                             .OfType <INamedTypeSymbol>()
                             .Where(t => t.Name == "DbSet" && t.TypeArguments.Length == 1)
                             .Select(t => t.TypeArguments.ElementAt(0).Name)
                             .ToArray();

                var missingEntities = entities.Except(dbSets).ToArray();

                if (missingEntities.Any())
                {
                    foreach (var location in dbContext.Locations)
                    {
                        context.ReportDiagnostic(Diagnostic.Create(DbContextMissingDbSetPropertiesRule, location, new[] { dbContext.Name, string.Join <string>(", ", missingEntities) }));
                    }
                }
            }
        }
Ejemplo n.º 17
0
 private static void DumpAdditionalFiles(CompilationAnalysisContext context)
 {
     foreach (AdditionalText additionalFile in context.Options.AdditionalFiles)
     {
         context.ReportDiagnostic(Diagnostic.Create(diagnostic, Location.None, additionalFile.Path));
     }
 }
Ejemplo n.º 18
0
		private static void AnalyzeCompilation(CompilationAnalysisContext context)
		{
			var compilation = context.Compilation;
			var plugins = compilation.SyntaxTrees
				.Select(x => x.GetCompilationUnitRoot())
				.SelectMany(x => x.FindSyntax<ClassDeclarationSyntax>())
				.Where(x => x.IsExportIPlugin())
				.ToArray();

			var dupe = plugins
				.GroupBy(x => x.GetGuidMetadataValue())
				.Where(x => 1 < x.Count())
				.ToArray();

			if (!dupe.Any()) return;

			foreach (var group in dupe)
			{
				foreach (var c in group)
				{
					var other = group.Except(new[] { c }).ToArray();
					context.ReportDiagnostic(Diagnostic.Create(
						DuplicateGuidRule,
						c.GetLocation(),
						string.Join(", ", other.Select(x => x.Identifier))));
				}
			}
		}
 private void AnalyzeWarningLevel(CompilationAnalysisContext context)
 {
     if (context.Compilation.Options.WarningLevel < 4)
     {
         context.ReportDiagnostic(Diagnostic.Create(Rule, Location.None));
     }
 }
        public static bool RegisterDiagnostic(CompilationAnalysisContext context, SyntaxNode method)
        {
            var diagnosedIssue = false;

            if (SyntaxNodeUtils.IsInsideOrchestrationTrigger(method))
            {
                foreach (SyntaxNode descendant in method.DescendantNodes())
                {
                    if (descendant is ParameterSyntax parameter)
                    {
                        var identifierType = parameter.Type;
                        if (identifierType != null && identifierType.ToString() == "CancellationToken")
                        {
                            var diagnostic = Diagnostic.Create(Rule, parameter.GetLocation());

                            context.ReportDiagnostic(diagnostic);

                            diagnosedIssue = true;
                        }
                    }
                }
            }

            return(diagnosedIssue);
        }
 public void HandleCompilation(CompilationAnalysisContext context)
 {
     if (Volatile.Read(ref this.documentationAnalysisDisabled))
     {
         context.ReportDiagnostic(Diagnostic.Create(Descriptor, Location.None));
     }
 }
        private static bool AnalyzeIdentifierTask(SyntaxNode method, CompilationAnalysisContext context, SemanticModel semanticModel)
        {
            var diagnosedIssue = false;

            foreach (SyntaxNode descendant in method.DescendantNodes())
            {
                if (descendant is IdentifierNameSyntax identifierName)
                {
                    var identifierText = identifierName.Identifier.ValueText;
                    if (identifierText == "Run" || identifierText == "Factory.StartNew")
                    {
                        var memberAccessExpression = identifierName.Parent;
                        if (SyntaxNodeUtils.TryGetISymbol(semanticModel, memberAccessExpression, out ISymbol memberSymbol))
                        {
                            if (memberSymbol.ToString().StartsWith("System.Threading.Tasks.Task"))
                            {
                                var diagnostic = Diagnostic.Create(Rule, memberAccessExpression.GetLocation(), memberAccessExpression);

                                context.ReportDiagnostic(diagnostic);

                                diagnosedIssue = true;
                            }
                        }
                    }
                }
            }

            return(diagnosedIssue);
        }
            internal void CompilationEnd(CompilationAnalysisContext context)
            {
                if (_codeFixProviders == null)
                {
                    // No fixers.
                    return;
                }

                if (_codeActionCreateInvocations == null && _codeActionObjectCreations == null)
                {
                    // No registered fixes.
                    return;
                }

                // Analyze all fixers that have FixAll support.
                // Otherwise, report RS1016 (OverrideGetFixAllProviderRule) to recommend adding FixAll support.
                foreach (INamedTypeSymbol fixer in _codeFixProviders)
                {
                    if (OverridesGetFixAllProvider(fixer))
                    {
                        AnalyzeFixerWithFixAll(fixer, context);
                    }
                    else if (fixer.BaseType != null && fixer.BaseType.Equals(_codeFixProviderSymbol))
                    {
                        Diagnostic diagnostic = Diagnostic.Create(OverrideGetFixAllProviderRule, fixer.Locations.First(), fixer.Name);
                        context.ReportDiagnostic(diagnostic);
                    }
                }
            }
Ejemplo n.º 24
0
        private string CheckAttribute(XElement element,
                                      string attributeName,
                                      string defaultValue,
                                      Func <string, bool> isGoodValue,
                                      DiagnosticDescriptor diagnosticDescriptor,
                                      XElement lastFoundElement,
                                      AdditionalText file,
                                      CompilationAnalysisContext context)
        {
            var attributeValue = element?.Attribute(attributeName);
            var value          = attributeValue?.Value ?? defaultValue;

            var v = value.Trim();

            if (isGoodValue(v))
            {
                return(v);
            }

            var lineInfo   = (IXmlLineInfo)lastFoundElement;
            int lineNumber = lastFoundElement != null && lineInfo.HasLineInfo() ? lineInfo.LineNumber : 1;

            context.ReportDiagnostic(ExternalDiagnostic.Create(diagnosticDescriptor,
                                                               file.Path,
                                                               lineNumber,
                                                               lastFoundElement.ToStringStartElement()));

            return(v);
        }
Ejemplo n.º 25
0
        private static bool AnalyzeIdentifierTask(SyntaxNode method, CompilationAnalysisContext context, SemanticModel semanticModel)
        {
            var diagnosedIssue = false;

            foreach (SyntaxNode descendant in method.DescendantNodes())
            {
                if (descendant is IdentifierNameSyntax identifierName)
                {
                    version = SyntaxNodeUtils.GetDurableVersion(semanticModel);

                    var identifierText = identifierName.Identifier.ValueText;
                    if (identifierText == "Delay")
                    {
                        var memberAccessExpression = identifierName.Parent;
                        var memberSymbol           = SyntaxNodeUtils.GetSyntaxTreeSemanticModel(semanticModel, memberAccessExpression).GetSymbolInfo(memberAccessExpression).Symbol;

                        if (memberSymbol != null && memberSymbol.ToString().StartsWith("System.Threading.Tasks.Task"))
                        {
                            if (TryGetRuleFromVersion(out DiagnosticDescriptor rule))
                            {
                                var expression = GetAwaitOrInvocationExpression(memberAccessExpression);

                                var diagnostic = Diagnostic.Create(rule, expression.GetLocation(), expression);

                                context.ReportDiagnostic(diagnostic);

                                diagnosedIssue = true;
                            }
                        }
                    }
                }
            }

            return(diagnosedIssue);
        }
Ejemplo n.º 26
0
        private static bool AnalyzeIdentifierThread(SyntaxNode method, CompilationAnalysisContext context, SemanticModel semanticModel)
        {
            var diagnosedIssue = false;

            foreach (SyntaxNode descendant in method.DescendantNodes())
            {
                if (descendant is IdentifierNameSyntax identifierName)
                {
                    var identifierText = identifierName.Identifier.ValueText;
                    if (identifierText == "Start")
                    {
                        var memberAccessExpression = identifierName.Parent;
                        var memberSymbol           = SyntaxNodeUtils.GetSyntaxTreeSemanticModel(semanticModel, memberAccessExpression).GetSymbolInfo(memberAccessExpression).Symbol;

                        if (memberSymbol != null && memberSymbol.ToString().StartsWith("System.Threading.Thread"))
                        {
                            var diagnostic = Diagnostic.Create(Rule, memberAccessExpression.GetLocation(), memberAccessExpression);

                            context.ReportDiagnostic(diagnostic);

                            diagnosedIssue = true;
                        }
                    }
                }
            }

            return(diagnosedIssue);
        }
		private static void AnalyzeCompilation(CompilationAnalysisContext context)
		{
			var compilation = context.Compilation;
			var allPlugins = compilation.SyntaxTrees
				.Select(x => x.GetCompilationUnitRoot())
				.SelectMany(x => x.FindSyntax<ClassDeclarationSyntax>())
				.Where(x => x.IsPluginClass())
				.ToArray();
			var plugins = allPlugins.Where(x => x.IsExportIPlugin()).ToArray();
			
			foreach (var p in allPlugins)
			{
				var semanticModel = compilation.GetSemanticModel(p.SyntaxTree);
				var syntax = p.GetGuidMetadataValueSyntax();
				if (syntax == null) continue;	//GUID な Metadata がない場合はスルー

				// GUID として解釈できない値か、IPlugin で未定義の GUID が指定されてたらアウト
				var guidMetadata = syntax.GetGuidMetadata(semanticModel);
				if (!guidMetadata.HasValue
					|| plugins.All(x => x.GetGuidMetadataValueSyntax()?.GetGuidMetadata(compilation.GetSemanticModel(x.SyntaxTree)) != guidMetadata))
				{
					context.ReportDiagnostic(Diagnostic.Create(InvalidGuidMetadataRule, p.GetLocation()));
				}
			}
		}
        private void Analyze(CompilationAnalysisContext context)
        {
            foreach (var attribute in context.Compilation.Assembly.GetAttributes())
            {
                if (attribute.AttributeClass.Name != "InternalsVisibleToAttribute" ||
                    attribute.ConstructorArguments.Length != 1)
                {
                    continue;
                }

                var parameter = Convert.ToString(attribute.ConstructorArguments[0].Value);
                var allowed   = false;

                foreach (var suffix in AllowedSuffixes)
                {
                    if (parameter.IndexOf(suffix, StringComparison.OrdinalIgnoreCase) != -1)
                    {
                        allowed = true;
                        break;
                    }
                }

                if (!allowed)
                {
                    context.ReportDiagnostic(
                        Diagnostic.Create(Descriptors.AZC0011,
                                          attribute.ApplicationSyntaxReference.GetSyntax().GetLocation()));
                }
            }
        }
Ejemplo n.º 29
0
        private void onCompilation(CompilationAnalysisContext context)
        {
            if (!context.Options.AdditionalFiles.Any())
            {
                return;
            }

            var srcFiles = FileFilter.GetFiles(context.Options.AdditionalFiles).ToList();

            if (!srcFiles.Any())
            {
                return;
            }

            foreach (IAdditionalTextAnalyzer analyzer in Analyzers)
            {
                var diagnosticInfo = analyzer.GetDiagnosticInfo(srcFiles, context.CancellationToken);
                foreach (var info in diagnosticInfo)
                {
                    var supportedDiagnostic = GetSupportedDiagnosticAttribute(analyzer);
                    var diagnostic          = DiagnosticFactory.Create(supportedDiagnostic.GetDescriptor(), info);

                    context.ReportDiagnostic(diagnostic);
                }
            }
        }
Ejemplo n.º 30
0
            internal void AnalyzeCompilationEnd(CompilationAnalysisContext context)
            {
                if (!_hasMemberNamedSymbolDeclaredEvent)
                {
                    return;
                }

                foreach ((INamedTypeSymbol sourceSymbol, _) in _sourceSymbolsToCheck)
                {
                    var found = false;
                    foreach (INamedTypeSymbol type in sourceSymbol.GetBaseTypesAndThis())
                    {
                        if (_typesWithSymbolDeclaredEventInvoked.ContainsKey(type))
                        {
                            found = true;
                            break;
                        }
                    }

                    if (!found)
                    {
                        Diagnostic diagnostic = Diagnostic.Create(SymbolDeclaredEventRule, sourceSymbol.Locations[0], sourceSymbol.Name, _compilationType.Name, SymbolDeclaredEventName);
                        context.ReportDiagnostic(diagnostic);
                    }
                }
            }
Ejemplo n.º 31
0
 private static void Analyze(CompilationAnalysisContext context)
 {
     if (!Analyze(context.Compilation))
     {
         context.ReportDiagnostic(Diagnostic.Create(DUR0004_DurianModulesAreValidOnlyInCSharp, Location.None));
     }
 }
Ejemplo n.º 32
0
        public static void AnalyzeCompilation(
            CompilationAnalysisContext ctx
            )
        {
            bool hasAnnotationsReference = ctx.Compilation
                                           .References
                                           .Any(IsTheAnnotationsAssembly);

            if (!hasAnnotationsReference)
            {
                ctx.ReportDiagnostic(
                    Diagnostic.Create(
                        Diagnostics.MustReferenceAnnotations,
                        Location.None
                        )
                    );
            }

            // TODO:
            // * How does VS sometimes offer you "Add reference to foo.dll" as
            //   a fix?
            // * Does it look at what other projects in the solution reference
            //   to get a symbol? That'd be  too complicated to implement here.
            // * Can we use their fix somehow?
            // * Should we open up a GitHub issue for this?
        }
Ejemplo n.º 33
0
        public static bool RegisterDiagnostic(SyntaxNode method, CompilationAnalysisContext context, SemanticModel semanticModel)
        {
            var diagnosedIssue = false;

            foreach (SyntaxNode descendant in method.DescendantNodes())
            {
                if (descendant is IdentifierNameSyntax identifierName)
                {
                    var identifierText = identifierName.Identifier.ValueText;
                    if (identifierText == "Now" || identifierText == "UtcNow" || identifierText == "Today")
                    {
                        var memberAccessExpression = identifierName.Parent;
                        if (SyntaxNodeUtils.TryGetISymbol(semanticModel, memberAccessExpression, out ISymbol memberSymbol))
                        {
                            //Covers both DateTime and DateTimeOffset
                            if (memberSymbol.ToString().StartsWith("System.DateTime"))
                            {
                                var diagnostic = Diagnostic.Create(Rule, memberAccessExpression.GetLocation(), memberAccessExpression);

                                context.ReportDiagnostic(diagnostic);

                                diagnosedIssue = true;
                            }
                        }
                    }
                }
            }

            return(diagnosedIssue);
        }
Ejemplo n.º 34
0
 public static void ReportDiagnostic(this CompilationAnalysisContext context, DiagnosticDescriptor descriptor, ImmutableDictionary <string, string>?properties, ISymbol symbol, params string[] messageArgs)
 {
     foreach (var location in symbol.Locations)
     {
         context.ReportDiagnostic(CreateDiagnostic(descriptor, location, properties, messageArgs));
     }
 }
 public void Evaluate(CompilationAnalysisContext compilationEndContext)
 {
     Parallel.ForEach(_badNodes, (identifierNameSyntax) =>
     {
         var diagnostic = DiagnosticFormatter.CreateDiagnostic(Rule, identifierNameSyntax);
         compilationEndContext.ReportDiagnostic(diagnostic);
     });
 }
Ejemplo n.º 36
0
 private void OnCompilation(CompilationAnalysisContext context)
 {
     // Report the hidden diagnostic on all trees in compilation.
     foreach (var tree in context.Compilation.SyntaxTrees)
     {
         context.ReportDiagnostic(Diagnostic.Create(Descriptor, tree.GetRoot().GetLocation()));
     }
 }
Ejemplo n.º 37
0
 private static void OnCompilation(CompilationAnalysisContext context)
 {
     var diags = OnCompilationAsync(context.Compilation).Result;
     foreach (var d in diags)
     {
         context.ReportDiagnostic(d);
     }
 }
 public void AnalyzeCompilation(CompilationAnalysisContext context)
 {
     foreach (var item in _fieldDisposedMap)
     {
         if (!item.Value)
         {
             context.ReportDiagnostic(item.Key.CreateDiagnostic(Rule));
         }
     }
 }
Ejemplo n.º 39
0
        private static void AnalyzeCompilation(CompilationAnalysisContext context)
        {
            // Get all the suppressed analyzer diagnostic IDs.
            var suppressedAnalyzerDiagnosticIds = GetSuppressedAnalyzerDiagnosticIds(context.Compilation.Options.SpecificDiagnosticOptions);

            foreach (var suppressedDiagnosticId in suppressedAnalyzerDiagnosticIds)
            {
                // For all such suppressed diagnostic IDs, produce a diagnostic.
                var diagnostic = Diagnostic.Create(Rule, Location.None, suppressedDiagnosticId);
                context.ReportDiagnostic(diagnostic);
            }
        }
Ejemplo n.º 40
0
		private static void AnalyzeCompilation(CompilationAnalysisContext context)
		{
			var compilation = context.Compilation;
			var isDefined = compilation.SyntaxTrees
				.Select(x => x.GetCompilationUnitRoot())
				.SelectMany(x => x.DescendantNodes().OfType<SimpleBaseTypeSyntax>())
				.Any(x => x.ToString() == "IPlugin" || x.ToString() == "Grabacr07.KanColleViewer.Composition.IPlugin")
				;

			if (!isDefined)
				context.ReportDiagnostic(Diagnostic.Create(RequireIPluginRule, Location.None));
		}
        private static void AnalyzeCompilation(CompilationAnalysisContext context)
        {
            INamedTypeSymbol assemblyVersionAttributeSymbol = WellKnownTypes.AssemblyVersionAttribute(context.Compilation);
            INamedTypeSymbol assemblyComplianceAttributeSymbol = WellKnownTypes.CLSCompliantAttribute(context.Compilation);

            if (assemblyVersionAttributeSymbol == null && assemblyComplianceAttributeSymbol == null)
            {
                return;
            }

            bool assemblyVersionAttributeFound = false;
            bool assemblyComplianceAttributeFound = false;

            // Check all assembly level attributes for the target attribute
            foreach (AttributeData attribute in context.Compilation.Assembly.GetAttributes())
            {
                if (attribute.AttributeClass.Equals(assemblyVersionAttributeSymbol))
                {
                    // Mark the version attribute as found
                    assemblyVersionAttributeFound = true;
                }
                else if (attribute.AttributeClass.Equals(assemblyComplianceAttributeSymbol))
                {
                    // Mark the compliance attribute as found
                    assemblyComplianceAttributeFound = true;
                }
            }

            if (!assemblyVersionAttributeFound && assemblyVersionAttributeSymbol != null)
            {
                context.ReportDiagnostic(Diagnostic.Create(CA1016Rule, Location.None));
            }

            if (!assemblyComplianceAttributeFound && assemblyComplianceAttributeSymbol != null)
            {
                context.ReportDiagnostic(Diagnostic.Create(CA1014Rule, Location.None));
            }
        }
Ejemplo n.º 42
0
 private void OnCompilationEnd(CompilationAnalysisContext context)
 {
     lock (_apisToEnsureExist)
     {
         if (_apisToEnsureExist.Count != 0)
         {
             // If we have not cleared the list of APIs that must exist then we need to give errors about them
             foreach (var missingAPI in _apisToEnsureExist)
             {
                 context.ReportDiagnostic(Diagnostic.Create(s_memberMustExistDiagnostic, Location.None, missingAPI));
             }
         }
     }
 }
        private static void HandleCompilation(CompilationAnalysisContext context)
        {
            try
            {
                SettingsHelper.GetStyleCopSettings(context.Options, DeserializationFailureBehavior.ThrowException, context.CancellationToken);
            }
            catch (JsonException ex)
            {
                string details = ex.Message;
                string completeDescription = string.Format(Description.ToString(CultureInfo.CurrentCulture), details);

                var completeDescriptor = new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, AnalyzerCategory.SpecialRules, DiagnosticSeverity.Warning, AnalyzerConstants.EnabledByDefault, completeDescription, HelpLink);
                context.ReportDiagnostic(Diagnostic.Create(completeDescriptor, Location.None));
            }
        }
        private void AnalizeCompilation(CompilationAnalysisContext context)
        {
            // Find CS0006: Metadata file '{0}' could not be found
            Diagnostic invalidMetadataDiagnostic = context.Compilation
                .GetDiagnostics().FirstOrDefault(d => string.Compare(d.Id, "CS0006") == 0);

            if (invalidMetadataDiagnostic != null)
            {
                var argument = invalidMetadataDiagnostic.GetDiagnosticMessageArguments().First().ToString();
                if (argument != null && string.Compare(Path.GetExtension(argument), ".dll") == 0)
                {
                    var diagnostic = Diagnostic.Create(_supportedRule, invalidMetadataDiagnostic.Location,
                        argument, ".dll");

                    context.ReportDiagnostic(diagnostic);
                }
            }
        }
		private static void AnalyzeCompilation(CompilationAnalysisContext context)
		{
			var compilation = context.Compilation;
			var allPlugins = compilation.SyntaxTrees
				.Select(x => x.GetCompilationUnitRoot())
				.SelectMany(x => x.FindSyntax<ClassDeclarationSyntax>())
				.Where(x => x.IsPluginClass())
				.ToArray();
			var plugins = allPlugins.Where(x => x.IsExportIPlugin()).ToArray();

			foreach (var p in allPlugins)
			{
				var guidVaue = p.GetGuidMetadataValue();
				if (guidVaue == null) continue;	//GUID な Metadata がない場合はスルー

				// GUID として解釈できない値か、IPlugin で未定義の GUID が指定されてたらアウト
				Guid guid;
				if (!Guid.TryParse(guidVaue, out guid)
					|| plugins.All(x => x.GetGuidMetadataValue().ToUpper() != guidVaue.ToUpper()))
					context.ReportDiagnostic(Diagnostic.Create(InvalidGuidMetadataRule, p.GetLocation()));
			}
		}
 void Report(CompilationAnalysisContext context, IFieldSymbol field, DiagnosticDescriptor descriptor)
 {
     context.ReportDiagnostic(Diagnostic.Create(descriptor, field.Locations.FirstOrDefault()));
 }
 //reports a diagnostics
 private static void ReportDiagnostic(CompilationAnalysisContext context, DiagnosticDescriptor rule, Location location, params string[] messageArgs)
 {
     Diagnostic diagnostic = Diagnostic.Create(rule, location, messageArgs);
     context.ReportDiagnostic(diagnostic);
 }
        private void AnalyzeCompilation(CompilationAnalysisContext context)
        {
            INamedTypeSymbol assemblyVersionAttributeSymbol = WellKnownTypes.AssemblyVersionAttribute(context.Compilation);
            INamedTypeSymbol assemblyComplianceAttributeSymbol = WellKnownTypes.CLSCompliantAttribute(context.Compilation);

            if (assemblyVersionAttributeSymbol == null && assemblyComplianceAttributeSymbol == null)
            {
                return;
            }

            bool assemblyVersionAttributeFound = false;
            bool assemblyComplianceAttributeFound = false;

            // Check all assembly level attributes for the target attribute
            foreach (AttributeData attribute in context.Compilation.Assembly.GetAttributes())
            {
                if (attribute.AttributeClass.Equals(assemblyVersionAttributeSymbol))
                {
                    // Mark the version attribute as found
                    assemblyVersionAttributeFound = true;
                }
                else if (attribute.AttributeClass.Equals(assemblyComplianceAttributeSymbol))
                {
                    // Mark the compliance attribute as found
                    assemblyComplianceAttributeFound = true;
                }
            }

            // Check for the case where we do not have the target attribute defined at all in our metadata references. If so, how can they reference it
            if (assemblyVersionAttributeSymbol == null)
            {
                assemblyVersionAttributeFound = false;
            }

            if (assemblyComplianceAttributeSymbol == null)
            {
                assemblyComplianceAttributeFound = false;
            }

            // If there's at least one diagnostic to report, let's report them
            if (!assemblyComplianceAttributeFound || !assemblyVersionAttributeFound)
            {
                if (!assemblyVersionAttributeFound)
                {
                    context.ReportDiagnostic(Diagnostic.Create(CA1016Rule, Location.None));
                }

                if (!assemblyComplianceAttributeFound)
                {
                    context.ReportDiagnostic(Diagnostic.Create(CA1014Rule, Location.None));
                }
            }
        }
        private static void ReportDisposeMethods(ImmutableHashSet<IMethodSymbol> allDisposeMethods, ImmutableHashSet<IMethodSymbol> implementingDisposeMethods,
            ImmutableDictionary<INamedTypeSymbol, ImmutableHashSet<IMethodSymbol>> disposeMethodsCalledFromDispose, CompilationAnalysisContext c)
        {
            foreach (var dispose in allDisposeMethods.Except(implementingDisposeMethods))
            {
                if (MethodCalledFromDispose(disposeMethodsCalledFromDispose, dispose))
                {
                    continue;
                }

                foreach (var declaringSyntaxReference in dispose.DeclaringSyntaxReferences)
                {
                    var methodDeclaration =
                        declaringSyntaxReference.GetSyntax() as MethodDeclarationSyntax;
                    if (methodDeclaration != null)
                    {
                        c.ReportDiagnostic(Diagnostic.Create(Rule, methodDeclaration.Identifier.GetLocation()));
                    }
                }
            }
        }
Ejemplo n.º 50
0
 private void OnCompilation(CompilationAnalysisContext context)
 {
     // Report the hidden diagnostic on all trees in compilation.
     foreach (var tree in context.Compilation.SyntaxTrees)
     {
         context.ReportDiagnostic(Diagnostic.Create(Descriptor, tree.GetRoot().GetLocation()));
     }
 }
 internal void OnCompilationEnd(CompilationAnalysisContext context)
 {
     List<ApiLine> deletedApiList = GetDeletedApiList();
     foreach (ApiLine cur in deletedApiList)
     {
         LinePositionSpan linePositionSpan = cur.SourceText.Lines.GetLinePositionSpan(cur.Span);
         Location location = Location.Create(cur.Path, cur.Span, linePositionSpan);
         ImmutableDictionary<string, string> propertyBag = ImmutableDictionary<string, string>.Empty.Add(PublicApiNamePropertyBagKey, cur.Text);
         context.ReportDiagnostic(Diagnostic.Create(RemoveDeletedApiRule, location, propertyBag, cur.Text));
     }
 }
Ejemplo n.º 52
0
		/// <summary>
		///   Emits a diagnostic for <paramref name="symbol" /> using the <paramref name="messageArgs" /> to format the
		///   diagnostic message.
		/// </summary>
		/// <param name="context">The context in which the diagnostic should be emitted.</param>
		/// <param name="symbol">The symbol node the diagnostic is emitted for.</param>
		/// <param name="messageArgs">The arguments for formatting the diagnostic message.</param>
		public void Emit(CompilationAnalysisContext context, [NotNull] ISymbol symbol, params object[] messageArgs)
		{
			context.ReportDiagnostic(CreateDiagnostic(symbol.Locations[0], messageArgs));
		}
        private void AnalyzeCompilation(CompilationAnalysisContext context)
        {
            // Get the particular attributes I need to look for.
            var companyAttributeSymbol = KnownTypes.CompanyAttribute(context.Compilation);
            var copyrightAttributeSymbol = KnownTypes.CopyrightAttribute(context.Compilation);
            var descriptionAttributeSymbol = KnownTypes.DescriptionAttribute(context.Compilation);
            var titleAttributeSymbol = KnownTypes.TitleAttribute(context.Compilation);

            // Assume they are all not found.
            Boolean companyAttributeGood = false;
            Boolean copyrightAttributeGood = false;
            Boolean descriptionAttributeGood = false;
            Boolean titleAttributeGood = false;

            // Pound through each attribute in the assembly checking that the specific ones
            // are present and the parameters are not empty.
            foreach (var attribute in context.Compilation.Assembly.GetAttributes())
            {
                if ((companyAttributeSymbol != null) && (attribute.AttributeClass.Equals(companyAttributeSymbol)))
                {
                    companyAttributeGood = CheckAttributeParameter(attribute);
                    continue;
                }

                if ((copyrightAttributeSymbol != null) && (attribute.AttributeClass.Equals(copyrightAttributeSymbol)))
                {
                    copyrightAttributeGood = CheckAttributeParameter(attribute);
                    continue;
                }

                if ((descriptionAttributeSymbol != null) && (attribute.AttributeClass.Equals(descriptionAttributeSymbol)))
                {
                    descriptionAttributeGood = CheckAttributeParameter(attribute);
                    continue;
                }

                if ((titleAttributeSymbol != null) && (attribute.AttributeClass.Equals(titleAttributeSymbol)))
                {
                    titleAttributeGood = CheckAttributeParameter(attribute);
                    continue;
                }
            }

            // If any of the assembly wide attributes are missing or empty, trigger a warning.
            if (!companyAttributeGood)
            {
                context.ReportDiagnostic(Diagnostic.Create(companyRule, Location.None));
            }

            if (!copyrightAttributeGood)
            {
                context.ReportDiagnostic(Diagnostic.Create(copyrightRule, Location.None));
            }

            if (!descriptionAttributeGood)
            {
                context.ReportDiagnostic(Diagnostic.Create(descriptionRule, Location.None));
            }

            if (!titleAttributeGood)
            {
                context.ReportDiagnostic(Diagnostic.Create(titleRule, Location.None));
            }
        }
 private void ReportUnwrittenFields(CompilationAnalysisContext context)
 {
     IEnumerable<IFieldSymbol> fieldsToMark = _candidateReadonlyFields.Except(_writtenFields);
     foreach (var field in fieldsToMark)
     {
         context.ReportDiagnostic(Diagnostic.Create(s_rule, field.Locations[0], field.Name));
     }
 }
        public void HandleCompilation(CompilationAnalysisContext context)
        {
            var compilation = context.Compilation;
            var globalNamespace = compilation.GlobalNamespace;
            var ruleDependencyAttributeSymbols = GetRuleDependencyAttributeTypeSymbols(globalNamespace);

            // if ANTLR 4 isn't referenced, no need to run this analyzer
            if (ruleDependencyAttributeSymbols.Length == 0)
                return;

            IEnumerable<INamedTypeSymbol> typesToCheck = GetAllTypes(compilation.SourceModule.GlobalNamespace);
            var builder = ImmutableArray.CreateBuilder<Tuple<AttributeData, ISymbol>>();
            foreach (var type in typesToCheck)
                builder.AddRange(GetDependencies(type, ruleDependencyAttributeSymbols));

            var dependencies = builder.ToImmutable();
            if (dependencies.Length == 0)
                return;

            var recognizerDependencies = new Dictionary<INamedTypeSymbol, IList<Tuple<AttributeData, ISymbol>>>();
            foreach (var dependency in dependencies)
            {
                if (dependency.Item1.AttributeConstructor == null)
                    continue;

                INamedTypeSymbol recognizerType = GetRecognizerType(dependency.Item1);
                if (recognizerType == null)
                    continue;

                IList<Tuple<AttributeData, ISymbol>> list;
                if (!recognizerDependencies.TryGetValue(recognizerType, out list))
                {
                    list = new List<Tuple<AttributeData, ISymbol>>();
                    recognizerDependencies[recognizerType] = list;
                }

                list.Add(dependency);
            }

            foreach (var entry in recognizerDependencies)
            {
                var diagnostics = CheckDependencies((CSharpCompilation)compilation, entry.Value, entry.Key);
                foreach (var diagnostic in diagnostics)
                    context.ReportDiagnostic(diagnostic);
            }
        }
            public void CompilationEndAction(CompilationAnalysisContext context)
            {
                if (_interfacesWithUnsecureMethods == null || _secureTypes == null)
                {
                    // No violating types.
                    return;
                }

                // Report diagnostic for violating named types.
                foreach (var secureType in _secureTypes)
                {
                    foreach (var unsecureInterface in _interfacesWithUnsecureMethods)
                    {
                        if (secureType.AllInterfaces.Contains(unsecureInterface))
                        {
                            var diagnostic = Diagnostic.Create(Rule, secureType.Locations[0], secureType.Name, SecureTypeInterfaceName, unsecureInterface.Name);
                            context.ReportDiagnostic(diagnostic);

                            break;
                        }
                    }
                }
            }