public void GetOrAddNew_should_return_value_if_key_exists()
        {
            var list = new List <int>();

            listDictionary[12] = list;

            Assert.Equal(list, listDictionary.GetOrAddNew(12));
        }
            public void ReplaceText(TextReaderWrapper tr, string textFileName)
            {
                stringEntries.Clear();
                messageEntries.Clear();
                numberedStrings.Clear();
                CodePatches.Clear();
                CodePatches2.Length = 0;

                currentFunctionName = "";
                stringDictionary    = stringEntries.GetOrAddNew(currentFunctionName);
                messageDictionary   = messageEntries.GetOrAddNew(currentFunctionName);

                ReadReplacementFile(tr, textFileName);
                ExportAndMerge();
            }
        private async Task EnsureWebooksLoadedAsync()
        {
            if (inMemoryWebhooks == null)
            {
                try
                {
                    await lockObject.WaitAsync();

                    if (inMemoryWebhooks == null)
                    {
                        var result = new Dictionary <Guid, Dictionary <Guid, List <ShortInfo> > >();

                        var webhooks = await Collection.Find(new BsonDocument()).ToListAsync();

                        foreach (var webhook in webhooks)
                        {
                            var list = result.GetOrAddNew(webhook.AppId).GetOrAddNew(webhook.SchemaId);

                            list.Add(SimpleMapper.Map(webhook, new ShortInfo()));
                        }

                        inMemoryWebhooks = result;
                    }
                }
                finally
                {
                    lockObject.Release();
                }
            }
        }
Ejemplo n.º 4
0
        private async Task RebuildRuleIndexes()
        {
            var rulesByApp = new Dictionary <Guid, HashSet <Guid> >();

            HashSet <Guid> Index(RuleEvent @event)
            {
                return(rulesByApp.GetOrAddNew(@event.AppId.Id));
            }

            await eventStore.QueryAsync(storedEvent =>
            {
                var @event = eventDataFormatter.Parse(storedEvent.Data);

                switch (@event.Payload)
                {
                case RuleCreated ruleCreated:
                    Index(ruleCreated).Add(ruleCreated.RuleId);
                    break;

                case RuleDeleted ruleDeleted:
                    Index(ruleDeleted).Remove(ruleDeleted.RuleId);
                    break;
                }

                return(TaskHelper.Done);
            }, "^rule\\-");

            foreach (var kvp in rulesByApp)
            {
                await indexRules.RebuildAsync(kvp.Key, kvp.Value);
            }
        }
        private void GetInitialValueDependencies()
        {
            foreach (var pair in initialValueExpressions)
            {
                var variable   = pair.Key;
                var expression = pair.Value;

                var symbols   = expression.GetSubexpressionsRecursive(TokenType.Identifier);
                var variables = symbols.Select(token => Symbols.GetOrNull(token.Token.Value)).ToArray();
                if (variables.Contains(null))
                {
                    //error
                }
                variables = variables.Distinct().ToArray();

                if (variables.Length == 0)
                {
                    var initialValue = EvaluateConstExpression(expression, variable.DataType, false);
                    if (initialValue != null)
                    {
                        InitialValues.Set(variable, initialValue);
                    }
                    else
                    {
                    }
                }
                else
                {
                    var depsList = initialDependencies.GetOrAddNew(variable);
                    depsList.AddRange(variables);
                }
            }
        }
Ejemplo n.º 6
0
        private void AddNewRowMapping(int columnRowIndex,
                                      JoinSide side,
                                      ColumnRowMapping keyRowsMapping,
                                      List <RowToUpdate> updateRows,
                                      TKey key,
                                      Dictionary <int, HashSet <int> > otherColumnRowsToJoinRows,
                                      Dictionary <int, HashSet <int> > columnRowsToJoinRows)
        {
            // For each distinct row on the other side we need to create a new row and link ourselves
            var otherRows   = GetDistinctOtherRows(keyRowsMapping, side);
            var otherRowIds = otherRows.ToArray();

            foreach (var otherRowId in otherRowIds)
            {
                int?joinedRowId = GetNewRowId();
                var joinRow     = CreateNewLinkedJoinRow(columnRowIndex, joinedRowId.Value, key, otherRowId, side);
                keyRowsMapping.ColRowMappings.Add(joinRow);

                AddNewRow(joinRow, updateRows, joinedRowId.Value);

                // Update the reverse lookup
                columnRowsToJoinRows.GetOrAddNew(columnRowIndex).Add(joinedRowId.Value);
                otherColumnRowsToJoinRows.GetOrAddNew(otherRowId.Value).Add(joinedRowId.Value);
            }

            // If there are no matching entries on the other side we still need to add a row and mapping
            if (otherRowIds.Length == 0)
            {
                UpdateNewKeyInExistingMapping(columnRowIndex, side, key, updateRows, columnRowsToJoinRows, keyRowsMapping);
            }
        }
Ejemplo n.º 7
0
            /// <summary>
            /// 如果当前节点处于 <see cref="FetchingStatus.Fetching"/> 状态,
            /// 则等待直到节点处于 <see cref="FetchingStatus.Fetched" /> 状态。
            /// </summary>
            /// <returns>
            /// 返回一个任务。如果当前节点处于 <see cref="FetchingStatus.Unfetched"/>
            /// 状态,则直接返回 false 。
            /// 否则会在(其他线程)探索结束后返回 <c>true</c>。
            /// </returns>
            public Task <bool> UntilFetchedAsync(FetchingDomainKey domainKey)
            {
                if (domainKey == null)
                {
                    throw new ArgumentNullException(nameof(domainKey));
                }
                syncLock.EnterWriteLock();
                try
                {
                    FetchingStatus s;
                    if (fetchingStatusDict.TryGetValue(domainKey, out s))
                    {
                        switch (s)
                        {
                        case FetchingStatus.Fetching:
                            // Wait for exploration
                            Debug.WriteLine("Wait-{0}: {1} @ {2}", domainKey, this, Task.CurrentId);
                            var tcs = fetchingTaskCompletionSourceDict.GetOrAddNew(domainKey);
                            return(tcs.Task.ContinueWith(r => true));

                        case FetchingStatus.Fetched:
                            return(Task.FromResult(true));

                        default:
                            Debug.Assert(s == FetchingStatus.Unfetched);
                            break;
                        }
                    }
                    return(Task.FromResult(false));
                }
                finally
                {
                    syncLock.ExitWriteLock();
                }
            }
Ejemplo n.º 8
0
        public void SendCommand(CommandType cmd, int factionId, int mapId, byte[] data, ServerPlayer sourcePlayer = null)
        {
            if (sourcePlayer != null && cmd == CommandType.Sync)
            {
                int syncId = BitConverter.ToInt32(data, 0);
                if (!MpVersion.IsDebug && debugOnlySyncCmds.Contains(syncId))
                {
                    return;
                }
            }

            byte[] toSave = new ScheduledCommand(cmd, gameTimer, factionId, mapId, data).Serialize();

            // todo cull target players if not global
            mapCmds.GetOrAddNew(mapId).Add(toSave);
            tmpMapCmds?.GetOrAddNew(mapId).Add(toSave);

            byte[] toSend       = toSave.Append(new byte[] { 0 });
            byte[] toSendSource = toSave.Append(new byte[] { 1 });

            foreach (var player in PlayingPlayers)
            {
                player.conn.Send(
                    Packets.Server_Command,
                    sourcePlayer == player ? toSendSource : toSend
                    );
            }
        }
Ejemplo n.º 9
0
        private async Task RebuildSchemaIndexes()
        {
            var schemasByApp = new Dictionary <Guid, Dictionary <string, Guid> >();

            Dictionary <string, Guid> Index(SchemaEvent @event)
            {
                return(schemasByApp.GetOrAddNew(@event.AppId.Id));
            }

            await eventStore.QueryAsync(storedEvent =>
            {
                var @event = eventDataFormatter.Parse(storedEvent.Data);

                switch (@event.Payload)
                {
                case SchemaCreated schemaCreated:
                    Index(schemaCreated)[schemaCreated.SchemaId.Name] = schemaCreated.SchemaId.Id;
                    break;

                case SchemaDeleted schemaDeleted:
                    Index(schemaDeleted).Remove(schemaDeleted.SchemaId.Name);
                    break;
                }

                return(TaskHelper.Done);
            }, "^schema\\-");

            foreach (var kvp in schemasByApp)
            {
                await indexSchemas.RebuildAsync(kvp.Key, kvp.Value);
            }
        }
Ejemplo n.º 10
0
        private async Task EnsureRulesLoadedAsync()
        {
            if (inMemoryRules == null)
            {
                try
                {
                    await lockObject.WaitAsync();

                    if (inMemoryRules == null)
                    {
                        inMemoryRules = new Dictionary <Guid, List <IRuleEntity> >();

                        var webhooks =
                            await Collection.Find(new BsonDocument())
                            .ToListAsync();

                        foreach (var webhook in webhooks)
                        {
                            inMemoryRules.GetOrAddNew(webhook.AppId).Add(webhook);
                        }
                    }
                }
                finally
                {
                    lockObject.Release();
                }
            }
        }
Ejemplo n.º 11
0
        private async Task RebuildAppIndexes()
        {
            var appsByName = new Dictionary <string, Guid>();
            var appsByUser = new Dictionary <string, HashSet <Guid> >();

            await statesForApps.ReadAllAsync((app, version) =>
            {
                if (!app.IsArchived)
                {
                    appsByName[app.Name] = app.Id;

                    foreach (var contributor in app.Contributors.Keys)
                    {
                        appsByUser.GetOrAddNew(contributor).Add(app.Id);
                    }
                }

                return(TaskHelper.Done);
            });

            await grainFactory.GetGrain <IAppsByNameIndex>(SingleGrain.Id).RebuildAsync(appsByName);

            foreach (var kvp in appsByUser)
            {
                await grainFactory.GetGrain <IAppsByUserIndex>(kvp.Key).RebuildAsync(kvp.Value);
            }
        }
Ejemplo n.º 12
0
        static void ScanCompiledFileSet(
            Dictionary <string, Dictionary <string, CompiledPackage> >
            compilerDictionary,
            Dictionary <string, CompiledLibrary> libraryDictionary,
            Platform platform)
        {
            foreach (
                var file in
                new DirectoryInfo(Path.Combine(
                                      Config.BoostDir, platform.Directory))
                .GetFiles())
            {
                var split    = file.Name.SplitFirst('-');
                var library  = split.Before.SplitFirst('_').After;
                var compiler = split.After.SplitFirst('-').Before;

                //
                var compiledLibrary = libraryDictionary.GetOrAddNew(library);
                var compiledPackage =
                    compiledLibrary.PackageDictionary.GetOrAddNew(compiler);
                compiledPackage.AddFile(platform, file.Name);

                // add the compiler and add the library to the compiler.
                compilerDictionary.GetOrAddNew(compiler)[library] =
                    compiledPackage;
            }
        }
Ejemplo n.º 13
0
 private void AddActorNow(Actor _actor)
 {
     //Add to depthSorter so that 1) the actor's depth in the constructor is used, and 2) if it is overridden in the actor's Start(),
     depthSorter.Add(_actor);
     _actor.Start();
     actorsByID[_actor.ID] = _actor;
     actorsByTypeID.GetOrAddNew(_actor.TypeID).Add(_actor);
 }
Ejemplo n.º 14
0
        public static Dictionary <T, List <T> > Reverse <T>(Dictionary <T, T[]> graph)
        {
            var result = new Dictionary <T, List <T> >();

            foreach (var kvp in graph)
            {
                var nodeFrom = kvp.Key;

                result.GetOrAddNew(nodeFrom);

                foreach (var nodeTo in kvp.Value)
                {
                    result.GetOrAddNew(nodeTo).Add(nodeFrom);
                }
            }

            return(result);
        }
Ejemplo n.º 15
0
        public IGraphType GetContentDataType(Guid schemaId)
        {
            var schema = schemasById.GetOrDefault(schemaId);

            if (schema == null)
            {
                return(null);
            }

            return(schema != null?contentDataTypes.GetOrAddNew(schema) : null);
        }
Ejemplo n.º 16
0
        public Task <string[]> GetWatchingUsersAsync(string resource, string userId)
        {
            Guard.NotNullOrEmpty(resource);
            Guard.NotNullOrEmpty(userId);

            var usersByResource = users.GetOrAddNew(resource);

            usersByResource[userId] = clock.GetCurrentInstant();

            return(Task.FromResult(usersByResource.Keys.ToArray()));
        }
Ejemplo n.º 17
0
        public override Task <bool> RestoreEventAsync(Envelope <IEvent> @event, Guid appId, BackupReader reader, RefToken actor)
        {
            switch (@event.Payload)
            {
            case ContentCreated contentCreated:
                contentIdsBySchemaId.GetOrAddNew(contentCreated.SchemaId.Id).Add(contentCreated.ContentId);
                break;

            case SchemaDeleted schemaDeleted:
                contentIdsBySchemaId.Remove(schemaDeleted.SchemaId.Id);
                break;
            }

            return(TaskHelper.True);
        }
Ejemplo n.º 18
0
        public Task <bool> RestoreEventAsync(Envelope <IEvent> @event, RestoreContext context)
        {
            switch (@event.Payload)
            {
            case ContentCreated contentCreated:
                contentIdsBySchemaId.GetOrAddNew(contentCreated.SchemaId.Id).Add(contentCreated.ContentId);
                break;

            case SchemaDeleted schemaDeleted:
                contentIdsBySchemaId.Remove(schemaDeleted.SchemaId.Id);
                break;
            }

            return(TaskHelper.True);
        }
Ejemplo n.º 19
0
        public Task <bool> RestoreEventAsync(Envelope <IEvent> @event, RestoreContext context)
        {
            switch (@event.Payload)
            {
            case ContentCreated contentCreated:
                contentIdsBySchemaId.GetOrAddNew(contentCreated.SchemaId.Id).Add(@event.Headers.AggregateId());
                break;

            case SchemaDeleted schemaDeleted:
                contentIdsBySchemaId.Remove(schemaDeleted.SchemaId.Id);
                break;
            }

            return(Task.FromResult(true));
        }
Ejemplo n.º 20
0
        private async Task <IReadOnlyCollection <KgNode[]> > FindHop3PathsAsync(KgNode node1, KgNode node2)
        {
            Debug.Assert(node1 != null);
            Debug.Assert(node2 != null);
            Logger.Magik.Enter(this, $"{node1} -> {node2}");
            // Notation
            // Node1 -- Node3 -- Node4 -- Node2
            var paths   = new List <KgNode[]>();
            var author1 = node1 as AuthorNode;

            if (author1 != null)
            {
                // Author 还需要补刀。
                await FetchAuthorsPapersAsync(new[] { author1 });
            }
            // 获取 Node1 出发所有可能的 Node3
            var nodes3 = graph.AdjacentOutVertices(node1.Id)
                         .Select(id => nodes[id])
                         .ToArray();

            // 探索 Node4
            await ExploreInterceptionNodesAsync(nodes3, node2);

            // 计算路径。
            // 从 Id1 出发,寻找所有可能的 Id3 。
            var id4PredecessorsDict = new Dictionary <long, List <long> >();

            foreach (var id3 in graph.AdjacentOutVertices(node1.Id))
            {
                foreach (var id4 in graph.AdjacentOutVertices(id3))
                {
                    id4PredecessorsDict.GetOrAddNew(id4).Add(id3);
                }
            }
            foreach (var id4 in graph.AdjacentInVertices(node2.Id))
            {
                var id3Nodes = id4PredecessorsDict.TryGetValue(id4);
                if (id3Nodes != null)
                {
                    // 有路径!
                    paths.AddRange(id3Nodes.Select(id3 =>
                                                   new[] { node1, nodes[id3], nodes[id4], node2 }));
                }
            }
            Logger.Magik.Trace(this, "在 {0} - {1} 之间找到了 {2} 条 3-hop 路径。", node1.Id, node2.Id, paths.Count);
            Logger.Magik.Exit(this);
            return(paths);
        }
Ejemplo n.º 21
0
        public static Dictionary <string, string> ToTexts(this NamedContentData data)
        {
            var result = new Dictionary <string, string>();

            if (data != null)
            {
                var languages = new Dictionary <string, StringBuilder>();

                void AppendText(string language, string text)
                {
                    if (!string.IsNullOrWhiteSpace(text))
                    {
                        var sb = languages.GetOrAddNew(language);

                        if (sb.Length > 0)
                        {
                            sb.Append(" ");
                        }

                        sb.Append(text);
                    }
                }

                foreach (var field in data)
                {
                    if (field.Value != null)
                    {
                        foreach (var fieldValue in field.Value)
                        {
                            var appendText = new Action <string>(text => AppendText(fieldValue.Key, text));

                            AppendJsonText(fieldValue.Value, appendText);
                        }
                    }
                }

                foreach (var kvp in languages)
                {
                    result[kvp.Key] = kvp.Value.ToString();
                }
            }

            return(result);
        }
Ejemplo n.º 22
0
        private async Task RebuildSchemaIndexes()
        {
            var schemasByApp = new Dictionary <Guid, Dictionary <string, Guid> >();

            await statesForSchemas.ReadAllAsync((schema, version) =>
            {
                if (!schema.IsDeleted)
                {
                    schemasByApp.GetOrAddNew(schema.AppId.Id)[schema.Name] = schema.Id;
                }

                return(TaskHelper.Done);
            });

            foreach (var kvp in schemasByApp)
            {
                await grainFactory.GetGrain <ISchemasByAppIndex>(kvp.Key).RebuildAsync(kvp.Value);
            }
        }
Ejemplo n.º 23
0
        private async Task RebuildRuleIndexes()
        {
            var rulesByApp = new Dictionary <Guid, HashSet <Guid> >();

            await statesForRules.ReadAllAsync((schema, version) =>
            {
                if (!schema.IsDeleted)
                {
                    rulesByApp.GetOrAddNew(schema.AppId.Id).Add(schema.Id);
                }

                return(TaskHelper.Done);
            });

            foreach (var kvp in rulesByApp)
            {
                await grainFactory.GetGrain <IRulesByAppIndex>(kvp.Key).RebuildAsync(kvp.Value);
            }
        }
Ejemplo n.º 24
0
        public static void ScheduleCommand(ScheduledCommand cmd)
        {
            MpLog.Log($"Cmd: {cmd.type}, faction: {cmd.factionId}, map: {cmd.mapId}, ticks: {cmd.ticks}");
            cachedMapCmds.GetOrAddNew(cmd.mapId).Add(cmd);

            if (Current.ProgramState != ProgramState.Playing)
            {
                return;
            }

            if (cmd.mapId == ScheduledCommand.Global)
            {
                Multiplayer.WorldComp.cmds.Enqueue(cmd);
            }
            else
            {
                cmd.GetMap()?.AsyncTime().cmds.Enqueue(cmd);
            }
        }
Ejemplo n.º 25
0
        private static Document CreateDocument(NamedContentData data)
        {
            var languages = new Dictionary <string, StringBuilder>();

            void AppendText(string language, string text)
            {
                if (!string.IsNullOrWhiteSpace(text))
                {
                    var sb = languages.GetOrAddNew(language);

                    if (sb.Length > 0)
                    {
                        sb.Append(" ");
                    }

                    sb.Append(text);
                }
            }

            foreach (var field in data)
            {
                if (field.Value != null)
                {
                    foreach (var fieldValue in field.Value)
                    {
                        var appendText = new Action <string>(text => AppendText(fieldValue.Key, text));

                        AppendJsonText(fieldValue.Value, appendText);
                    }
                }
            }

            var document = new Document();

            foreach (var field in languages)
            {
                document.AddTextField(field.Key, field.Value.ToString(), Field.Store.NO);
            }

            return(document);
        }
Ejemplo n.º 26
0
        private void UpdateNewKeyInExistingMapping(int columnRowIndex,
                                                   JoinSide side,
                                                   TKey key,
                                                   List <RowToUpdate> updateRows,
                                                   Dictionary <int, HashSet <int> > columnRowsToJoinRows,
                                                   ColumnRowMapping keyRowsMapping)
        {
            var shouldAddUnlinkedRow = ShouldAddUnlinkedRow(side);
            var joinedRowId          = shouldAddUnlinkedRow ? GetNewRowId() : (int?)null;
            var joinRow = CreateNewJoinRow(columnRowIndex, key, joinedRowId, side);

            keyRowsMapping.ColRowMappings.Add(joinRow);

            if (shouldAddUnlinkedRow)
            {
                AddNewRow(joinRow, updateRows, joinedRowId.Value);

                // Update the reverse lookup
                columnRowsToJoinRows.GetOrAddNew(columnRowIndex).Add(joinedRowId.Value);
            }
        }
Ejemplo n.º 27
0
        private void LinkNewItemToUnlinkedRows(int columnRowIndex,
                                               JoinSide side,
                                               ColumnRowMapping keyRowsMapping,
                                               List <RowToUpdate> updateRows,
                                               Dictionary <int, HashSet <int> > otherColumnRowsToJoinRows,
                                               Dictionary <int, HashSet <int> > columnRowsToJoinRows,
                                               int i)
        {
            int?joinedRowId;
            // Link the row to the joined row.
            var rowToLink = keyRowsMapping.ColRowMappings[i];

            LinkRow(ref rowToLink, columnRowIndex, side);

            // We need to create the new row here (when we link)
            if (!rowToLink.RowId.HasValue)
            {
                joinedRowId = GetNewRowId();

                rowToLink.RowId = joinedRowId; // Can't forget to update the existing row object with the new id
                AddNewRow(rowToLink, updateRows, joinedRowId.Value);

                // Need to update the reverse mapping for the other side too as it wasn't done before
                var otherRowId = side == JoinSide.Left ? rowToLink.RightRowId : rowToLink.LeftRowId;
                otherColumnRowsToJoinRows.GetOrAddNew(otherRowId.Value).Add(joinedRowId.Value);
            }
            else
            {
                updateRows.Add(new RowToUpdate {
                    RowIndex = rowToLink.RowId.Value, Type = RowToUpdate.RowUpdateType.Link
                });
                joinedRowId = rowToLink.RowId;
            }

            keyRowsMapping.ColRowMappings[i] = rowToLink;
            _rows[joinedRowId.Value]         = rowToLink;

            // Update the reverse lookup
            columnRowsToJoinRows.GetOrAddNew(columnRowIndex).Add(joinedRowId.Value);
        }
Ejemplo n.º 28
0
        public void SendCommand(CommandType cmd, int factionId, int mapId, byte[] data, ServerPlayer sourcePlayer = null)
        {
            if (sourcePlayer != null)
            {
                bool debugCmd =
                    cmd == CommandType.DebugTools ||
                    cmd == CommandType.Sync && debugOnlySyncCmds.Contains(BitConverter.ToInt32(data, 0));

                if (!debugMode && debugCmd)
                {
                    return;
                }

                bool hostOnly = cmd == CommandType.Sync && hostOnlySyncCmds.Contains(BitConverter.ToInt32(data, 0));
                if (!sourcePlayer.IsHost && hostOnly)
                {
                    return;
                }
            }

            byte[] toSave = new ScheduledCommand(cmd, gameTimer, factionId, mapId, data).Serialize();

            // todo cull target players if not global
            mapCmds.GetOrAddNew(mapId).Add(toSave);
            tmpMapCmds?.GetOrAddNew(mapId).Add(toSave);

            byte[] toSend       = toSave.Append(new byte[] { 0 });
            byte[] toSendSource = toSave.Append(new byte[] { 1 });

            foreach (var player in PlayingPlayers)
            {
                player.conn.Send(
                    Packets.Server_Command,
                    sourcePlayer == player ? toSendSource : toSend
                    );
            }

            cmdId++;
        }
Ejemplo n.º 29
0
        public async Task <bool> RestoreEventAsync(Envelope <IEvent> @event, RestoreContext context,
                                                   CancellationToken ct)
        {
            switch (@event.Payload)
            {
            case AppCreated appCreated:
                assetsUrlNew = GetUrls(appCreated.Name);
                assetsUrlOld = await ReadUrlsAsync(context.Reader, ct);

                break;

            case SchemaDeleted schemaDeleted:
                contentIdsBySchemaId.Remove(schemaDeleted.SchemaId.Id);
                break;

            case ContentCreated contentCreated:
                contentIdsBySchemaId.GetOrAddNew(contentCreated.SchemaId.Id)
                .Add(@event.Headers.AggregateId());

                if (assetsUrlNew != null && assetsUrlOld != null)
                {
                    ReplaceAssetUrl(contentCreated.Data);
                }

                break;

            case ContentUpdated contentUpdated:
                if (assetsUrlNew != null && assetsUrlOld != null)
                {
                    ReplaceAssetUrl(contentUpdated.Data);
                }

                break;
            }

            return(true);
        }
Ejemplo n.º 30
0
        static void ScanCompiledFileSet(
            Dictionary <string, Dictionary <string, CompiledPackage> > compilerDictionary,
            Dictionary <string, CompiledLibrary> libraryDictionary)
        {
            foreach (var dir in new DirectoryInfo(Config.BoostDir).GetDirectories("address-model-*"))
            {
                foreach (var file in dir.GetFiles("lib/*boost*"))
                {
                    var split    = file.Name.SplitFirst('-');
                    var library  = split.Before.SplitFirst('_').After;
                    var compiler = split.After.SplitFirst('-').Before;

                    //
                    var compiledLibrary = libraryDictionary.GetOrAddNew(library);
                    var compiledPackage =
                        compiledLibrary.PackageDictionary.GetOrAddNew(compiler);
                    compiledPackage.AddFile(dir.Name, "lib/" + file.Name);

                    // add the compiler and add the library to the compiler.
                    compilerDictionary.GetOrAddNew(compiler)[library] =
                        compiledPackage;
                }
            }
        }
Ejemplo n.º 31
0
        static void ScanCompiledFileSet(
            Dictionary<string, Dictionary<string, CompiledPackage>> 
                compilerDictionary,
            Dictionary<string, CompiledLibrary> libraryDictionary,
            Platform platform)
        {
            foreach (
                var file in
                    new DirectoryInfo(Path.Combine(
                        Config.BoostDir, platform.Directory))
                    .GetFiles())
            {
                var split = file.Name.SplitFirst('-');
                var library = split.Before.SplitFirst('_').After;
                var compiler = split.After.SplitFirst('-').Before;

                //
                var compiledLibrary = libraryDictionary.GetOrAddNew(library);
                var compiledPackage =
                    compiledLibrary.PackageDictionary.GetOrAddNew(compiler);
                compiledPackage.AddFile(platform, file.Name);

                // add the compiler and add the library to the compiler.
                compilerDictionary.GetOrAddNew(compiler)[library] =
                    compiledPackage;
            }
        }
Ejemplo n.º 32
0
        public void CachePCHUsageForModuleSourceFiles(CPPEnvironment ModuleCompileEnvironment)
        {
            if( ProcessedDependencies == null )
            {
                var PCHCacheTimerStart = DateTime.UtcNow;

                var BuildPlatform = UEBuildPlatform.GetBuildPlatformForCPPTargetPlatform( ModuleCompileEnvironment.Config.Target.Platform );

                bool bFoundAProblemWithPCHs = false;

                FileItem UniquePCH = null;
                foreach( var CPPFile in SourceFilesFound.CPPFiles )	// @todo ubtmake: We're not caching CPPEnvironments for .c/.mm files, etc.  Even though they don't use PCHs, they still have #includes!  This can break dependency checking!
                {
                    // Build a single list of include paths to search.
                    var IncludePathsToSearch = ModuleCompileEnvironment.Config.CPPIncludeInfo.GetIncludesPathsToSearch( CPPFile );

                    // Store the module compile environment along with the .cpp file.  This is so that we can use it later on when looking
                    // for header dependencies
                    CPPFile.CachedCPPIncludeInfo = ModuleCompileEnvironment.Config.CPPIncludeInfo;

                    // Find headers used by the source file.
                    var PCH = UEBuildModuleCPP.CachePCHUsageForCPPFile(Target, CPPFile, BuildPlatform, IncludePathsToSearch, ModuleCompileEnvironment.Config.CPPIncludeInfo.IncludeFileSearchDictionary);
                    if( PCH == null )
                    {
                        throw new BuildException( "Source file \"{0}\" is not including any headers.  We expect all modules to include a header file for precompiled header generation.  Please add an #include statement.", CPPFile.AbsolutePath );
                    }

                    if( UniquePCH == null )
                    {
                        UniquePCH = PCH;
                    }
                    else if( !UniquePCH.Info.Name.Equals( PCH.Info.Name, StringComparison.InvariantCultureIgnoreCase ) )		// @todo ubtmake: We do a string compare on the file name (not path) here, because sometimes the include resolver will pick an Intermediate copy of a PCH header file and throw off our comparisons
                    {
                        // OK, looks like we have multiple source files including a different header file first.  We'll keep track of this and print out
                        // helpful information afterwards.
                        bFoundAProblemWithPCHs = true;
                    }
                }

                ProcessedDependencies = new ProcessedDependenciesClass{ UniquePCHHeaderFile = UniquePCH };

                if( bFoundAProblemWithPCHs )
                {
                    // Map from pch header string to the source files that use that PCH
                    var UsageMapPCH = new Dictionary<string, List<FileItem>>( StringComparer.InvariantCultureIgnoreCase );
                    foreach( var CPPFile in SourceFilesToBuild.CPPFiles )
                    {
                        // Create a new entry if not in the pch usage map
                        UsageMapPCH.GetOrAddNew( CPPFile.PrecompiledHeaderIncludeFilename ).Add( CPPFile );
                    }

                    if( BuildConfiguration.bPrintDebugInfo )
                    {
                        Log.TraceVerbose( "{0} PCH files for module {1}:", UsageMapPCH.Count, Name );
                        int MostFilesIncluded = 0;
                        foreach( var CurPCH in UsageMapPCH )
                        {
                            if( CurPCH.Value.Count > MostFilesIncluded )
                            {
                                MostFilesIncluded = CurPCH.Value.Count;
                            }

                            Log.TraceVerbose("   {0}  ({1} files including it: {2}, ...)", CurPCH.Key, CurPCH.Value.Count, CurPCH.Value[0].AbsolutePath);
                        }
                    }

                    if( UsageMapPCH.Count > 1 )
                    {
                        // Keep track of the PCH file that is most used within this module
                        string MostFilesAreIncludingPCH = string.Empty;
                        int MostFilesIncluded = 0;
                        foreach( var CurPCH in UsageMapPCH.Where( PCH => PCH.Value.Count > MostFilesIncluded ) )
                        {
                            MostFilesAreIncludingPCH = CurPCH.Key;
                            MostFilesIncluded        = CurPCH.Value.Count;
                        }

                        // Find all of the files that are not including our "best" PCH header
                        var FilesNotIncludingBestPCH = new StringBuilder();
                        foreach( var CurPCH in UsageMapPCH.Where( PCH => PCH.Key != MostFilesAreIncludingPCH ) )
                        {
                            foreach( var SourceFile in CurPCH.Value )
                            {
                                FilesNotIncludingBestPCH.AppendFormat( "{0} (including {1})\n", SourceFile.AbsolutePath, CurPCH.Key );
                            }
                        }

                        // Bail out and let the user know which source files may need to be fixed up
                        throw new BuildException(
                            "All source files in module \"{0}\" must include the same precompiled header first.  Currently \"{1}\" is included by most of the source files.  The following source files are not including \"{1}\" as their first include:\n\n{2}",
                            Name,
                            MostFilesAreIncludingPCH,
                            FilesNotIncludingBestPCH );
                    }
                }

                if( BuildConfiguration.bPrintPerformanceInfo )
                {
                    var PCHCacheTime = ( DateTime.UtcNow - PCHCacheTimerStart ).TotalSeconds;
                    TotalPCHCacheTime += PCHCacheTime;
                }
            }
        }