Example #1
0
        public void SerializeDictionary()
        {
            ImmutableDictionary <int, string> l = ImmutableDictionary.CreateRange(new Dictionary <int, string>
            {
                { 1, "One" },
                { 2, "II" },
                { 3, "3" }
            });

            string  json = JsonConvertX.SerializeObject(l, Formatting.Indented);
            JObject a    = JObject.Parse(json);

            Assert.AreEqual(3, a.Count);
            Assert.AreEqual("One", (string)a["1"]);
            Assert.AreEqual("II", (string)a["2"]);
            Assert.AreEqual("3", (string)a["3"]);
        }
        public void ReadImmutableDictionaryOfInt32()
        {
            ImmutableDictionary <int, int> expected = ImmutableDictionary.CreateRange(new Dictionary <int, int>
            {
                { 1, 1 },
                { 2, 2 },
                { 3, 3 }
            });
            const string json = @"{""1"":1,""2"":2,""3"":3}";

            JsonSerializerOptions options = new JsonSerializerOptions();

            options.SetupExtensions();
            ImmutableDictionary <int, int> actual = JsonSerializer.Deserialize <ImmutableDictionary <int, int> >(json, options);

            Assert.Equal(expected, actual);
        }
Example #3
0
        public void SerializeDictionary()
        {
            ImmutableDictionary <int, string> data = ImmutableDictionary.CreateRange(new Dictionary <int, string>
            {
                { 1, "One" },
                { 2, "II" },
                { 3, "3" }
            });

            string json = JsonSerializer.Serialize(data, s_indentedOption);
            ImmutableDictionary <int, string> a = JsonSerializer.Deserialize <ImmutableDictionary <int, string> >(json);

            Assert.Equal(3, a.Count);
            Assert.Equal("One", (string)a[1]);
            Assert.Equal("II", (string)a[2]);
            Assert.Equal("3", (string)a[3]);
        }
Example #4
0
 private static void Handle(SyntaxNodeAnalysisContext context)
 {
     if (!context.IsExcludedFromAnalysis() &&
         context.Node is PropertyDeclarationSyntax propertyDeclaration &&
         context.ContainingSymbol is IPropertySymbol property &&
         property.ContainingType.IsAssignableTo(KnownSymbols.MarkupExtension, context.Compilation) &&
         !Attribute.TryFind(propertyDeclaration, KnownSymbols.ConstructorArgumentAttribute, context.SemanticModel, context.CancellationToken, out _) &&
         ConstructorArgument.TryGetParameterName(property, context.SemanticModel, context.CancellationToken, out var parameterName))
     {
         context.ReportDiagnostic(
             Diagnostic.Create(
                 Descriptors.WPF0083UseConstructorArgumentAttribute,
                 propertyDeclaration.Identifier.GetLocation(),
                 ImmutableDictionary.CreateRange(new[] { new KeyValuePair <string, string>(nameof(ConstructorArgument), parameterName) }),
                 parameterName));
     }
 }
Example #5
0
        public void ORSet_must_verify_SubtractDots()
        {
            var dot = VersionVector.Create(ImmutableDictionary.CreateRange(new Dictionary <UniqueAddress, long>
            {
                { _nodeA, 3L }, { _nodeB, 2L }, { _nodeD, 14L }, { _nodeG, 22L }
            }));
            var vvector = VersionVector.Create(ImmutableDictionary.CreateRange(new Dictionary <UniqueAddress, long>
            {
                { _nodeA, 4L }, { _nodeB, 1L }, { _nodeC, 1L }, { _nodeD, 14L }, { _nodeE, 5L }, { _nodeF, 2L }
            }));
            var expected = VersionVector.Create(ImmutableDictionary.CreateRange(new Dictionary <UniqueAddress, long>
            {
                { _nodeB, 2L }, { _nodeG, 22L }
            }));

            ORSet.SubtractDots(dot, vvector).Should().Be(expected);
        }
        public void WriteImmutableDictionaryOfInt32()
        {
            ImmutableDictionary <int, int> value = ImmutableDictionary.CreateRange(new Dictionary <int, int>
            {
                { 1, 1 },
                { 2, 2 },
                { 3, 3 }
            });
            const string expected = @"{""1"":1,""2"":2,""3"":3}";

            JsonSerializerOptions options = new JsonSerializerOptions();

            options.SetupExtensions();
            string actual = JsonSerializer.Serialize(value, value.GetType(), options);

            Assert.Equal(expected, actual);
        }
        private static void Analyze(SyntaxNodeAnalysisContext context, MemberDeclarationSyntax declaration, SyntaxTokenList modifiers)
        {
            Accessibility accessibility = GetAccessibility(context, declaration, modifiers);

            if (accessibility == Accessibility.NotApplicable)
                return;

            Location location = GetLocation(declaration);

            if (location == null)
                return;

            DiagnosticHelpers.ReportDiagnostic(context,
                DiagnosticDescriptors.AddAccessibilityModifiers,
                location,
                ImmutableDictionary.CreateRange(new KeyValuePair<string, string>[] { new KeyValuePair<string, string>(nameof(Accessibility), accessibility.ToString()) }));
        }
Example #8
0
        protected virtual void LoadWords()
        {
            using (var ctx = GetNewContext())
            {
                IDsToWords = ImmutableDictionary.CreateRange(
                    ctx.Words.ToList().Select(kvp => CreateKVP(kvp.ID, kvp.WordString))
                    );

                var wordsToNouns = new Dictionary <string, List <Noun> >();
                foreach (Noun noun in ctx.Nouns)
                {
                    string lowerWord = IDsToWords[noun.WordID].ToLowerInvariant();

                    List <Noun> existingNouns;
                    if (!wordsToNouns.TryGetValue(lowerWord, out existingNouns))
                    {
                        existingNouns           = new List <Noun>();
                        wordsToNouns[lowerWord] = existingNouns;
                    }

                    existingNouns.Add(noun);
                }
                LowerWordToNouns = ImmutableDictionary.CreateRange(
                    wordsToNouns.Select(kvp => CreateKVP(kvp.Key, ImmutableList.CreateRange(kvp.Value)))
                    );

                var wordsToAdjectives = new Dictionary <string, List <Adjective> >();
                foreach (Adjective adj in ctx.Adjectives)
                {
                    string lowerWord = IDsToWords[adj.WordID].ToLowerInvariant();

                    List <Adjective> existingAdjectives;
                    if (!wordsToAdjectives.TryGetValue(lowerWord, out existingAdjectives))
                    {
                        existingAdjectives           = new List <Adjective>();
                        wordsToAdjectives[lowerWord] = existingAdjectives;
                    }

                    existingAdjectives.Add(adj);
                }
                LowerWordToAdjectives = ImmutableDictionary.CreateRange(
                    wordsToAdjectives.Select(kvp => CreateKVP(kvp.Key, ImmutableList.CreateRange(kvp.Value)))
                    );
            }
        }
Example #9
0
        public static void Main()
        {
            string?searchType = null;

            while (true)
            {
                Console.Write("Depth-first or Breadth-first search? (d/b): ");
                searchType = Console.ReadLine();
                if ((searchType == "d") || (searchType == "b"))
                {
                    break;
                }
                Console.WriteLine("Invalid Selection");
                Console.WriteLine();
            }

            try
            {
                var findStarted = DateTime.UtcNow;

                var initialState = new PuzzleState(
                    AirTimeMinutesRemaining:    21,
                    AstronautLocations:         ImmutableDictionary.CreateRange(new[]
                {
                    new KeyValuePair <Astronaut, StationSection>(Astronaut.Neil, StationSection.SectionA),
                    new KeyValuePair <Astronaut, StationSection>(Astronaut.Michael, StationSection.SectionA),
                    new KeyValuePair <Astronaut, StationSection>(Astronaut.Valentina, StationSection.SectionA),
                    new KeyValuePair <Astronaut, StationSection>(Astronaut.Yuri, StationSection.SectionA),
                    new KeyValuePair <Astronaut, StationSection>(Astronaut.Edwin, StationSection.SectionA)
                }),
                    SuitsLocation:              StationSection.SectionA);

                var(solution, solutionsChecked) = (searchType == "d")
                    ? PuzzleSolution.FindDepth(initialState)
                    : PuzzleSolution.FindBreadth(initialState);

                var findDuration = DateTime.UtcNow - findStarted;

                Console.WriteLine("Solution found");
                Console.WriteLine("Steps:");
                foreach (var mutation in solution.Mutations)
                {
                    Console.WriteLine($"\t{string.Join(" and ", mutation.AstronautsMoved)} spend{((mutation.AstronautsMoved.Length == 1) ? "s" : "")} {mutation.TravelTimeMinutes} minute{((mutation.TravelTimeMinutes == 1) ? "" : "s")} moving to {mutation.TargetStationSection}");
                }
                var finalState = solution.States[^ 1];
        private static void Handle(SyntaxNodeAnalysisContext context)
        {
            if (context.IsExcludedFromAnalysis())
            {
                return;
            }

            if (context.Node is ObjectCreationExpressionSyntax objectCreation &&
                context.SemanticModel.TryGetSymbol(objectCreation, context.CancellationToken, out var ctor))
            {
                if (objectCreation.ArgumentList is ArgumentListSyntax argumentList &&
                    argumentList.Arguments.Count > 0 &&
                    context.ContainingSymbol is IMethodSymbol method &&
                    ctor.ContainingType.IsEither(KnownSymbol.ArgumentException, KnownSymbol.ArgumentNullException, KnownSymbol.ArgumentOutOfRangeException) &&
                    ctor.TryFindParameter("paramName", out var nameParameter))
                {
                    if (objectCreation.TryFindArgument(nameParameter, out var nameArgument) &&
                        objectCreation.Parent is ThrowExpressionSyntax throwExpression &&
                        throwExpression.Parent is BinaryExpressionSyntax binary &&
                        binary.IsKind(SyntaxKind.CoalesceExpression) &&
                        nameArgument.TryGetStringValue(context.SemanticModel, context.CancellationToken, out var name) &&
                        binary.Left is IdentifierNameSyntax identifierName &&
                        identifierName.Identifier.ValueText != name)
                    {
                        var properties = ImmutableDictionary.CreateRange(
                            new[] { new KeyValuePair <string, string>("Name", identifierName.Identifier.ValueText) });
                        context.ReportDiagnostic(
                            Diagnostic.Create(
                                GU0013CheckNameInThrow.Descriptor,
                                nameArgument.GetLocation(),
                                properties));
                    }

                    if (TryGetWithParameterName(argumentList, method.Parameters, out var argument) &&
                        argument.NameColon == null &&
                        objectCreation.ArgumentList.Arguments.IndexOf(argument) != ctor.Parameters.IndexOf(nameParameter))
                    {
                        context.ReportDiagnostic(
                            Diagnostic.Create(
                                GU0005ExceptionArgumentsPositions.Descriptor,
                                argument.GetLocation()));
                    }
                }
            }
        }
        public static void Analyze(SyntaxNodeAnalysisContext context, InvocationExpressionSyntax invocation, MemberAccessExpressionSyntax memberAccess)
        {
            if (SyntaxAnalyzer.IsEnumerableExtensionMethod(invocation, "Count", 1, context.SemanticModel, context.CancellationToken))
            {
                string propertyName = SyntaxHelper.GetCountOrLengthPropertyName(memberAccess.Expression, context.SemanticModel, allowImmutableArray: true, cancellationToken: context.CancellationToken);

                if (propertyName != null)
                {
                    TextSpan span = TextSpan.FromBounds(memberAccess.Name.Span.Start, invocation.Span.End);
                    if (invocation
                        .DescendantTrivia(span)
                        .All(f => f.IsWhitespaceOrEndOfLineTrivia()))
                    {
                        Diagnostic diagnostic = Diagnostic.Create(
                            DiagnosticDescriptors.ReplaceCountMethodWithCountOrLengthProperty,
                            Location.Create(context.Node.SyntaxTree, span),
                            ImmutableDictionary.CreateRange(new KeyValuePair <string, string>[] { new KeyValuePair <string, string>("PropertyName", propertyName) }),
                            propertyName);

                        context.ReportDiagnostic(diagnostic);
                    }
                }
                else if (invocation.Parent?.IsKind(
                             SyntaxKind.EqualsExpression,
                             SyntaxKind.GreaterThanExpression,
                             SyntaxKind.LessThanExpression) == true)
                {
                    var binaryExpression = (BinaryExpressionSyntax)invocation.Parent;

                    if (IsFixableBinaryExpression(binaryExpression))
                    {
                        TextSpan span = TextSpan.FromBounds(invocation.Span.End, binaryExpression.Span.End);

                        if (binaryExpression
                            .DescendantTrivia(span)
                            .All(f => f.IsWhitespaceOrEndOfLineTrivia()))
                        {
                            context.ReportDiagnostic(
                                DiagnosticDescriptors.ReplaceCountMethodWithAnyMethod,
                                binaryExpression.GetLocation());
                        }
                    }
                }
            }
        }
Example #12
0
 private static void Handle(SyntaxNodeAnalysisContext context)
 {
     if (!context.IsExcludedFromAnalysis() &&
         context.Node is AttributeSyntax attribute &&
         context.SemanticModel.TryGetNamedType(attribute, KnownSymbols.XmlnsDefinitionAttribute, context.CancellationToken, out _))
     {
         using var walker = Walker.Create(context.SemanticModel.Compilation, context.SemanticModel, context.CancellationToken);
         if (walker.NotMapped.Count != 0)
         {
             context.ReportDiagnostic(
                 Diagnostic.Create(
                     Descriptors.WPF0052XmlnsDefinitionsDoesNotMapAllNamespaces,
                     attribute.GetLocation(),
                     ImmutableDictionary.CreateRange(walker.NotMapped.Select(x => new KeyValuePair <string, string?>(x, x))),
                     string.Join(Environment.NewLine, walker.NotMapped)));
         }
     }
 }
Example #13
0
        public void ORMultiDictionary_must_be_able_to_add_entries()
        {
            var m = ORMultiValueDictionary <string, string> .Empty.AddItem(_node1, "a", "A").AddItem(_node1, "b", "B");

            Assert.Equal(ImmutableDictionary.CreateRange(new[]
            {
                new KeyValuePair <string, IImmutableSet <string> >("a", ImmutableHashSet.Create("A")),
                new KeyValuePair <string, IImmutableSet <string> >("b", ImmutableHashSet.Create("B"))
            }), m.Entries);

            var m2 = m.AddItem(_node1, "a", "C");

            Assert.Equal(ImmutableDictionary.CreateRange(new[]
            {
                new KeyValuePair <string, IImmutableSet <string> >("a", ImmutableHashSet.Create("A", "C")),
                new KeyValuePair <string, IImmutableSet <string> >("b", ImmutableHashSet.Create("B"))
            }), m2.Entries);
        }
Example #14
0
        private object CoordinatorStateFromBinary(byte[] binary)
        {
            using (var stream = Decompress(binary))
            {
                var state             = CoordinatorState.ParseFrom(stream);
                var shards            = ImmutableDictionary.CreateRange(state.ShardsList.Select(entry => new KeyValuePair <string, IActorRef>(entry.ShardId, ResolveActorRef(entry.RegionRef))));
                var regionsZero       = ImmutableDictionary.CreateRange(state.RegionsList.Select(region => new KeyValuePair <IActorRef, IImmutableList <string> >(ResolveActorRef(region), ImmutableList <string> .Empty)));
                var regions           = shards.Aggregate(regionsZero, (acc, entry) => acc.SetItem(entry.Value, acc[entry.Value].Add(entry.Key)));
                var proxies           = state.RegionProxiesList.Select(ResolveActorRef).ToImmutableHashSet();
                var unallocatedShards = state.UnallocatedShardsList.ToImmutableHashSet();

                return(new PersistentShardCoordinator.State(
                           shards: shards,
                           regions: regions,
                           regionProxies: proxies,
                           unallocatedShards: unallocatedShards));
            }
        }
        private ImmutableDictionary <string, PropertyInfo> PropertyInfoDictionaryFromSchema()
        {
            var entries = new List <KeyValuePair <string, PropertyInfo> >();

            if (_schema.Properties != null)
            {
                foreach (KeyValuePair <string, JsonSchema> schemaProperty in _schema.Properties)
                {
                    string     propertyName   = schemaProperty.Key;
                    JsonSchema propertySchema = schemaProperty.Value;
                    bool       isRequired     = _schema.Required?.Contains(propertyName) == true;

                    AddPropertyInfoFromPropertySchema(entries, propertyName, propertySchema, isRequired);
                }
            }

            return(ImmutableDictionary.CreateRange(entries));
        }
Example #16
0
        public Unit Execute(ModelEntity e)
        {
            var excludedTypes = new[] { TaggedValueTypes.Const("").TypeName };

            var tvs = ImmutableDictionary.CreateRange(
                from tv in e.TaggedValues
                join proto in ADTechnology.Technologies.AD.TaggedValues on tv.Key equals proto.Name
                where !proto.Type.TypeName.In(excludedTypes)
                select tv);

            Form.GetSelected(tvs).Do(selectedTVs =>
            {
                var selectedTags = selectedTVs.Select(p => p.Key).ToImmutableHashSet();
                Clipboard.Exchange(new TaggedValuesClipboard(e, selectedTags), GetType());
            });

            return(Unit.Instance);
        }
Example #17
0
        public void A_LWWDictionary_should_be_able_to_have_its_entries_correctly_merged_with_another_LWWMap_with_other_entries()
        {
            var m1 = LWWDictionary.Create(
                Tuple.Create(_node1, "a", 1),
                Tuple.Create(_node1, "b", 2));
            var m2 = LWWDictionary.Create(_node2, "c", 3);

            var expected = ImmutableDictionary.CreateRange(new[]
            {
                new KeyValuePair <string, int>("a", 1),
                new KeyValuePair <string, int>("b", 2),
                new KeyValuePair <string, int>("c", 3),
            });

            // merge both ways
            Assert.Equal(expected, m1.Merge(m2).Entries);
            Assert.Equal(expected, m2.Merge(m1).Entries);
        }
Example #18
0
            internal virtual async Task <ImmutableDictionary <Project, ImmutableArray <Diagnostic> > > GetProjectDiagnosticsToFixAsync(
                FixAllContext fixAllContext)
            {
                using (Logger.LogBlock(FunctionId.CodeFixes_FixAllOccurrencesComputation_Diagnostics, fixAllContext.CancellationToken))
                {
                    var project = fixAllContext.Project;
                    if (project != null)
                    {
                        switch (fixAllContext.Scope)
                        {
                        case FixAllScope.Project:
                            var diagnostics = await fixAllContext.GetProjectDiagnosticsAsync(project).ConfigureAwait(false);

                            var kvp = SpecializedCollections.SingletonEnumerable(KeyValuePair.Create(project, diagnostics));
                            return(ImmutableDictionary.CreateRange(kvp));

                        case FixAllScope.Solution:
                            var projectsAndDiagnostics = ImmutableDictionary.CreateBuilder <Project, ImmutableArray <Diagnostic> >();

                            var tasks = project.Solution.Projects.Select(async p => new
                            {
                                Project     = p,
                                Diagnostics = await fixAllContext.GetProjectDiagnosticsAsync(p).ConfigureAwait(false)
                            }).ToArray();

                            await Task.WhenAll(tasks).ConfigureAwait(false);

                            foreach (var task in tasks)
                            {
                                var projectAndDiagnostics = await task.ConfigureAwait(false);

                                if (projectAndDiagnostics.Diagnostics.Any())
                                {
                                    projectsAndDiagnostics[projectAndDiagnostics.Project] = projectAndDiagnostics.Diagnostics;
                                }
                            }

                            return(projectsAndDiagnostics.ToImmutable());
                        }
                    }

                    return(ImmutableDictionary <Project, ImmutableArray <Diagnostic> > .Empty);
                }
            }
Example #19
0
        public static void Analyze(SyntaxNodeAnalysisContext context, InvocationExpressionSyntax invocation, MemberAccessExpressionSyntax memberAccess)
        {
            if (invocation.Parent?.IsKind(SyntaxKind.SimpleMemberAccessExpression) == false &&
                SyntaxAnalyzer.IsEnumerableExtensionMethod(invocation, "Any", 1, context.SemanticModel, context.CancellationToken))
            {
                string propertyName = SyntaxHelper.GetCountOrLengthPropertyName(memberAccess.Expression, context.SemanticModel, allowImmutableArray: false, cancellationToken: context.CancellationToken);

                if (propertyName != null)
                {
                    string messageArg = null;

                    TextSpan span = TextSpan.FromBounds(memberAccess.Name.Span.Start, invocation.Span.End);

                    if (invocation.DescendantTrivia(span).All(f => f.IsWhitespaceOrEndOfLineTrivia()))
                    {
                        if (invocation.Parent?.IsKind(SyntaxKind.LogicalNotExpression) == true)
                        {
                            var logicalNot = (PrefixUnaryExpressionSyntax)invocation.Parent;

                            if (logicalNot.OperatorToken.TrailingTrivia.All(f => f.IsWhitespaceOrEndOfLineTrivia()) &&
                                logicalNot.Operand.GetLeadingTrivia().All(f => f.IsWhitespaceOrEndOfLineTrivia()))
                            {
                                messageArg = $"{propertyName} == 0";
                            }
                        }
                        else
                        {
                            messageArg = $"{propertyName} > 0";
                        }
                    }

                    if (messageArg != null)
                    {
                        Diagnostic diagnostic = Diagnostic.Create(
                            DiagnosticDescriptors.ReplaceAnyMethodWithCountOrLengthProperty,
                            Location.Create(context.Node.SyntaxTree, span),
                            ImmutableDictionary.CreateRange(new KeyValuePair <string, string>[] { new KeyValuePair <string, string>("PropertyName", propertyName) }),
                            messageArg);

                        context.ReportDiagnostic(diagnostic);
                    }
                }
            }
        }
        private static void Handle(ExpressionSyntax mutation, ExpressionSyntax backing, SyntaxNodeAnalysisContext context)
        {
            if (context.ContainingSymbol.ContainingType is { } containingType&&
                containingType.IsAssignableTo(KnownSymbol.INotifyPropertyChanged, context.Compilation) &&
                mutation.TryFirstAncestorOrSelf <TypeDeclarationSyntax>(out var typeDeclaration))
            {
                using var pathWalker = MemberPath.PathWalker.Borrow(backing);
                if (!pathWalker.TryFirst(out var firstTokenInPath))
                {
                    return;
                }

                var firstIdentifierNameSymbol = context.SemanticModel.GetSymbolInfo(firstTokenInPath.Parent, context.CancellationToken).Symbol;
                if (firstIdentifierNameSymbol?.ContainingType != containingType)
                {
                    return;
                }

                foreach (var member in typeDeclaration.Members)
                {
                    if (member is PropertyDeclarationSyntax propertyDeclaration &&
                        propertyDeclaration.Modifiers.Any(SyntaxKind.PublicKeyword, SyntaxKind.InternalKeyword) &&
                        ExpressionBodyOrGetter(propertyDeclaration) is { } getter&&
                        !getter.Contains(backing) &&
                        PropertyPath.Uses(getter, pathWalker, context) &&
                        !Property.IsLazy(propertyDeclaration, context.SemanticModel, context.CancellationToken) &&
                        context.SemanticModel.GetDeclaredSymbolSafe(propertyDeclaration, context.CancellationToken) is { } property&&
                        PropertyChanged.InvokesPropertyChangedFor(mutation, property, context.SemanticModel, context.CancellationToken) == AnalysisResult.No)
                    {
                        if (context.Node.TryFirstAncestor(out PropertyDeclarationSyntax? inProperty) &&
                            ReferenceEquals(inProperty, propertyDeclaration) &&
                            Property.TrySingleReturned(inProperty, out var returned) &&
                            PropertyPath.Uses(backing, returned, context))
                        {
                            // We let INPC002 handle this
                            continue;
                        }

                        var properties = ImmutableDictionary.CreateRange(new[] { new KeyValuePair <string, string>(PropertyNameKey, property.Name), });
                        context.ReportDiagnostic(Diagnostic.Create(Descriptors.INPC003NotifyForDependentProperty, context.Node.GetLocation(), properties, property.Name));
                    }
                }
            }
        }
Example #21
0
        private async Task <ImmutableDictionary <Document, ImmutableArray <TextSpan> > > GetFixAllSpansAsync(
            Document document, TextSpan span, bool fixAllInContainingMember, CancellationToken cancellationToken)
        {
            var decl = await GetContainingMemberOrTypeDeclarationAsync(document, fixAllInContainingMember, span, cancellationToken).ConfigureAwait(false);

            if (decl == null)
            {
                return(await GetFixAllSpansIfWithinGlobalStatementAsync(document, span, cancellationToken).ConfigureAwait(false));
            }

            if (fixAllInContainingMember)
            {
                return(ImmutableDictionary.CreateRange(SpecializedCollections.SingletonEnumerable(
                                                           KeyValuePairUtil.Create(document, ImmutableArray.Create(decl.FullSpan)))));
            }
            else
            {
                var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);

                var symbol = semanticModel.GetDeclaredSymbol(decl, cancellationToken);
                if (symbol?.DeclaringSyntaxReferences.Length > 1)
                {
                    var syntaxFacts = document.GetRequiredLanguageService <ISyntaxFactsService>();
                    var builder     = PooledDictionary <Document, ArrayBuilder <TextSpan> > .GetInstance();

                    foreach (var syntaxRef in symbol.DeclaringSyntaxReferences)
                    {
                        var documentForLocation = document.Project.GetDocument(syntaxRef.SyntaxTree);
                        Contract.ThrowIfNull(documentForLocation);
                        var root = await syntaxRef.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);

                        var partialDeclSpan = syntaxFacts.GetContainingTypeDeclaration(root, syntaxRef.Span.Start) !.FullSpan;
                        builder.MultiAdd(documentForLocation, partialDeclSpan);
                    }

                    return(builder.ToImmutableMultiDictionaryAndFree());
                }
                else
                {
                    return(ImmutableDictionary.CreateRange(SpecializedCollections.SingletonEnumerable(
                                                               KeyValuePairUtil.Create(document, ImmutableArray.Create(decl.FullSpan)))));
                }
            }
        }
Example #22
0
        internal ORDictionary <TKey, TValue> AddOrUpdate(UniqueAddress node, TKey key, TValue initial, bool valueDeltas,
                                                         Func <TValue, TValue> modify)
        {
            bool hasOldValue;

            if (!ValueMap.TryGetValue(key, out var oldValue))
            {
                oldValue    = initial;
                hasOldValue = false;
            }
            else
            {
                hasOldValue = true;
            }

            // Optimization: for some types - like GSet, GCounter, PNCounter and ORSet  - that are delta based
            // we can emit (and later merge) their deltas instead of full updates.
            // However to avoid necessity of tombstones, the derived map type needs to support this
            // with clearing the value (e.g. removing all elements if value is a set)
            // before removing the key - like e.g. ORMultiMap does
            var newKeys = KeySet.ResetDelta().Add(node, key);

            if (valueDeltas && oldValue is IDeltaReplicatedData deltaOldValue)
            {
                var newValue      = modify((TValue)deltaOldValue.ResetDelta());
                var newValueDelta = ((IDeltaReplicatedData)newValue).Delta;
                if (newValueDelta != null && hasOldValue)
                {
                    var op = new UpdateDeltaOperation(newKeys.Delta, ImmutableDictionary.CreateRange(new[] { new KeyValuePair <TKey, IReplicatedData>(key, newValueDelta) }));
                    return(new ORDictionary <TKey, TValue>(newKeys, ValueMap.SetItem(key, newValue), NewDelta(op)));
                }
                else
                {
                    var op = new PutDeltaOperation(newKeys.Delta, key, newValue);
                    return(new ORDictionary <TKey, TValue>(newKeys, ValueMap.SetItem(key, newValue), NewDelta(op)));
                }
            }
            else
            {
                var newValue = modify(oldValue);
                var delta    = new PutDeltaOperation(newKeys.Delta, key, newValue);
                return(new ORDictionary <TKey, TValue>(newKeys, ValueMap.SetItem(key, newValue), NewDelta(delta)));
            }
        }
Example #23
0
        public App()
        {
            var states = ImmutableDictionary.CreateRange(
                new Dictionary <string, object>()
            {
                { DisplayFormat, Constants.TimeSpanFormatNoMillsecond },
                { NowSpan, TimeSpan.Zero },
                { Mode, StopwatchMode.Init },
                { ButtonLabel, Constants.StartLabel },
                { StartTime, new DateTime() },
                { Now, new DateTime() },
                { LapTimeList, new ObservableCollection <LapTime>() },
                { MaxLapTime, TimeSpan.Zero },
                { MinLapTime, TimeSpan.Zero },
            });
            var initialState = new ApplicationState(states, _scheduler);

            Store = new Store <ApplicationState>(Reducers.ReduceApplication, initialState);
        }
Example #24
0
        private void CreateTypeBuilderConfig()
        {
            var typeMappings = new Dictionary <string, TsTypeReference>();

            void AddTypeMappingsFromAssembly(Assembly asm)
            {
                foreach (var attribute in TypeUtils.GetAssemblyCustomAttributesData(asm).Where(a =>
                                                                                               a.AttributeType.Name == Constants.DefineTypeScriptTypeForExternalTypeAttributeName && a.ConstructorArguments.Count == 2 && a.ConstructorArguments[1].Value is string))
                {
                    string key;
                    if (attribute.ConstructorArguments[0].Value is Type type)
                    {
                        key = TypeUtils.GetFullNameWithGenericArguments(type);
                    }
                    else if (attribute.ConstructorArguments[0].Value is string s)
                    {
                        key = s;
                    }
                    else
                    {
                        continue;
                    }

                    typeMappings[key] = TsTypeReference.Simple((string)attribute.ConstructorArguments[1].Value);
                }
            }

            foreach (var assembly in _generatorContext.Assemblies)
            {
                AddTypeMappingsFromAssembly(assembly);
            }

            // override mappings from config
            foreach (var mapping in _config.TypeMappings)
            {
                var reference = TsTypeReference.Simple(mapping.Value);
                typeMappings[mapping.Key] = reference;
            }

            var mappings = ImmutableDictionary.CreateRange(typeMappings);

            _typeBuilderConfig = new TypeBuilderConfig(mappings, _config.CustomTypeScriptIgnoreAttributeFullName, _config.WrapConstEnumsInTemplateStrings);
        }
Example #25
0
 public Image Build()
 {
     return(new Image(
                imageFormat,
                created,
                architecture,
                os,
                imageLayersBuilder.Build(),
                historyBuilder.ToImmutable(),
                ImmutableDictionary.CreateRange(environmentBuilder),
                entrypoint,
                programArguments,
                healthCheck,
                ImmutableHashSet.CreateRange(exposedPortsBuilder),
                ImmutableHashSet.CreateRange(volumesBuilder),
                ImmutableDictionary.CreateRange(labelsBuilder),
                workingDirectory,
                user));
 }
Example #26
0
        public async Task <IReadOnlyDictionary <string, DeferredProjectInformation> > GetDeferredProjectInfoForConfigurationAsync(
            string solutionConfiguration,
            CancellationToken cancellationToken)
        {
            var commandLineInfos = await _solutionWorkspaceService.Value.GetManagedCommandLineInfoAsync(
                solutionConfiguration, cancellationToken).ConfigureAwait(false);

            // NOTE: Anycode gives us the project references as if they were command line arguments with
            // "/ProjectReference:" prepended.  Strip that off here.
            var result = ImmutableDictionary.CreateRange(
                commandLineInfos.Select(kvp => KeyValuePair.Create(
                                            kvp.Key,
                                            new DeferredProjectInformation(
                                                kvp.Value.TargetPath,
                                                kvp.Value.CommandLineArgs,
                                                kvp.Value.ProjectReferences.Select(p => p.Substring("/ProjectReference:".Length)).ToImmutableArray()))));

            return(result);
        }
        public void DeltaPropagationSelector_must_collect_1_when_one_node()
        {
            var selector = new TestSelector(selfUniqueAddress, nodes.Take(1).ToImmutableArray());

            selector.Update("A", DeltaA);
            selector.Update("B", DeltaB);
            selector.CleanupDeltaEntries();
            selector.HasDeltaEntries("A").Should().BeTrue();
            selector.HasDeltaEntries("B").Should().BeTrue();
            var expected = new DeltaPropagation(selfUniqueAddress, false, ImmutableDictionary <string, Delta> .Empty
                                                .Add("A", new Delta(new DataEnvelope(DeltaA), 1L, 1L))
                                                .Add("B", new Delta(new DataEnvelope(DeltaB), 1L, 1L)));

            selector.CollectPropagations().Should().Equal(ImmutableDictionary.CreateRange(new[] { new KeyValuePair <Address, DeltaPropagation>(nodes[0], expected), }));
            selector.CollectPropagations().Should().BeEmpty();
            selector.CleanupDeltaEntries();
            selector.HasDeltaEntries("A").Should().BeFalse();
            selector.HasDeltaEntries("B").Should().BeFalse();
        }
Example #28
0
        public static void Analyze(SyntaxNodeAnalysisContext context, MemberDeclarationSyntax declaration)
        {
            SyntaxTokenList modifiers = declaration.GetModifiers();

            Accessibility accessibility = GetAccessModifier(context, declaration, modifiers);

            if (accessibility != Accessibility.NotApplicable)
            {
                Location location = GetLocation(declaration);

                if (location != null)
                {
                    context.ReportDiagnostic(
                        DiagnosticDescriptors.AddDefaultAccessModifier,
                        location,
                        ImmutableDictionary.CreateRange(new KeyValuePair <string, string>[] { new KeyValuePair <string, string>(nameof(Accessibility), accessibility.ToString()) }));
                }
            }
        }
Example #29
0
            /// <summary>
            /// TBD
            /// </summary>
            /// <param name="records">TBD</param>
            public Cache(ImmutableList <Record> records)
            {
                if (records.IsEmpty)
                {
                    _observerRowsMap = ImmutableDictionary.Create <UniqueAddress, ImmutableDictionary <UniqueAddress, Record> >();
                    _allTerminated   = ImmutableHashSet.Create <UniqueAddress>();
                    _allUnreachable  = ImmutableHashSet.Create <UniqueAddress>();
                }
                else
                {
                    var mapBuilder         = new Dictionary <UniqueAddress, ImmutableDictionary <UniqueAddress, Record> >();
                    var terminatedBuilder  = ImmutableHashSet.CreateBuilder <UniqueAddress>();
                    var unreachableBuilder = ImmutableHashSet.CreateBuilder <UniqueAddress>();

                    foreach (var r in records)
                    {
                        ImmutableDictionary <UniqueAddress, Record> m = mapBuilder.TryGetValue(r.Observer, out m)
                            ? m.SetItem(r.Subject, r)
                                                                        //TODO: Other collections take items for Create. Create unnecessary array here
                            : ImmutableDictionary.CreateRange(new[] { new KeyValuePair <UniqueAddress, Record>(r.Subject, r) });


                        mapBuilder.AddOrSet(r.Observer, m);

                        if (r.Status == ReachabilityStatus.Unreachable)
                        {
                            unreachableBuilder.Add(r.Subject);
                        }
                        else if (r.Status == ReachabilityStatus.Terminated)
                        {
                            terminatedBuilder.Add(r.Subject);
                        }
                    }

                    _observerRowsMap = ImmutableDictionary.CreateRange(mapBuilder);
                    _allTerminated   = terminatedBuilder.ToImmutable();
                    _allUnreachable  = unreachableBuilder.ToImmutable().Except(AllTerminated);
                }

                _allUnreachableOrTerminated = _allTerminated.IsEmpty
                    ? AllUnreachable
                    : AllUnreachable.Union(AllTerminated);
            }
Example #30
0
        private static void Handle(SyntaxNodeAnalysisContext context)
        {
            if (context.IsExcludedFromAnalysis())
            {
                return;
            }

            if (context.Node is LiteralExpressionSyntax literal &&
                literal.Parent is ArgumentSyntax &&
                SyntaxFacts.IsValidIdentifier(literal.Token.ValueText))
            {
                foreach (var symbol in context.SemanticModel.LookupSymbols(literal.SpanStart, name: literal.Token.ValueText))
                {
                    switch (symbol)
                    {
                    case IParameterSymbol _:
                        context.ReportDiagnostic(Diagnostic.Create(Descriptors.GU0006UseNameof, literal.GetLocation()));
                        break;

                    case IFieldSymbol _:
                    case IEventSymbol _:
                    case IPropertySymbol _:
                    case IMethodSymbol _:
                        if (symbol.IsStatic)
                        {
                            context.ReportDiagnostic(Diagnostic.Create(Descriptors.GU0006UseNameof, literal.GetLocation()));
                        }
                        else
                        {
                            var properties = ImmutableDictionary.CreateRange(new[] { new KeyValuePair <string, string>("member", symbol.Name) });
                            context.ReportDiagnostic(Diagnostic.Create(Descriptors.GU0006UseNameof, literal.GetLocation(), properties));
                        }

                        break;

                    case ILocalSymbol local when IsVisible(literal, local, context.CancellationToken):
                        context.ReportDiagnostic(Diagnostic.Create(Descriptors.GU0006UseNameof, literal.GetLocation()));

                        break;
                    }
                }
            }
        }