/// <summary>
        /// Check if a call to this function with the given arguments is equal to an expression.
        /// </summary>
        /// <param name="Arguments"></param>
        /// <param name="E"></param>
        /// <returns></returns>
        public virtual bool CallEquals(IEnumerable<Expression> Arguments, Expression E)
        {
            Call C = E as Call;
            if (ReferenceEquals(C, null)) return false;

            return Equals(C.Target) && Arguments.SequenceEqual(C.Arguments);
        }
 /**
  * Check the end of the game
  * if a new generation died or changed then the end
  * @param currentGeneration
  * @param nextGeneration
  * @return if end then true
  */
 bool CheckFinishingGeneration(IEnumerable<Cell> currentGeneration, 
     IEnumerable<Cell> nextGeneration)
 {
     if (currentGeneration != null && nextGeneration != null)
         return (nextGeneration.Count() == 0 || currentGeneration.SequenceEqual(nextGeneration));
     else
         return true;
 }
        private static void VerifyAgainstBaselineResults(EntityDataReader reader, IEnumerable<object> expectedResults)
        {
            var actualResults = new List<object>();
            while (reader.Read())
            {
                actualResults.Add(reader.GetValue(0));
            }

            Assert.True(expectedResults.SequenceEqual(actualResults));
        }
        public IEnumerable<string> RandomizePlayerOrder(IEnumerable<string> players)
        {
            IEnumerable<string> randomOrderOfPlayers = players.OrderBy(c => generator.Generate(1, players.Count())).ToList();

            if (players.SequenceEqual(randomOrderOfPlayers))
            {
                randomOrderOfPlayers = RandomizePlayerOrder(randomOrderOfPlayers);
            }

            return randomOrderOfPlayers;
        }
        private static void AssertDatabaseMigrationsAreEqual(
            string appliedMigrationId, 
            IEnumerable<string> expected, 
            IEnumerable<string> actual)
        {
            if (expected.SequenceEqual(actual))
            {
                return;
            }

            throw new MigrationAssertFailedExecption(
                appliedMigrationId,
                $"Expected migrations did not match the actual migrations after migrating to {appliedMigrationId}.");
        }
        /// <summary>
        /// Constructor</summary>
        /// <param name="selectionContext">Selection context. See <see cref="ISelectionContext"/>.</param>
        /// <param name="previous">Selection's previous state</param>
        /// <param name="next">Selection's next state</param>
        public SetSelectionCommand(
            ISelectionContext selectionContext,
            IEnumerable<object> previous,
            IEnumerable<object> next)
            : base("Set Selection".Localize())
        {
            if (selectionContext == null)
                throw new ArgumentNullException("selectionContext");

            m_selectionContext = selectionContext;

            m_previous = Snapshot(previous);
            // if previous is the same as next, then use the same array
            if (previous.SequenceEqual(next))
                m_next = m_previous;
            else
                m_next = Snapshot(next);
        }
        private void ContainsCompletions(IEnumerable<string> completions, params string[] expected)
        {
            var same = completions.SequenceEqual(expected);
            if (!same)
            {
                System.Console.Error.WriteLine("Expected");
                System.Console.Error.WriteLine("--------");
                foreach (var completion in expected)
                {
                    System.Console.WriteLine(completion);
                }
                System.Console.Error.WriteLine();
                System.Console.Error.WriteLine("Found");
                System.Console.Error.WriteLine("-----");
                foreach (var completion in completions)
                {
                    System.Console.WriteLine(completion);
                }

            }
            Assert.Equal(expected, completions);
        }
 /// <summary>Assert.True(actual.SequenceEqual(expected, comparison))</summary>
 public static void Is <T>(this IEnumerable <T> actual, IEnumerable <T> expected, Func <T, T, bool> equalityComparison)
 {
     Assert.True(actual.SequenceEqual(expected, new EqualityComparer <T>(equalityComparison)));
 }
Beispiel #9
0
 void AssertSequenceEquals <T>(IEnumerable <T> one, IEnumerable <T> two)
 {
     Assert.IsTrue(one.SequenceEqual(two));
 }
Beispiel #10
0
 public bool IsEqual(IEnumerable <string> path, string name)
 {
     return(Path != null && path.SequenceEqual(Path) && name.Equals(Name));
 }
 public bool Equals(IEnumerable <T> x, IEnumerable <T> y)
 {
     return(Object.ReferenceEquals(x, y) || (x != null && y != null && x.SequenceEqual(y)));
 }
            private static bool SequenceEquals(IEnumerable<string> s1, IEnumerable<string> s2)
            {
                if (s1 == s2)
                {
                    return true;
                }

                return s1 != null && s2 != null && s1.SequenceEqual(s2);
            }
Beispiel #13
0
 bool CheckHelloMessageHeader (IEnumerable<byte> receivedHeader)
 {
     return receivedHeader.SequenceEqual (expectedHeader);
 }
Beispiel #14
0
        private byte[] ServiceReadRequestAndWriterResponseForMultipartBatchVerifyDependsOnIds(string requestPayload, ODataVersion maxVersion)
        {
            byte[] responseBytes = null;

            IODataRequestMessage requestMessage = new InMemoryMessage()
            {
                Stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(requestPayload))
            };

            requestMessage.SetHeader("Content-Type", batchContentTypeMultipartMime);
            ODataMessageReaderSettings settings = new ODataMessageReaderSettings {
                MaxProtocolVersion = maxVersion
            };

            using (ODataMessageReader messageReader = new ODataMessageReader(requestMessage, settings, this.userModel))
            {
                MemoryStream responseStream = new MemoryStream();

                IODataResponseMessage responseMessage = new InMemoryMessage {
                    Stream = responseStream
                };

                // Client is expected to receive the response message in the same format as that is used in the request sent.
                responseMessage.SetHeader("Content-Type", batchContentTypeMultipartMime);
                using (ODataMessageWriter messageWriter = new ODataMessageWriter(responseMessage))
                {
                    ODataBatchWriter batchWriter = messageWriter.CreateODataBatchWriter();
                    batchWriter.WriteStartBatch();

                    ODataBatchReader batchReader = messageReader.CreateODataBatchReader();
                    while (batchReader.Read())
                    {
                        switch (batchReader.State)
                        {
                        case ODataBatchReaderState.Operation:
                            // Encountered an operation (either top-level or in a change set)
                            ODataBatchOperationRequestMessage operationMessage =
                                batchReader.CreateOperationRequestMessage();

                            // Verify DependsOnIds are set correctly
                            IEnumerable <string> dependsOnIds = operationMessage.DependsOnIds;
                            switch (operationMessage.ContentId)
                            {
                            case "1":
                            case "2A":
                                Assert.True(dependsOnIds.Count() == 0);
                                break;

                            case "2B":
                                Assert.True(dependsOnIds.SequenceEqual(new List <string> {
                                    "2A"
                                }));
                                break;

                            case "2C":
                                Assert.True(dependsOnIds.SequenceEqual(new List <string> {
                                    "2A", "2B"
                                }));
                                break;

                            case "3":
                                Assert.True(dependsOnIds.SequenceEqual(new List <string> {
                                    "1"
                                }));
                                break;

                            default:
                                break;
                            }

                            ODataBatchOperationResponseMessage response =
                                batchWriter.CreateOperationResponseMessage(operationMessage.ContentId);
                            if (operationMessage.Method == "PATCH")
                            {
                                response.StatusCode = 204;
                                response.SetHeader("Content-Type", "application/json;odata.metadata=none");
                            }
                            else if (operationMessage.Method == "PUT")
                            {
                                response.StatusCode = 201;
                                response.SetHeader("Content-Type", "application/json;");
                            }

                            break;

                        case ODataBatchReaderState.ChangesetStart:
                            batchWriter.WriteStartChangeset();
                            break;

                        case ODataBatchReaderState.ChangesetEnd:
                            batchWriter.WriteEndChangeset();
                            break;
                        }
                    }

                    batchWriter.WriteEndBatch();

                    responseStream.Position = 0;
                    responseBytes           = responseStream.ToArray();
                }

                return(responseBytes);
            }
        }
Beispiel #15
0
        private async Task SaveAllMembersFromCacheAsync(IEnumerable <string> inputs, string outputFolder, bool forceRebuild)
        {
            var projectCache = new ConcurrentDictionary <string, Project>();
            // Project<=>Documents
            var      documentCache          = new ProjectDocumentCache();
            var      projectDependencyGraph = new ConcurrentDictionary <string, List <string> >();
            DateTime triggeredTime          = DateTime.UtcNow;
            var      solutions = inputs.Where(s => IsSupportedSolution(s));
            var      projects  = inputs.Where(s => IsSupportedProject(s));

            var sourceFiles = inputs.Where(s => IsSupportedSourceFile(s));

            // Exclude not supported files from inputs
            inputs = solutions.Concat(projects).Concat(sourceFiles);

            // Add filter config file into inputs and cache
            if (!string.IsNullOrEmpty(_filterConfigFile))
            {
                inputs = inputs.Concat(new string[] { _filterConfigFile });
                documentCache.AddDocument(_filterConfigFile, _filterConfigFile);
            }

            // No matter is incremental or not, we have to load solutions into memory
            await solutions.ForEachInParallelAsync(async path =>
            {
                documentCache.AddDocument(path, path);
                var solution = await GetSolutionAsync(path);
                if (solution != null)
                {
                    foreach (var project in solution.Projects)
                    {
                        var filePath = project.FilePath;

                        // If the project is csproj/vbproj, add to project dictionary, otherwise, ignore
                        if (IsSupportedProject(filePath))
                        {
                            projectCache.GetOrAdd(StringExtension.ToNormalizedFullPath(project.FilePath), s => project);
                        }
                        else
                        {
                            var value = string.Join(",", SupportedExtensions);
                            Logger.Log(LogLevel.Warning, $"Project {filePath} inside solution {path} is not supported, supported file extension are: {value}. The project will be ignored.");
                        }
                    }
                }
            }, 60);

            // Load additional projects out if it is not contained in expanded solution
            projects = projects.Except(projectCache.Keys).Distinct();

            await projects.ForEachInParallelAsync(async path =>
            {
                var project = await GetProjectAsync(path);
                if (project != null)
                {
                    projectCache.GetOrAdd(path, s => project);
                }
            }, 60);

            foreach (var item in projectCache)
            {
                var path    = item.Key;
                var project = item.Value;
                documentCache.AddDocument(path, path);
                documentCache.AddDocuments(path, project.Documents.Select(s => s.FilePath));
                documentCache.AddDocuments(path, project.MetadataReferences
                                           .Where(s => s is PortableExecutableReference)
                                           .Select(s => ((PortableExecutableReference)s).FilePath));
                FillProjectDependencyGraph(projectCache, projectDependencyGraph, project);
            }

            documentCache.AddDocuments(sourceFiles);

            // Incremental check for inputs as a whole:
            var applicationCache = ApplicationLevelCache.Get(inputs);

            if (!forceRebuild)
            {
                BuildInfo buildInfo = applicationCache.GetValidConfig(inputs);
                if (buildInfo != null && buildInfo.ShouldSkipMarkup == _shouldSkipMarkup)
                {
                    IncrementalCheck check = new IncrementalCheck(buildInfo);
                    // 1. Check if sln files/ project files and its contained documents/ source files are modified
                    var projectModified = check.AreFilesModified(documentCache.Documents);

                    if (!projectModified)
                    {
                        // 2. Check if documents/ assembly references are changed in a project
                        // e.g. <Compile Include="*.cs* /> and file added/deleted
                        foreach (var project in projectCache.Values)
                        {
                            var key = StringExtension.ToNormalizedFullPath(project.FilePath);
                            IEnumerable <string> currentContainedFiles = documentCache.GetDocuments(project.FilePath);
                            var previousDocumentCache = new ProjectDocumentCache(buildInfo.ContainedFiles);

                            IEnumerable <string> previousContainedFiles = previousDocumentCache.GetDocuments(project.FilePath);
                            if (previousContainedFiles != null && currentContainedFiles != null)
                            {
                                projectModified = !previousContainedFiles.SequenceEqual(currentContainedFiles);
                            }
                            else
                            {
                                // When one of them is not null, project is modified
                                if (!object.Equals(previousContainedFiles, currentContainedFiles))
                                {
                                    projectModified = true;
                                }
                            }
                            if (projectModified)
                            {
                                break;
                            }
                        }
                    }

                    if (!projectModified)
                    {
                        // Nothing modified, use the result in cache
                        try
                        {
                            CopyFromCachedResult(buildInfo, inputs, outputFolder);
                            return;
                        }
                        catch (Exception e)
                        {
                            Logger.Log(LogLevel.Warning, $"Unable to copy results from cache: {e.Message}. Rebuild starts.");
                        }
                    }
                }
            }

            // Build all the projects to get the output and save to cache
            List <MetadataItem> projectMetadataList = new List <MetadataItem>();
            ConcurrentDictionary <string, bool>        projectRebuildInfo = new ConcurrentDictionary <string, bool>();
            ConcurrentDictionary <string, Compilation> compilationCache   = await GetProjectCompilationAsync(projectCache);

            var extensionMethods = GetAllExtensionMethods(compilationCache.Values);

            foreach (var key in GetTopologicalSortedItems(projectDependencyGraph))
            {
                var dependencyRebuilt     = projectDependencyGraph[key].Any(r => projectRebuildInfo[r]);
                var projectMetadataResult = await GetProjectMetadataFromCacheAsync(projectCache[key], compilationCache[key], outputFolder, documentCache, forceRebuild, _shouldSkipMarkup, _preserveRawInlineComments, _filterConfigFile, extensionMethods, dependencyRebuilt);

                var projectMetadata = projectMetadataResult.Item1;
                if (projectMetadata != null)
                {
                    projectMetadataList.Add(projectMetadata);
                }
                projectRebuildInfo[key] = projectMetadataResult.Item2;
            }

            var csFiles = sourceFiles.Where(s => IsSupportedCSSourceFile(s));

            if (csFiles.Any())
            {
                var csContent     = string.Join(Environment.NewLine, csFiles.Select(s => File.ReadAllText(s)));
                var csCompilation = CompilationUtility.CreateCompilationFromCsharpCode(csContent);
                if (csCompilation != null)
                {
                    var csMetadata = await GetFileMetadataFromCacheAsync(csFiles, csCompilation, outputFolder, forceRebuild, _shouldSkipMarkup, _preserveRawInlineComments, _filterConfigFile, extensionMethods);

                    if (csMetadata != null)
                    {
                        projectMetadataList.Add(csMetadata.Item1);
                    }
                }
            }

            var vbFiles = sourceFiles.Where(s => IsSupportedVBSourceFile(s));

            if (vbFiles.Any())
            {
                var vbContent     = string.Join(Environment.NewLine, vbFiles.Select(s => File.ReadAllText(s)));
                var vbCompilation = CompilationUtility.CreateCompilationFromVBCode(vbContent);
                if (vbCompilation != null)
                {
                    var vbMetadata = await GetFileMetadataFromCacheAsync(vbFiles, vbCompilation, outputFolder, forceRebuild, _preserveRawInlineComments, _shouldSkipMarkup, _filterConfigFile, extensionMethods);

                    if (vbMetadata != null)
                    {
                        projectMetadataList.Add(vbMetadata.Item1);
                    }
                }
            }

            var allMemebers   = MergeYamlProjectMetadata(projectMetadataList);
            var allReferences = MergeYamlProjectReferences(projectMetadataList);

            if (allMemebers == null || allMemebers.Count == 0)
            {
                var value = StringExtension.ToDelimitedString(projectMetadataList.Select(s => s.Name));
                Logger.Log(LogLevel.Warning, $"No metadata is generated for {value}.");
                applicationCache.SaveToCache(inputs, null, triggeredTime, outputFolder, null, _shouldSkipMarkup);
            }
            else
            {
                // TODO: need an intermediate folder? when to clean it up?
                // Save output to output folder
                var outputFiles = ResolveAndExportYamlMetadata(allMemebers, allReferences, outputFolder, _validInput.IndexFileName, _validInput.TocFileName, _validInput.ApiFolderName, _preserveRawInlineComments, _shouldSkipMarkup, _rawInput.ExternalReferences, _useCompatibilityFileName);
                applicationCache.SaveToCache(inputs, documentCache.Cache, triggeredTime, outputFolder, outputFiles, _shouldSkipMarkup);
            }
        }
 private static bool MetaDataChanged(
     IEnumerable <KeyValuePair <string, string> > lh,
     IEnumerable <KeyValuePair <string, string> > rh)
 {
     return(lh.SequenceEqual(rh, new NameValueEqualityComparer()) == false);
 }
 public bool Equals(IEnumerable <int> x, IEnumerable <int> y)
 {
     return(x.SequenceEqual(y));
 }
Beispiel #18
0
 public static IEnumerable <T> ShouldSequenceEqual <T>(this IEnumerable <T> actual, IEnumerable <T> expected)
 {
     Assert.IsTrue(actual.SequenceEqual(expected));
     return(actual);
 }
Beispiel #19
0
        private static int VerifyInjectionDefinition(MethodDefinition injectMethod,
                                                     MethodDefinition injectTarget,
                                                     InjectFlags flags,
                                                     int[] localVarIDs = null,
                                                     params FieldDefinition[] memberReferences)
        {
            Assert(
                injectMethod.IsStatic,
                $"{nameof(injectMethod)} must be static in order to be used as the injection.");
            Assert(injectMethod.IsPublic, $"{nameof(injectMethod)} must be public.");
            Assert(
                injectMethod.HasBody,
                $"{nameof(injectMethod)} must have a definition in order to be used as the injecton.");

            InjectValues hFlags = flags.ToValues();

            bool isVoid = injectTarget.ReturnType.FullName == "System.Void";

            Assert(
                !hFlags.PassLocals || localVarIDs != null,
                $"Supposed to pass local references, but {nameof(localVarIDs)} is empty");
            Assert(
                !hFlags.PassFields || memberReferences != null,
                $"Supposed to pass member fields, but {nameof(memberReferences)} is empty!");

            int prefixCount = Convert.ToInt32(hFlags.PassTag) +
                              Convert.ToInt32(hFlags.PassInvokingInstance) +
                              Convert.ToInt32(hFlags.ModifyReturn && !isVoid);
            int localsCount    = hFlags.PassLocals ? localVarIDs.Length : 0;
            int memberRefCount = hFlags.PassFields ? memberReferences.Length : 0;
            int paramCount     = hFlags.PassParameters ? injectTarget.Parameters.Count : 0;
            int parameters     = injectMethod.Parameters.Count - prefixCount - localsCount - memberRefCount;

            Assert(
                hFlags.PassParameters && 0 < parameters && parameters <= injectTarget.Parameters.Count ||
                !hFlags.PassParameters && parameters == 0,
                $@"The injection method has a wrong number of parameters! Check that the provided target method, local variables, member references and injection flags add up to the right number of parameters.
Needed parameters: Prefix: {prefixCount}, Locals: {localsCount}, Members: {memberRefCount}, Parameters: {
                            (hFlags.PassParameters ? "between 1 and " + paramCount : "0")
                        }, TOTAL: {
                            (hFlags.PassParameters
                                ? $"between {prefixCount + localsCount + memberRefCount + 1} and "
                                : "")
                        }{prefixCount + localsCount + memberRefCount + paramCount}.
Injection has {injectMethod.Parameters.Count} parameters.");

            TypeComparer comparer = TypeComparer.Instance;

            if (hFlags.PassTag)
            {
                string typeName = Enum.GetName(typeof(InjectValues.PassTagType), hFlags.TagType);
                Assert(
                    injectMethod.Parameters[0].ParameterType.FullName == $"System.{typeName}",
                    $"Supposed to pass a tag, but the provided tag must be of type System.{typeName}.");
            }

            if (hFlags.PassInvokingInstance)
            {
                Assert(
                    !injectTarget.IsStatic,
                    "Supposed to pass invoking instance, but the target method is static and thus is not bound to any instances.");
                Assert(
                    comparer.Equals(
                        injectMethod.Parameters[Convert.ToInt32(hFlags.PassTag)].ParameterType,
                        injectTarget.DeclaringType),
                    "Supposed to pass invoking instance, but the type of the instance does not match with the type declared in the injection method.");
            }

            if (hFlags.ModifyReturn)
            {
                Assert(
                    injectMethod.ReturnType.FullName == "System.Boolean",
                    "The injection method must return a boolean in order to alter the return value.");
                Assert(
                    isVoid ||
                    comparer.Equals(
                        injectMethod
                        .Parameters[Convert.ToInt32(hFlags.PassTag) +
                                    Convert.ToInt32(hFlags.PassInvokingInstance)]
                        .ParameterType,
                        new ByReferenceType(injectTarget.ReturnType)),
                    "Supposed to modify the return value, but the provided return type does not match with the return type of the target method! Also make sure the type is passed by reference (out/ref).");
            }

            if (hFlags.PassLocals)
            {
                Assert(injectTarget.Body.HasVariables, "The target method does not have any locals.");
                Assert(
                    localVarIDs.Length != 0,
                    "Supposed to pass method locals, but the IDs of the locals were not specified.");
                Assert(
                    localVarIDs.All(i => 0 <= i && i < injectTarget.Body.Variables.Count),
                    "Supposed to receive local references, but the provided local variable index/indices do not exist in the target method!");
                Assert(
                    injectMethod.Parameters.Slice(prefixCount, localsCount)
                    .Select((p, i) => new
                {
                    param = p,
                    index = localVarIDs[i]
                })
                    .All(
                        t =>
                        t.param.ParameterType.IsByReference &&
                        comparer.Equals(
                            t.param.ParameterType,
                            new ByReferenceType(injectTarget.Body.Variables[t.index].VariableType))),
                    "Supposed to receive local references, but the types between injection method and target method mismatch. Also make sure they are passed by reference (ref/out).");
            }

            if (hFlags.PassFields)
            {
                Assert(!injectTarget.IsStatic, "Cannot pass member references if the injection method is static!");
                Assert(
                    memberReferences.Length != 0,
                    "Supposed to pass member references, but no members were specified.");
                Assert(
                    memberReferences.All(
                        m =>
                        m.DeclaringType.FullName == injectTarget.DeclaringType.FullName &&
                        m.DeclaringType.BaseType.FullName == injectTarget.DeclaringType.BaseType.FullName),
                    $"The provided member fields do not belong to {injectTarget.DeclaringType}");

                IEnumerable <TypeReference> paramRefs =
                    injectMethod.Parameters.Slice(prefixCount + localsCount, memberRefCount)
                    .Select(p => p.ParameterType);
                IEnumerable <TypeReference> typeReferences = paramRefs as TypeReference[] ?? paramRefs.ToArray();

                Assert(
                    typeReferences.All(p => p.IsByReference),
                    "Supposed to pass class members, but the provided parameters in the injection method are not of a reference type (ref)!");
                Assert(
                    typeReferences.SequenceEqual(
                        memberReferences.Select(f => (TypeReference) new ByReferenceType(f.FieldType)),
                        comparer),
                    "Supposed to pass class members, but the existing members are of a different type than the ones specified in the injection method.");
            }

            if (hFlags.PassParameters)
            {
                Assert(
                    injectMethod.HasGenericParameters ==
                    injectTarget.Parameters.Any(p => p.ParameterType.IsGenericParameter),
                    "The injection and target methods have mismatching specification of generic parameters!");

                Assert(
                    !injectMethod.HasGenericParameters ||
                    injectMethod.GenericParameters.Count <=
                    injectTarget.GenericParameters.Count +
                    injectTarget.DeclaringType.GenericParameters.Count,
                    "The injection and target methods have a mismatching number of generic parameters! The injection method must have less or the same number of generic parameters as the target!");

                Assert(
                    !hFlags.PassParametersByRef ||
                    injectMethod.Parameters.Skip(prefixCount + localsCount + memberRefCount)
                    .All(p => p.ParameterType.IsByReference),
                    "Supposed to pass target method parameters by reference, but the provided parameters in the injection method are not of a reference type (ref).");

                Assert(
                    injectMethod.Parameters.Skip(prefixCount + localsCount + memberRefCount)
                    .Select(p => p.ParameterType)
                    .SequenceEqual(
                        injectTarget.Parameters.Take(parameters)
                        .Select(
                            p =>
                            hFlags.PassParametersByRef
                                                            ? new ByReferenceType(p.ParameterType)
                                                            : p.ParameterType),
                        comparer),
                    "Supposed to pass target method parameters by reference, but the types specified in injection and target methods do not match.");
            }

            return(parameters);
        }
 private IReturnValueConfiguration<string> FakeCallToSerializer(IEnumerable<dynamic> expectedArgument)
 {
     return A.CallTo(() => serializer.Serialize(arrayOfObjects)).WhenArgumentsMatch(x => expectedArgument.SequenceEqual((IEnumerable<dynamic>)x[0]));
 }
 private static bool _matchInOrderWithTitles(List<Book> books, IEnumerable<string> titles)
 {
     return titles.SequenceEqual(books.Select(b => b.Title));
 }
        // CA1720: Identifier 'obj' contains type name
        // TOODO: Remove the below suppression once https://github.com/dotnet/roslyn-analyzers/issues/938 is fixed.
#pragma warning disable CA1720
        public override bool Equals(object obj)
#pragma warning restore CA1720
        {
            var d = obj as DiagnosticDescription;

            if (obj == null)
            {
                return(false);
            }

            if (!_code.Equals(d._code))
            {
                return(false);
            }

            if (_isWarningAsError != d._isWarningAsError)
            {
                return(false);
            }

            if (!_ignoreArgumentsWhenComparing)
            {
                if (_squiggledText != d._squiggledText)
                {
                    return(false);
                }
            }

            if (_startPosition != null)
            {
                if (d._startPosition != null)
                {
                    if (_startPosition.Value != d._startPosition.Value)
                    {
                        _showPosition   = true;
                        d._showPosition = true;
                        return(false);
                    }

                    _showPosition   = false;
                    d._showPosition = false;
                }
            }

            if (_syntaxPredicate != null)
            {
                if (d._location == null)
                {
                    return(false);
                }

                if (!_syntaxPredicate(d._location.SourceTree.GetRoot().FindToken(_location.SourceSpan.Start, true).Parent))
                {
                    _showPredicate = true;
                    return(false);
                }

                _showPredicate = false;
            }
            if (d._syntaxPredicate != null)
            {
                if (_location == null)
                {
                    return(false);
                }

                if (!d._syntaxPredicate(_location.SourceTree.GetRoot().FindToken(_location.SourceSpan.Start, true).Parent))
                {
                    d._showPredicate = true;
                    return(false);
                }

                d._showPredicate = false;
            }

            // If ignoring arguments, we can skip the rest of this method.
            if (_ignoreArgumentsWhenComparing || d._ignoreArgumentsWhenComparing)
            {
                return(true);
            }

            // Only validation of arguments should happen between here and the end of this method.
            if (_arguments == null)
            {
                if (d._arguments != null)
                {
                    return(false);
                }
            }
            else // _arguments != null
            {
                if (d._arguments == null)
                {
                    return(false);
                }

                // we'll compare the arguments as strings
                IEnumerable <string> args1 = GetArgumentsAsStrings();
                IEnumerable <string> args2 = d.GetArgumentsAsStrings();
                if (_argumentOrderDoesNotMatter || d._argumentOrderDoesNotMatter)
                {
                    if (args1.Count() != args2.Count() || !args1.SetEquals(args2))
                    {
                        return(false);
                    }
                }
                else
                {
                    if (!args1.SequenceEqual(args2))
                    {
                        return(false);
                    }
                }
            }

            return(true);
        }
Beispiel #23
0
 private bool CheckCompatibility(Game game, IEnumerable<PropertyDef> properties)
 {
     return properties.SequenceEqual(game.CustomProperties);
 }
Beispiel #24
0
 /// <summary>
 /// Determines if two collections have equals elements, with the same ordering. Supports <c>null</c> arguments.
 /// </summary>
 /// <typeparam name="T">The type of the elements.</typeparam>
 /// <param name="c1">The first collection.</param>
 /// <param name="c2">The second collection.</param>
 /// <param name="comparer">The element comparer.</param>
 /// <returns><c>true</c> if collections are equals, <c>false</c> otherwise.</returns>
 public static bool SequenceEquals <T>(IEnumerable <T> c1, IEnumerable <T> c2, IEqualityComparer <T> comparer)
 => FastCheckEquality(c1, c2) ?? c1.SequenceEqual(c2, comparer);
 private static bool IsEqualToParentState(INode node, IEnumerable<int> state)
 {
     return node != null && state.SequenceEqual(((EightPuzzleNode) node).Tiles);
 }
        public void GetServicesShouldReturnExpectedObjects( IReadOnlyList<Tuple<Type, string, object>> services, Type serviceType, IEnumerable<object> expected )
        {
            // arrange
            var serviceProvider = new ServiceProviderAdapter(
                ( t, s ) => services.Where( i => i.Item1 == t && i.Item2 == s ).Select( i => i.Item3 ).FirstOrDefault(),
                ( t, s ) => services.Where( i => i.Item1 == t && i.Item2 == s ).Select( i => i.Item3 ) );

            // act
            var actual = serviceProvider.GetServices( serviceType );

            // assert
            Assert.True( expected.SequenceEqual( actual ) );
        }
Beispiel #27
0
 public bool Equals(IEnumerable <T> array1, IEnumerable <T> array2)
 {
     return(array1.SequenceEqual(array2));
 }
Beispiel #28
0
 public bool Equals(IEnumerable <TokenColour> a,
                    IEnumerable <TokenColour> b) => a.SequenceEqual(b);
Beispiel #29
0
        /// <summary>
        /// An optimized version of <see cref="Enumerable.SequenceEqual{T}(IEnumerable{T}, IEnumerable{T}, IEqualityComparer{T})"/>
        /// that allows nulls, considers reference equality and count before beginning the enumeration.
        /// </summary>
        /// <typeparam name="T">The type of elements in the sequence.</typeparam>
        /// <param name="sequence1">The first sequence.</param>
        /// <param name="sequence2">The second sequence.</param>
        /// <param name="equalityComparer">The equality comparer to use for the elements.</param>
        /// <returns><c>true</c> if the sequences are equal (same elements in the same order); <c>false</c> otherwise.</returns>
        internal static bool CollectionEquals <T>(this IEnumerable <T> sequence1, IEnumerable sequence2, IEqualityComparer equalityComparer = null)
        {
            if (sequence1 == sequence2)
            {
                return(true);
            }

            if ((sequence1 == null) ^ (sequence2 == null))
            {
                return(false);
            }

            int count1, count2;

            if (sequence1.TryGetCount(out count1) && sequence2.TryGetCount <T>(out count2))
            {
                if (count1 != count2)
                {
                    return(false);
                }

                if (count1 == 0 && count2 == 0)
                {
                    return(true);
                }
            }

            if (equalityComparer == null)
            {
                equalityComparer = EqualityComparer <T> .Default;
            }

            // If we have generic types we can use, use them to avoid boxing.
            var sequence2OfT        = sequence2 as IEnumerable <T>;
            var equalityComparerOfT = equalityComparer as IEqualityComparer <T>;

            if (sequence2OfT != null && equalityComparerOfT != null)
            {
                return(sequence1.SequenceEqual(sequence2OfT, equalityComparerOfT));
            }
            else
            {
                // We have to fall back to doing it manually since the underlying collection
                // being compared isn't a (matching) generic type.
                using (var enumerator = sequence1.GetEnumerator())
                {
                    var enumerator2 = sequence2.GetEnumerator();
                    try
                    {
                        while (enumerator.MoveNext())
                        {
                            if (!enumerator2.MoveNext() || !equalityComparer.Equals(enumerator.Current, enumerator2.Current))
                            {
                                return(false);
                            }
                        }

                        if (enumerator2.MoveNext())
                        {
                            return(false);
                        }

                        return(true);
                    }
                    finally
                    {
                        var enum2Disposable = enumerator2 as IDisposable;
                        if (enum2Disposable != null)
                        {
                            enum2Disposable.Dispose();
                        }
                    }
                }
            }
        }
 public static bool Eq(IEnumerable <int> v1, IEnumerable <int> v2)
 {
     return(v1.SequenceEqual(v2));
 }
Beispiel #31
0
 /// <summary>
 /// TBD
 /// </summary>
 /// <typeparam name="T">TBD</typeparam>
 /// <param name="self">TBD</param>
 /// <param name="other">TBD</param>
 public static void ShouldBe <T>(this IEnumerable <T> self, IEnumerable <T> other)
 {
     Assert.True(self.SequenceEqual(other), "Expected " + other.Select(i => string.Format("'{0}'", i)).Join(",") + " got " + self.Select(i => string.Format("'{0}'", i)).Join(","));
 }
Beispiel #32
0
        private async Task SaveAllMembersFromCacheAsync()
        {
            var forceRebuild = _rebuild;
            var outputFolder = _outputFolder;

            var projectCache = new ConcurrentDictionary <string, AbstractProject>();

            // Project<=>Documents
            var      documentCache          = new ProjectDocumentCache();
            var      projectDependencyGraph = new ConcurrentDictionary <string, List <string> >();
            DateTime triggeredTime          = DateTime.UtcNow;

            // Exclude not supported files from inputs
            var cacheKey = GetCacheKey(_files.SelectMany(s => s.Value));

            Logger.LogInfo("Loading projects...");
            if (_files.TryGetValue(FileType.Solution, out var sln))
            {
                var solutions = sln.Select(s => s.NormalizedPath);
                // No matter is incremental or not, we have to load solutions into memory
                foreach (var path in solutions)
                {
                    using (new LoggerFileScope(path))
                    {
                        documentCache.AddDocument(path, path);
                        var solution = await GetSolutionAsync(path);

                        if (solution != null)
                        {
                            foreach (var project in solution.Projects)
                            {
                                var projectFile = new FileInformation(project.FilePath);

                                // If the project is supported, add to project dictionary, otherwise, ignore
                                if (projectFile.IsSupportedProject())
                                {
                                    projectCache.GetOrAdd(projectFile.NormalizedPath,
                                                          s => _loader.Load(projectFile.NormalizedPath));
                                }
                                else
                                {
                                    Logger.LogWarning($"Project {projectFile.RawPath} inside solution {path} is ignored, supported projects are csproj, fsproj and vbproj.");
                                }
                            }
                        }
                    }
                }
            }

            if (_files.TryGetValue(FileType.Project, out var p))
            {
                foreach (var pp in p)
                {
                    GetProject(projectCache, pp.NormalizedPath);
                }
            }

            if (_files.TryGetValue(FileType.ProjectJsonProject, out var pjp))
            {
                await pjp.Select(s => s.NormalizedPath).ForEachInParallelAsync(path =>
                {
                    projectCache.GetOrAdd(path, s => new RoslynProject(GetProjectJsonProject(s)));
                    return(Task.CompletedTask);
                }, 60);
            }

            foreach (var item in projectCache)
            {
                var path    = item.Key;
                var project = item.Value;
                documentCache.AddDocument(path, path);
                if (project.HasDocuments)
                {
                    documentCache.AddDocuments(path, project.Documents.Select(s => s.FilePath));
                }
                else
                {
                    Logger.Log(LogLevel.Warning, $"Project '{project.FilePath}' does not contain any documents.");
                }
                documentCache.AddDocuments(path, project.PortableExecutableMetadataReferences);
                FillProjectDependencyGraph(projectCache, projectDependencyGraph, project);
            }

            var csFiles       = new List <string>();
            var vbFiles       = new List <string>();
            var assemblyFiles = new List <string>();

            if (_files.TryGetValue(FileType.CSSourceCode, out var cs))
            {
                csFiles.AddRange(cs.Select(s => s.NormalizedPath));
                documentCache.AddDocuments(csFiles);
            }

            if (_files.TryGetValue(FileType.VBSourceCode, out var vb))
            {
                vbFiles.AddRange(vb.Select(s => s.NormalizedPath));
                documentCache.AddDocuments(vbFiles);
            }

            if (_files.TryGetValue(FileType.Assembly, out var asm))
            {
                assemblyFiles.AddRange(asm.Select(s => s.NormalizedPath));
                documentCache.AddDocuments(assemblyFiles);
            }

            // Incremental check for inputs as a whole:
            var applicationCache = ApplicationLevelCache.Get(cacheKey);

            var options = _options;

            if (!forceRebuild)
            {
                var buildInfo = applicationCache.GetValidConfig(cacheKey);
                if (buildInfo != null)
                {
                    IncrementalCheck check = new IncrementalCheck(buildInfo);
                    if (!options.HasChanged(check, true))
                    {
                        // 1. Check if sln files/ project files and its contained documents/ source files are modified
                        var projectModified = check.AreFilesModified(documentCache.Documents);

                        if (!projectModified)
                        {
                            // 2. Check if documents/ assembly references are changed in a project
                            // e.g. <Compile Include="*.cs* /> and file added/deleted
                            foreach (var project in projectCache.Values)
                            {
                                var key = StringExtension.ToNormalizedFullPath(project.FilePath);
                                IEnumerable <string> currentContainedFiles = documentCache.GetDocuments(project.FilePath);
                                var previousDocumentCache = new ProjectDocumentCache(buildInfo.ContainedFiles);

                                IEnumerable <string> previousContainedFiles = previousDocumentCache.GetDocuments(project.FilePath);
                                if (previousContainedFiles != null && currentContainedFiles != null)
                                {
                                    projectModified = !previousContainedFiles.SequenceEqual(currentContainedFiles);
                                }
                                else
                                {
                                    // When one of them is not null, project is modified
                                    if (!object.Equals(previousContainedFiles, currentContainedFiles))
                                    {
                                        projectModified = true;
                                    }
                                }
                                if (projectModified)
                                {
                                    break;
                                }
                            }
                        }

                        if (!projectModified)
                        {
                            // Nothing modified, use the result in cache
                            try
                            {
                                CopyFromCachedResult(buildInfo, cacheKey, outputFolder);
                                return;
                            }
                            catch (Exception e)
                            {
                                Logger.Log(LogLevel.Warning, $"Unable to copy results from cache: {e.Message}. Rebuild starts.");
                            }
                        }
                    }
                }
            }

            Logger.LogInfo("Generating metadata for each project...");

            // Build all the projects to get the output and save to cache
            List <MetadataItem> projectMetadataList = new List <MetadataItem>();
            ConcurrentDictionary <string, bool> projectRebuildInfo = new ConcurrentDictionary <string, bool>();
            ConcurrentDictionary <string, AbstractCompilation> compilationCache =
                await GetProjectCompilationAsync(projectCache);

            var roslynProjects = compilationCache.Values.OfType <RoslynCompilation>().Select(rc => rc.Compilation);

            options.RoslynExtensionMethods =
                RoslynIntermediateMetadataExtractor.GetAllExtensionMethodsFromCompilation(roslynProjects);
            foreach (var key in GetTopologicalSortedItems(projectDependencyGraph))
            {
                var dependencyRebuilt = projectDependencyGraph[key].Any(r => projectRebuildInfo[r]);
                var k          = documentCache.GetDocuments(key);
                var input      = new ProjectFileInputParameters(options, k, key, dependencyRebuilt);
                var controller = compilationCache[key].GetBuildController();

                var projectMetadataResult = GetMetadataFromProjectLevelCache(controller, input);
                var projectMetadata       = projectMetadataResult.Item1;
                if (projectMetadata != null)
                {
                    projectMetadataList.Add(projectMetadata);
                }
                projectRebuildInfo[key] = projectMetadataResult.Item2;
            }

            if (csFiles.Count > 0)
            {
                var csContent     = string.Join(Environment.NewLine, csFiles.Select(s => File.ReadAllText(s)));
                var csCompilation = CompilationUtility.CreateCompilationFromCsharpCode(csContent);
                if (csCompilation != null)
                {
                    var input      = new SourceFileInputParameters(options, csFiles);
                    var controller = new RoslynSourceFileBuildController(csCompilation);

                    var csMetadata = GetMetadataFromProjectLevelCache(controller, input);
                    if (csMetadata != null)
                    {
                        projectMetadataList.Add(csMetadata.Item1);
                    }
                }
            }

            if (vbFiles.Count > 0)
            {
                var vbContent     = string.Join(Environment.NewLine, vbFiles.Select(s => File.ReadAllText(s)));
                var vbCompilation = CompilationUtility.CreateCompilationFromVBCode(vbContent);
                if (vbCompilation != null)
                {
                    var input      = new SourceFileInputParameters(options, vbFiles);
                    var controller = new RoslynSourceFileBuildController(vbCompilation);

                    var vbMetadata = GetMetadataFromProjectLevelCache(controller, input);
                    if (vbMetadata != null)
                    {
                        projectMetadataList.Add(vbMetadata.Item1);
                    }
                }
            }

            if (assemblyFiles.Count > 0)
            {
                var assemblyCompilation = CompilationUtility.CreateCompilationFromAssembly(assemblyFiles);
                if (assemblyCompilation != null)
                {
                    var commentFiles = (from file in assemblyFiles
                                        select Path.ChangeExtension(file, XmlCommentFileExtension) into xmlFile
                                        where File.Exists(xmlFile)
                                        select xmlFile).ToList();

                    var referencedAssemblyList = CompilationUtility.GetAssemblyFromAssemblyComplation(assemblyCompilation).ToList();
                    // TODO: why not merge with compilation's extension methods?
                    var assemblyExtension = RoslynIntermediateMetadataExtractor.GetAllExtensionMethodsFromAssembly(assemblyCompilation, referencedAssemblyList.Select(s => s.Item2));
                    options.RoslynExtensionMethods = assemblyExtension;
                    foreach (var assembly in referencedAssemblyList)
                    {
                        var input      = new AssemblyFileInputParameters(options, assembly.Item1.Display);
                        var controller = new RoslynSourceFileBuildController(assemblyCompilation, assembly.Item2);

                        var mta = GetMetadataFromProjectLevelCache(controller, input);

                        if (mta != null)
                        {
                            MergeCommentsHelper.MergeComments(mta.Item1, commentFiles);
                            projectMetadataList.Add(mta.Item1);
                        }
                    }
                }
            }

            Dictionary <string, MetadataItem>  allMembers;
            Dictionary <string, ReferenceItem> allReferences;

            using (new PerformanceScope("MergeMetadata"))
            {
                allMembers = MergeYamlProjectMetadata(projectMetadataList);
            }

            using (new PerformanceScope("MergeReference"))
            {
                allReferences = MergeYamlProjectReferences(projectMetadataList);
            }

            if (allMembers == null || allMembers.Count == 0)
            {
                var value = StringExtension.ToDelimitedString(projectMetadataList.Select(s => s.Name));
                Logger.Log(LogLevel.Warning, $"No metadata is generated for {value}.");
                applicationCache.SaveToCache(cacheKey, null, triggeredTime, outputFolder, null, options);
            }
            else
            {
                // TODO: need an intermediate folder? when to clean it up?
                // Save output to output folder
                List <string> outputFiles;
                using (new PerformanceScope("ResolveAndExport"))
                {
                    outputFiles = ResolveAndExportYamlMetadata(allMembers, allReferences, outputFolder, options.PreserveRawInlineComments, options.ShouldSkipMarkup, _useCompatibilityFileName).ToList();
                }

                applicationCache.SaveToCache(cacheKey, documentCache.Cache, triggeredTime, outputFolder, outputFiles, options);
            }
        }
 /// <summary>Assert.False(actual.SequenceEqual(notExpected, comparer))</summary>
 public static void IsNot <T>(this IEnumerable <T> actual, IEnumerable <T> notExpected, IEqualityComparer <T> comparer)
 {
     Assert.False(actual.SequenceEqual(notExpected, comparer));
 }
Beispiel #34
0
 public static void Equal <T>(IEnumerable <T> exp, IEnumerable <T> actual)
 {
     True(exp.SequenceEqual(actual), "IEnumerables NOT Equal: Expected\n "
          + AsString(exp) + " \n but was \n " + AsString(actual));
 }
 private static bool IsEqualToParentState(NodeInterface node, IEnumerable<int> state)
 {
     return node != null && state.SequenceEqual(((GameNode) node).Tiles);
 }
Beispiel #36
0
 public static void AssertSequenceEquals <T>(this IEnumerable <T> v1, params T[] v2)
 {
     Assert.IsTrue(v1.SequenceEqual(v2));
 }
 public bool Equals(IEnumerable <T> x, IEnumerable <T> y)
 {
     return(x?.SequenceEqual(y) ?? false);
 }
Beispiel #38
0
 public static bool SequencesEqual <T>(IEnumerable <T> x, params IEnumerable <T>[] list) =>
 list.All((y) => x.SequenceEqual(y));
 private void RecoverCollection(IEnumerable<TestDomainObject> originalCollection, CollectionMemento memento) {
     IEnumerable<TestDomainObject> recoveredCollection = memento.RecoverCollection().GetAsEnumerable().Select(no => no.GetDomainObject<TestDomainObject>());
     Assert.IsTrue(originalCollection.SequenceEqual(recoveredCollection), "recovered collection not same as original");
 }
 public static bool SequenceEqual <TSource>(
     this IEnumerable <TSource> first,
     IEnumerable <TSource> second,
     Func <TSource, TSource, bool> equals,
     Func <TSource, int> getHashCode = null) =>
 first.SequenceEqual(second, ToEqualityComparer(equals, getHashCode));
        public void WithLinksReturnsCorrectResult(
            AtomFeed sut,
            IEnumerable<AtomLink> newLinks)
        {
            AtomFeed actual = sut.WithLinks(newLinks);

            var expected = sut.AsSource().OfLikeness<AtomFeed>()
                .With(x => x.Links).EqualsWhen(
                    (s, d) => newLinks.SequenceEqual(d.Links));
            expected.ShouldEqual(actual);
        }
Beispiel #42
0
 private bool same(IEnumerable<string> got, params string[] elm)
 {
     return got.SequenceEqual(elm);
 }
 private static bool MetaDataChanged(
     IEnumerable<KeyValuePair<string, string>> lh,
     IEnumerable<KeyValuePair<string, string>> rh)
 {
     return lh.SequenceEqual(rh, new NameValueEqualityComparer()) == false;
 }
Beispiel #44
0
 public static bool SafeSequenceEqual <T>(this IEnumerable <T>?first, IEnumerable <T>?second)
 => first == null && second == null || second != null && first?.SequenceEqual(second) == true;
 private static void CheckList( IEnumerable<int> a, params int[] p )
 {
     Assert.That( a.SequenceEqual( p ) );
 }
 internal static FakeOptions HasArgumentsForConstructor(this IArgumentConstraintManager<FakeOptions> scope, IEnumerable<object> argumentsForConstructor)
 {
     return scope.Matches(x => argumentsForConstructor.SequenceEqual(x.ArgumentsForConstructor), "Constructor arguments ({0})".FormatInvariant(string.Join(", ", argumentsForConstructor.Select(x => x.ToString()).ToArray())));
 }
Beispiel #47
0
 /// <inheritdoc />
 public bool Equals(IEnumerable <T> a, IEnumerable <T> b)
 {
     return(a.SequenceEqual(b));
 }
 /// <summary>Assert.False(actual.SequenceEqual(notExpected, comparison))</summary>
 public static void IsNot <T>(this IEnumerable <T> actual, IEnumerable <T> notExpected, Func <T, T, bool> equalityComparison)
 {
     Assert.False(actual.SequenceEqual(notExpected, new EqualityComparer <T>(equalityComparison)));
 }
        /// <summary>
        /// <para>Returns all canLeaveChargeds that the player could possibly be able to retroactively use, according to the pathing in this in-game state.
        /// Does not check whether the player is able to use any strats on those canLeaveChargeds, or whether charging or sparking is currently doable.
        /// To check all of that, see <see cref="CanLeaveCharged.IsUsable(SuperMetroidModel, InGameState, bool)"/>.</para>
        /// <para>"Retroactive use" is meant to be done right after entering a room, and aims to retroactively decide how the last room was exited.</para>
        /// <para>A canLeaveCharged would typically be used retroactively to satisfy a canComeInCharged
        /// that is being executed soon after entry of the new room.</para>
        /// </summary>
        /// <param name="model">A model that can be used to obtain data about the current game configuration.</param>
        /// <param name="requiredInRoomPath">The path that must have been followed in the current room (as successive node IDs) in order to be able to use
        /// retroactive canLeavechargeds in the current context. The first node in this path also dictates the node to which
        /// the retroactive charged exit must lead.</param>
        /// <param name="usePreviousRoom">If true, indicates that the "new" room is already the previous room in this InGameState.</param>
        /// <returns></returns>
        public IEnumerable <CanLeaveCharged> GetRetroactiveCanLeaveChargeds(SuperMetroidModel model, IEnumerable <int> requiredInRoomPath, bool usePreviousRoom = false)
        {
            // Since this is a retroactive check, we already have to look at the room prior to the one we're asked to evaluate
            // If we were already evaluating the previous room, we have no way to obtain the state of the room before that so just return
            if (usePreviousRoom)
            {
                return(Enumerable.Empty <CanLeaveCharged>());
            }

            // We will need to know what nodes were visited in the current room. If this info is missing, we can't do anything retroactively.
            IEnumerable <int> visitedNodeIds = GetVisitedNodeIds(usePreviousRoom);

            // If we don't know at what node we entered, we can't identify any usable runways
            if (!visitedNodeIds.Any())
            {
                return(Enumerable.Empty <CanLeaveCharged>());
            }

            // If the current in-room state doesn't respect the in-room path necessary to use retroactive runways, we can't use any
            if (!visitedNodeIds.SequenceEqual(requiredInRoomPath))
            {
                return(Enumerable.Empty <CanLeaveCharged>());
            }

            RoomNode entryNode = GetCurrentRoom(usePreviousRoom).Nodes[visitedNodeIds.First()];

            // At this point we know our behavior in the current room respects the provided requirements for retroactively using a CanLeaveCharged.

            // Figure out through what node we left the previous room...
            RoomNode previousRoomExitNode = GetCurrentNode(usePreviousRoom: true);

            // If we can't figure out how we left previous room, we can't return any canLeaveChargeds
            if (previousRoomExitNode == null)
            {
                return(Enumerable.Empty <CanLeaveCharged>());
            }

            // If the last room was exited by bypassing a lock, canLeaveChargeds can't be used
            if (BypassingExitLock(usePreviousRoom: true))
            {
                return(Enumerable.Empty <CanLeaveCharged>());
            }

            // If we didn't leave the previous room via a node that led to the node by which we entered current room, no canLeavechargeds are usable
            if (previousRoomExitNode.OutNode != entryNode)
            {
                return(Enumerable.Empty <CanLeaveCharged>());
            }

            // Return all CanLeaveCharged that are valid to retroactively execute
            return(previousRoomExitNode.CanLeaveCharged.Where(clc => {
                // If the CanLeaveCharged is initiated remotely, we must take a closer look at what happened in that room
                if (clc.IsInitiatedRemotely)
                {
                    // This CanLeaveCharged is initiated at a specific node,
                    // and is executed by following a specific path through the room, with a subset of allowed strats.
                    // We will check whether last room's exit is compatible with this CanLeaveCharged,
                    // to see if it can possibly be executed retroactively.

                    var lastRoomPath = GetVisitedPath(usePreviousRoom: true);
                    // If we haven't visited as many nodes as the prescribed path to door (+ 1 more node to enter the room),
                    // we know for sure our exit isn't compatible with this CanLeaveCharged. Reject it.
                    if (lastRoomPath.Count() < clc.InitiateRemotely.PathToDoor.Count() + 1)
                    {
                        return false;
                    }

                    // Check the last n visited nodes to make sure they correspond to the prescribed path.
                    // But before this, check the node we were at immediately before those, to make sure we're starting at the right place.
                    IEnumerable <(RoomNode node, Strat strat)> lastRoomFinalPath
                        = lastRoomPath.TakeLast(clc.InitiateRemotely.PathToDoor.Count() + 1);
                    if (lastRoomFinalPath.First().node != clc.InitiateRemotely.InitiateAtNode)
                    {
                        return false;
                    }

                    if (!clc.InitiateRemotely.PathToDoor.Zip
                            (lastRoomFinalPath.Skip(1), (expectedPath, actualPath) => {
                        // These two path nodes match up if they go to the same room node, and if the actual path uses one of the valid strats
                        return expectedPath.link.TargetNode == actualPath.node &&
                        expectedPath.strats.Contains(actualPath.strat, ObjectReferenceEqualityComparer <Strat> .Default);
                    })
                        // If any node in the actual path does not respect the expected path,
                        // then last room's exit is incompatible with this CanLeaveCharged
                        .All(valid => valid))
                    {
                        return false;
                    }

                    // If there is a requirement that the door be opened first,
                    // there are two additional requirements to execute the CanLeaveCharged retroactively.
                    if (clc.InitiateRemotely.MustOpenDoorFirst)
                    {
                        // The exit node must not have any active locks when the CanLeaveCharged execution begins.
                        // This means we can't have opened the lock on the way out
                        if (OpeningExitLock(usePreviousRoom: true))
                        {
                            return false;
                        }

                        // The exit node must have been visited before the CanLeaveCharge execution would begin.
                        // The node where execution begins is hence the last one where we could have opened the door.
                        if (!lastRoomPath.SkipLast(clc.InitiateRemotely.PathToDoor.Count()).Where(pathNode => pathNode.node == previousRoomExitNode).Any())
                        {
                            return false;
                        }
                    }
                    // We found no reason to invalidate the retroactive execution. This is valid to retroactively use.
                    return true;
                }
                // If the CanLeaveCharged is initiated at the exit node, we have no more conditions to check. This is valid to retroactively use.
                else
                {
                    return true;
                }
            }));
        }
Beispiel #50
0
 public bool Equals(IEnumerable <int> x, IEnumerable <int> y) => x.SequenceEqual(y);
Beispiel #51
0
 static bool HashesEqual(IEnumerable<byte> expectedHash, IEnumerable<byte> hash)
 {
     return expectedHash.SequenceEqual(hash);
 }
 public static void SequenceEquals <T>(
     this Assert assert, IEnumerable <T> expected, IEnumerable <T> actual)
 {
     Assert.IsTrue(expected.SequenceEqual(actual));
 }
Beispiel #53
0
        // requires: domain not have any Negated constants other than NotNull
        // Also, cellQuery contains all final oneOfConsts or all partial oneOfConsts
        // cellquery must contain a whereclause of the form "True", "OneOfConst" or "
        // "OneOfConst AND ... AND OneOfConst"
        // slot must present in cellQuery and incomingDomain is the domain for it
        // effects: Returns the set of values that slot can take as restricted by cellQuery's whereClause
        private static bool TryGetDomainRestrictedByWhereClause(IEnumerable<Constant> domain, MemberProjectedSlot slot, CellQuery cellQuery, out CellConstantSet result)
        {

            var conditionsForSlot = cellQuery.GetConjunctsFromWhereClause()
                                  .Where(restriction => MemberPath.EqualityComparer.Equals(restriction.RestrictedMemberSlot.MemberPath, slot.MemberPath))
                                  .Select(restriction => new CellConstantSet(restriction.Domain.Values, Constant.EqualityComparer));

            //Debug.Assert(!conditionsForSlot.Skip(1).Any(), "More than one Clause with the same path");

            if (!conditionsForSlot.Any())
            {
                // If the slot was not mentioned in the query return the domain without restricting it 
                result = new CellConstantSet(domain);
                return false;
            }



            // Now get all the possible values from domain and conditionValues
            CellConstantSet possibleValues = DeterminePossibleValues(conditionsForSlot.SelectMany(m => m.Select(c => c)), domain);

            Domain restrictedDomain = new Domain(domain, possibleValues);
            foreach (var conditionValues in conditionsForSlot)
            {
                // Domain derived from Edm-Type INTERSECTED with Conditions
                restrictedDomain = restrictedDomain.Intersect(new Domain(conditionValues, possibleValues));
            }

            result = new CellConstantSet(restrictedDomain.Values, Constant.EqualityComparer);
            return !domain.SequenceEqual(result);
        }
Beispiel #54
0
 private bool FileHashIsEqual(IEnumerable<byte> expectedHash, IEnumerable<byte> actualHash)
 {
     return expectedHash.SequenceEqual(actualHash);
 }