/// <summary>
 /// Creates a new <see cref="CompilationWithAnalyzersOptions"/>.
 /// </summary>
 /// <param name="options">Options that are passed to analyzers.</param>
 /// <param name="onAnalyzerException">Action to invoke if an analyzer throws an exception.</param>
 /// <param name="concurrentAnalysis">Flag indicating whether analysis can be performed concurrently on multiple threads.</param>
 /// <param name="logAnalyzerExecutionTime">Flag indicating whether analyzer execution time should be logged.</param>
 public CompilationWithAnalyzersOptions(AnalyzerOptions options, Action<Exception, DiagnosticAnalyzer, Diagnostic> onAnalyzerException, bool concurrentAnalysis, bool logAnalyzerExecutionTime)
 {
     _options = options;
     _onAnalyzerException = onAnalyzerException;
     _concurrentAnalysis = concurrentAnalysis;
     _logAnalyzerExecutionTime = logAnalyzerExecutionTime;
 }
        public IDiagnosticAnalyzer CreateAnalyzerWithinCompilation(Compilation compilation, AnalyzerOptions options, CancellationToken cancellationToken)
        {
            var eventHandler = WellKnownTypes.EventHandler(compilation);
            if (eventHandler == null)
            {
                return null;
            }

            var genericEventHandler = WellKnownTypes.GenericEventHandler(compilation);
            if (genericEventHandler == null)
            {
                return null;
            }

            var eventArgs = WellKnownTypes.EventArgs(compilation);
            if (eventArgs == null)
            {
                return null;
            }

            var comSourceInterfacesAttribute = WellKnownTypes.ComSourceInterfaceAttribute(compilation);
            if (comSourceInterfacesAttribute == null)
            {
                return null;
            }

            return GetAnalyzer(compilation, eventHandler, genericEventHandler, eventArgs, comSourceInterfacesAttribute);
        }
        /// <summary>
        /// Create an analyzer driver.
        /// </summary>
        /// <param name="analyzers">The set of analyzers to include in the analysis</param>
        /// <param name="options">Options that are passed to analyzers</param>
        /// <param name="cancellationToken">a cancellation token that can be used to abort analysis</param>
        /// <param name="continueOnAnalyzerException">Delegate which is invoked when an analyzer throws an exception.
        /// If a non-null delegate is provided and it returns true, then the exception is handled and converted into a diagnostic and driver continues with other analyzers.
        /// Otherwise if it returns false, then the exception is not handled by the driver.
        /// If null, then the driver always handles the exception.
        /// </param>
        protected AnalyzerDriver(ImmutableArray<IDiagnosticAnalyzer> analyzers, AnalyzerOptions options, CancellationToken cancellationToken, Func<Exception, IDiagnosticAnalyzer, bool> continueOnAnalyzerException = null)
        {
            this.CompilationEventQueue = new AsyncQueue<CompilationEvent>();
            this.DiagnosticQueue = new AsyncQueue<Diagnostic>();
            this.addDiagnostic = GetDiagnosticSinkWithSuppression();
            this.analyzerOptions = options;

            Func<Exception, IDiagnosticAnalyzer, bool> defaultExceptionHandler = (exception, analyzer) => true;
            this.continueOnAnalyzerException = continueOnAnalyzerException ?? defaultExceptionHandler;

            // start the first task to drain the event queue. The first compilation event is to be handled before
            // any other ones, so we cannot have more than one event processing task until the first event has been handled.
            initialWorker = Task.Run(async () =>
            {
                try
                {
                    await InitialWorkerAsync(analyzers, continueOnAnalyzerException, cancellationToken).ConfigureAwait(false);
                }
                catch (OperationCanceledException)
                {
                    // If creation is cancelled we had better not use the driver any longer
                    this.Dispose();
                }
            });
        }
Exemplo n.º 4
0
        public ICodeBlockEndedAnalyzer OnCodeBlockStarted(SyntaxNode codeBlock, ISymbol ownerSymbol, SemanticModel semanticModel, Action<Diagnostic> addDiagnostic, AnalyzerOptions options, CancellationToken cancellationToken)
        {
            var methodSymbol = ownerSymbol as IMethodSymbol;

            if (methodSymbol == null ||
                methodSymbol.ReturnsVoid ||
                methodSymbol.ReturnType.Kind == SymbolKind.ArrayType ||
                methodSymbol.Parameters.Length > 0 ||
                !(methodSymbol.DeclaredAccessibility == Accessibility.Public || methodSymbol.DeclaredAccessibility == Accessibility.Protected) ||
                methodSymbol.IsAccessorMethod() ||
                !IsPropertyLikeName(methodSymbol.Name))
            {
                return null;
            }

            // Fxcop has a few additional checks to reduce the noise for this diagnostic:
            // Ensure that the method is non-generic, non-virtual/override, has no overloads and doesn't have special names: 'GetHashCode' or 'GetEnumerator'.
            // Also avoid generating this diagnostic if the method body has any invocation expressions.
            if (methodSymbol.IsGenericMethod ||
                methodSymbol.IsVirtual ||
                methodSymbol.IsOverride ||
                methodSymbol.ContainingType.GetMembers(methodSymbol.Name).Length > 1 ||
                methodSymbol.Name == GetHashCodeName ||
                methodSymbol.Name == GetEnumeratorName)
            {
                return null;
            }

            return GetCodeBlockEndedAnalyzer();
        }
        public void AnalyzeCompilation(Compilation compilation, Action<Diagnostic> addDiagnostic, AnalyzerOptions options, CancellationToken cancellationToken)
        {
            if (AssemblyHasPublicTypes(compilation.Assembly))
            {
                var comVisibleAttributeSymbol = WellKnownTypes.ComVisibleAttribute(compilation);
                if (comVisibleAttributeSymbol == null)
                {
                    return;
                }

                var attributeInstance = 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'.
                        addDiagnostic(Diagnostic.Create(Rule, Location.None, string.Format(FxCopRulesResources.CA1017_AttributeTrue, compilation.Assembly.Name)));
                    }
                }
                else
                {
                    // No ComVisible attribute at all.
                    addDiagnostic(Diagnostic.Create(Rule, Location.None, string.Format(FxCopRulesResources.CA1017_NoAttribute, compilation.Assembly.Name)));
                }
            }

            return;
        }
Exemplo n.º 6
0
        public ICompilationEndedAnalyzer OnCompilationStarted(Compilation compilation, Action<Diagnostic> addDiagnostic, AnalyzerOptions options, CancellationToken cancellationToken)
        {
            var eventHandler = WellKnownTypes.EventHandler(compilation);
            if (eventHandler == null)
            {
                return null;
            }

            var genericEventHandler = WellKnownTypes.GenericEventHandler(compilation);
            if (genericEventHandler == null)
            {
                return null;
            }

            var eventArgs = WellKnownTypes.EventArgs(compilation);
            if (eventArgs == null)
            {
                return null;
            }

            var comSourceInterfacesAttribute = WellKnownTypes.ComSourceInterfaceAttribute(compilation);
            if (comSourceInterfacesAttribute == null)
            {
                return null;
            }

            return GetAnalyzer(compilation, eventHandler, genericEventHandler, eventArgs, comSourceInterfacesAttribute);
        }
        public IDiagnosticAnalyzer CreateAnalyzerWithinCompilation(Compilation compilation, AnalyzerOptions options, CancellationToken cancellationToken)
        {
            var iserializableTypeSymbol = compilation.GetTypeByMetadataName("System.Runtime.Serialization.ISerializable");
            if (iserializableTypeSymbol == null)
            {
                return null;
            }

            var serializationInfoTypeSymbol = compilation.GetTypeByMetadataName("System.Runtime.Serialization.SerializationInfo");
            if (serializationInfoTypeSymbol == null)
            {
                return null;
            }

            var streamingContextTypeSymbol = compilation.GetTypeByMetadataName("System.Runtime.Serialization.StreamingContext");
            if (streamingContextTypeSymbol == null)
            {
                return null;
            }

            var serializableAttributeTypeSymbol = compilation.GetTypeByMetadataName("System.SerializableAttribute");
            if (serializableAttributeTypeSymbol == null)
            {
                return null;
            }

            return new Analyzer(iserializableTypeSymbol, serializationInfoTypeSymbol, streamingContextTypeSymbol, serializableAttributeTypeSymbol);
        }
Exemplo n.º 8
0
        public override void AnalyzeSymbol(INamedTypeSymbol symbol, Compilation compilation, Action<Diagnostic> addDiagnostic, AnalyzerOptions options, CancellationToken cancellationToken)
        {
            if (symbol.TypeKind != TypeKind.Enum)
            {
                return;
            }

            var flagsAttribute = WellKnownTypes.FlagsAttribute(compilation);
            if (flagsAttribute == null)
            {
                return;
            }

            var zeroValuedFields = GetZeroValuedFields(symbol).ToImmutableArray();

            bool hasFlagsAttribute = symbol.GetAttributes().Any(a => a.AttributeClass == flagsAttribute);
            if (hasFlagsAttribute)
            {
                CheckFlags(symbol, zeroValuedFields, addDiagnostic);
            }
            else
            {
                CheckNonFlags(symbol, zeroValuedFields, addDiagnostic);
            }
        }
Exemplo n.º 9
0
 public override void AnalyzeSymbol(INamedTypeSymbol symbol, Compilation compilation, Action<Diagnostic> addDiagnostic, AnalyzerOptions options, CancellationToken cancellationToken)
 {
     if (symbol.GetMembers().Any(member => IsDllImport(member)) && !IsTypeNamedCorrectly(symbol.Name))
     {
         addDiagnostic(symbol.CreateDiagnostic(Rule));
     }
 }
        public IDiagnosticAnalyzer CreateAnalyzerWithinCompilation(Compilation compilation, AnalyzerOptions options, CancellationToken cancellationToken)
        {
            var dllImportType = compilation.GetTypeByMetadataName("System.Runtime.InteropServices.DllImportAttribute");
            if (dllImportType == null)
            {
                return null;
            }

            var marshalAsType = compilation.GetTypeByMetadataName("System.Runtime.InteropServices.MarshalAsAttribute");
            if (marshalAsType == null)
            {
                return null;
            }

            var stringBuilderType = compilation.GetTypeByMetadataName("System.Text.StringBuilder");
            if (stringBuilderType == null)
            {
                return null;
            }

            var unmanagedType = compilation.GetTypeByMetadataName("System.Runtime.InteropServices.UnmanagedType");
            if (unmanagedType == null)
            {
                return null;
            }

            return new Analyzer(dllImportType, marshalAsType, stringBuilderType, unmanagedType);
        }
        public IDiagnosticAnalyzer CreateAnalyzerWithinCompilation(Compilation compilation, AnalyzerOptions options, CancellationToken cancellationToken)
        {
            var specializedCollectionsSymbol = compilation.GetTypeByMetadataName(SpecializedCollectionsMetadataName);
            if (specializedCollectionsSymbol == null)
            {
                // TODO: In the future, we may want to run this analyzer even if the SpecializedCollections
                // type cannot be found in this compilation. In some cases, we may want to add a reference
                // to SpecializedCollections as a linked file or an assembly that contains it. With this
                // check, we will not warn where SpecializedCollections is not yet referenced.
                return null;
            }

            var genericEnumerableSymbol = compilation.GetTypeByMetadataName(IEnumerableMetadataName);
            if (genericEnumerableSymbol == null)
            {
                return null;
            }

            var linqEnumerableSymbol = compilation.GetTypeByMetadataName(LinqEnumerableMetadataName);
            if (linqEnumerableSymbol == null)
            {
                return null;
            }

            var genericEmptyEnumerableSymbol = linqEnumerableSymbol.GetMembers(EmptyMethodName).FirstOrDefault() as IMethodSymbol;
            if (genericEmptyEnumerableSymbol == null ||
                genericEmptyEnumerableSymbol.Arity != 1 ||
                genericEmptyEnumerableSymbol.Parameters.Length != 0)
            {
                return null;
            }

            return GetCodeBlockStartedAnalyzer(genericEnumerableSymbol, genericEmptyEnumerableSymbol);
        }
Exemplo n.º 12
0
 protected override void AnalyzeSymbol(INamedTypeSymbol namedTypeSymbol, Compilation compilation, Action<Diagnostic> addDiagnostic, AnalyzerOptions options, CancellationToken cancellationToken)
 {
     if (namedTypeSymbol.IsValueType && IsOverridesEquals(namedTypeSymbol) && !IsEqualityOperatorImplemented(namedTypeSymbol))
     {
         addDiagnostic(namedTypeSymbol.CreateDiagnostic(Rule));
     }
 }
 public void AnalyzeCodeBlock(SyntaxNode codeBlock, ISymbol ownerSymbol, SemanticModel semanticModel, Action<Diagnostic> addDiagnostic, AnalyzerOptions options, CancellationToken cancellationToken)
 {
     if (IsEmptyFinalizer(codeBlock, semanticModel))
     {
         addDiagnostic(ownerSymbol.CreateDiagnostic(Rule));
     }
 }
            public AnalyzerAndOptions(DiagnosticAnalyzer analyzer, AnalyzerOptions analyzerOptions)
            {
                Debug.Assert(analyzer != null);
                Debug.Assert(analyzerOptions != null);

                Analyzer = analyzer;
                _analyzerOptions = analyzerOptions;
            }
 /// <summary>
 /// Creates a new <see cref="CompilationWithAnalyzersOptions"/>.
 /// </summary>
 /// <param name="options">Options that are passed to analyzers.</param>
 /// <param name="onAnalyzerException">Action to invoke if an analyzer throws an exception.</param>
 /// <param name="concurrentAnalysis">Flag indicating whether analysis can be performed concurrently on multiple threads.</param>
 /// <param name="logAnalyzerExecutionTime">Flag indicating whether analyzer execution time should be logged.</param>
 /// <param name="reportDiagnosticsWithSourceSuppression">Flag indicating whether analyzer diagnostics with <see cref="Diagnostic.IsSuppressed"/> should be reported.</param>
 public CompilationWithAnalyzersOptions(AnalyzerOptions options, Action<Exception, DiagnosticAnalyzer, Diagnostic> onAnalyzerException, bool concurrentAnalysis, bool logAnalyzerExecutionTime, bool reportDiagnosticsWithSourceSuppression)
 {
     _options = options;
     _onAnalyzerException = onAnalyzerException;
     _concurrentAnalysis = concurrentAnalysis;
     _logAnalyzerExecutionTime = logAnalyzerExecutionTime;
     _reportDiagnosticsWithSourceSuppression = reportDiagnosticsWithSourceSuppression;
 }
 /// <summary>
 /// Creates a new <see cref="CompilationWithAnalyzersOptions"/>.
 /// </summary>
 /// <param name="options">Options that are passed to analyzers.</param>
 /// <param name="onAnalyzerException">Action to invoke if an analyzer throws an exception.</param>
 /// <param name="concurrentAnalysis">Flag indicating whether analysis can be performed concurrently on multiple threads.</param>
 /// <param name="logAnalyzerExecutionTime">Flag indicating whether analyzer execution time should be logged.</param>
 public CompilationWithAnalyzersOptions(
     AnalyzerOptions options,
     Action<Exception, DiagnosticAnalyzer, Diagnostic> onAnalyzerException,
     bool concurrentAnalysis,
     bool logAnalyzerExecutionTime)
     : this(options, onAnalyzerException, concurrentAnalysis, logAnalyzerExecutionTime, reportSuppressedDiagnostics: false)
 {
 }
Exemplo n.º 17
0
 public static IOrderedEnumerable<Diagnostic> GetSortedDiagnostics(string filePath,
                                                                   DiagnosticAnalyzer analyzer,
                                                                   string settingsPath)
 {
     var options = new AnalyzerOptions(ImmutableArray.Create<AdditionalText>(new SettingsFile(settingsPath)));
     return GetSortedDiagnosticsFromDocuments(analyzer,
                                              DocumentSetCreator.CreateDocumentSetFromSources(filePath),
                                              options);
 }
 public void AnalyzeCompilation(Compilation compilation, Action<Diagnostic> addDiagnostic, AnalyzerOptions options, CancellationToken cancellationToken)
 {
     foreach (var item in this.fieldDisposedMap)
     {
         if (!item.Value)
         {
             addDiagnostic(item.Key.CreateDiagnostic(Rule));
         }
     }
 }
        public override void AnalyzeSymbol(INamedTypeSymbol namedType, Compilation compilation, Action<Diagnostic> addDiagnostic, AnalyzerOptions options, CancellationToken cancellationToken)
        {
            if (namedType.IsAbstract || namedType.IsSealed || !namedType.IsAttribute())
            {
                return;
            }

            // Non-sealed non-abstract attribute type.
            addDiagnostic(namedType.CreateDiagnostic(Rule));
        }
        public void AnalyzeCompilation(Compilation compilation, Action<Diagnostic> addDiagnostic, AnalyzerOptions options, CancellationToken cancellationToken)
        {
            var globalNamespaces = compilation.GlobalNamespace.GetNamespaceMembers()
                .Where(item => item.ContainingAssembly == compilation.Assembly);

            var globalTypes = compilation.GlobalNamespace.GetTypeMembers().Where(item =>
                    item.ContainingAssembly == compilation.Assembly &&
                    IsExternallyVisible(item));

            CheckTypeNames(globalTypes, addDiagnostic);
            CheckNamespaceMembers(globalNamespaces, compilation, addDiagnostic);
        }
Exemplo n.º 21
0
        private static IOrderedEnumerable<Diagnostic> GetSortedDiagnosticsFromDocuments(DiagnosticAnalyzer analyzer,
                                                                                        TextDocument document,
                                                                                        AnalyzerOptions options)
        {
            var diagnostics = document.Project.GetCompilationAsync()
                                      .Result
                                      .WithAnalyzers(ImmutableArray.Create(analyzer),
                                                     options)
                                      .GetAnalyzerDiagnosticsAsync().Result;

            return SortDiagnostics(diagnostics);
        }
        public void AnalyzeCompilation(Compilation compilation, Action<Diagnostic> addDiagnostic, AnalyzerOptions options, CancellationToken cancellationToken)
        {
            var assemblyVersionAttributeSymbol = WellKnownTypes.AssemblyVersionAttribute(compilation);
            var assemblyComplianceAttributeSymbol = WellKnownTypes.CLSCompliantAttribute(compilation);

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

            bool assemblyVersionAttributeFound = false;
            bool assemblyComplianceAttributeFound = false;

            // Check all assembly level attributes for the target attribute
            foreach (var attribute in 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)
                {
                    addDiagnostic(Diagnostic.Create(CA1016Rule, Location.None));
                }

                if (!assemblyComplianceAttributeFound)
                {
                    addDiagnostic(Diagnostic.Create(CA1014Rule, Location.None));
                }
            }
        }
Exemplo n.º 23
0
 protected override void AnalyzeSymbol(INamedTypeSymbol symbol, Compilation compilation, Action<Diagnostic> addDiagnostic, AnalyzerOptions options, CancellationToken cancellationToken)
 {
     if (symbol != null && symbol.IsAttribute() && symbol.DeclaredAccessibility != Accessibility.Private)
     {
         IEnumerable<IParameterSymbol> parametersToCheck = GetAllPublicConstructorParameters(symbol);
         if (parametersToCheck.Any())
         {
             IDictionary<string, IPropertySymbol> propertiesMap = GetAllPropertiesInTypeChain(symbol);
             AnalyzeParameters(compilation, parametersToCheck, propertiesMap, symbol, addDiagnostic);
         }
     }
 }
Exemplo n.º 24
0
        /// <summary>
        /// Creates a new compilation by attaching diagnostic analyzers to an existing compilation.
        /// </summary>
        /// <param name="compilation">The original compilation.</param>
        /// <param name="analyzers">The set of analyzers to include in future analyses.</param>
        /// <param name="options">Options that are passed to analyzers.</param>
        /// <param name="cancellationToken">A cancellation token that can be used to abort analysis.</param>
        public CompilationWithAnalyzers(Compilation compilation, ImmutableArray<DiagnosticAnalyzer> analyzers, AnalyzerOptions options, CancellationToken cancellationToken)
        {
            if (compilation == null)
            {
                throw new ArgumentNullException(nameof(compilation));
            }

            VerifyAnalyzersArgument(analyzers);

            _cancellationToken = cancellationToken;
            _exceptionDiagnostics = new ConcurrentSet<Diagnostic>();
            _driver = AnalyzerDriver.Create(compilation, analyzers, options, AnalyzerManager.Instance, AddExceptionDiagnostic, false, out _compilation, _cancellationToken);
        }
        public void AnalyzeSymbol(ISymbol symbol, Compilation compilation, Action<Diagnostic> addDiagnostic, AnalyzerOptions options, CancellationToken cancellationToken)
        {
            switch (symbol.Kind)
            {
                case SymbolKind.NamedType:
                    AnalyzeNamedTypeSymbol((INamedTypeSymbol)symbol, addDiagnostic);
                    break;

                case SymbolKind.Method:
                    AnalyzeMethodSymbol((IMethodSymbol)symbol, addDiagnostic);
                    break;
            }
        }
            public AnalyzerAndOptions(DiagnosticAnalyzer analyzer, AnalyzerOptions analyzerOptions)
            {
                Debug.Assert(analyzer != null);
                Debug.Assert(analyzerOptions != null);

                Analyzer = analyzer;
                // _analyzerOptions is used only as a key for equality testing, and only the properties
                // declared by AnalyzerOptions are appropriate for use in the comparison. (For example,
                // two AnalyzersAndOptions that differ only by Workspace ought to be treated as equal.)
                // If the supplied analyzerOptions is an instance of a derived type, holding on to that object
                // can introduce a memory leak, as well as causing false negatives in comparison. Avoid these
                // issues by creating a new object with only the desired properties. 
                _analyzerOptions = new AnalyzerOptions(analyzerOptions.AdditionalFiles);
            }
Exemplo n.º 27
0
        public static void SetParameterValues(DiagnosticAnalyzer parameteredAnalyzer,
            AnalyzerOptions options)
        {
            if (ProcessedAnalyzers.ContainsKey(parameteredAnalyzer))
            {
                return;
            }

            var additionalFile = options.AdditionalFiles
                .FirstOrDefault(f => ConfigurationFilePathMatchesExpected(f.Path));

            if (additionalFile == null)
            {
                return;
            }

            var filePath = additionalFile.Path;
            var xml = XDocument.Load(filePath);
            var parameters = ParseParameters(xml);

            var propertyParameterPairs = parameteredAnalyzer.GetType()
                .GetProperties()
                .Select(p => new { Property = p, Descriptor = p.GetCustomAttributes<RuleParameterAttribute>().SingleOrDefault() })
                .Where(p => p.Descriptor != null);

            foreach (var propertyParameterPair in propertyParameterPairs)
            {
                var parameter = parameters
                    .FirstOrDefault(p => p.RuleId == parameteredAnalyzer.SupportedDiagnostics.Single().Id);

                if (parameter == null)
                {
                    return;
                }

                var parameterValue = parameter.ParameterValues
                    .FirstOrDefault(pv => pv.ParameterKey == propertyParameterPair.Descriptor.Key);

                if (parameterValue == null)
                {
                    return;
                }

                var value = parameterValue.ParameterValue;
                var convertedValue = ChangeParameterType(value, propertyParameterPair.Descriptor.Type);
                propertyParameterPair.Property.SetValue(parameteredAnalyzer, convertedValue);
            }

            ProcessedAnalyzers.AddOrUpdate(parameteredAnalyzer, 0, (a, b) => b);
        }
 protected override void AnalyzeSymbol(
     INamedTypeSymbol symbol,
     Compilation compilation,
     Action<Diagnostic> addDiagnostic,
     AnalyzerOptions options,
     CancellationToken cancellationToken)
 {
     if (!symbol.IsStatic
         && (symbol.IsPublic() || symbol.IsProtected())
         && symbol.IsStaticHolderType())
     {
         addDiagnostic(symbol.CreateDiagnostic(Rule, symbol.Name));
     }
 }
        public IDiagnosticAnalyzer CreateAnalyzerWithinCodeBlock(SyntaxNode codeBlock, ISymbol ownerSymbol, SemanticModel semanticModel, AnalyzerOptions options, CancellationToken cancellationToken)
        {
            var method = ownerSymbol as IMethodSymbol;
            if (method == null)
            {
                return null;
            }

            if (!IsDestructor(method))
            {
                return null;
            }

            return GetCodeBlockEndedAnalyzer();
        }
Exemplo n.º 30
0
        public ICodeBlockEndedAnalyzer OnCodeBlockStarted(SyntaxNode codeBlock, ISymbol ownerSymbol, SemanticModel semanticModel, Action<Diagnostic> addDiagnostic, AnalyzerOptions options, CancellationToken cancellationToken)
        {
            var method = ownerSymbol as IMethodSymbol;
            if (method == null)
            {
                return null;
            }

            if (!IsDestructor(method))
            {
                return null;
            }

            return GetCodeBlockEndedAnalyzer();
        }
Exemplo n.º 31
0
 internal static Compilation AttachAnalyzerDriverToCompilation(Compilation compilation, ImmutableArray <IDiagnosticAnalyzer> analyzers, out AnalyzerDriver3 analyzerDriver3, AnalyzerOptions options, CancellationToken cancellationToken)
 {
     analyzerDriver3 = compilation.AnalyzerForLanguage(analyzers, options, cancellationToken);
     return(compilation.WithEventQueue(analyzerDriver3.CompilationEventQueue));
 }
Exemplo n.º 32
0
 public WorkspaceAnalyzerOptions(AnalyzerOptions options, OptionSet optionSet, Solution solution)
     : base(options.AdditionalFiles)
 {
     _solution  = solution;
     _optionSet = optionSet;
 }
Exemplo n.º 33
0
 public SyntaxNodeAnalysisContext(SyntaxNode node, SemanticModel semanticModel, AnalyzerOptions options, Action <Diagnostic> reportDiagnostic, CancellationToken cancellationToken)
 {
     _node              = node;
     _semanticModel     = semanticModel;
     _options           = options;
     _reportDiagnostic  = reportDiagnostic;
     _cancellationToken = cancellationToken;
 }
Exemplo n.º 34
0
 public CodeBlockAnalysisContext(SyntaxNode codeBlock, ISymbol owningSymbol, SemanticModel semanticModel, AnalyzerOptions options, Action <Diagnostic> reportDiagnostic, CancellationToken cancellationToken)
 {
     _codeBlock         = codeBlock;
     _owningSymbol      = owningSymbol;
     _semanticModel     = semanticModel;
     _options           = options;
     _reportDiagnostic  = reportDiagnostic;
     _cancellationToken = cancellationToken;
 }
Exemplo n.º 35
0
 protected CodeBlockStartAnalysisContext(SyntaxNode codeBlock, ISymbol owningSymbol, SemanticModel semanticModel, AnalyzerOptions options, CancellationToken cancellationToken)
 {
     _codeBlock         = codeBlock;
     _owningSymbol      = owningSymbol;
     _semanticModel     = semanticModel;
     _options           = options;
     _cancellationToken = cancellationToken;
 }
Exemplo n.º 36
0
 public static AnalyzerConfigOptions GetAnalyzerOptionSet(this AnalyzerOptions analyzerOptions, SyntaxTree syntaxTree, CancellationToken cancellationToken)
 {
     return(analyzerOptions.AnalyzerConfigOptionsProvider.GetOptions(syntaxTree));
 }
Exemplo n.º 37
0
 /// <summary>
 /// Creates a new <see cref="CompilationWithAnalyzersOptions"/>.
 /// </summary>
 /// <param name="options">Options that are passed to analyzers.</param>
 /// <param name="onAnalyzerException">Action to invoke if an analyzer throws an exception.</param>
 /// <param name="concurrentAnalysis">Flag indicating whether analysis can be performed concurrently on multiple threads.</param>
 /// <param name="logAnalyzerExecutionTime">Flag indicating whether analyzer execution time should be logged.</param>
 public CompilationWithAnalyzersOptions(AnalyzerOptions options, Action <Exception, DiagnosticAnalyzer, Diagnostic> onAnalyzerException, bool concurrentAnalysis, bool logAnalyzerExecutionTime)
     : this(options, onAnalyzerException, concurrentAnalysis, logAnalyzerExecutionTime, reportDiagnosticsWithSourceSuppression : false)
 {
 }
Exemplo n.º 38
0
 /// <summary>
 /// Creates a new compilation by attaching diagnostic analyzers to an existing compilation.
 /// </summary>
 /// <param name="compilation">The original compilation.</param>
 /// <param name="analyzers">The set of analyzers to include in future analyses.</param>
 /// <param name="options">Options that are passed to analyzers.</param>
 /// <param name="cancellationToken">A cancellation token that can be used to abort analysis.</param>
 public CompilationWithAnalyzers(Compilation compilation, ImmutableArray <DiagnosticAnalyzer> analyzers, AnalyzerOptions options, CancellationToken cancellationToken)
 {
     _cancellationToken    = cancellationToken;
     _exceptionDiagnostics = new ConcurrentSet <Diagnostic>();
     _driver = AnalyzerDriver.Create(compilation, analyzers, options, AnalyzerManager.Instance, AddExceptionDiagnostic, out _compilation, _cancellationToken);
 }
Exemplo n.º 39
0
#pragma warning disable IDE0060 // Remove unused parameter - Needed to share this method signature between CodeStyle and Features layer.
        public static AnalyzerConfigOptions GetAnalyzerOptionSet(this AnalyzerOptions analyzerOptions, SyntaxTree syntaxTree, CancellationToken cancellationToken)
#pragma warning restore IDE0060 // Remove unused parameter
        => analyzerOptions.AnalyzerConfigOptionsProvider.GetOptions(syntaxTree);
Exemplo n.º 40
0
 public static OptionSet GetOptionSet(this AnalyzerOptions analyzerOptions)
 {
     return((analyzerOptions as WorkspaceAnalyzerOptions)?.Workspace.Options);
 }
Exemplo n.º 41
0
 public WorkspaceAnalyzerOptions(AnalyzerOptions options, Project project)
     : this(options, project.Solution, IdeAnalyzerOptions.FromProject(project))
 {
 }
Exemplo n.º 42
0
 public WorkspaceAnalyzerOptions(AnalyzerOptions options, Solution solution)
     : base(options.AdditionalFiles, options.AnalyzerConfigOptionsProvider)
 {
     _solution = solution;
 }
Exemplo n.º 43
0
 /// <summary>
 /// Returns a new compilation with attached diagnostic analyzers.
 /// </summary>
 /// <param name="compilation">Compilation to which analyzers are to be added.</param>
 /// <param name="analyzers">The set of analyzers to include in future analyses.</param>
 /// <param name="options">Options that are passed to analyzers.</param>
 /// <param name="cancellationToken">A cancellation token that can be used to abort analysis.</param>
 public static CompilationWithAnalyzers WithAnalyzers(this Compilation compilation, ImmutableArray <DiagnosticAnalyzer> analyzers, AnalyzerOptions options = null, CancellationToken cancellationToken = default(CancellationToken))
 {
     return(new CompilationWithAnalyzers(compilation, analyzers, options, cancellationToken));
 }
Exemplo n.º 44
0
        /// <summary>
        /// Creates a new compilation by attaching diagnostic analyzers to an existing compilation.
        /// </summary>
        /// <param name="compilation">The original compilation.</param>
        /// <param name="analyzers">The set of analyzers to include in future analyses.</param>
        /// <param name="options">Options that are passed to analyzers.</param>
        /// <param name="cancellationToken">A cancellation token that can be used to abort analysis.</param>
        public CompilationWithAnalyzers(Compilation compilation, ImmutableArray <DiagnosticAnalyzer> analyzers, AnalyzerOptions options, CancellationToken cancellationToken)
        {
            if (compilation == null)
            {
                throw new ArgumentNullException(nameof(compilation));
            }

            VerifyAnalyzersArgument(analyzers);

            _cancellationToken    = cancellationToken;
            _exceptionDiagnostics = new ConcurrentSet <Diagnostic>();
            _driver = AnalyzerDriver.Create(compilation, analyzers, options, AnalyzerManager.Instance, AddExceptionDiagnostic, false, out _compilation, _cancellationToken);
        }
 public CollectCompilationActionsContext(Compilation compilation, AnalyzerOptions analyzerOptions)
 {
     _compilation     = compilation;
     _analyzerOptions = analyzerOptions;
 }
Exemplo n.º 46
0
        private static ImmutableArray <IDiagnosticAnalyzer> GetEffectiveAnalyzers(IEnumerable <IDiagnosticAnalyzer> analyzers, Compilation compilation, AnalyzerOptions analyzerOptions, Action <Diagnostic> addDiagnostic, bool continueOnError, CancellationToken cancellationToken)
        {
            var effectiveAnalyzers = ImmutableArray.CreateBuilder <IDiagnosticAnalyzer>();

            foreach (var analyzer in analyzers)
            {
                cancellationToken.ThrowIfCancellationRequested();
                if (!IsDiagnosticAnalyzerSuppressed(analyzer, compilation.Options, addDiagnostic, continueOnError, cancellationToken))
                {
                    effectiveAnalyzers.Add(analyzer);
                    var startAnalyzer = analyzer as ICompilationStartedAnalyzer;
                    if (startAnalyzer != null)
                    {
                        ExecuteAndCatchIfThrows(startAnalyzer, addDiagnostic, continueOnError, cancellationToken, () =>
                        {
                            var compilationAnalyzer = startAnalyzer.OnCompilationStarted(compilation, addDiagnostic, analyzerOptions, cancellationToken);
                            if (compilationAnalyzer != null)
                            {
                                effectiveAnalyzers.Add(compilationAnalyzer);
                            }
                        });
                    }
                }
            }

            return(effectiveAnalyzers.ToImmutable());
        }
Exemplo n.º 47
0
 protected CompilationStartAnalysisContext(Compilation compilation, AnalyzerOptions options, CancellationToken cancellationToken)
 {
     _compilation       = compilation;
     _options           = options;
     _cancellationToken = cancellationToken;
 }
Exemplo n.º 48
0
 public WorkspaceAnalyzerOptions(AnalyzerOptions options, Workspace workspace)
     : base(options.AdditionalFiles)
 {
     this.Workspace = workspace;
 }
Exemplo n.º 49
0
 public static T GetOption <T>(this AnalyzerOptions analyzerOptions, Option2 <T> option, SyntaxTree syntaxTree, CancellationToken cancellationToken)
 => GetOption <T>(analyzerOptions, option, language: null, syntaxTree, cancellationToken);
Exemplo n.º 50
0
        public static bool TryGetEditorConfigOption <T>(this AnalyzerOptions analyzerOptions, TOption option, SyntaxTree syntaxTree, out T value)
        {
            var configOptions = analyzerOptions.AnalyzerConfigOptionsProvider.GetOptions(syntaxTree);

            return(configOptions.TryGetEditorConfigOption(option, out value));
        }
Exemplo n.º 51
0
 public AnalyzerCompilationStartAnalysisContext(DiagnosticAnalyzer analyzer, HostCompilationStartAnalysisScope scope, Compilation compilation, AnalyzerOptions options, CancellationToken cancellationToken)
     : base(compilation, options, cancellationToken)
 {
     _analyzer = analyzer;
     _scope    = scope;
 }
 public CollectNestedCompilationContext(Compilation compilation, AnalyzerOptions options, CancellationToken cancellationToken)
     : base(compilation, options, cancellationToken)
 {
 }
            private ConditionalWeakTable <Compilation, Task <HostCompilationStartAnalysisScope> > GetOrCreateCompilationActionsCache(AnalyzerOptions analyzerOptions)
            {
                lock (_gate)
                {
                    ConditionalWeakTable <Compilation, Task <HostCompilationStartAnalysisScope> > compilationActionsCache;

                    if (_lazyCompilationScopeMap == null)
                    {
                        _lazyCompilationScopeMap = new Dictionary <AnalyzerOptions, ConditionalWeakTable <Compilation, Task <HostCompilationStartAnalysisScope> > >();
                    }
                    else if (_lazyCompilationScopeMap.TryGetValue(analyzerOptions, out compilationActionsCache))
                    {
                        return(compilationActionsCache);
                    }

                    compilationActionsCache = new ConditionalWeakTable <Compilation, Task <HostCompilationStartAnalysisScope> >();
                    _lazyCompilationScopeMap.Add(analyzerOptions, compilationActionsCache);
                    return(compilationActionsCache);
                }
            }
Exemplo n.º 54
0
 public static T GetOption <T>(this AnalyzerOptions analyzerOptions, PerLanguageOption2 <T> option, string?language, SyntaxTree syntaxTree, CancellationToken cancellationToken)
 => GetOption <T>(analyzerOptions, (IOption2)option, language, syntaxTree, cancellationToken);
Exemplo n.º 55
0
 /// <summary>
 /// Creates a new compilation by attaching diagnostic analyzers to an existing compilation.
 /// </summary>
 /// <param name="compilation">The original compilation.</param>
 /// <param name="analyzers">The set of analyzers to include in future analyses.</param>
 /// <param name="options">Options that are passed to analyzers.</param>
 /// <param name="cancellationToken">A cancellation token that can be used to abort analysis.</param>
 public CompilationWithAnalyzers(Compilation compilation, ImmutableArray <DiagnosticAnalyzer> analyzers, AnalyzerOptions options, CancellationToken cancellationToken)
 {
     _cancellationToken = cancellationToken;
     _driver            = AnalyzerDriver.Create(compilation, analyzers, options, out _compilation, _cancellationToken);
 }