private void Add(ref ImmutableDictionary <DocumentId, ImmutableArray <DiagnosticData> > .Builder locals, DocumentId documentId, ImmutableArray <DiagnosticData> diagnostics) { locals = locals ?? ImmutableDictionary.CreateBuilder <DocumentId, ImmutableArray <DiagnosticData> >(); locals.Add(documentId, diagnostics); }
protected bool TrySimplifyTypeNameExpression(SemanticModel model, SyntaxNode node, AnalyzerOptions analyzerOptions, out Diagnostic diagnostic, CancellationToken cancellationToken) { diagnostic = default; var syntaxTree = node.SyntaxTree; var optionSet = analyzerOptions.GetDocumentOptionSetAsync(syntaxTree, cancellationToken).GetAwaiter().GetResult(); if (optionSet == null) { return(false); } if (!CanSimplifyTypeNameExpressionCore(model, node, optionSet, out var issueSpan, out string diagnosticId, cancellationToken)) { return(false); } if (model.SyntaxTree.OverlapsHiddenPosition(issueSpan, cancellationToken)) { return(false); } PerLanguageOption <CodeStyleOption <bool> > option; DiagnosticDescriptor descriptor; switch (diagnosticId) { case IDEDiagnosticIds.SimplifyNamesDiagnosticId: descriptor = s_descriptorSimplifyNames; break; case IDEDiagnosticIds.SimplifyMemberAccessDiagnosticId: descriptor = s_descriptorSimplifyMemberAccess; break; case IDEDiagnosticIds.RemoveQualificationDiagnosticId: descriptor = GetRemoveQualificationDiagnosticDescriptor(model, node, optionSet, cancellationToken); break; case IDEDiagnosticIds.PreferIntrinsicPredefinedTypeInDeclarationsDiagnosticId: option = CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration; descriptor = GetApplicablePredefinedTypeDiagnosticDescriptor( IDEDiagnosticIds.PreferIntrinsicPredefinedTypeInDeclarationsDiagnosticId, option, optionSet); break; case IDEDiagnosticIds.PreferIntrinsicPredefinedTypeInMemberAccessDiagnosticId: option = CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess; descriptor = GetApplicablePredefinedTypeDiagnosticDescriptor( IDEDiagnosticIds.PreferIntrinsicPredefinedTypeInMemberAccessDiagnosticId, option, optionSet); break; default: throw ExceptionUtilities.UnexpectedValue(diagnosticId); } if (descriptor == null) { return(false); } var tree = model.SyntaxTree; var builder = ImmutableDictionary.CreateBuilder <string, string>(); builder["OptionName"] = nameof(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess); // TODO: need the actual one builder["OptionLanguage"] = model.Language; diagnostic = Diagnostic.Create(descriptor, tree.GetLocation(issueSpan), builder.ToImmutable()); return(true); }
public InterceptedProjectProperties(ImmutableArray <Lazy <IInterceptingPropertyValueProvider, IInterceptingPropertyValueProviderMetadata> > valueProviders, IProjectProperties defaultProperties) : base(defaultProperties) { Requires.NotNullOrEmpty(valueProviders, nameof(valueProviders)); ImmutableDictionary <string, Lazy <IInterceptingPropertyValueProvider, IInterceptingPropertyValueProviderMetadata> > .Builder builder = ImmutableDictionary.CreateBuilder <string, Lazy <IInterceptingPropertyValueProvider, IInterceptingPropertyValueProviderMetadata> >(StringComparers.PropertyNames); foreach (Lazy <IInterceptingPropertyValueProvider, IInterceptingPropertyValueProviderMetadata> valueProvider in valueProviders) { string[] propertyNames = valueProvider.Metadata.PropertyNames; foreach (string propertyName in propertyNames) { Requires.Argument(!string.IsNullOrEmpty(propertyName), nameof(valueProvider), "A null or empty property name was found"); // CONSIDER: Allow duplicate intercepting property value providers for same property name. Requires.Argument(!builder.ContainsKey(propertyName), nameof(valueProviders), "Duplicate property value providers for same property name"); builder.Add(propertyName, valueProvider); } } _valueProviders = builder.ToImmutable(); }
protected override ImmutableDictionary <TKey, TValue> .Builder Create(int count) { return(ImmutableDictionary.CreateBuilder <TKey, TValue>()); }
private ImmutableDictionary <string, DiagnosticDescriptor> LoadDiagnosticsById() { ImmutableDictionary <string, DiagnosticDescriptor> .Builder diagnosticsById = ImmutableDictionary.CreateBuilder <string, DiagnosticDescriptor>(); diagnosticsById.AddRange(Analyzers .SelectMany(f => f.SupportedDiagnostics) .Distinct(DiagnosticDescriptorComparer.Id) .OrderBy(f => f, DiagnosticDescriptorComparer.Id) .Select(f => new KeyValuePair <string, DiagnosticDescriptor>(f.Id, f))); foreach (CodeFixProvider fixer in Fixers) { foreach (string diagnosticId in fixer.FixableDiagnosticIds) { if (!diagnosticsById.ContainsKey(diagnosticId)) { diagnosticsById[diagnosticId] = null; } } } return(diagnosticsById.ToImmutable()); }
protected override ComposablePartDefinition CreatePart(Type partType, bool typeExplicitlyRequested) { Requires.NotNull(partType, nameof(partType)); // We want to ignore abstract classes, but we want to consider static classes. // Static classes claim to be both abstract and sealed. So to ignore just abstract // ones, we check that they are not sealed. if (partType.IsAbstract && !partType.IsSealed) { return(null); } BindingFlags everythingLocal = BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; BindingFlags instanceLocal = BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; // If the type is abstract only find local static exports var exportBindingFlags = everythingLocal; if (partType.IsAbstract) { exportBindingFlags &= ~BindingFlags.Instance; } var declaredMethods = partType.GetMethods(exportBindingFlags); // methods can only export, not import var declaredProperties = partType.GetProperties(everythingLocal); var declaredFields = partType.GetFields(everythingLocal); var allLocalMembers = declaredMethods.Concat <MemberInfo>(declaredProperties).Concat(declaredFields); var exportingMembers = from member in allLocalMembers from export in member.GetAttributes <ExportAttribute>() select new KeyValuePair <MemberInfo, ExportAttribute>(member, export); var exportedTypes = from export in partType.GetAttributes <ExportAttribute>() select new KeyValuePair <MemberInfo, ExportAttribute>(partType, export); var inheritedExportedTypes = from baseTypeOrInterface in partType.GetInterfaces().Concat(partType.EnumTypeAndBaseTypes().Skip(1)) where baseTypeOrInterface != typeof(object) from export in baseTypeOrInterface.GetAttributes <InheritedExportAttribute>() select new KeyValuePair <MemberInfo, ExportAttribute>(baseTypeOrInterface, export); var exportsByMember = (from export in exportingMembers.Concat(exportedTypes).Concat(inheritedExportedTypes) group export.Value by export.Key into exportsByType select exportsByType).Select(g => new KeyValuePair <MemberInfo, ExportAttribute[]>(g.Key, g.ToArray())).ToArray(); if (exportsByMember.Length == 0) { return(null); } // Check for PartNotDiscoverable only after we've established it's an interesting part. // This optimizes for the fact that most types have no exports, in which case it's not a discoverable // part anyway. Checking for the PartNotDiscoverableAttribute first, which is rarely defined, // doesn't usually pay for itself in terms of short-circuiting. But it does add an extra // attribute to look for that we don't need to find for all the types that have no export attributes either. if (!typeExplicitlyRequested && partType.IsAttributeDefined <PartNotDiscoverableAttribute>()) { return(null); } TypeRef partTypeRef = TypeRef.Get(partType, this.Resolver); Type partTypeAsGenericTypeDefinition = partType.IsGenericType ? partType.GetGenericTypeDefinition() : null; // Collect information for all imports. var imports = ImmutableList.CreateBuilder <ImportDefinitionBinding>(); this.AddImportsFromMembers(declaredProperties, declaredFields, partTypeRef, imports); Type baseType = partType.BaseType; while (baseType != null && baseType != typeof(object)) { this.AddImportsFromMembers(baseType.GetProperties(instanceLocal), baseType.GetFields(instanceLocal), partTypeRef, imports); baseType = baseType.BaseType; } var partCreationPolicy = CreationPolicy.Any; var partCreationPolicyAttribute = partType.GetFirstAttribute <PartCreationPolicyAttribute>(); if (partCreationPolicyAttribute != null) { partCreationPolicy = (CreationPolicy)partCreationPolicyAttribute.CreationPolicy; } var allExportsMetadata = ImmutableDictionary.CreateRange(PartCreationPolicyConstraint.GetExportMetadata(partCreationPolicy)); var inheritedExportContractNamesFromNonInterfaces = ImmutableHashSet.CreateBuilder <string>(); var exportDefinitions = ImmutableList.CreateBuilder <KeyValuePair <MemberInfo, ExportDefinition> >(); foreach (var export in exportsByMember) { var memberExportMetadata = allExportsMetadata.AddRange(GetExportMetadata(export.Key)); if (export.Key is MethodInfo) { var method = export.Key as MethodInfo; var exportAttributes = export.Value; if (exportAttributes.Any()) { foreach (var exportAttribute in exportAttributes) { Type exportedType = exportAttribute.ContractType ?? ReflectionHelpers.GetContractTypeForDelegate(method); string contractName = string.IsNullOrEmpty(exportAttribute.ContractName) ? GetContractName(exportedType) : exportAttribute.ContractName; var exportMetadata = memberExportMetadata .Add(CompositionConstants.ExportTypeIdentityMetadataName, ContractNameServices.GetTypeIdentity(exportedType)); var exportDefinition = new ExportDefinition(contractName, exportMetadata); exportDefinitions.Add(new KeyValuePair <MemberInfo, ExportDefinition>(export.Key, exportDefinition)); } } } else { MemberInfo exportingTypeOrPropertyOrField = export.Key; Verify.Operation(export.Key is Type || !partType.IsGenericTypeDefinition, Strings.ExportsOnMembersNotAllowedWhenDeclaringTypeGeneric); Type exportSiteType = ReflectionHelpers.GetMemberType(exportingTypeOrPropertyOrField); foreach (var exportAttribute in export.Value) { Type exportedType = exportAttribute.ContractType ?? partTypeAsGenericTypeDefinition ?? exportSiteType; string contractName = string.IsNullOrEmpty(exportAttribute.ContractName) ? GetContractName(exportedType) : exportAttribute.ContractName; if (export.Key is Type && exportAttribute is InheritedExportAttribute) { if (inheritedExportContractNamesFromNonInterfaces.Contains(contractName)) { // We already have an export with this contract name on this type (from a more derived type) // using InheritedExportAttribute. continue; } if (!((Type)export.Key).IsInterface) { inheritedExportContractNamesFromNonInterfaces.Add(contractName); } } var exportMetadata = memberExportMetadata .Add(CompositionConstants.ExportTypeIdentityMetadataName, ContractNameServices.GetTypeIdentity(exportedType)); var exportDefinition = new ExportDefinition(contractName, exportMetadata); exportDefinitions.Add(new KeyValuePair <MemberInfo, ExportDefinition>(export.Key, exportDefinition)); } } } MethodInfo onImportsSatisfied = null; if (typeof(IPartImportsSatisfiedNotification).IsAssignableFrom(partType)) { onImportsSatisfied = OnImportsSatisfiedMethodInfo; } var importingConstructorParameters = ImmutableList.CreateBuilder <ImportDefinitionBinding>(); var importingCtor = GetImportingConstructor <ImportingConstructorAttribute>(partType, publicOnly: false); if (importingCtor != null) // some parts have exports merely for metadata -- they can't be instantiated { foreach (var parameter in importingCtor.GetParameters()) { var import = this.CreateImport(parameter); if (import.ImportDefinition.Cardinality == ImportCardinality.ZeroOrMore) { Verify.Operation(PartDiscovery.IsImportManyCollectionTypeCreateable(import), Strings.CollectionMustBePublicAndPublicCtorWhenUsingImportingCtor); } importingConstructorParameters.Add(import); } } var partMetadata = ImmutableDictionary.CreateBuilder <string, object>(); foreach (var partMetadataAttribute in partType.GetAttributes <PartMetadataAttribute>()) { partMetadata[partMetadataAttribute.Name] = partMetadataAttribute.Value; } var exportsOnType = exportDefinitions.Where(kv => kv.Key is Type).Select(kv => kv.Value).ToArray(); var exportsOnMembers = (from kv in exportDefinitions where !(kv.Key is Type) group kv.Value by kv.Key into byMember select byMember).ToDictionary(g => MemberRef.Get(g.Key, this.Resolver), g => (IReadOnlyCollection <ExportDefinition>)g.ToArray()); var assemblyNamesForMetadataAttributes = ImmutableHashSet.CreateBuilder <AssemblyName>(); foreach (var export in exportsByMember) { GetAssemblyNamesFromMetadataAttributes <MetadataAttributeAttribute>(export.Key, assemblyNamesForMetadataAttributes); } return(new ComposablePartDefinition( TypeRef.Get(partType, this.Resolver), partMetadata.ToImmutable(), exportsOnType, exportsOnMembers, imports.ToImmutable(), partCreationPolicy != CreationPolicy.NonShared ? string.Empty : null, MethodRef.Get(onImportsSatisfied, this.Resolver), ConstructorRef.Get(importingCtor, this.Resolver), importingCtor != null ? importingConstructorParameters.ToImmutable() : null, // some MEF parts are only for metadata partCreationPolicy, assemblyNamesForMetadataAttributes, partCreationPolicy != CreationPolicy.NonShared)); }
public override async Task ProvideCompletionsAsync(CompletionContext context) { if (!context.Options.GetOption(RegularExpressionsOptions.ProvideRegexCompletions, context.Document.Project.Language)) { return; } if (context.Trigger.Kind != CompletionTriggerKind.Invoke && context.Trigger.Kind != CompletionTriggerKind.InvokeAndCommitIfUnique && context.Trigger.Kind != CompletionTriggerKind.Insertion) { return; } var position = context.Position; var(tree, stringToken) = await _language.TryGetTreeAndTokenAtPositionAsync( context.Document, position, context.CancellationToken).ConfigureAwait(false); if (tree == null || position <= stringToken.SpanStart || position >= stringToken.Span.End) { return; } var embeddedContext = new EmbeddedCompletionContext(_language, context, tree, stringToken); ProvideCompletions(embeddedContext); if (embeddedContext.Items.Count == 0) { return; } foreach (var embeddedItem in embeddedContext.Items) { var change = embeddedItem.Change; var textChange = change.TextChange; var properties = ImmutableDictionary.CreateBuilder <string, string>(); properties.Add(StartKey, textChange.Span.Start.ToString()); properties.Add(LengthKey, textChange.Span.Length.ToString()); properties.Add(NewTextKey, textChange.NewText); properties.Add(DescriptionKey, embeddedItem.FullDescription); properties.Add(EmbeddedLanguageCompletionProvider.EmbeddedProviderName, Name); if (change.NewPosition != null) { properties.Add(NewPositionKey, change.NewPosition.ToString()); } // Keep everything sorted in the order we just produced the items in. var sortText = context.Items.Count.ToString("0000"); context.AddItem(CompletionItem.Create( displayText: embeddedItem.DisplayText, inlineDescription: embeddedItem.InlineDescription, sortText: sortText, properties: properties.ToImmutable(), rules: s_rules)); } context.IsExclusive = true; }
private static ImmutableDictionary <IAssemblySymbol, ImmutableSortedSet <string> > GetRestrictedInternalsVisibleToMap(Compilation compilation) { var restrictedInternalsVisibleToAttribute = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemRuntimeCompilerServicesRestrictedInternalsVisibleToAttribute); if (restrictedInternalsVisibleToAttribute == null) { return(ImmutableDictionary <IAssemblySymbol, ImmutableSortedSet <string> > .Empty); } var builder = ImmutableDictionary.CreateBuilder <IAssemblySymbol, ImmutableSortedSet <string> >(); foreach (var referencedAssemblySymbol in compilation.References.Select(compilation.GetAssemblyOrModuleSymbol).OfType <IAssemblySymbol>()) { // Check IVT if (!referencedAssemblySymbol.GivesAccessTo(compilation.Assembly)) { continue; } var namespaceNameComparer = compilation.IsCaseSensitive ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase; var namespaceBuilder = ImmutableSortedSet.CreateBuilder(namespaceNameComparer); foreach (var assemblyAttribute in referencedAssemblySymbol.GetAttributes()) { // Look for ctor: "RestrictedInternalsVisibleToAttribute(string assemblyName, params string[] namespaces)" if (!Equals(assemblyAttribute.AttributeClass, restrictedInternalsVisibleToAttribute) || assemblyAttribute.AttributeConstructor.Parameters.Length != 2 || assemblyAttribute.AttributeConstructor.Parameters[0].Type.SpecialType != SpecialType.System_String || !(assemblyAttribute.AttributeConstructor.Parameters[1].Type is IArrayTypeSymbol arrayType) || arrayType.Rank != 1 || arrayType.ElementType.SpecialType != SpecialType.System_String || !assemblyAttribute.AttributeConstructor.Parameters[1].IsParams) { continue; } // Ensure the Restricted IVT is for the current compilation's assembly. if (assemblyAttribute.ConstructorArguments.Length != 2 || assemblyAttribute.ConstructorArguments[0].Kind != TypedConstantKind.Primitive || !(assemblyAttribute.ConstructorArguments[0].Value is string assemblyName) || !string.Equals(assemblyName, compilation.Assembly.Name, StringComparison.OrdinalIgnoreCase)) { continue; } // Ensure second constructor argument is string array. if (assemblyAttribute.ConstructorArguments[1].Kind != TypedConstantKind.Array || !(assemblyAttribute.ConstructorArguments[1].Values is var namespaceConstants)) { continue; } // Add namespaces specified in the second constructor argument. foreach (TypedConstant namespaceConstant in namespaceConstants) { if (namespaceConstant.Kind == TypedConstantKind.Primitive && namespaceConstant.Value is string namespaceName) { namespaceBuilder.Add(namespaceName); } } } if (namespaceBuilder.Count > 0) { builder.Add(referencedAssemblySymbol, namespaceBuilder.ToImmutable()); } } return(builder.ToImmutable()); }
static GatewayBucket() { GatewayBucket[] buckets = new[] { new GatewayBucket(GatewayBucketType.Unbucketed, BucketId.Create(null, "<gateway-unbucketed>", null), 120, 60), new GatewayBucket(GatewayBucketType.Identify, BucketId.Create(null, "<gateway-identify>", null), 1, 5), new GatewayBucket(GatewayBucketType.PresenceUpdate, BucketId.Create(null, "<gateway-presenceupdate>", null), 5, 60), }; ImmutableDictionary <GatewayBucketType, GatewayBucket> .Builder builder = ImmutableDictionary.CreateBuilder <GatewayBucketType, GatewayBucket>(); foreach (GatewayBucket bucket in buckets) { builder.Add(bucket.Type, bucket); } DefsByType = builder.ToImmutable(); ImmutableDictionary <BucketId, GatewayBucket> .Builder builder2 = ImmutableDictionary.CreateBuilder <BucketId, GatewayBucket>(); foreach (GatewayBucket bucket in buckets) { builder2.Add(bucket.Id, bucket); } DefsById = builder2.ToImmutable(); }
public TaintedDataSymbolMap(WellKnownTypeProvider wellKnownTypeProvider, IEnumerable <TInfo> taintedDataInfos) { if (wellKnownTypeProvider == null) { throw new ArgumentNullException(nameof(wellKnownTypeProvider)); } if (taintedDataInfos == null) { throw new ArgumentNullException(nameof(taintedDataInfos)); } ImmutableDictionary <ITypeSymbol, TInfo> .Builder concreteInfosBuilder = ImmutableDictionary.CreateBuilder <ITypeSymbol, TInfo>(); ImmutableDictionary <ITypeSymbol, TInfo> .Builder interfaceInfosBuilder = ImmutableDictionary.CreateBuilder <ITypeSymbol, TInfo>(); foreach (TInfo info in taintedDataInfos) { if (!TryResolveDependencies(info, wellKnownTypeProvider)) { continue; } if (wellKnownTypeProvider.TryGetOrCreateTypeByMetadataName(info.FullTypeName, out INamedTypeSymbol? namedTypeSymbol)) { if (info.IsInterface) { interfaceInfosBuilder[namedTypeSymbol] = info; } else { concreteInfosBuilder[namedTypeSymbol] = info; } if (info.RequiresValueContentAnalysis) { RequiresValueContentAnalysis = true; } if (info.RequiresParameterReferenceAnalysis) { RequiresParameterReferenceAnalysis = true; } } } this.ConcreteInfos = concreteInfosBuilder.ToImmutable(); this.InterfaceInfos = interfaceInfosBuilder.ToImmutable(); }
public static async Task <ImmutableDictionary <DiagnosticAnalyzer, DiagnosticAnalysisResultBuilder> > ToResultBuilderMapAsync( this AnalysisResult analysisResult, ImmutableArray <Diagnostic> additionalPragmaSuppressionDiagnostics, DocumentAnalysisScope?documentAnalysisScope, Project project, VersionStamp version, Compilation compilation, IEnumerable <DiagnosticAnalyzer> analyzers, SkippedHostAnalyzersInfo skippedAnalyzersInfo, bool includeSuppressedDiagnostics, CancellationToken cancellationToken) { SyntaxTree? treeToAnalyze = null; AdditionalText?additionalFileToAnalyze = null; if (documentAnalysisScope != null) { if (documentAnalysisScope.TextDocument is Document document) { treeToAnalyze = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); } else { additionalFileToAnalyze = documentAnalysisScope.AdditionalFile; } } var builder = ImmutableDictionary.CreateBuilder <DiagnosticAnalyzer, DiagnosticAnalysisResultBuilder>(); foreach (var analyzer in analyzers) { cancellationToken.ThrowIfCancellationRequested(); if (skippedAnalyzersInfo.SkippedAnalyzers.Contains(analyzer)) { continue; } var result = new DiagnosticAnalysisResultBuilder(project, version); var diagnosticIdsToFilter = skippedAnalyzersInfo.FilteredDiagnosticIdsForAnalyzers.GetValueOrDefault( analyzer, ImmutableArray <string> .Empty); if (documentAnalysisScope != null) { RoslynDebug.Assert(treeToAnalyze != null || additionalFileToAnalyze != null); var spanToAnalyze = documentAnalysisScope.Span; var kind = documentAnalysisScope.Kind; ImmutableDictionary <DiagnosticAnalyzer, ImmutableArray <Diagnostic> >?diagnosticsByAnalyzerMap; switch (kind) { case AnalysisKind.Syntax: if (treeToAnalyze != null) { if (analysisResult.SyntaxDiagnostics.TryGetValue(treeToAnalyze, out diagnosticsByAnalyzerMap)) { AddAnalyzerDiagnosticsToResult(analyzer, diagnosticsByAnalyzerMap, ref result, compilation, treeToAnalyze, additionalDocumentId: null, spanToAnalyze, AnalysisKind.Syntax, diagnosticIdsToFilter, includeSuppressedDiagnostics); } } else if (analysisResult.AdditionalFileDiagnostics.TryGetValue(additionalFileToAnalyze !, out diagnosticsByAnalyzerMap)) { AddAnalyzerDiagnosticsToResult(analyzer, diagnosticsByAnalyzerMap, ref result, compilation, tree: null, documentAnalysisScope.TextDocument.Id, spanToAnalyze, AnalysisKind.Syntax, diagnosticIdsToFilter, includeSuppressedDiagnostics); } break; case AnalysisKind.Semantic: if (analysisResult.SemanticDiagnostics.TryGetValue(treeToAnalyze !, out diagnosticsByAnalyzerMap)) { AddAnalyzerDiagnosticsToResult(analyzer, diagnosticsByAnalyzerMap, ref result, compilation, treeToAnalyze, additionalDocumentId: null, spanToAnalyze, AnalysisKind.Semantic, diagnosticIdsToFilter, includeSuppressedDiagnostics); } break; default: throw ExceptionUtilities.UnexpectedValue(kind); } } else { foreach (var(tree, diagnosticsByAnalyzerMap) in analysisResult.SyntaxDiagnostics) { AddAnalyzerDiagnosticsToResult(analyzer, diagnosticsByAnalyzerMap, ref result, compilation, tree, additionalDocumentId: null, span: null, AnalysisKind.Syntax, diagnosticIdsToFilter, includeSuppressedDiagnostics); } foreach (var(tree, diagnosticsByAnalyzerMap) in analysisResult.SemanticDiagnostics) { AddAnalyzerDiagnosticsToResult(analyzer, diagnosticsByAnalyzerMap, ref result, compilation, tree, additionalDocumentId: null, span: null, AnalysisKind.Semantic, diagnosticIdsToFilter, includeSuppressedDiagnostics); } foreach (var(file, diagnosticsByAnalyzerMap) in analysisResult.AdditionalFileDiagnostics) { var additionalDocumentId = project.GetDocumentForFile(file); var kind = additionalDocumentId != null ? AnalysisKind.Syntax : AnalysisKind.NonLocal; AddAnalyzerDiagnosticsToResult(analyzer, diagnosticsByAnalyzerMap, ref result, compilation, tree: null, additionalDocumentId, span: null, kind, diagnosticIdsToFilter, includeSuppressedDiagnostics); } AddAnalyzerDiagnosticsToResult(analyzer, analysisResult.CompilationDiagnostics, ref result, compilation, tree: null, additionalDocumentId: null, span: null, AnalysisKind.NonLocal, diagnosticIdsToFilter, includeSuppressedDiagnostics); } // Special handling for pragma suppression diagnostics. if (!additionalPragmaSuppressionDiagnostics.IsEmpty && analyzer is IPragmaSuppressionsAnalyzer) { if (documentAnalysisScope != null) { if (treeToAnalyze != null) { var diagnostics = additionalPragmaSuppressionDiagnostics.WhereAsArray(d => d.Location.SourceTree == treeToAnalyze); AddDiagnosticsToResult(diagnostics, ref result, compilation, treeToAnalyze, additionalDocumentId: null, documentAnalysisScope !.Span, AnalysisKind.Semantic, diagnosticIdsToFilter, includeSuppressedDiagnostics); } } else { foreach (var group in additionalPragmaSuppressionDiagnostics.GroupBy(d => d.Location.SourceTree !)) { AddDiagnosticsToResult(group.AsImmutable(), ref result, compilation, group.Key, additionalDocumentId: null, span: null, AnalysisKind.Semantic, diagnosticIdsToFilter, includeSuppressedDiagnostics); } } additionalPragmaSuppressionDiagnostics = ImmutableArray <Diagnostic> .Empty; } builder.Add(analyzer, result); } return(builder.ToImmutable());
private bool MergeChanges( IDependenciesChanges changes, IEnumerable <IDependenciesSnapshotFilter> snapshotFilters, IEnumerable <IProjectDependenciesSubTreeProvider> subTreeProviders, HashSet <string> projectItemSpecs) { var worldBuilder = ImmutableDictionary.CreateBuilder <string, IDependency>( StringComparer.OrdinalIgnoreCase); worldBuilder.AddRange(DependenciesWorld); var topLevelBuilder = ImmutableHashSet.CreateBuilder <IDependency>(); topLevelBuilder.AddRange(TopLevelDependencies); var anyChanges = false; foreach (var removed in changes.RemovedNodes) { var targetedId = Dependency.GetID(TargetFramework, removed.ProviderType, removed.Id); if (!worldBuilder.TryGetValue(targetedId, out IDependency dependency)) { continue; } if (snapshotFilters != null) { foreach (var filter in snapshotFilters) { dependency = filter.BeforeRemove( ProjectPath, TargetFramework, dependency, worldBuilder, topLevelBuilder, out bool filterAnyChanges); anyChanges |= filterAnyChanges; if (dependency == null) { break; } } } if (dependency == null) { continue; } anyChanges = true; worldBuilder.Remove(targetedId); topLevelBuilder.Remove(dependency); } var subTreeProvidersMap = GetSubTreeProviderMap(subTreeProviders); foreach (var added in changes.AddedNodes) { IDependency newDependency = new Dependency(added, TargetFramework, ProjectPath); if (snapshotFilters != null) { foreach (var filter in snapshotFilters) { newDependency = filter.BeforeAdd( ProjectPath, TargetFramework, newDependency, worldBuilder, topLevelBuilder, subTreeProvidersMap, projectItemSpecs, out bool filterAnyChanges); anyChanges |= filterAnyChanges; if (newDependency == null) { break; } } } if (newDependency == null) { continue; } anyChanges = true; worldBuilder.Remove(newDependency.Id); worldBuilder.Add(newDependency.Id, newDependency); if (newDependency.TopLevel) { topLevelBuilder.Remove(newDependency); topLevelBuilder.Add(newDependency); } } DependenciesWorld = worldBuilder.ToImmutable(); TopLevelDependencies = topLevelBuilder.ToImmutable(); ConstructTopLevelDependenciesByPathMap(); return(anyChanges); }
private async Task <AggregateWorkspaceProjectContext> CreateProjectContextAsyncCore() { string languageName = await GetLanguageServiceName().ConfigureAwait(false); if (string.IsNullOrEmpty(languageName)) { return(null); } Guid projectGuid = await GetProjectGuidAsync().ConfigureAwait(false); string targetPath = await GetTargetPathAsync().ConfigureAwait(false); if (string.IsNullOrEmpty(targetPath)) { return(null); } // Don't initialize until the project has been loaded into the IDE and available in Solution Explorer await _asyncLoadDashboard.ProjectLoadedInHost.ConfigureAwait(false); // TODO: https://github.com/dotnet/roslyn-project-system/issues/353 return(await _taskScheduler.RunAsync(TaskSchedulerPriority.UIThreadBackgroundPriority, async() => { await _commonServices.ThreadingService.SwitchToUIThread(); var projectData = GetProjectData(); // Get the set of active configured projects ignoring target framework. #pragma warning disable CS0618 // Type or member is obsolete var configuredProjectsMap = await _activeConfiguredProjectsProvider.GetActiveConfiguredProjectsMapAsync().ConfigureAwait(true); #pragma warning restore CS0618 // Type or member is obsolete // Get the unconfigured project host object (shared host object). var configuredProjectsToRemove = new HashSet <ConfiguredProject>(_configuredProjectHostObjectsMap.Keys); var activeProjectConfiguration = _commonServices.ActiveConfiguredProject.ProjectConfiguration; var innerProjectContextsBuilder = ImmutableDictionary.CreateBuilder <string, IWorkspaceProjectContext>(); string activeTargetFramework = string.Empty; IConfiguredProjectHostObject activeIntellisenseProjectHostObject = null; foreach (var kvp in configuredProjectsMap) { var targetFramework = kvp.Key; var configuredProject = kvp.Value; if (!TryGetConfiguredProjectState(configuredProject, out IWorkspaceProjectContext workspaceProjectContext, out IConfiguredProjectHostObject configuredProjectHostObject)) { // Get the target path for the configured project. var projectProperties = configuredProject.Services.ExportProvider.GetExportedValue <ProjectProperties>(); var configurationGeneralProperties = await projectProperties.GetConfigurationGeneralPropertiesAsync().ConfigureAwait(true); targetPath = (string)await configurationGeneralProperties.TargetPath.GetValueAsync().ConfigureAwait(true); var targetFrameworkMoniker = (string)await configurationGeneralProperties.TargetFrameworkMoniker.GetValueAsync().ConfigureAwait(true); var displayName = GetDisplayName(configuredProject, projectData, targetFramework); configuredProjectHostObject = _projectHostProvider.GetConfiguredProjectHostObject(_unconfiguredProjectHostObject, displayName, targetFrameworkMoniker); // TODO: https://github.com/dotnet/roslyn-project-system/issues/353 await _commonServices.ThreadingService.SwitchToUIThread(); // HACK HACK: Roslyn's CreateProjectContext only supports C# and VB and for F#, a new overload was added. Instead, that should be removed and the main overload should just take an optional error prefix. if (languageName == "F#") { workspaceProjectContext = _contextFactory.Value.CreateProjectContext(languageName, displayName, projectData.FullPath, projectGuid, configuredProjectHostObject, targetPath, null); } else { workspaceProjectContext = _contextFactory.Value.CreateProjectContext(languageName, displayName, projectData.FullPath, projectGuid, configuredProjectHostObject, targetPath); } // By default, set "LastDesignTimeBuildSucceeded = false" to turn off diagnostics until first design time build succeeds for this project. workspaceProjectContext.LastDesignTimeBuildSucceeded = false; AddConfiguredProjectState(configuredProject, workspaceProjectContext, configuredProjectHostObject); } innerProjectContextsBuilder.Add(targetFramework, workspaceProjectContext); if (activeIntellisenseProjectHostObject == null && configuredProject.ProjectConfiguration.Equals(activeProjectConfiguration)) { activeIntellisenseProjectHostObject = configuredProjectHostObject; activeTargetFramework = targetFramework; } } _unconfiguredProjectHostObject.ActiveIntellisenseProjectHostObject = activeIntellisenseProjectHostObject; return new AggregateWorkspaceProjectContext(innerProjectContextsBuilder.ToImmutable(), configuredProjectsMap, activeTargetFramework, _unconfiguredProjectHostObject); }));
private async Task <ImmutableDictionary <Document, ImmutableArray <Diagnostic> > > GetDocumentDiagnosticsToFixAsync(IEnumerable <DiagnosticData> diagnosticsToFix, Func <Project, bool> shouldFixInProject, bool filterStaleDiagnostics, CancellationToken cancellationToken) { var builder = ImmutableDictionary.CreateBuilder <DocumentId, List <DiagnosticData> >(); foreach (var diagnosticData in diagnosticsToFix.Where(IsDocumentDiagnostic)) { if (!builder.TryGetValue(diagnosticData.DocumentId, out var diagnosticsPerDocument)) { diagnosticsPerDocument = new List <DiagnosticData>(); builder[diagnosticData.DocumentId] = diagnosticsPerDocument; } diagnosticsPerDocument.Add(diagnosticData); } if (builder.Count == 0) { return(ImmutableDictionary <Document, ImmutableArray <Diagnostic> > .Empty); } var finalBuilder = ImmutableDictionary.CreateBuilder <Document, ImmutableArray <Diagnostic> >(); var latestDocumentDiagnosticsMapOpt = filterStaleDiagnostics ? new Dictionary <DocumentId, ImmutableHashSet <DiagnosticData> >() : null; foreach (var group in builder.GroupBy(kvp => kvp.Key.ProjectId)) { var projectId = group.Key; var project = _workspace.CurrentSolution.GetProject(projectId); if (project == null || !shouldFixInProject(project)) { continue; } if (filterStaleDiagnostics) { var uniqueDiagnosticIds = group.SelectMany(kvp => kvp.Value.Select(d => d.Id)).ToImmutableHashSet(); var latestProjectDiagnostics = (await _diagnosticService.GetDiagnosticsForIdsAsync(project.Solution, project.Id, diagnosticIds: uniqueDiagnosticIds, includeSuppressedDiagnostics: true, cancellationToken: cancellationToken) .ConfigureAwait(false)).Where(IsDocumentDiagnostic); latestDocumentDiagnosticsMapOpt.Clear(); foreach (var kvp in latestProjectDiagnostics.Where(d => d.DocumentId != null).GroupBy(d => d.DocumentId)) { latestDocumentDiagnosticsMapOpt.Add(kvp.Key, kvp.ToImmutableHashSet()); } } foreach (var documentDiagnostics in group) { var document = project.GetDocument(documentDiagnostics.Key); if (document == null) { continue; } IEnumerable <DiagnosticData> documentDiagnosticsToFix; if (filterStaleDiagnostics) { if (!latestDocumentDiagnosticsMapOpt.TryGetValue(document.Id, out var latestDocumentDiagnostics)) { // Ignore stale diagnostics in error list. latestDocumentDiagnostics = ImmutableHashSet <DiagnosticData> .Empty; } // Filter out stale diagnostics in error list. documentDiagnosticsToFix = documentDiagnostics.Value.Where(d => latestDocumentDiagnostics.Contains(d) || SuppressionHelpers.IsSynthesizedExternalSourceDiagnostic(d)); } else { documentDiagnosticsToFix = documentDiagnostics.Value; } if (documentDiagnosticsToFix.Any()) { var diagnostics = await documentDiagnosticsToFix.ToDiagnosticsAsync(project, cancellationToken).ConfigureAwait(false); finalBuilder.Add(document, diagnostics); } } } return(finalBuilder.ToImmutableDictionary());
/// <exception cref="InvalidOperationException">Bad data.</exception> private static void GetCSharpDynamicLocalInfo( byte[] customDebugInfo, IEnumerable <ISymUnmanagedScope> scopes, out ImmutableDictionary <int, ImmutableArray <bool> > dynamicLocalMap, out ImmutableDictionary <string, ImmutableArray <bool> > dynamicLocalConstantMap) { dynamicLocalMap = null; dynamicLocalConstantMap = null; var record = CustomDebugInfoReader.TryGetCustomDebugInfoRecord(customDebugInfo, CustomDebugInfoKind.DynamicLocals); if (record.IsDefault) { return; } var localKindsByName = PooledDictionary <string, LocalKind> .GetInstance(); GetLocalKindByName(localKindsByName, scopes); ImmutableDictionary <int, ImmutableArray <bool> > .Builder localBuilder = null; ImmutableDictionary <string, ImmutableArray <bool> > .Builder constantBuilder = null; var dynamicLocals = CustomDebugInfoReader.DecodeDynamicLocalsRecord(record); foreach (var dynamicLocal in dynamicLocals) { int slot = dynamicLocal.SlotId; var flags = dynamicLocal.Flags; if (slot == 0) { LocalKind kind; var name = dynamicLocal.LocalName; localKindsByName.TryGetValue(name, out kind); switch (kind) { case LocalKind.DuplicateName: // Drop locals with ambiguous names. continue; case LocalKind.ConstantName: constantBuilder = constantBuilder ?? ImmutableDictionary.CreateBuilder <string, ImmutableArray <bool> >(); constantBuilder[name] = flags; continue; } } localBuilder = localBuilder ?? ImmutableDictionary.CreateBuilder <int, ImmutableArray <bool> >(); localBuilder[slot] = flags; } if (localBuilder != null) { dynamicLocalMap = localBuilder.ToImmutable(); } if (constantBuilder != null) { dynamicLocalConstantMap = constantBuilder.ToImmutable(); } localKindsByName.Free(); }
public static AnalyzerConfig Parse(SourceText text, string pathToFile) { if (!Path.IsPathRooted(pathToFile) || string.IsNullOrEmpty(Path.GetFileName(pathToFile))) { throw new ArgumentException("Must be an absolute path to an editorconfig file", nameof(pathToFile)); } Section?globalSection = null; var namedSectionBuilder = ImmutableArray.CreateBuilder <Section>(); // N.B. The editorconfig documentation is quite loose on property interpretation. // Specifically, it says: // Currently all properties and values are case-insensitive. // They are lowercased when parsed. // To accommodate this, we use a lower case Unicode mapping when adding to the // dictionary, but we also use a case-insensitive key comparer when doing lookups var activeSectionProperties = ImmutableDictionary.CreateBuilder <string, string>( Section.PropertiesKeyComparer); string activeSectionName = ""; foreach (var textLine in text.Lines) { string line = textLine.ToString(); if (string.IsNullOrWhiteSpace(line)) { continue; } if (IsComment(line)) { continue; } var sectionMatches = s_sectionMatcher.Matches(line); if (sectionMatches.Count > 0 && sectionMatches[0].Groups.Count > 0) { addNewSection(); var sectionName = sectionMatches[0].Groups[1].Value; Debug.Assert(!string.IsNullOrEmpty(sectionName)); activeSectionName = sectionName; activeSectionProperties = ImmutableDictionary.CreateBuilder <string, string>( Section.PropertiesKeyComparer); continue; } var propMatches = s_propertyMatcher.Matches(line); if (propMatches.Count > 0 && propMatches[0].Groups.Count > 1) { var key = propMatches[0].Groups[1].Value; var value = propMatches[0].Groups[2].Value; Debug.Assert(!string.IsNullOrEmpty(key)); Debug.Assert(key == key.Trim()); Debug.Assert(value == value?.Trim()); key = CaseInsensitiveComparison.ToLower(key); if (ReservedKeys.Contains(key) || ReservedValues.Contains(value)) { value = CaseInsensitiveComparison.ToLower(value); } activeSectionProperties[key] = value ?? ""; continue; } } // Add the last section addNewSection(); return(new AnalyzerConfig(globalSection !, namedSectionBuilder.ToImmutable(), pathToFile)); void addNewSection() { // Close out the previous section var previousSection = new Section(activeSectionName, activeSectionProperties.ToImmutable()); if (activeSectionName == "") { // This is the global section globalSection = previousSection; } else { namedSectionBuilder.Add(previousSection); } } }
private static void ReadLocalScopeInformation( MetadataReader reader, MethodDefinitionHandle methodHandle, int ilOffset, EESymbolProvider <TTypeSymbol, TLocalSymbol> symbolProvider, bool isVisualBasicMethod, out ImmutableArray <ImmutableArray <ImportRecord> > importGroups, out ImmutableArray <ExternAliasRecord> externAliases, out ImmutableArray <string> localVariableNames, out ImmutableDictionary <int, ImmutableArray <bool> > dynamicLocals, out ImmutableArray <TLocalSymbol> localConstants, out ILSpan reuseSpan) { var localVariableNamesBuilder = ArrayBuilder <string> .GetInstance(); var localConstantsBuilder = ArrayBuilder <TLocalSymbol> .GetInstance(); ImmutableDictionary <int, ImmutableArray <bool> > .Builder lazyDynamicLocalsBuilder = null; var innerMostImportScope = default(ImportScopeHandle); uint reuseSpanStart = 0; uint reuseSpanEnd = uint.MaxValue; try { foreach (var scopeHandle in reader.GetLocalScopes(methodHandle)) { try { var scope = reader.GetLocalScope(scopeHandle); if (ilOffset < scope.StartOffset) { // scopes are sorted by StartOffset, hence all scopes that follow can't contain ilOffset reuseSpanEnd = Math.Min(reuseSpanEnd, (uint)scope.StartOffset); break; } if (ilOffset >= scope.EndOffset) { // ilOffset is not in this scope, go to next one reuseSpanStart = Math.Max(reuseSpanStart, (uint)scope.EndOffset); continue; } // reuse span is a subspan of the inner-most scope containing the IL offset: reuseSpanStart = Math.Max(reuseSpanStart, (uint)scope.StartOffset); reuseSpanEnd = Math.Min(reuseSpanEnd, (uint)scope.EndOffset); // imports (use the inner-most): innerMostImportScope = scope.ImportScope; // locals (from all contained scopes): foreach (var variableHandle in scope.GetLocalVariables()) { var variable = reader.GetLocalVariable(variableHandle); if ((variable.Attributes & LocalVariableAttributes.DebuggerHidden) != 0) { continue; } localVariableNamesBuilder.SetItem(variable.Index, reader.GetString(variable.Name)); var dynamicFlags = ReadDynamicCustomDebugInformation(reader, variableHandle); if (!dynamicFlags.IsDefault) { lazyDynamicLocalsBuilder = lazyDynamicLocalsBuilder ?? ImmutableDictionary.CreateBuilder <int, ImmutableArray <bool> >(); lazyDynamicLocalsBuilder[variable.Index] = dynamicFlags; } } // constants (from all contained scopes): foreach (var constantHandle in scope.GetLocalConstants()) { var constant = reader.GetLocalConstant(constantHandle); TTypeSymbol typeSymbol; ConstantValue value; var sigReader = reader.GetBlobReader(constant.Signature); symbolProvider.DecodeLocalConstant(ref sigReader, out typeSymbol, out value); var dynamicFlags = ReadDynamicCustomDebugInformation(reader, constantHandle); localConstantsBuilder.Add(symbolProvider.GetLocalConstant(reader.GetString(constant.Name), typeSymbol, value, dynamicFlags)); } } catch (Exception e) when(e is UnsupportedSignatureContent || e is BadImageFormatException) { // ignore scopes with invalid data } } } finally { localVariableNames = localVariableNamesBuilder.ToImmutableAndFree(); localConstants = localConstantsBuilder.ToImmutableAndFree(); dynamicLocals = lazyDynamicLocalsBuilder?.ToImmutable(); reuseSpan = new ILSpan(reuseSpanStart, reuseSpanEnd); } var importGroupsBuilder = ArrayBuilder <ImmutableArray <ImportRecord> > .GetInstance(); var externAliasesBuilder = ArrayBuilder <ExternAliasRecord> .GetInstance(); try { if (!innerMostImportScope.IsNil) { PopulateImports(reader, innerMostImportScope, symbolProvider, isVisualBasicMethod, importGroupsBuilder, externAliasesBuilder); } } catch (Exception e) when(e is UnsupportedSignatureContent || e is BadImageFormatException) { // ignore invalid imports } importGroups = importGroupsBuilder.ToImmutableAndFree(); externAliases = externAliasesBuilder.ToImmutableAndFree(); }
private static partial ImmutableDictionary <Type, IEnumerable> BuildDataSets() { var builder = ImmutableDictionary.CreateBuilder <Type, IEnumerable>(); // double data-set var doubleDataSet = ImmutableList.CreateBuilder <double>(); doubleDataSet.Add(-25.234324D); doubleDataSet.Add(-22.8885915D); doubleDataSet.Add(-20.542859D); doubleDataSet.Add(-18.1971265D); doubleDataSet.Add(-15.851393999999999D); doubleDataSet.Add(-13.505661499999999D); doubleDataSet.Add(-11.159928999999998D); doubleDataSet.Add(-8.814196499999998D); doubleDataSet.Add(-6.468463999999997D); doubleDataSet.Add(-4.122731499999997D); doubleDataSet.Add(-1.7769989999999969D); doubleDataSet.Add(0.5687335000000031D); doubleDataSet.Add(2.914466000000003D); doubleDataSet.Add(5.260198500000003D); doubleDataSet.Add(7.6059310000000036D); doubleDataSet.Add(9.951663500000004D); doubleDataSet.Add(12.297396000000004D); doubleDataSet.Add(14.643128500000005D); doubleDataSet.Add(16.988861000000004D); doubleDataSet.Add(19.334593500000004D); doubleDataSet.Add(21.680326000000004D); doubleDataSet.Add(24.026058500000005D); doubleDataSet.Add(26.371791000000005D); doubleDataSet.Add(28.717523500000006D); doubleDataSet.Add(31.063256000000006D); builder.Add(typeof(double), doubleDataSet.ToImmutable()); // decimal? data-set var nullableDecimalDataSet = ImmutableList.CreateBuilder <decimal?>(); nullableDecimalDataSet.Add(-25.234324M); nullableDecimalDataSet.Add(null); nullableDecimalDataSet.Add(-22.8885915M); nullableDecimalDataSet.Add(-20.542859M); nullableDecimalDataSet.Add(-18.1971265M); nullableDecimalDataSet.Add(-15.851394M); nullableDecimalDataSet.Add(null); nullableDecimalDataSet.Add(-13.5056615M); nullableDecimalDataSet.Add(-11.159929M); nullableDecimalDataSet.Add(-8.8141965M); nullableDecimalDataSet.Add(-6.468464M); nullableDecimalDataSet.Add(null); nullableDecimalDataSet.Add(-4.1227315M); nullableDecimalDataSet.Add(-1.776999M); nullableDecimalDataSet.Add(0.568733500000003M); nullableDecimalDataSet.Add(2.914466M); nullableDecimalDataSet.Add(null); nullableDecimalDataSet.Add(5.2601985M); nullableDecimalDataSet.Add(7.605931M); nullableDecimalDataSet.Add(9.9516635M); nullableDecimalDataSet.Add(12.297396M); nullableDecimalDataSet.Add(null); nullableDecimalDataSet.Add(14.6431285M); nullableDecimalDataSet.Add(16.988861M); nullableDecimalDataSet.Add(19.3345935M); nullableDecimalDataSet.Add(21.680326M); nullableDecimalDataSet.Add(null); nullableDecimalDataSet.Add(24.0260585M); nullableDecimalDataSet.Add(26.371791M); nullableDecimalDataSet.Add(28.7175235M); nullableDecimalDataSet.Add(31.063256M); nullableDecimalDataSet.Add(null); builder.Add(typeof(decimal?), nullableDecimalDataSet.ToImmutable()); // float? data-set var nullableSingleDataSet = ImmutableList.CreateBuilder <float?>(); nullableSingleDataSet.Add(-25.234324F); nullableSingleDataSet.Add(null); nullableSingleDataSet.Add(-22.888592F); nullableSingleDataSet.Add(-20.542858F); nullableSingleDataSet.Add(-18.197126F); nullableSingleDataSet.Add(-15.851394F); nullableSingleDataSet.Add(null); nullableSingleDataSet.Add(-13.505662F); nullableSingleDataSet.Add(-11.159929F); nullableSingleDataSet.Add(-8.814197F); nullableSingleDataSet.Add(-6.468464F); nullableSingleDataSet.Add(null); nullableSingleDataSet.Add(-4.1227317F); nullableSingleDataSet.Add(-1.776999F); nullableSingleDataSet.Add(0.5687335F); nullableSingleDataSet.Add(2.914466F); nullableSingleDataSet.Add(null); nullableSingleDataSet.Add(5.2601986F); nullableSingleDataSet.Add(7.605931F); nullableSingleDataSet.Add(9.951664F); nullableSingleDataSet.Add(12.297396F); nullableSingleDataSet.Add(null); nullableSingleDataSet.Add(14.643128F); nullableSingleDataSet.Add(16.988861F); nullableSingleDataSet.Add(19.334593F); nullableSingleDataSet.Add(21.680326F); nullableSingleDataSet.Add(null); nullableSingleDataSet.Add(24.026058F); nullableSingleDataSet.Add(26.371792F); nullableSingleDataSet.Add(28.717524F); nullableSingleDataSet.Add(31.063255F); nullableSingleDataSet.Add(null); builder.Add(typeof(float?), nullableSingleDataSet.ToImmutable()); // double? data-set var nullableDoubleDataSet = ImmutableList.CreateBuilder <double?>(); nullableDoubleDataSet.Add(-25.234324D); nullableDoubleDataSet.Add(null); nullableDoubleDataSet.Add(-22.8885915D); nullableDoubleDataSet.Add(-20.542859D); nullableDoubleDataSet.Add(-18.1971265D); nullableDoubleDataSet.Add(-15.851393999999999D); nullableDoubleDataSet.Add(null); nullableDoubleDataSet.Add(-13.505661499999999D); nullableDoubleDataSet.Add(-11.159928999999998D); nullableDoubleDataSet.Add(-8.814196499999998D); nullableDoubleDataSet.Add(-6.468463999999997D); nullableDoubleDataSet.Add(null); nullableDoubleDataSet.Add(-4.122731499999997D); nullableDoubleDataSet.Add(-1.7769989999999969D); nullableDoubleDataSet.Add(0.5687335000000031D); nullableDoubleDataSet.Add(2.914466000000003D); nullableDoubleDataSet.Add(null); nullableDoubleDataSet.Add(5.260198500000003D); nullableDoubleDataSet.Add(7.6059310000000036D); nullableDoubleDataSet.Add(9.951663500000004D); nullableDoubleDataSet.Add(12.297396000000004D); nullableDoubleDataSet.Add(null); nullableDoubleDataSet.Add(14.643128500000005D); nullableDoubleDataSet.Add(16.988861000000004D); nullableDoubleDataSet.Add(19.334593500000004D); nullableDoubleDataSet.Add(21.680326000000004D); nullableDoubleDataSet.Add(null); nullableDoubleDataSet.Add(24.026058500000005D); nullableDoubleDataSet.Add(26.371791000000005D); nullableDoubleDataSet.Add(28.717523500000006D); nullableDoubleDataSet.Add(31.063256000000006D); nullableDoubleDataSet.Add(null); builder.Add(typeof(double?), nullableDoubleDataSet.ToImmutable()); // decimal data-set var decimalDataSet = ImmutableList.CreateBuilder <decimal>(); decimalDataSet.Add(-25.234324M); decimalDataSet.Add(-22.8885915M); decimalDataSet.Add(-20.542859M); decimalDataSet.Add(-18.1971265M); decimalDataSet.Add(-15.851394M); decimalDataSet.Add(-13.5056615M); decimalDataSet.Add(-11.159929M); decimalDataSet.Add(-8.8141965M); decimalDataSet.Add(-6.468464M); decimalDataSet.Add(-4.1227315M); decimalDataSet.Add(-1.776999M); decimalDataSet.Add(0.568733500000003M); decimalDataSet.Add(2.914466M); decimalDataSet.Add(5.2601985M); decimalDataSet.Add(7.605931M); decimalDataSet.Add(9.9516635M); decimalDataSet.Add(12.297396M); decimalDataSet.Add(14.6431285M); decimalDataSet.Add(16.988861M); decimalDataSet.Add(19.3345935M); decimalDataSet.Add(21.680326M); decimalDataSet.Add(24.0260585M); decimalDataSet.Add(26.371791M); decimalDataSet.Add(28.7175235M); decimalDataSet.Add(31.063256M); builder.Add(typeof(decimal), decimalDataSet.ToImmutable()); // float data-set var singleDataSet = ImmutableList.CreateBuilder <float>(); singleDataSet.Add(-25.234324F); singleDataSet.Add(-22.888592F); singleDataSet.Add(-20.542858F); singleDataSet.Add(-18.197126F); singleDataSet.Add(-15.851394F); singleDataSet.Add(-13.505662F); singleDataSet.Add(-11.159929F); singleDataSet.Add(-8.814197F); singleDataSet.Add(-6.468464F); singleDataSet.Add(-4.1227317F); singleDataSet.Add(-1.776999F); singleDataSet.Add(0.5687335F); singleDataSet.Add(2.914466F); singleDataSet.Add(5.2601986F); singleDataSet.Add(7.605931F); singleDataSet.Add(9.951664F); singleDataSet.Add(12.297396F); singleDataSet.Add(14.643128F); singleDataSet.Add(16.988861F); singleDataSet.Add(19.334593F); singleDataSet.Add(21.680326F); singleDataSet.Add(24.026058F); singleDataSet.Add(26.371792F); singleDataSet.Add(28.717524F); singleDataSet.Add(31.063255F); builder.Add(typeof(float), singleDataSet.ToImmutable()); // long? data-set var nullableInt64DataSet = ImmutableList.CreateBuilder <long?>(); nullableInt64DataSet.Add(-25L); nullableInt64DataSet.Add(null); nullableInt64DataSet.Add(-23L); nullableInt64DataSet.Add(-21L); nullableInt64DataSet.Add(-18L); nullableInt64DataSet.Add(-16L); nullableInt64DataSet.Add(null); nullableInt64DataSet.Add(-14L); nullableInt64DataSet.Add(-11L); nullableInt64DataSet.Add(-9L); nullableInt64DataSet.Add(-6L); nullableInt64DataSet.Add(null); nullableInt64DataSet.Add(-4L); nullableInt64DataSet.Add(-2L); nullableInt64DataSet.Add(1L); nullableInt64DataSet.Add(3L); nullableInt64DataSet.Add(null); nullableInt64DataSet.Add(5L); nullableInt64DataSet.Add(8L); nullableInt64DataSet.Add(10L); nullableInt64DataSet.Add(12L); nullableInt64DataSet.Add(null); nullableInt64DataSet.Add(15L); nullableInt64DataSet.Add(17L); nullableInt64DataSet.Add(19L); nullableInt64DataSet.Add(22L); nullableInt64DataSet.Add(null); nullableInt64DataSet.Add(24L); nullableInt64DataSet.Add(26L); nullableInt64DataSet.Add(29L); nullableInt64DataSet.Add(31L); nullableInt64DataSet.Add(null); builder.Add(typeof(long?), nullableInt64DataSet.ToImmutable()); // int? data-set var nullableInt32DataSet = ImmutableList.CreateBuilder <int?>(); nullableInt32DataSet.Add(-25); nullableInt32DataSet.Add(null); nullableInt32DataSet.Add(-23); nullableInt32DataSet.Add(-21); nullableInt32DataSet.Add(-18); nullableInt32DataSet.Add(-16); nullableInt32DataSet.Add(null); nullableInt32DataSet.Add(-14); nullableInt32DataSet.Add(-11); nullableInt32DataSet.Add(-9); nullableInt32DataSet.Add(-6); nullableInt32DataSet.Add(null); nullableInt32DataSet.Add(-4); nullableInt32DataSet.Add(-2); nullableInt32DataSet.Add(1); nullableInt32DataSet.Add(3); nullableInt32DataSet.Add(null); nullableInt32DataSet.Add(5); nullableInt32DataSet.Add(8); nullableInt32DataSet.Add(10); nullableInt32DataSet.Add(12); nullableInt32DataSet.Add(null); nullableInt32DataSet.Add(15); nullableInt32DataSet.Add(17); nullableInt32DataSet.Add(19); nullableInt32DataSet.Add(22); nullableInt32DataSet.Add(null); nullableInt32DataSet.Add(24); nullableInt32DataSet.Add(26); nullableInt32DataSet.Add(29); nullableInt32DataSet.Add(31); nullableInt32DataSet.Add(null); builder.Add(typeof(int?), nullableInt32DataSet.ToImmutable()); // long data-set var int64DataSet = ImmutableList.CreateBuilder <long>(); int64DataSet.Add(-25L); int64DataSet.Add(-23L); int64DataSet.Add(-21L); int64DataSet.Add(-18L); int64DataSet.Add(-16L); int64DataSet.Add(-14L); int64DataSet.Add(-11L); int64DataSet.Add(-9L); int64DataSet.Add(-6L); int64DataSet.Add(-4L); int64DataSet.Add(-2L); int64DataSet.Add(1L); int64DataSet.Add(3L); int64DataSet.Add(5L); int64DataSet.Add(8L); int64DataSet.Add(10L); int64DataSet.Add(12L); int64DataSet.Add(15L); int64DataSet.Add(17L); int64DataSet.Add(19L); int64DataSet.Add(22L); int64DataSet.Add(24L); int64DataSet.Add(26L); int64DataSet.Add(29L); int64DataSet.Add(31L); builder.Add(typeof(long), int64DataSet.ToImmutable()); // int data-set var int32DataSet = ImmutableList.CreateBuilder <int>(); int32DataSet.Add(-25); int32DataSet.Add(-23); int32DataSet.Add(-21); int32DataSet.Add(-18); int32DataSet.Add(-16); int32DataSet.Add(-14); int32DataSet.Add(-11); int32DataSet.Add(-9); int32DataSet.Add(-6); int32DataSet.Add(-4); int32DataSet.Add(-2); int32DataSet.Add(1); int32DataSet.Add(3); int32DataSet.Add(5); int32DataSet.Add(8); int32DataSet.Add(10); int32DataSet.Add(12); int32DataSet.Add(15); int32DataSet.Add(17); int32DataSet.Add(19); int32DataSet.Add(22); int32DataSet.Add(24); int32DataSet.Add(26); int32DataSet.Add(29); int32DataSet.Add(31); builder.Add(typeof(int), int32DataSet.ToImmutable()); return(builder.ToImmutable()); }
static SyntaxWrapperHelper() { var csharpCodeAnalysisAssembly = typeof(CSharpSyntaxNode).GetTypeInfo().Assembly; var builder = ImmutableDictionary.CreateBuilder <Type, Type>(); builder.Add(typeof(BaseExpressionColonSyntaxWrapper), csharpCodeAnalysisAssembly.GetType(BaseExpressionColonSyntaxWrapper.WrappedTypeName)); var baseNamespaceDeclarationSyntaxType = csharpCodeAnalysisAssembly.GetType(BaseNamespaceDeclarationSyntaxWrapper.WrappedTypeName) ?? csharpCodeAnalysisAssembly.GetType(BaseNamespaceDeclarationSyntaxWrapper.FallbackWrappedTypeName); builder.Add(typeof(BaseNamespaceDeclarationSyntaxWrapper), baseNamespaceDeclarationSyntaxType); var objectCreationExpressionSyntaxType = csharpCodeAnalysisAssembly.GetType(BaseObjectCreationExpressionSyntaxWrapper.WrappedTypeName) ?? csharpCodeAnalysisAssembly.GetType(BaseObjectCreationExpressionSyntaxWrapper.FallbackWrappedTypeName); builder.Add(typeof(BaseObjectCreationExpressionSyntaxWrapper), objectCreationExpressionSyntaxType); builder.Add(typeof(BaseParameterSyntaxWrapper), csharpCodeAnalysisAssembly.GetType(BaseParameterSyntaxWrapper.WrappedTypeName)); builder.Add(typeof(BinaryPatternSyntaxWrapper), csharpCodeAnalysisAssembly.GetType(BinaryPatternSyntaxWrapper.WrappedTypeName)); builder.Add(typeof(CasePatternSwitchLabelSyntaxWrapper), csharpCodeAnalysisAssembly.GetType(CasePatternSwitchLabelSyntaxWrapper.WrappedTypeName)); var forEachStatementSyntaxType = csharpCodeAnalysisAssembly.GetType(CommonForEachStatementSyntaxWrapper.WrappedTypeName) ?? csharpCodeAnalysisAssembly.GetType(CommonForEachStatementSyntaxWrapper.FallbackWrappedTypeName); builder.Add(typeof(CommonForEachStatementSyntaxWrapper), forEachStatementSyntaxType); builder.Add(typeof(ConstantPatternSyntaxWrapper), csharpCodeAnalysisAssembly.GetType(ConstantPatternSyntaxWrapper.WrappedTypeName)); builder.Add(typeof(DeclarationExpressionSyntaxWrapper), csharpCodeAnalysisAssembly.GetType(DeclarationExpressionSyntaxWrapper.WrappedTypeName)); builder.Add(typeof(DeclarationPatternSyntaxWrapper), csharpCodeAnalysisAssembly.GetType(DeclarationPatternSyntaxWrapper.WrappedTypeName)); builder.Add(typeof(DefaultConstraintSyntaxWrapper), csharpCodeAnalysisAssembly.GetType(DefaultConstraintSyntaxWrapper.WrappedTypeName)); builder.Add(typeof(DiscardDesignationSyntaxWrapper), csharpCodeAnalysisAssembly.GetType(DiscardDesignationSyntaxWrapper.WrappedTypeName)); builder.Add(typeof(DiscardPatternSyntaxWrapper), csharpCodeAnalysisAssembly.GetType(DiscardPatternSyntaxWrapper.WrappedTypeName)); builder.Add(typeof(ExpressionColonSyntaxWrapper), csharpCodeAnalysisAssembly.GetType(ExpressionColonSyntaxWrapper.WrappedTypeName)); builder.Add(typeof(ExpressionOrPatternSyntaxWrapper), csharpCodeAnalysisAssembly.GetType(ExpressionOrPatternSyntaxWrapper.WrappedTypeName)); builder.Add(typeof(FileScopedNamespaceDeclarationSyntaxWrapper), csharpCodeAnalysisAssembly.GetType(FileScopedNamespaceDeclarationSyntaxWrapper.WrappedTypeName)); builder.Add(typeof(ForEachVariableStatementSyntaxWrapper), csharpCodeAnalysisAssembly.GetType(ForEachVariableStatementSyntaxWrapper.WrappedTypeName)); builder.Add(typeof(FunctionPointerCallingConventionSyntaxWrapper), csharpCodeAnalysisAssembly.GetType(FunctionPointerCallingConventionSyntaxWrapper.WrappedTypeName)); builder.Add(typeof(FunctionPointerParameterListSyntaxWrapper), csharpCodeAnalysisAssembly.GetType(FunctionPointerParameterListSyntaxWrapper.WrappedTypeName)); builder.Add(typeof(FunctionPointerParameterSyntaxWrapper), csharpCodeAnalysisAssembly.GetType(FunctionPointerParameterSyntaxWrapper.WrappedTypeName)); builder.Add(typeof(FunctionPointerTypeSyntaxWrapper), csharpCodeAnalysisAssembly.GetType(FunctionPointerTypeSyntaxWrapper.WrappedTypeName)); builder.Add(typeof(FunctionPointerUnmanagedCallingConventionListSyntaxWrapper), csharpCodeAnalysisAssembly.GetType(FunctionPointerUnmanagedCallingConventionListSyntaxWrapper.WrappedTypeName)); builder.Add(typeof(FunctionPointerUnmanagedCallingConventionSyntaxWrapper), csharpCodeAnalysisAssembly.GetType(FunctionPointerUnmanagedCallingConventionSyntaxWrapper.WrappedTypeName)); builder.Add(typeof(ImplicitObjectCreationExpressionSyntaxWrapper), csharpCodeAnalysisAssembly.GetType(ImplicitObjectCreationExpressionSyntaxWrapper.WrappedTypeName)); builder.Add(typeof(ImplicitStackAllocArrayCreationExpressionSyntaxWrapper), csharpCodeAnalysisAssembly.GetType(ImplicitStackAllocArrayCreationExpressionSyntaxWrapper.WrappedTypeName)); builder.Add(typeof(IsPatternExpressionSyntaxWrapper), csharpCodeAnalysisAssembly.GetType(IsPatternExpressionSyntaxWrapper.WrappedTypeName)); builder.Add(typeof(LineDirectivePositionSyntaxWrapper), csharpCodeAnalysisAssembly.GetType(LineDirectivePositionSyntaxWrapper.WrappedTypeName)); builder.Add(typeof(LineOrSpanDirectiveTriviaSyntaxWrapper), csharpCodeAnalysisAssembly.GetType(LineOrSpanDirectiveTriviaSyntaxWrapper.WrappedTypeName)); builder.Add(typeof(LineSpanDirectiveTriviaSyntaxWrapper), csharpCodeAnalysisAssembly.GetType(LineSpanDirectiveTriviaSyntaxWrapper.WrappedTypeName)); builder.Add(typeof(LocalFunctionStatementSyntaxWrapper), csharpCodeAnalysisAssembly.GetType(LocalFunctionStatementSyntaxWrapper.WrappedTypeName)); builder.Add(typeof(NullableDirectiveTriviaSyntaxWrapper), csharpCodeAnalysisAssembly.GetType(NullableDirectiveTriviaSyntaxWrapper.WrappedTypeName)); builder.Add(typeof(ParenthesizedPatternSyntaxWrapper), csharpCodeAnalysisAssembly.GetType(ParenthesizedPatternSyntaxWrapper.WrappedTypeName)); builder.Add(typeof(ParenthesizedVariableDesignationSyntaxWrapper), csharpCodeAnalysisAssembly.GetType(ParenthesizedVariableDesignationSyntaxWrapper.WrappedTypeName)); builder.Add(typeof(PatternSyntaxWrapper), csharpCodeAnalysisAssembly.GetType(PatternSyntaxWrapper.WrappedTypeName)); builder.Add(typeof(PositionalPatternClauseSyntaxWrapper), csharpCodeAnalysisAssembly.GetType(PositionalPatternClauseSyntaxWrapper.WrappedTypeName)); builder.Add(typeof(PrimaryConstructorBaseTypeSyntaxWrapper), csharpCodeAnalysisAssembly.GetType(PrimaryConstructorBaseTypeSyntaxWrapper.WrappedTypeName)); builder.Add(typeof(PropertyPatternClauseSyntaxWrapper), csharpCodeAnalysisAssembly.GetType(PropertyPatternClauseSyntaxWrapper.WrappedTypeName)); builder.Add(typeof(RangeExpressionSyntaxWrapper), csharpCodeAnalysisAssembly.GetType(RangeExpressionSyntaxWrapper.WrappedTypeName)); builder.Add(typeof(RecordDeclarationSyntaxWrapper), csharpCodeAnalysisAssembly.GetType(RecordDeclarationSyntaxWrapper.WrappedTypeName)); builder.Add(typeof(RecursivePatternSyntaxWrapper), csharpCodeAnalysisAssembly.GetType(RecursivePatternSyntaxWrapper.WrappedTypeName)); builder.Add(typeof(RefExpressionSyntaxWrapper), csharpCodeAnalysisAssembly.GetType(RefExpressionSyntaxWrapper.WrappedTypeName)); builder.Add(typeof(RefTypeSyntaxWrapper), csharpCodeAnalysisAssembly.GetType(RefTypeSyntaxWrapper.WrappedTypeName)); builder.Add(typeof(RelationalPatternSyntaxWrapper), csharpCodeAnalysisAssembly.GetType(RelationalPatternSyntaxWrapper.WrappedTypeName)); builder.Add(typeof(SingleVariableDesignationSyntaxWrapper), csharpCodeAnalysisAssembly.GetType(SingleVariableDesignationSyntaxWrapper.WrappedTypeName)); builder.Add(typeof(SubpatternSyntaxWrapper), csharpCodeAnalysisAssembly.GetType(SubpatternSyntaxWrapper.WrappedTypeName)); builder.Add(typeof(SwitchExpressionArmSyntaxWrapper), csharpCodeAnalysisAssembly.GetType(SwitchExpressionArmSyntaxWrapper.WrappedTypeName)); builder.Add(typeof(SwitchExpressionSyntaxWrapper), csharpCodeAnalysisAssembly.GetType(SwitchExpressionSyntaxWrapper.WrappedTypeName)); builder.Add(typeof(ThrowExpressionSyntaxWrapper), csharpCodeAnalysisAssembly.GetType(ThrowExpressionSyntaxWrapper.WrappedTypeName)); builder.Add(typeof(TupleElementSyntaxWrapper), csharpCodeAnalysisAssembly.GetType(TupleElementSyntaxWrapper.WrappedTypeName)); builder.Add(typeof(TupleExpressionSyntaxWrapper), csharpCodeAnalysisAssembly.GetType(TupleExpressionSyntaxWrapper.WrappedTypeName)); builder.Add(typeof(TupleTypeSyntaxWrapper), csharpCodeAnalysisAssembly.GetType(TupleTypeSyntaxWrapper.WrappedTypeName)); builder.Add(typeof(TypePatternSyntaxWrapper), csharpCodeAnalysisAssembly.GetType(TypePatternSyntaxWrapper.WrappedTypeName)); builder.Add(typeof(UnaryPatternSyntaxWrapper), csharpCodeAnalysisAssembly.GetType(UnaryPatternSyntaxWrapper.WrappedTypeName)); builder.Add(typeof(VariableDesignationSyntaxWrapper), csharpCodeAnalysisAssembly.GetType(VariableDesignationSyntaxWrapper.WrappedTypeName)); builder.Add(typeof(VarPatternSyntaxWrapper), csharpCodeAnalysisAssembly.GetType(VarPatternSyntaxWrapper.WrappedTypeName)); builder.Add(typeof(WhenClauseSyntaxWrapper), csharpCodeAnalysisAssembly.GetType(WhenClauseSyntaxWrapper.WrappedTypeName)); builder.Add(typeof(WithExpressionSyntaxWrapper), csharpCodeAnalysisAssembly.GetType(WithExpressionSyntaxWrapper.WrappedTypeName)); WrappedTypes = builder.ToImmutable(); }
private static void AnalyzeCompilationStart(CompilationStartAnalysisContext context) { var baseTypeSuffixMapBuilder = ImmutableDictionary.CreateBuilder <INamedTypeSymbol, SuffixInfo>(); var interfaceTypeSuffixMapBuilder = ImmutableDictionary.CreateBuilder <INamedTypeSymbol, SuffixInfo>(); foreach (var tuple in s_baseTypesAndTheirSuffix) { var wellKnownNamedType = context.Compilation.GetTypeByMetadataName(tuple.Item1); if (wellKnownNamedType != null && wellKnownNamedType.OriginalDefinition != null) { // If the type is interface if (wellKnownNamedType.OriginalDefinition.TypeKind == TypeKind.Interface) { interfaceTypeSuffixMapBuilder.Add(wellKnownNamedType.OriginalDefinition, SuffixInfo.Create(tuple.Item2, tuple.Item3)); } else { baseTypeSuffixMapBuilder.Add(wellKnownNamedType.OriginalDefinition, SuffixInfo.Create(tuple.Item2, tuple.Item3)); } } } if (baseTypeSuffixMapBuilder.Count > 0 || interfaceTypeSuffixMapBuilder.Count > 0) { var baseTypeSuffixMap = baseTypeSuffixMapBuilder.ToImmutable(); var interfaceTypeSuffixMap = interfaceTypeSuffixMapBuilder.ToImmutable(); context.RegisterSymbolAction((saContext) => { var namedTypeSymbol = (INamedTypeSymbol)saContext.Symbol; if (namedTypeSymbol.GetResultantVisibility() != SymbolVisibility.Public) { return; } var baseType = namedTypeSymbol.GetBaseTypes().FirstOrDefault(bt => baseTypeSuffixMap.ContainsKey(bt.OriginalDefinition)); if (baseType != null) { var suffixInfo = baseTypeSuffixMap[baseType.OriginalDefinition]; // SpecialCollectionRule - Rename 'LastInFirstOut<T>' to end in either 'Collection' or 'Stack'. // DefaultRule - Rename 'MyStringObjectHashtable' to end in 'Dictionary'. var rule = suffixInfo.CanSuffixBeCollection ? SpecialCollectionRule : DefaultRule; if ((suffixInfo.CanSuffixBeCollection && !namedTypeSymbol.Name.EndsWith("Collection", StringComparison.Ordinal) && !namedTypeSymbol.Name.EndsWith(suffixInfo.Suffix, StringComparison.Ordinal)) || (!suffixInfo.CanSuffixBeCollection && !namedTypeSymbol.Name.EndsWith(suffixInfo.Suffix, StringComparison.Ordinal))) { saContext.ReportDiagnostic(namedTypeSymbol.CreateDiagnostic(rule, namedTypeSymbol.ToDisplayString(), suffixInfo.Suffix)); } return; } var implementedInterface = namedTypeSymbol.AllInterfaces.FirstOrDefault(i => interfaceTypeSuffixMap.ContainsKey(i.OriginalDefinition)); if (implementedInterface != null) { var suffixInfo = interfaceTypeSuffixMap[implementedInterface.OriginalDefinition]; if (!namedTypeSymbol.Name.EndsWith(suffixInfo.Suffix, StringComparison.Ordinal)) { saContext.ReportDiagnostic(namedTypeSymbol.CreateDiagnostic(DefaultRule, namedTypeSymbol.ToDisplayString(), suffixInfo.Suffix)); } } } , SymbolKind.NamedType); context.RegisterSymbolAction((saContext) => { const string eventHandlerString = "EventHandler"; var eventSymbol = saContext.Symbol as IEventSymbol; if (!eventSymbol.Type.Name.EndsWith(eventHandlerString, StringComparison.Ordinal)) { saContext.ReportDiagnostic(eventSymbol.CreateDiagnostic(DefaultRule, eventSymbol.Type.Name, eventHandlerString)); } }, SymbolKind.Event); } }
protected override ImmutableDictionary <TKey, TValue> .Builder Create(int count, MessagePackSerializerOptions options) { return(ImmutableDictionary.CreateBuilder <TKey, TValue>()); }
public QueryAdapterEntriesBuilder() { _entriesBuilder = ImmutableDictionary.CreateBuilder <Type, IEnumerable>(); }
private static async Task <ImmutableDictionary <ProjectId, ImmutableArray <Diagnostic> > > GetAnalyzerDiagnosticsAsync(Solution solution, string solutionPath, ImmutableArray <DiagnosticAnalyzer> analyzers, bool force, CancellationToken cancellationToken) { List <KeyValuePair <ProjectId, Task <ImmutableArray <Diagnostic> > > > projectDiagnosticTasks = new List <KeyValuePair <ProjectId, Task <ImmutableArray <Diagnostic> > > >(); // Make sure we analyze the projects in parallel foreach (var project in solution.Projects) { if (project.Language != LanguageNames.CSharp) { continue; } projectDiagnosticTasks.Add(new KeyValuePair <ProjectId, Task <ImmutableArray <Diagnostic> > >(project.Id, GetProjectAnalyzerDiagnosticsAsync(analyzers, project, force, cancellationToken))); } ImmutableDictionary <ProjectId, ImmutableArray <Diagnostic> > .Builder projectDiagnosticBuilder = ImmutableDictionary.CreateBuilder <ProjectId, ImmutableArray <Diagnostic> >(); foreach (var task in projectDiagnosticTasks) { projectDiagnosticBuilder.Add(task.Key, await task.Value.ConfigureAwait(false)); } return(projectDiagnosticBuilder.ToImmutable()); }
protected bool TrySimplifyTypeNameExpression(SemanticModel model, SyntaxNode node, AnalyzerOptions analyzerOptions, out Diagnostic diagnostic, CancellationToken cancellationToken) { diagnostic = default; var syntaxTree = node.SyntaxTree; var optionSet = analyzerOptions.GetDocumentOptionSetAsync(syntaxTree, cancellationToken).GetAwaiter().GetResult(); if (optionSet == null) { return(false); } if (!CanSimplifyTypeNameExpressionCore( model, node, optionSet, out var issueSpan, out var diagnosticId, out var inDeclaration, cancellationToken)) { return(false); } if (model.SyntaxTree.OverlapsHiddenPosition(issueSpan, cancellationToken)) { return(false); } PerLanguageOption <CodeStyleOption <bool> > option; DiagnosticDescriptor descriptor; ReportDiagnostic severity; switch (diagnosticId) { case IDEDiagnosticIds.SimplifyNamesDiagnosticId: descriptor = s_descriptorSimplifyNames; severity = descriptor.DefaultSeverity.ToReportDiagnostic(); break; case IDEDiagnosticIds.SimplifyMemberAccessDiagnosticId: descriptor = s_descriptorSimplifyMemberAccess; severity = descriptor.DefaultSeverity.ToReportDiagnostic(); break; case IDEDiagnosticIds.PreferBuiltInOrFrameworkTypeDiagnosticId: option = inDeclaration ? CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration : CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess; descriptor = s_descriptorPreferBuiltinOrFrameworkType; var optionValue = optionSet.GetOption(option, GetLanguageName()); severity = optionValue.Notification.Severity; break; default: throw ExceptionUtilities.UnexpectedValue(diagnosticId); } if (descriptor == null) { return(false); } var tree = model.SyntaxTree; var builder = ImmutableDictionary.CreateBuilder <string, string>(); builder["OptionName"] = nameof(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess); // TODO: need the actual one builder["OptionLanguage"] = model.Language; diagnostic = DiagnosticHelper.Create(descriptor, tree.GetLocation(issueSpan), severity, additionalLocations: null, builder.ToImmutable()); #if LOG var logLine = tree.FilePath + "\t" + diagnosticId + "\t" + inDeclaration + "\t"; var sourceText = tree.GetText(cancellationToken); sourceText.GetLineAndOffset(issueSpan.Start, out var startLineNumber, out var startOffset); sourceText.GetLineAndOffset(issueSpan.End, out var endLineNumber, out var endOffset); var leading = sourceText.ToString(TextSpan.FromBounds( sourceText.Lines[startLineNumber].Start, issueSpan.Start)); var mid = sourceText.ToString(issueSpan); var trailing = sourceText.ToString(TextSpan.FromBounds( issueSpan.End, sourceText.Lines[endLineNumber].End)); var contents = leading + "[|" + s_newlinePattern.Replace(mid, " ") + "|]" + trailing; logLine += contents + "\r\n"; lock (_logGate) { File.AppendAllText(_logFile, logLine); } #endif return(true); }