Add() public method

public Add ( key, value ) : void
return void
示例#1
0
 public ImmutableDictionary<string, object> PrepareMetadata(ImmutableDictionary<string, object> metadata)
 {
     if (!metadata.ContainsKey("_enableSearch"))
     {
         metadata = metadata.Add("_enableSearch", true);
     }
     return metadata;
 }
 public void ImmutableDictionary_AddTest()
 {
     Dictionary<int, string> dictionary = new Dictionary<int, string>
     {
         {1,"asaas"},
         {2,"sasas"},
         {3,"tak"}
     };
     ImmutableDictionary<int, string> test = new ImmutableDictionary<int, string>(dictionary);
     test.Add(3, "dddfd");
 }
示例#3
0
        public static CompletionItem Create(
            string displayText,
            TextSpan span,
            Glyph? glyph = null,
            ImmutableArray<SymbolDisplayPart> description = default(ImmutableArray<SymbolDisplayPart>),
            string sortText = null,
            string filterText = null,
            bool preselect = false,
            bool showsWarningIcon = false,
            bool shouldFormatOnCommit = false,
            bool isArgumentName = false,
            ImmutableDictionary<string, string> properties = null,
            ImmutableArray<string> tags = default(ImmutableArray<string>),
            CompletionItemRules rules = null)
        {
            tags = tags.IsDefault ? ImmutableArray<string>.Empty : tags;

            if (glyph != null)
            {
                // put glyph tags first
                tags = GlyphTags.GetTags(glyph.Value).AddRange(tags);
            }

            if (showsWarningIcon)
            {
                tags = tags.Add(CompletionTags.Warning);
            }

            if (isArgumentName)
            {
                tags = tags.Add(CompletionTags.ArgumentName);
            }

            properties = properties ?? ImmutableDictionary<string, string>.Empty;
            if (!description.IsDefault && description.Length > 0)
            {
                properties = properties.Add("Description", EncodeDescription(description));
            }

            rules = rules ?? CompletionItemRules.Default;
            rules = rules.WithPreselect(preselect)
                         .WithFormatOnCommit(shouldFormatOnCommit);

            return CompletionItem.Create(
                displayText: displayText,
                filterText: filterText,
                sortText: sortText,
                span: span,
                properties: properties,
                tags: tags,
                rules: rules);
        }
示例#4
0
        public static CompletionItem Create(
            string displayText,
            Glyph? glyph = null,
            ImmutableArray<SymbolDisplayPart> description = default(ImmutableArray<SymbolDisplayPart>),
            string sortText = null,
            string filterText = null,
            int? matchPriority = null,
            bool showsWarningIcon = false,
            bool shouldFormatOnCommit = false,
            ImmutableDictionary<string, string> properties = null,
            ImmutableArray<string> tags = default(ImmutableArray<string>),
            CompletionItemRules rules = null)
        {
            tags = tags.NullToEmpty();

            if (glyph != null)
            {
                // put glyph tags first
                tags = GlyphTags.GetTags(glyph.Value).AddRange(tags);
            }

            if (showsWarningIcon)
            {
                tags = tags.Add(CompletionTags.Warning);
            }

            properties = properties ?? ImmutableDictionary<string, string>.Empty;
            if (!description.IsDefault && description.Length > 0)
            {
                properties = properties.Add("Description", EncodeDescription(description));
            }

            rules = rules ?? CompletionItemRules.Default;
            rules = rules.WithMatchPriority(matchPriority.GetValueOrDefault())
                         .WithFormatOnCommit(shouldFormatOnCommit);

            return CompletionItem.Create(
                displayText: displayText,
                filterText: filterText,
                sortText: sortText,
                properties: properties,
                tags: tags,
                rules: rules);
        }
        public PointsToAbstractValue GetOrCreateDefaultValue(AnalysisEntity analysisEntity)
        {
            if (!_defaultPointsToValueMapBuilder.TryGetValue(analysisEntity, out PointsToAbstractValue value))
            {
                if (analysisEntity.SymbolOpt?.Kind == SymbolKind.Local ||
                    analysisEntity.SymbolOpt is IParameterSymbol parameter && parameter.RefKind == RefKind.Out ||
                    analysisEntity.CaptureIdOpt != null)
                {
                    return(PointsToAbstractValue.Undefined);
                }
                else if (!analysisEntity.Type.IsReferenceTypeOrNullableValueType())
                {
                    return(PointsToAbstractValue.NoLocation);
                }
                else if (analysisEntity.HasUnknownInstanceLocation)
                {
                    return(PointsToAbstractValue.Unknown);
                }

                value = PointsToAbstractValue.Create(AbstractLocation.CreateAnalysisEntityDefaultLocation(analysisEntity), mayBeNull: true);
                _trackedEntitiesBuilder.AllEntities.Add(analysisEntity);
                _defaultPointsToValueMapBuilder.Add(analysisEntity, value);
            }
示例#6
0
        public static ImmutableDictionary <CaptureId, FlowCaptureKind> CreateLValueFlowCaptures(ControlFlowGraph cfg)
        {
            // This method identifies flow capture reference operations that are target of an assignment
            // and marks them as lvalue flow captures.
            // Note that currently the control flow graph does not contain flow captures
            // that are r-value captures at some point and l-values captures at other point in
            // the flow graph. The debug only asserts in this method ensure this invariant.
            // If these asserts fire, we should adjust this algorithm.

            ImmutableDictionary <CaptureId, FlowCaptureKind> .Builder lvalueFlowCaptureIdBuilder = null;
#if DEBUG
            var rvalueFlowCaptureIds = new HashSet <CaptureId>();
#endif
            foreach (var flowCaptureReference in cfg.DescendantOperations <IFlowCaptureReferenceOperation>(OperationKind.FlowCaptureReference))
            {
                if (flowCaptureReference.Parent is IAssignmentOperation assignment &&
                    assignment.Target == flowCaptureReference ||
                    flowCaptureReference.IsInLeftOfDeconstructionAssignment(out _))
                {
                    lvalueFlowCaptureIdBuilder = lvalueFlowCaptureIdBuilder ?? ImmutableDictionary.CreateBuilder <CaptureId, FlowCaptureKind>();
                    var captureKind = flowCaptureReference.Parent is ICompoundAssignmentOperation ? FlowCaptureKind.LValueAndRValueCapture : FlowCaptureKind.LValueCapture;
                    lvalueFlowCaptureIdBuilder.Add(flowCaptureReference.Id, captureKind);
                }
示例#7
0
        static EnumHelper()
        {
            LocalAssembly = typeof(EnumHelper).Assembly;
            CultureInfo currentCulture = CultureInfo.CurrentCulture;

            ImmutableDictionary <Type, EnumField[]> .Builder builder = ImmutableDictionary.CreateBuilder <Type, EnumField[]>();
            ImmutableDictionary <FieldInfo, ImmutableDictionary <CultureInfo, string> > .Builder builder2 = ImmutableDictionary.CreateBuilder <FieldInfo, ImmutableDictionary <CultureInfo, string> >();
            TypeInfo[] array = LocalAssembly.DefinedTypes.Where((TypeInfo x) => x.IsEnum).ToArray();
            foreach (TypeInfo typeInfo in array)
            {
                EnumField[] enumFieldsInner = GetEnumFieldsInner(typeInfo, currentCulture);
                builder.Add(typeInfo, enumFieldsInner);
                EnumField[] array2 = enumFieldsInner;
                foreach (EnumField enumField in array2)
                {
                    ImmutableDictionary <CultureInfo, string> .Builder builder3 = ImmutableDictionary.CreateBuilder <CultureInfo, string>();
                    builder3.Add(currentCulture, enumField.Description);
                    builder2.Add(enumField.FieldInfo, ImmutableDictionary.ToImmutableDictionary <CultureInfo, string>(builder3));
                }
            }
            EnumFiledCache            = ImmutableDictionary.ToImmutableDictionary <Type, EnumField[]>(builder);
            FiledInfoCultureDescCache = ImmutableDictionary.ToImmutableDictionary <FieldInfo, ImmutableDictionary <CultureInfo, string> >(builder2);
        }
示例#8
0
        public override string GetMangledStringName(string literal)
        {
            Debug.Assert(OrdinalReceived);

            string mangledName;

            if (_mangledStringLiterals.TryGetValue(literal, out mangledName))
            {
                return(mangledName);
            }

            mangledName = SanitizeNameWithHash(literal);

            lock (this)
            {
                if (!_mangledStringLiterals.ContainsKey(literal))
                {
                    _mangledStringLiterals = _mangledStringLiterals.Add(literal, mangledName);
                }
            }

            return(mangledName);
        }
        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 (var 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();
        }
示例#10
0
        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();
        }
示例#11
0
        private static async Task <ImmutableDictionary <ProjectId, ImmutableArray <Diagnostic> > > GetAnalyzerDiagnosticsAsync(Solution solution, 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());
        }
        public static CompletionItem Create(
            string displayText,
            Glyph?glyph = null,
            ImmutableArray <SymbolMarkupToken> description = default(ImmutableArray <SymbolMarkupToken>),
            string sortText       = null,
            string filterText     = null,
            bool showsWarningIcon = false,
            ImmutableDictionary <string, string> properties = null,
            ImmutableArray <string> tags = default(ImmutableArray <string>))
        {
            tags = tags.NullToEmpty();

            //if (glyph != null)
            //{
            //    // put glyph tags first
            //    tags = GlyphTags.GetTags(glyph.Value).AddRange(tags);
            //}

            if (showsWarningIcon)
            {
                tags = tags.Add(WellKnownTags.Warning);
            }

            properties = properties ?? ImmutableDictionary <string, string> .Empty;
            if (!description.IsDefault && description.Length > 0)
            {
                properties = properties.Add("Description", EncodeDescription(description));
            }

            return(CompletionItem.Create(
                       displayText: displayText,
                       filterText: filterText,
                       sortText: sortText,
                       properties: properties,
                       glyph: glyph ?? Glyph.None,
                       tags: tags));
        }
        public override IDependency BeforeRemove(
            string projectPath,
            ITargetFramework targetFramework,
            IDependency dependency,
            ImmutableDictionary <string, IDependency> .Builder worldBuilder,
            ImmutableHashSet <IDependency> .Builder topLevelBuilder,
            out bool filterAnyChanges)
        {
            filterAnyChanges = false;
            if (!dependency.TopLevel || !dependency.Resolved)
            {
                return(dependency);
            }

            if (dependency.Flags.Contains(DependencyTreeFlags.PackageNodeFlags))
            {
                // find sdk with the same name and clean dependencyIDs
                var sdkModelId = dependency.Name;
                var sdkId      = Dependency.GetID(targetFramework, SdkRuleHandler.ProviderTypeString, sdkModelId);

                if (worldBuilder.TryGetValue(sdkId, out IDependency sdk))
                {
                    filterAnyChanges = true;
                    // clean up sdk when corresponding package is removing
                    sdk = sdk.ToUnresolved(
                        schemaName: SdkReference.SchemaName,
                        dependencyIDs: ImmutableList <string> .Empty);

                    worldBuilder.Remove(sdk.Id);
                    worldBuilder.Add(sdk.Id, sdk);
                    topLevelBuilder.Remove(sdk);
                    topLevelBuilder.Add(sdk);
                }
            }

            return(dependency);
        }
示例#14
0
        static void TestDynamicTable()
        {
            long      time        = 0;
            Stopwatch watch       = new Stopwatch();
            Random    r           = new Random();
            string    fileContent = fileHeader;
            ImmutableDictionary <int, int> dynamicTable = ImmutableDictionary <int, int> .Empty;

            for (int i = 1; i <= 10; i++)
            {
                Console.WriteLine("Running dynamic table with " + i + " fields...");
                for (int u = minUpdates; u <= updates; u *= 10)
                {
                    int[] keys = new int[i];
                    for (int d = 0; d < i; d++)
                    {
                        keys[d]      = r.Next();
                        dynamicTable = dynamicTable.Add(keys[d], r.Next(-100, 100));
                    }
                    watch.Restart();
                    for (int j = 0; j < u; j++)
                    {
                        dynamicTable.Last();
                    }
                    watch.Stop();
                    time        += watch.ElapsedMilliseconds;
                    fileContent += i + "," + u + "," + ((double)watch.ElapsedMilliseconds / updates) + "\n";
                }
                Console.WriteLine("Done");
            }
            if (!System.IO.Directory.Exists("Benchmark"))
            {
                System.IO.Directory.CreateDirectory("Benchmark");
            }
            System.IO.File.WriteAllText("Benchmark\\benchmark_dynamic_table.csv", fileContent);
        }
示例#15
0
        private Task <IMongoCollection <TEntry> > GetCollectionAsync <TEntry>(bool isInTransaction, CancellationToken cancellation)
        {
            Task <IMongoCollection <TEntry> > result;

            if (_collections.TryGetValue(typeof(TEntry), out var entry))
            {
                result = (Task <IMongoCollection <TEntry> >)entry;
            }
            else
            {
                lock (_collectionsLock)
                {
                    if (_collections.TryGetValue(typeof(TEntry), out entry))
                    {
                        result = (Task <IMongoCollection <TEntry> >)entry;
                    }
                    else
                    {
                        var lazy = new AsyncLazy <IMongoCollection <TEntry> >(
                            CreateCollectionAsync <TEntry>,
                            AsyncLazyFlags.ExecuteOnCallingThread | AsyncLazyFlags.RetryOnFailure);

                        result       = lazy.Task;
                        _collections = _collections.Add(typeof(TEntry), result);
                    }
                }
            }

            // Cannot create a collection while beeing in a transaction.
            if (isInTransaction && !result.IsCompleted)
            {
                return(Task.FromResult <IMongoCollection <TEntry> >(null));
            }

            return(result);
        }
示例#16
0
        public static ImmutableDictionary <CaptureId, FlowCaptureKind> CreateLValueFlowCaptures(ControlFlowGraph cfg)
        {
            // This method identifies flow capture reference operations that are target of an assignment
            // and marks them as lvalue flow captures.
            // Control flow graph can also contain flow captures
            // that are r-value captures at some point and l-values captures at other point in
            // the flow graph. Specifically, for an ICoalesceOperation a flow capture acts
            // as both an r-value and l-value flow capture.

            ImmutableDictionary <CaptureId, FlowCaptureKind> .Builder lvalueFlowCaptureIdBuilder = null;
            var rvalueFlowCaptureIds = new HashSet <CaptureId> ();

            foreach (var flowCaptureReference in cfg.DescendantOperations <IFlowCaptureReferenceOperation> (OperationKind.FlowCaptureReference))
            {
                if (flowCaptureReference.Parent is IAssignmentOperation assignment &&
                    assignment.Target == flowCaptureReference ||
                    flowCaptureReference.IsInLeftOfDeconstructionAssignment(out _))
                {
                    lvalueFlowCaptureIdBuilder ??= ImmutableDictionary.CreateBuilder <CaptureId, FlowCaptureKind> ();
                    var captureKind = flowCaptureReference.Parent.IsAnyCompoundAssignment() || rvalueFlowCaptureIds.Contains(flowCaptureReference.Id)
                                                ? FlowCaptureKind.LValueAndRValueCapture
                                                : FlowCaptureKind.LValueCapture;
                    lvalueFlowCaptureIdBuilder.Add(flowCaptureReference.Id, captureKind);
                }
示例#17
0
        public Tissue2D Create(int maxX, int maxY, float ratioHealthyCells, float ratioInfectedCells)
        {
            maxX = Math.Abs(maxX);
            maxY = Math.Abs(maxY);
            var totalCount = maxY * maxX;

            if (ratioHealthyCells + ratioInfectedCells > 1)
            {
                throw new InvalidOperationException("Cannot create more then 100% cells.");
            }

            int countHealthyCells  = (int)Math.Floor(ratioHealthyCells * totalCount);
            int countInfectedCells = (int)Math.Floor(ratioInfectedCells * totalCount);

            var xList = _shuffler.Shuffle(Enumerable.Range(0, maxX));
            var yList = _shuffler.Shuffle(Enumerable.Range(0, maxY));
            var cells = new List <ICell>();

            cells.AddRange(CreateHealthyCells(countHealthyCells));
            cells.AddRange(CreateInfectedCells(countInfectedCells));
            cells.AddRange(CreateEmptyPlaces(totalCount - countHealthyCells - countInfectedCells));
            var cellList = _shuffler.Shuffle(cells);

            for (int y = 0; y < maxY; y++)
            {
                for (int x = 0; x < maxX; x++)
                {
                    var currentCell = (y + 1) * (x + 1);
                    _tissue = _tissue.Add(
                        new Location(xList.ElementAt(x), yList.ElementAt(y)),
                        cellList.ElementAt(currentCell - 1));
                }
            }

            return(new Tissue2D(_tissue));
        }
示例#18
0
        internal static DefinitionItem CreateMetadataDefinition(
            ImmutableArray <string> tags,
            ImmutableArray <TaggedText> displayParts,
            ImmutableArray <TaggedText> nameDisplayParts,
            Solution solution,
            ISymbol symbol,
            ImmutableDictionary <string, string> properties = null,
            bool displayIfNoReferences = true
            )
        {
            properties ??= ImmutableDictionary <string, string> .Empty;

            var symbolKey = symbol.GetSymbolKey().ToString();

            var projectId = solution.GetOriginatingProjectId(symbol);

            Contract.ThrowIfNull(projectId);

            properties = properties
                         .Add(MetadataSymbolKey, symbolKey)
                         .Add(MetadataSymbolOriginatingProjectIdGuid, projectId.Id.ToString())
                         .Add(MetadataSymbolOriginatingProjectIdDebugName, projectId.DebugName);

            var originationParts = GetOriginationParts(symbol);

            return(new DefaultDefinitionItem(
                       tags,
                       displayParts,
                       nameDisplayParts,
                       originationParts,
                       sourceSpans: ImmutableArray <DocumentSpan> .Empty,
                       properties: properties,
                       displayableProperties: ImmutableDictionary <string, string> .Empty,
                       displayIfNoReferences: displayIfNoReferences
                       ));
        }
示例#19
0
        internal static DefinitionItem CreateMetadataDefinition(
            ImmutableArray <string> tags,
            ImmutableArray <TaggedText> displayParts,
            ImmutableArray <TaggedText> nameDisplayParts,
            Solution solution, ISymbol symbol,
            ImmutableDictionary <string, string> properties = null,
            bool displayIfNoReferences = true)
        {
            properties = properties ?? ImmutableDictionary <string, string> .Empty;

            var symbolKey = symbol.GetSymbolKey().ToString();
            var assemblyIdentityDisplayName = symbol.ContainingAssembly?.Identity.GetDisplayName();

            properties = properties.Add(MetadataSymbolKey, symbolKey)
                         .Add(MetadataAssemblyIdentityDisplayName, assemblyIdentityDisplayName);

            var originationParts = GetOriginationParts(symbol);

            return(new DefaultDefinitionItem(
                       tags, displayParts, nameDisplayParts, originationParts,
                       sourceSpans: ImmutableArray <DocumentSpan> .Empty,
                       properties: properties,
                       displayIfNoReferences: displayIfNoReferences));
        }
示例#20
0
 protected override void OnReceive(object message)
 {
     if (message is CreateOmnetNode create)
     {
         var actorRef = create.Node;
         var id       = OmnetSimulation.Instance().CreateNodeAndId();
         _idToRef = _idToRef.Add(id, actorRef);
         _refToId = _refToId.Add(actorRef, id);
     }
     else if (message is Subscribe subscribe)
     {
         if (!_subscribers.ContainsKey(subscribe.Topic))
         {
             _subscribers = _subscribers.Add(subscribe.Topic, ImmutableList <IActorRef> .Empty);
         }
         _subscribers.SetItem(subscribe.Topic, _subscribers[subscribe.Topic].Add(subscribe.Subscriber));
     }
     else if (message is Broadcast broadcast)
     {
         // There seems to be no way to use publish here... we need to implement pubsub manually.
         if (_subscribers.ContainsKey(broadcast.Message.GetType()))
         {
             var subs = _subscribers[broadcast.Message.GetType()];
             BroadcastInOmnet(broadcast.Sender, broadcast.Message).ContinueWith(
                 result =>
             {
                 subs.ForEach(sub => sub.Tell(broadcast.Message, broadcast.Sender));
             });
         }
     }
     else if (message is Send send)
     {
         SendInOmnet(send.Sender, send.Receiver, send.Message)
         .ContinueWith(result => { send.Receiver.Tell(send.Message, send.Sender); });
     }
 }
示例#21
0
        static SortingConfiguration()
        {
            ImmutableDictionary <string, SyntaxKind> .Builder kindConfigMappingBuilder = ImmutableDictionary.CreateBuilder <string, SyntaxKind>();
            kindConfigMappingBuilder.Add("enum", SyntaxKind.EnumDeclaration);
            kindConfigMappingBuilder.Add("delegate", SyntaxKind.DelegateDeclaration);
            kindConfigMappingBuilder.Add("field", SyntaxKind.FieldDeclaration);
            kindConfigMappingBuilder.Add("event", SyntaxKind.EventDeclaration);           // Events declared as fields
            kindConfigMappingBuilder.Add("eventField", SyntaxKind.EventFieldDeclaration); // Events declared using the property-like syntax (with add and remove blocks)
            kindConfigMappingBuilder.Add("constructor", SyntaxKind.ConstructorDeclaration);
            kindConfigMappingBuilder.Add("destructor", SyntaxKind.DestructorDeclaration);
            kindConfigMappingBuilder.Add("indexer", SyntaxKind.IndexerDeclaration);
            kindConfigMappingBuilder.Add("property", SyntaxKind.PropertyDeclaration);
            kindConfigMappingBuilder.Add("operator", SyntaxKind.OperatorDeclaration);
            kindConfigMappingBuilder.Add("implicitexplicit", SyntaxKind.ConversionOperatorDeclaration);
            kindConfigMappingBuilder.Add("method", SyntaxKind.MethodDeclaration);
            kindConfigMappingBuilder.Add("struct", SyntaxKind.StructDeclaration);
            kindConfigMappingBuilder.Add("class", SyntaxKind.ClassDeclaration);
            kindConfigMappingBuilder.Add("interface", SyntaxKind.InterfaceDeclaration);
            kindSortOrderConfigurationMapping = kindConfigMappingBuilder.ToImmutableDictionary(StringComparer.OrdinalIgnoreCase);

            ImmutableDictionary <string, AccessModifier> .Builder accessModifierConfigMappingBuilder = ImmutableDictionary.CreateBuilder <string, AccessModifier>();
            accessModifierConfigMappingBuilder.Add("public", AccessModifier.Public);
            accessModifierConfigMappingBuilder.Add("internal", AccessModifier.Internal);
            accessModifierConfigMappingBuilder.Add("protected", AccessModifier.Protected);
            accessModifierConfigMappingBuilder.Add("protectedinternal", AccessModifier.ProtectedInternal);
            accessModifierConfigMappingBuilder.Add("private", AccessModifier.Private);
            accessModifierConfigMappingBuilder.Add("privateprotected", AccessModifier.PrivateProtected);
            accessModifierConfigurationMapping = accessModifierConfigMappingBuilder.ToImmutableDictionary(StringComparer.OrdinalIgnoreCase);

            ImmutableDictionary <string, Sorter> .Builder modifiersConfigMappingBuilder = ImmutableDictionary.CreateBuilder <string, Sorter>();
            modifiersConfigMappingBuilder.Add("kind", Sorter.Kind);
            modifiersConfigMappingBuilder.Add("extern", Sorter.Extern);
            modifiersConfigMappingBuilder.Add("const", Sorter.Const);
            modifiersConfigMappingBuilder.Add("readonly", Sorter.Readonly);
            modifiersConfigMappingBuilder.Add("static", Sorter.Static);
            modifiersConfigMappingBuilder.Add("accessibility", Sorter.Accessibility);
            modifiersConfigMappingBuilder.Add("name", Sorter.Name);
            modifiersConfigMappingBuilder.Add("numberofmethodargs", Sorter.MethodArguments);
            modifiersConfigurationMapping = modifiersConfigMappingBuilder.ToImmutableDictionary(StringComparer.OrdinalIgnoreCase);
        }
示例#22
0
 private void Register(ImmutableDictionary <RecvOp, IPacketHandler <T> > .Builder builder,
                       IPacketHandler <T> packetHandler)
 {
     builder.Add(packetHandler.OpCode, packetHandler);
 }
示例#23
0
        private Utf8String ComputeMangledMethodName(MethodDesc method)
        {
            string prependTypeName = null;

            if (!_mangleForCplusPlus)
            {
                prependTypeName = GetMangledTypeName(method.OwningType);
            }

            if (method is EcmaMethod)
            {
                var deduplicator = new HashSet <string>();

                // Add consistent names for all methods of the type, independent on the order in which
                // they are compiled
                lock (this)
                {
                    foreach (var m in method.OwningType.GetMethods())
                    {
                        string name = SanitizeName(m.Name);

                        name = DisambiguateName(name, deduplicator);
                        deduplicator.Add(name);

                        if (prependTypeName != null)
                        {
                            name = prependTypeName + "__" + name;
                        }

                        _mangledMethodNames = _mangledMethodNames.Add(m, name);
                    }
                }

                return(_mangledMethodNames[method]);
            }


            string mangledName;

            var methodDefinition = method.GetTypicalMethodDefinition();

            if (methodDefinition != method)
            {
                mangledName = GetMangledMethodName(methodDefinition.GetMethodDefinition()).ToString();

                var    inst = method.Instantiation;
                string mangledInstantiation = "";
                for (int i = 0; i < inst.Length; i++)
                {
                    string instArgName = GetMangledTypeName(inst[i]);
                    if (_mangleForCplusPlus)
                    {
                        instArgName = instArgName.Replace("::", "_");
                    }
                    if (i > 0)
                    {
                        mangledInstantiation += "__";
                    }
                    mangledInstantiation += instArgName;
                }
                mangledName += NestMangledName(mangledInstantiation);
            }
            else
            {
                // Assume that Name is unique for all other methods
                mangledName = SanitizeName(method.Name);
            }

            if (prependTypeName != null)
            {
                mangledName = prependTypeName + "__" + mangledName;
            }

            Utf8String utf8MangledName = new Utf8String(mangledName);

            lock (this)
            {
                _mangledMethodNames = _mangledMethodNames.Add(method, utf8MangledName);
            }

            return(utf8MangledName);
        }
示例#24
0
 /// <summary>
 /// Adds a new, or replaces an existing dependency (keyed on <see cref="IDependency.Id"/>).
 /// </summary>
 /// <remarks>
 /// In the course of filtering one dependency, the filter may wish to modify or add other
 /// dependencies in the project's tree. This method allows that to happen.
 /// </remarks>
 public void AddOrUpdate(IDependency dependency)
 {
     _worldBuilder.Remove(dependency.Id);
     _worldBuilder.Add(dependency.Id, dependency);
     Changed = true;
 }
示例#25
0
 public ImmutableDictionary <string, object> Load(string applicantId, string key, ImmutableDictionary <string, object> input)
 {
     return(input.Add(Variables.CreditScore, CalculateCreditScore((int)input[Variables.CreditA], (int)input[Variables.CreditB], (Address)input[Variables.Address])));
 }
示例#26
0
 protected void ContainsValueTestHelper <TKey, TValue>(ImmutableDictionary <TKey, TValue> map, TKey key, TValue value)
 {
     Assert.False(map.ContainsValue(value));
     Assert.True(map.Add(key, value).ContainsValue(value));
 }
示例#27
0
        private Utf8String ComputeUnqualifiedMangledMethodName(MethodDesc method)
        {
            if (method is EcmaMethod)
            {
                var deduplicator = new HashSet <string>();

                // Add consistent names for all methods of the type, independent on the order in which
                // they are compiled
                lock (this)
                {
                    if (!_unqualifiedMangledMethodNames.ContainsKey(method))
                    {
                        foreach (var m in method.OwningType.GetMethods())
                        {
                            string name = SanitizeName(m.Name);

                            name = DisambiguateName(name, deduplicator);
                            deduplicator.Add(name);

                            _unqualifiedMangledMethodNames = _unqualifiedMangledMethodNames.Add(m, name);
                        }
                    }
                }

                return(_unqualifiedMangledMethodNames[method]);
            }

            Utf8String utf8MangledName;

            var methodDefinition = method.GetMethodDefinition();

            if (methodDefinition != method)
            {
                // Instantiated generic method
                Utf8StringBuilder sb = new Utf8StringBuilder();
                sb.Append(GetUnqualifiedMangledMethodName(methodDefinition.GetTypicalMethodDefinition()));

                sb.Append(EnterNameScopeSequence);

                var inst = method.Instantiation;
                for (int i = 0; i < inst.Length; i++)
                {
                    string instArgName = GetMangledTypeName(inst[i]);
                    if (_mangleForCplusPlus)
                    {
                        instArgName = instArgName.Replace("::", "_");
                    }
                    if (i > 0)
                    {
                        sb.Append("__");
                    }
                    sb.Append(instArgName);
                }

                sb.Append(ExitNameScopeSequence);

                utf8MangledName = sb.ToUtf8String();
            }
            else
            {
                var typicalMethodDefinition = method.GetTypicalMethodDefinition();
                if (typicalMethodDefinition != method)
                {
                    // Method on an instantiated type
                    utf8MangledName = GetUnqualifiedMangledMethodName(typicalMethodDefinition);
                }
                else if (method is IPrefixMangledMethod)
                {
                    utf8MangledName = GetPrefixMangledMethodName((IPrefixMangledMethod)method);
                }
                else if (method is IPrefixMangledType)
                {
                    utf8MangledName = GetPrefixMangledTypeName((IPrefixMangledType)method);
                }
                else if (method is IPrefixMangledSignature)
                {
                    utf8MangledName = GetPrefixMangledSignatureName((IPrefixMangledSignature)method);
                }
                else
                {
                    // Assume that Name is unique for all other methods
                    utf8MangledName = new Utf8String(SanitizeName(method.Name));
                }
            }

            // Unless we're doing CPP mangling, there's no point in caching the unqualified
            // method name. We only needed it to construct the fully qualified name. Nobody
            // is going to ask for the unqualified name again.
            if (_mangleForCplusPlus)
            {
                lock (this)
                {
                    if (!_unqualifiedMangledMethodNames.ContainsKey(method))
                    {
                        _unqualifiedMangledMethodNames = _unqualifiedMangledMethodNames.Add(method, utf8MangledName);
                    }
                }
            }

            return(utf8MangledName);
        }
            private async Task<ImmutableDictionary<DiagnosticAnalyzer, AnalysisResult>> MergeProjectDiagnosticAnalyzerDiagnosticsAsync(
                Project project, IEnumerable<StateSet> stateSets, Compilation compilationOpt, ImmutableDictionary<DiagnosticAnalyzer, AnalysisResult> result, CancellationToken cancellationToken)
            {
                // check whether there is IDE specific project diagnostic analyzer
                var ideAnalyzers = stateSets.Select(s => s.Analyzer).Where(a => a is ProjectDiagnosticAnalyzer || a is DocumentDiagnosticAnalyzer).ToImmutableArrayOrEmpty();
                if (ideAnalyzers.Length <= 0)
                {
                    return result;
                }

                // create result map
                var version = await GetDiagnosticVersionAsync(project, cancellationToken).ConfigureAwait(false);
                var builder = new CompilerDiagnosticExecutor.Builder(project, version);

                foreach (var analyzer in ideAnalyzers)
                {
                    var documentAnalyzer = analyzer as DocumentDiagnosticAnalyzer;
                    if (documentAnalyzer != null)
                    {
                        foreach (var document in project.Documents)
                        {
                            if (document.SupportsSyntaxTree)
                            {
                                var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
                                builder.AddSyntaxDiagnostics(tree, await ComputeDocumentDiagnosticAnalyzerDiagnosticsAsync(document, documentAnalyzer, AnalysisKind.Syntax, compilationOpt, cancellationToken).ConfigureAwait(false));
                                builder.AddSemanticDiagnostics(tree, await ComputeDocumentDiagnosticAnalyzerDiagnosticsAsync(document, documentAnalyzer, AnalysisKind.Semantic, compilationOpt, cancellationToken).ConfigureAwait(false));
                            }
                            else
                            {
                                builder.AddExternalSyntaxDiagnostics(document.Id, await ComputeDocumentDiagnosticAnalyzerDiagnosticsAsync(document, documentAnalyzer, AnalysisKind.Syntax, compilationOpt, cancellationToken).ConfigureAwait(false));
                                builder.AddExternalSemanticDiagnostics(document.Id, await ComputeDocumentDiagnosticAnalyzerDiagnosticsAsync(document, documentAnalyzer, AnalysisKind.Semantic, compilationOpt, cancellationToken).ConfigureAwait(false));
                            }
                        }
                    }

                    var projectAnalyzer = analyzer as ProjectDiagnosticAnalyzer;
                    if (projectAnalyzer != null)
                    {
                        builder.AddCompilationDiagnostics(await ComputeProjectDiagnosticAnalyzerDiagnosticsAsync(project, projectAnalyzer, compilationOpt, cancellationToken).ConfigureAwait(false));
                    }

                    // merge the result to existing one.
                    result = result.Add(analyzer, builder.ToResult());
                }

                return result;
            }
            private static void AddDiagnosticForSymbolIfNeeded(ISymbol targetSymbol, Diagnostic diagnostic, ImmutableDictionary<ISymbol, List<Diagnostic>>.Builder diagnosticsMapBuilder)
            {
                if (diagnostic.IsSuppressed)
                {
                    return;
                }

                if (!diagnosticsMapBuilder.TryGetValue(targetSymbol, out var diagnosticsForSymbol))
                {
                    diagnosticsForSymbol = new List<Diagnostic>();
                    diagnosticsMapBuilder.Add(targetSymbol, diagnosticsForSymbol);
                }

                diagnosticsForSymbol.Add(diagnostic);
            }
        private static MSBuildWorkspace CreateWorkspace(ImmutableDictionary<string, string> propertiesOpt = null)
        {
            propertiesOpt = propertiesOpt ?? ImmutableDictionary<string, string>.Empty;

            // Explicitly add "CheckForSystemRuntimeDependency = true" property to correctly resolve facade references.
            // See https://github.com/dotnet/roslyn/issues/560
            propertiesOpt = propertiesOpt.Add("CheckForSystemRuntimeDependency", "true");
            propertiesOpt = propertiesOpt.Add("VisualStudioVersion", "14.0");

            var w = MSBuildWorkspace.Create(properties: propertiesOpt, hostServices: WorkspaceHacks.Pack);
            w.LoadMetadataForReferencedProjects = true;
            return w;
        }
示例#31
0
 private ImmutableDictionary<string, string> AddSolutionProperties(ImmutableDictionary<string, string> properties, string solutionFilePath)
 {
     // http://referencesource.microsoft.com/#MSBuildFiles/C/ProgramFiles(x86)/MSBuild/14.0/bin_/amd64/Microsoft.Common.CurrentVersion.targets,296
     properties = properties ?? ImmutableDictionary<string, string>.Empty;
     properties = properties.Add("SolutionName", Path.GetFileNameWithoutExtension(solutionFilePath));
     properties = properties.Add("SolutionFileName", Path.GetFileName(solutionFilePath));
     properties = properties.Add("SolutionPath", solutionFilePath);
     properties = properties.Add("SolutionDir", Path.GetDirectoryName(solutionFilePath));
     properties = properties.Add("SolutionExt", Path.GetExtension(solutionFilePath));
     return properties;
 }
示例#32
0
        private static MSBuildWorkspace CreateWorkspace(ImmutableDictionary<string, string> propertiesOpt = null)
        {
            propertiesOpt = propertiesOpt ?? ImmutableDictionary<string, string>.Empty;

            // Explicitly add "CheckForSystemRuntimeDependency = true" property to correctly resolve facade references.
            // See https://github.com/dotnet/roslyn/issues/560
            propertiesOpt = propertiesOpt.Add("CheckForSystemRuntimeDependency", "true");
            propertiesOpt = propertiesOpt.Add("VisualStudioVersion", "14.0");

            try
            {
                Microsoft.CodeAnalysis.Host.HostServices hostServices = WorkspaceHacks.Pack;
                return MSBuildWorkspace.Create(properties: propertiesOpt, hostServices: hostServices);
            } catch {}

            return MSBuildWorkspace.Create(properties: propertiesOpt);
        }
 public void Remove_Test()
 {
 	Dictionary<int, string> _dictionary = new Dictionary<int, string>
     {
         {1, "aabb"},
         {2, "bbcc"},
         {3, "ccdd"}
     };
 	ImmutableDictionary<int, string> _immutableDictionary = new ImmutableDictionary<int, string>(_dictionary);
 	_immutableDictionary.Add(new KeyValuePair<int, string>(4, "ddee"));
 }
示例#34
0
 public void Bind(TypeVariable variable, Type type)
 {
     Map = Map.Add(variable, type);
 }
示例#35
0
        /// <summary>
        /// If given <param name="type"/> is an <see cref="EcmaType"/> precompute its mangled type name
        /// along with all the other types from the same module as <param name="type"/>.
        /// Otherwise, it is a constructed type and to the EcmaType's mangled name we add a suffix to
        /// show what kind of constructed type it is (e.g. appending __Array for an array type).
        /// </summary>
        /// <param name="type">Type to mangled</param>
        /// <returns>Mangled name for <param name="type"/>.</returns>
        private string ComputeMangledTypeName(TypeDesc type)
        {
            if (type is EcmaType)
            {
                EcmaType ecmaType = (EcmaType)type;

                string assemblyName    = ((EcmaAssembly)ecmaType.EcmaModule).GetName().Name;
                bool   isSystemPrivate = assemblyName.StartsWith("System.Private.");

                // Abbreviate System.Private to S.P. This might conflict with user defined assembly names,
                // but we already have a problem due to running SanitizeName without disambiguating the result
                // This problem needs a better fix.
                if (isSystemPrivate && !_mangleForCplusPlus)
                {
                    assemblyName = "S.P." + assemblyName.Substring(15);
                }
                string prependAssemblyName = SanitizeName(assemblyName);

                var deduplicator = new HashSet <string>();

                // Add consistent names for all types in the module, independent on the order in which
                // they are compiled
                lock (this)
                {
                    bool isSystemModule = ecmaType.Module == ecmaType.Context.SystemModule;

                    if (!_mangledTypeNames.ContainsKey(type))
                    {
                        foreach (MetadataType t in ecmaType.EcmaModule.GetAllTypes())
                        {
                            string name = t.GetFullName();

                            // Include encapsulating type
                            DefType containingType = t.ContainingType;
                            while (containingType != null)
                            {
                                name           = containingType.GetFullName() + "_" + name;
                                containingType = containingType.ContainingType;
                            }

                            name = SanitizeName(name, true);

                            if (_mangleForCplusPlus)
                            {
                                // Always generate a fully qualified name
                                name = "::" + prependAssemblyName + "::" + name;
                            }
                            else
                            {
                                name = prependAssemblyName + "_" + name;

                                // If this is one of the well known types, use a shorter name
                                // We know this won't conflict because all the other types are
                                // prefixed by the assembly name.
                                if (isSystemModule)
                                {
                                    switch (t.Category)
                                    {
                                    case TypeFlags.Boolean: name = "Bool"; break;

                                    case TypeFlags.Byte: name = "UInt8"; break;

                                    case TypeFlags.SByte: name = "Int8"; break;

                                    case TypeFlags.UInt16: name = "UInt16"; break;

                                    case TypeFlags.Int16: name = "Int16"; break;

                                    case TypeFlags.UInt32: name = "UInt32"; break;

                                    case TypeFlags.Int32: name = "Int32"; break;

                                    case TypeFlags.UInt64: name = "UInt64"; break;

                                    case TypeFlags.Int64: name = "Int64"; break;

                                    case TypeFlags.Char: name = "Char"; break;

                                    case TypeFlags.Double: name = "Double"; break;

                                    case TypeFlags.Single: name = "Single"; break;

                                    case TypeFlags.IntPtr: name = "IntPtr"; break;

                                    case TypeFlags.UIntPtr: name = "UIntPtr"; break;

                                    default:
                                        if (t.IsObject)
                                        {
                                            name = "Object";
                                        }
                                        else if (t.IsString)
                                        {
                                            name = "String";
                                        }
                                        break;
                                    }
                                }
                            }

                            // Ensure that name is unique and update our tables accordingly.
                            name = DisambiguateName(name, deduplicator);
                            deduplicator.Add(name);
                            _mangledTypeNames = _mangledTypeNames.Add(t, name);
                        }
                    }
                }

                return(_mangledTypeNames[type]);
            }

            string mangledName;

            switch (type.Category)
            {
            case TypeFlags.Array:
                mangledName = "__MDArray" +
                              EnterNameScopeSequence +
                              GetMangledTypeName(((ArrayType)type).ElementType) +
                              DelimitNameScopeSequence +
                              ((ArrayType)type).Rank.ToStringInvariant() +
                              ExitNameScopeSequence;
                break;

            case TypeFlags.SzArray:
                mangledName = "__Array" + NestMangledName(GetMangledTypeName(((ArrayType)type).ElementType));
                break;

            case TypeFlags.ByRef:
                mangledName = GetMangledTypeName(((ByRefType)type).ParameterType) + NestMangledName("ByRef");
                break;

            case TypeFlags.Pointer:
                mangledName = GetMangledTypeName(((PointerType)type).ParameterType) + NestMangledName("Pointer");
                break;

            default:
                // Case of a generic type. If `type' is a type definition we use the type name
                // for mangling, otherwise we use the mangling of the type and its generic type
                // parameters, e.g. A <B> becomes A_<___B_>_ in RyuJIT compilation, or A_A___B_V_
                // in C++ compilation.
                var typeDefinition = type.GetTypeDefinition();
                if (typeDefinition != type)
                {
                    mangledName = GetMangledTypeName(typeDefinition);

                    var    inst = type.Instantiation;
                    string mangledInstantiation = "";
                    for (int i = 0; i < inst.Length; i++)
                    {
                        string instArgName = GetMangledTypeName(inst[i]);
                        if (_mangleForCplusPlus)
                        {
                            instArgName = instArgName.Replace("::", "_");
                        }
                        if (i > 0)
                        {
                            mangledInstantiation += "__";
                        }

                        mangledInstantiation += instArgName;
                    }
                    mangledName += NestMangledName(mangledInstantiation);
                }
                else if (type is IPrefixMangledMethod)
                {
                    mangledName = GetPrefixMangledMethodName((IPrefixMangledMethod)type).ToString();
                }
                else if (type is IPrefixMangledType)
                {
                    mangledName = GetPrefixMangledTypeName((IPrefixMangledType)type).ToString();
                }
                else
                {
                    // This is a type definition. Since we didn't fall in the `is EcmaType` case above,
                    // it's likely a compiler-generated type.
                    mangledName = SanitizeName(((DefType)type).GetFullName(), true);

                    // Always generate a fully qualified name
                    if (_mangleForCplusPlus)
                    {
                        mangledName = "::" + mangledName;
                    }
                }
                break;
            }

            lock (this)
            {
                // Ensure that name is unique and update our tables accordingly.
                if (!_mangledTypeNames.ContainsKey(type))
                {
                    _mangledTypeNames = _mangledTypeNames.Add(type, mangledName);
                }
            }

            return(mangledName);
        }
            private static void AddStringFormatMap(ImmutableDictionary<IMethodSymbol, Info>.Builder builder, INamedTypeSymbol type, string methodName)
            {
                if (type == null)
                {
                    return;
                }

                foreach (IMethodSymbol method in type.GetMembers(methodName).OfType<IMethodSymbol>())
                {
                    int formatIndex = FindParameterIndexOfName(method.Parameters, Format);
                    if (formatIndex < 0 || formatIndex == method.Parameters.Length - 1)
                    {
                        // no valid format string
                        continue;
                    }

                    int expectedArguments = GetExpectedNumberOfArguments(method.Parameters, formatIndex);
                    builder.Add(method, new Info(formatIndex, expectedArguments));
                }
            }
示例#37
0
        public static Imports FromSyntax(
            CSharpSyntaxNode declarationSyntax,
            InContainerBinder binder,
            ConsList <Symbol> basesBeingResolved,
            bool inUsing)
        {
            SyntaxList <UsingDirectiveSyntax>       usingDirectives;
            SyntaxList <ExternAliasDirectiveSyntax> externAliasDirectives;

            if (declarationSyntax.Kind() == SyntaxKind.CompilationUnit)
            {
                var compilationUnit = (CompilationUnitSyntax)declarationSyntax;
                // using directives are not in scope within using directives
                usingDirectives       = inUsing ? default(SyntaxList <UsingDirectiveSyntax>) : compilationUnit.Usings;
                externAliasDirectives = compilationUnit.Externs;
            }
            else if (declarationSyntax.Kind() == SyntaxKind.NamespaceDeclaration)
            {
                var namespaceDecl = (NamespaceDeclarationSyntax)declarationSyntax;
                // using directives are not in scope within using directives
                usingDirectives       = inUsing ? default(SyntaxList <UsingDirectiveSyntax>) : namespaceDecl.Usings;
                externAliasDirectives = namespaceDecl.Externs;
            }
            else
            {
                return(Empty);
            }

            if (usingDirectives.Count == 0 && externAliasDirectives.Count == 0)
            {
                return(Empty);
            }

            // define all of the extern aliases first. They may used by the target of a using

            // using Bar=Goo::Bar;
            // using Goo::Baz;
            // extern alias Goo;

            var diagnostics = new DiagnosticBag();

            var compilation = binder.Compilation;

            var externAliases = BuildExternAliases(externAliasDirectives, binder, diagnostics);
            var usings        = ArrayBuilder <NamespaceOrTypeAndUsingDirective> .GetInstance();

            ImmutableDictionary <string, AliasAndUsingDirective> .Builder usingAliases = null;
            if (usingDirectives.Count > 0)
            {
                // A binder that contains the extern aliases but not the usings. The resolution of the target of a using directive or alias
                // should not make use of other peer usings.
                Binder usingsBinder;
                if (declarationSyntax.SyntaxTree.Options.Kind != SourceCodeKind.Regular)
                {
                    usingsBinder = compilation.GetBinderFactory(declarationSyntax.SyntaxTree).GetImportsBinder(declarationSyntax, inUsing: true);
                }
                else
                {
                    var imports = externAliases.Length == 0
                        ? Empty
                        : new Imports(
                        compilation,
                        ImmutableDictionary <string, AliasAndUsingDirective> .Empty,
                        ImmutableArray <NamespaceOrTypeAndUsingDirective> .Empty,
                        externAliases,
                        diagnostics: null);
                    usingsBinder = new InContainerBinder(binder.Container, binder.Next, imports);
                }

                var uniqueUsings = PooledHashSet <NamespaceOrTypeSymbol> .GetInstance();

                foreach (var usingDirective in usingDirectives)
                {
                    compilation.RecordImport(usingDirective);

                    if (usingDirective.Alias != null)
                    {
                        if (usingDirective.Alias.Name.Identifier.ContextualKind() == SyntaxKind.GlobalKeyword)
                        {
                            diagnostics.Add(ErrorCode.WRN_GlobalAliasDefn, usingDirective.Alias.Name.Location);
                        }

                        if (usingDirective.StaticKeyword != default(SyntaxToken))
                        {
                            diagnostics.Add(ErrorCode.ERR_NoAliasHere, usingDirective.Alias.Name.Location);
                        }

                        string identifierValueText = usingDirective.Alias.Name.Identifier.ValueText;
                        if (usingAliases != null && usingAliases.ContainsKey(identifierValueText))
                        {
                            // Suppress diagnostics if we're already broken.
                            if (!usingDirective.Name.IsMissing)
                            {
                                // The using alias '{0}' appeared previously in this namespace
                                diagnostics.Add(ErrorCode.ERR_DuplicateAlias, usingDirective.Alias.Name.Location, identifierValueText);
                            }
                        }
                        else
                        {
                            // an O(m*n) algorithm here but n (number of extern aliases) will likely be very small.
                            foreach (var externAlias in externAliases)
                            {
                                if (externAlias.Alias.Name == identifierValueText)
                                {
                                    // The using alias '{0}' appeared previously in this namespace
                                    diagnostics.Add(ErrorCode.ERR_DuplicateAlias, usingDirective.Location, identifierValueText);
                                    break;
                                }
                            }

                            if (usingAliases == null)
                            {
                                usingAliases = ImmutableDictionary.CreateBuilder <string, AliasAndUsingDirective>();
                            }

                            // construct the alias sym with the binder for which we are building imports. That
                            // way the alias target can make use of extern alias definitions.
                            usingAliases.Add(identifierValueText, new AliasAndUsingDirective(new AliasSymbol(usingsBinder, usingDirective), usingDirective));
                        }
                    }
                    else
                    {
                        if (usingDirective.Name.IsMissing)
                        {
                            //don't try to lookup namespaces inserted by parser error recovery
                            continue;
                        }

                        var declarationBinder = usingsBinder.WithAdditionalFlags(BinderFlags.SuppressConstraintChecks);
                        var imported          = declarationBinder.BindNamespaceOrTypeSymbol(usingDirective.Name, diagnostics, basesBeingResolved).NamespaceOrTypeSymbol;
                        if (imported.Kind == SymbolKind.Namespace)
                        {
                            if (usingDirective.StaticKeyword != default(SyntaxToken))
                            {
                                diagnostics.Add(ErrorCode.ERR_BadUsingType, usingDirective.Name.Location, imported);
                            }
                            else if (uniqueUsings.Contains(imported))
                            {
                                diagnostics.Add(ErrorCode.WRN_DuplicateUsing, usingDirective.Name.Location, imported);
                            }
                            else
                            {
                                uniqueUsings.Add(imported);
                                usings.Add(new NamespaceOrTypeAndUsingDirective(imported, usingDirective));
                            }
                        }
                        else if (imported.Kind == SymbolKind.NamedType)
                        {
                            if (usingDirective.StaticKeyword == default(SyntaxToken))
                            {
                                diagnostics.Add(ErrorCode.ERR_BadUsingNamespace, usingDirective.Name.Location, imported);
                            }
                            else
                            {
                                var importedType = (NamedTypeSymbol)imported;
                                if (uniqueUsings.Contains(importedType))
                                {
                                    diagnostics.Add(ErrorCode.WRN_DuplicateUsing, usingDirective.Name.Location, importedType);
                                }
                                else
                                {
                                    declarationBinder.ReportDiagnosticsIfObsolete(diagnostics, importedType, usingDirective.Name, hasBaseReceiver: false);

                                    uniqueUsings.Add(importedType);
                                    usings.Add(new NamespaceOrTypeAndUsingDirective(importedType, usingDirective));
                                }
                            }
                        }
                        else if (imported.Kind != SymbolKind.ErrorType)
                        {
                            // Do not report additional error if the symbol itself is erroneous.

                            // error: '<symbol>' is a '<symbol kind>' but is used as 'type or namespace'
                            diagnostics.Add(ErrorCode.ERR_BadSKknown, usingDirective.Name.Location,
                                            usingDirective.Name,
                                            imported.GetKindText(),
                                            MessageID.IDS_SK_TYPE_OR_NAMESPACE.Localize());
                        }
                    }
                }

                uniqueUsings.Free();
            }

            if (diagnostics.IsEmptyWithoutResolution)
            {
                diagnostics = null;
            }

            return(new Imports(compilation, usingAliases.ToImmutableDictionaryOrEmpty(), usings.ToImmutableAndFree(), externAliases, diagnostics));
        }
示例#38
0
        private static bool TryAddImport(
            string alias,
            NamespaceOrTypeSymbol targetSymbol,
            ArrayBuilder<NamespaceOrTypeAndUsingDirective> usingsBuilder,
            ImmutableDictionary<string, AliasAndUsingDirective>.Builder usingAliases,
            InContainerBinder binder,
            ImportRecord importRecord)
        {
            if (alias == null)
            {
                usingsBuilder.Add(new NamespaceOrTypeAndUsingDirective(targetSymbol, usingDirective: null));
            }
            else
            {
                IdentifierNameSyntax aliasSyntax;
                if (!TryParseIdentifierNameSyntax(alias, out aliasSyntax))
                {
                    Debug.WriteLine($"Import record '{importRecord}' has syntactically invalid alias '{alias}'");
                    return false;
                }

                var aliasSymbol = AliasSymbol.CreateCustomDebugInfoAlias(targetSymbol, aliasSyntax.Identifier, binder);
                usingAliases.Add(alias, new AliasAndUsingDirective(aliasSymbol, usingDirective: null));
            }

            return true;
        }
 public IBidirectionalMap <TKey, TValue> Add(TKey key, TValue value)
 {
     return(new BidirectionalMap <TKey, TValue>(
                _forwardMap.Add(key, value),
                _backwardMap.Add(value, key)));
 }
示例#40
0
 /// <summary>
 /// Adds a key-value pair to the object being built.
 /// </summary>
 /// <param name="key">the key to add</param>
 /// <param name="value">the value to add</param>
 /// <returns>the same builder</returns>
 public ObjectBuilder Add(string key, LdValue value)
 {
     _builder.Add(key, value);
     return(this);
 }
示例#41
0
        /// <summary>
        /// If given <param name="type"/> is an <see cref="EcmaType"/> precompute its mangled type name
        /// along with all the other types from the same module as <param name="type"/>.
        /// Otherwise, it is a constructed type and to the EcmaType's mangled name we add a suffix to
        /// show what kind of constructed type it is (e.g. appending __Array for an array type).
        /// </summary>
        /// <param name="type">Type to mangled</param>
        /// <returns>Mangled name for <param name="type"/>.</returns>
        private string ComputeMangledTypeName(TypeDesc type)
        {
            if (type is EcmaType)
            {
                EcmaType ecmaType = (EcmaType)type;

                string prependAssemblyName = SanitizeName(((EcmaAssembly)ecmaType.EcmaModule).GetName().Name);

                var deduplicator = new HashSet <string>();

                // Add consistent names for all types in the module, independent on the order in which
                // they are compiled
                lock (this)
                {
                    if (!_mangledTypeNames.ContainsKey(type))
                    {
                        foreach (MetadataType t in ((EcmaType)type).EcmaModule.GetAllTypes())
                        {
                            string name = t.GetFullName();

                            // Include encapsulating type
                            DefType containingType = t.ContainingType;
                            while (containingType != null)
                            {
                                name           = containingType.GetFullName() + "_" + name;
                                containingType = containingType.ContainingType;
                            }

                            name = SanitizeName(name, true);
                            name = prependAssemblyName + "_" + name;

                            // Ensure that name is unique and update our tables accordingly.
                            name = DisambiguateName(name, deduplicator);
                            deduplicator.Add(name);
                            _mangledTypeNames = _mangledTypeNames.Add(t, name);
                        }
                    }
                }

                return(_mangledTypeNames[type]);
            }

            string mangledName;

            switch (type.Category)
            {
            case TypeFlags.Array:
            case TypeFlags.SzArray:
                mangledName = GetMangledTypeName(((ArrayType)type).ElementType) + "__";

                if (type.IsMdArray)
                {
                    mangledName += NestMangledName("ArrayRank" + ((ArrayType)type).Rank.ToStringInvariant());
                }
                else
                {
                    mangledName += NestMangledName("Array");
                }
                break;

            case TypeFlags.ByRef:
                mangledName = GetMangledTypeName(((ByRefType)type).ParameterType) + NestMangledName("ByRef");
                break;

            case TypeFlags.Pointer:
                mangledName = GetMangledTypeName(((PointerType)type).ParameterType) + NestMangledName("Pointer");
                break;

            default:
                // Case of a generic type. If `type' is a type definition we use the type name
                // for mangling, otherwise we use the mangling of the type and its generic type
                // parameters, e.g. A <B> becomes A_<___B_>_ in RyuJIT compilation, or A_A___B_V_
                // in C++ compilation.
                var typeDefinition = type.GetTypeDefinition();
                if (typeDefinition != type)
                {
                    mangledName = GetMangledTypeName(typeDefinition);

                    var    inst = type.Instantiation;
                    string mangledInstantiation = "";
                    for (int i = 0; i < inst.Length; i++)
                    {
                        string instArgName = GetMangledTypeName(inst[i]);
                        if (i > 0)
                        {
                            mangledInstantiation += "__";
                        }

                        mangledInstantiation += instArgName;
                    }
                    mangledName += NestMangledName(mangledInstantiation);
                }
                else
                {
                    mangledName = SanitizeName(((DefType)type).GetFullName(), true);
                }
                break;
            }

            lock (this)
            {
                // Ensure that name is unique and update our tables accordingly.
                if (!_mangledTypeNames.ContainsKey(type))
                {
                    _mangledTypeNames = _mangledTypeNames.Add(type, mangledName);
                }
            }

            return(mangledName);
        }
示例#42
0
 public Task <(string?id, object state)> NewStorageAccount(MockResourceArgs args, ImmutableDictionary <string, object> .Builder outputs)
 {
     outputs.Add("name", args.Inputs["accountName"]);
     return(Task.FromResult((args.Id, (object)outputs)));
 }