Use std::index_sequence and std::make_unique

This commit is contained in:
Fangrui Song 2018-03-10 15:40:27 -08:00
parent 3995a9d5b8
commit 640f548e7c
18 changed files with 50 additions and 81 deletions

View File

@ -689,7 +689,7 @@ void ClangCompleteManager::CodeComplete(
const lsRequestId& id,
const lsTextDocumentPositionParams& completion_location,
const OnComplete& on_complete) {
completion_request_.PushBack(MakeUnique<CompletionRequest>(
completion_request_.PushBack(std::make_unique<CompletionRequest>(
id, completion_location.textDocument, completion_location.position,
on_complete, false));
}
@ -698,7 +698,7 @@ void ClangCompleteManager::DiagnosticsUpdate(
const lsRequestId& id,
const lsTextDocumentIdentifier& document) {
completion_request_.PushBack(
MakeUnique<CompletionRequest>(id, document, true));
std::make_unique<CompletionRequest>(id, document, true));
}
void ClangCompleteManager::NotifyView(const std::string& filename) {

View File

@ -98,7 +98,7 @@ std::unique_ptr<ClangTranslationUnit> ClangTranslationUnit::Create(
switch (error_code) {
case CXError_Success:
return MakeUnique<ClangTranslationUnit>(cx_tu);
return std::make_unique<ClangTranslationUnit>(cx_tu);
case CXError_Failure:
LOG_S(ERROR) << "libclang generic failure for " << filepath << ". "
<< make_msg();

View File

@ -203,9 +203,9 @@ void RunQueryDbThread(const std::string& bin_name,
});
IncludeComplete include_complete(config, &project);
auto global_code_complete_cache = MakeUnique<CodeCompleteCache>();
auto non_global_code_complete_cache = MakeUnique<CodeCompleteCache>();
auto signature_cache = MakeUnique<CodeCompleteCache>();
auto global_code_complete_cache = std::make_unique<CodeCompleteCache>();
auto non_global_code_complete_cache = std::make_unique<CodeCompleteCache>();
auto signature_cache = std::make_unique<CodeCompleteCache>();
ImportManager import_manager;
ImportPipelineStatus import_pipeline_status;
TimestampManager timestamp_manager;
@ -423,8 +423,7 @@ int main(int argc, char** argv) {
loguru::init(argc, argv);
MultiQueueWaiter querydb_waiter, indexer_waiter, stdout_waiter;
QueueManager::CreateInstance(&querydb_waiter, &indexer_waiter,
&stdout_waiter);
QueueManager::Init(&querydb_waiter, &indexer_waiter, &stdout_waiter);
PlatformInit();
IndexInit();
@ -489,7 +488,7 @@ int main(int argc, char** argv) {
}
// std::cerr << "Running language server" << std::endl;
auto config = MakeUnique<Config>();
auto config = std::make_unique<Config>();
LanguageServerMain(argv[0], config.get(), &querydb_waiter, &indexer_waiter,
&stdout_waiter);
}

View File

@ -6,7 +6,7 @@
void DiagnosticsEngine::Init(Config* config) {
frequencyMs_ = config->diagnostics.frequencyMs;
match_ = MakeUnique<GroupMatch>(config->diagnostics.whitelist,
match_ = std::make_unique<GroupMatch>(config->diagnostics.whitelist,
config->diagnostics.blacklist);
}

View File

@ -84,7 +84,7 @@ IndexFile* FileConsumer::TryConsumeFile(CXFile file,
// Build IndexFile instance.
*is_first_ownership = true;
local_[file_id] = MakeUnique<IndexFile>(file_name, *contents);
local_[file_id] = std::make_unique<IndexFile>(file_name, *contents);
return local_[file_id].get();
}

View File

@ -30,15 +30,15 @@ struct ClangIndexer : IIndexer {
struct TestIndexer : IIndexer {
static std::unique_ptr<TestIndexer> FromEntries(
const std::vector<TestEntry>& entries) {
auto result = MakeUnique<TestIndexer>();
auto result = std::make_unique<TestIndexer>();
for (const TestEntry& entry : entries) {
std::vector<std::unique_ptr<IndexFile>> indexes;
if (entry.num_indexes > 0)
indexes.push_back(MakeUnique<IndexFile>(entry.path, "<empty>"));
indexes.push_back(std::make_unique<IndexFile>(entry.path, "<empty>"));
for (int i = 1; i < entry.num_indexes; ++i) {
indexes.push_back(MakeUnique<IndexFile>(
indexes.push_back(std::make_unique<IndexFile>(
entry.path + "_extra_" + std::to_string(i) + ".h", "<empty>"));
}
@ -82,7 +82,7 @@ IIndexer::TestEntry::TestEntry(const std::string& path, int num_indexes)
// static
std::unique_ptr<IIndexer> IIndexer::MakeClangIndexer() {
return MakeUnique<ClangIndexer>();
return std::make_unique<ClangIndexer>();
}
// static

View File

@ -677,8 +677,8 @@ void QueryDb_DoIdMap(QueueManager* queue,
if (!file)
return nullptr;
auto id_map = MakeUnique<IdMap>(db, file->id_cache);
return MakeUnique<Index_OnIdMapped::File>(std::move(file),
auto id_map = std::make_unique<IdMap>(db, file->id_cache);
return std::make_unique<Index_OnIdMapped::File>(std::move(file),
std::move(id_map));
};
response.current = make_map(std::move(request->current));
@ -763,8 +763,7 @@ bool QueryDb_ImportMain(Config* config,
TEST_SUITE("ImportPipeline") {
struct Fixture {
Fixture() {
QueueManager::CreateInstance(&querydb_waiter, &indexer_waiter,
&stdout_waiter);
QueueManager::Init(&querydb_waiter, &indexer_waiter, &stdout_waiter);
queue = QueueManager::instance();
cache_manager = ICacheManager::MakeFake({});
@ -810,7 +809,7 @@ TEST_SUITE("ImportPipeline") {
const std::vector<std::string>& new_args = {}) {
std::unique_ptr<IndexFile> opt_previous_index;
if (!old_args.empty()) {
opt_previous_index = MakeUnique<IndexFile>("---.cc", "<empty>");
opt_previous_index = std::make_unique<IndexFile>("---.cc", "<empty>");
opt_previous_index->args = old_args;
}
optional<std::string> from;

View File

@ -112,7 +112,7 @@ void IncludeComplete::Rescan() {
if (!match_ && (!config_->completion.includeWhitelist.empty() ||
!config_->completion.includeBlacklist.empty()))
match_ = MakeUnique<GroupMatch>(config_->completion.includeWhitelist,
match_ = std::make_unique<GroupMatch>(config_->completion.includeWhitelist,
config_->completion.includeBlacklist);
is_scanning = true;

View File

@ -47,7 +47,7 @@ struct MessageRegistryRegister {
std::string method_name = IpcIdToString(T::kIpcId);
MessageRegistry::instance()->allocators[method_name] =
[](Reader& visitor, std::unique_ptr<BaseIpcMessage>* message) {
*message = MakeUnique<T>();
*message = std::make_unique<T>();
// Reflect may throw and *message will be partially deserialized.
Reflect(visitor, static_cast<T&>(**message));
};

View File

@ -9,12 +9,14 @@
#include "semantic_highlight_symbol_cache.h"
#include "serializers/json.h"
#include "timer.h"
#include "work_thread.h"
#include "working_files.h"
#include <loguru.hpp>
#include <iostream>
#include <stdexcept>
#include <thread>
// TODO Cleanup global variables
extern std::string g_init_options;

View File

@ -52,20 +52,14 @@ Index_OnIndexed::Index_OnIndexed(IndexUpdate&& update,
PerformanceImportFile perf)
: update(std::move(update)), perf(perf) {}
QueueManager* QueueManager::instance_ = nullptr;
std::unique_ptr<QueueManager> QueueManager::instance_;
// static
QueueManager* QueueManager::instance() {
return instance_;
}
// static
void QueueManager::CreateInstance(MultiQueueWaiter* querydb_waiter,
MultiQueueWaiter* indexer_waiter,
MultiQueueWaiter* stdout_waiter) {
if (instance_)
delete instance_;
instance_ = new QueueManager(querydb_waiter, indexer_waiter, stdout_waiter);
void QueueManager::Init(MultiQueueWaiter* querydb_waiter,
MultiQueueWaiter* indexer_waiter,
MultiQueueWaiter* stdout_waiter) {
instance_ = std::unique_ptr<QueueManager>(
new QueueManager(querydb_waiter, indexer_waiter, stdout_waiter));
}
// static

View File

@ -78,16 +78,19 @@ struct Index_OnIndexed {
Index_OnIndexed(IndexUpdate&& update, PerformanceImportFile perf);
};
struct QueueManager {
static QueueManager* instance();
static void CreateInstance(MultiQueueWaiter* querydb_waiter,
MultiQueueWaiter* indexer_waiter,
MultiQueueWaiter* stdout_waiter);
class QueueManager {
static std::unique_ptr<QueueManager> instance_;
public:
static QueueManager* instance() { return instance_.get(); }
static void Init(MultiQueueWaiter* querydb_waiter,
MultiQueueWaiter* indexer_waiter,
MultiQueueWaiter* stdout_waiter);
static void WriteStdout(IpcId id, lsBaseOutMessage& response);
bool HasWork();
// Runs on stdout thread.
// Messages received by "stdout" thread.
ThreadedQueue<Stdout_Request> for_stdout;
// Runs on querydb thread.
@ -107,6 +110,4 @@ struct QueueManager {
explicit QueueManager(MultiQueueWaiter* querydb_waiter,
MultiQueueWaiter* indexer_waiter,
MultiQueueWaiter* stdout_waiter);
static QueueManager* instance_;
};

View File

@ -61,7 +61,7 @@ SemanticHighlightSymbolCache::SemanticHighlightSymbolCache()
: cache_(kCacheSize) {}
void SemanticHighlightSymbolCache::Init(Config* config) {
match_ = MakeUnique<GroupMatch>(config->highlight.whitelist,
match_ = std::make_unique<GroupMatch>(config->highlight.whitelist,
config->highlight.blacklist);
}

View File

@ -383,7 +383,7 @@ std::unique_ptr<IndexFile> Deserialize(
if (reader.HasParseError())
return nullptr;
file = MakeUnique<IndexFile>(path, file_content);
file = std::make_unique<IndexFile>(path, file_content);
JsonReader json_reader{&reader};
try {
Reflect(json_reader, *file);
@ -405,7 +405,7 @@ std::unique_ptr<IndexFile> Deserialize(
memcpy(upk.buffer(), serialized_index_content.data(),
serialized_index_content.size());
upk.buffer_consumed(serialized_index_content.size());
file = MakeUnique<IndexFile>(path, file_content);
file = std::make_unique<IndexFile>(path, file_content);
MessagePackReader reader(&upk);
Reflect(reader, major);
Reflect(reader, minor);

View File

@ -6,8 +6,8 @@
#include <doctest/doctest.h>
TaskManager::TaskManager() {
pending_tasks_[TaskThread::Indexer] = MakeUnique<TaskQueue>();
pending_tasks_[TaskThread::QueryDb] = MakeUnique<TaskQueue>();
pending_tasks_[TaskThread::Indexer] = std::make_unique<TaskQueue>();
pending_tasks_[TaskThread::QueryDb] = std::make_unique<TaskQueue>();
}
void TaskManager::Post(TaskThread thread, const TTask& task) {

View File

@ -1,7 +1,6 @@
#pragma once
#include "utils.h"
#include "work_thread.h"
#include <optional.h>
@ -11,6 +10,7 @@
#include <deque>
#include <mutex>
#include <tuple>
#include <utility>
// TODO: cleanup includes.
@ -19,24 +19,6 @@ struct BaseThreadQueue {
virtual ~BaseThreadQueue() = default;
};
// TODO Remove after migration to C++14
namespace {
template <size_t... Is>
struct index_sequence {};
template <size_t I, size_t... Is>
struct make_index_sequence {
using type = typename make_index_sequence<I - 1, I - 1, Is...>::type;
};
template <size_t... Is>
struct make_index_sequence<0, Is...> {
using type = index_sequence<Is...>;
};
} // namespace
// std::lock accepts two or more arguments. We define an overload for one
// argument.
namespace std {
@ -51,20 +33,20 @@ struct MultiQueueLock {
MultiQueueLock(Queue... lockable) : tuple_{lockable...} { lock(); }
~MultiQueueLock() { unlock(); }
void lock() {
lock_impl(typename make_index_sequence<sizeof...(Queue)>::type{});
lock_impl(typename std::make_index_sequence<sizeof...(Queue)>{});
}
void unlock() {
unlock_impl(typename make_index_sequence<sizeof...(Queue)>::type{});
unlock_impl(typename std::make_index_sequence<sizeof...(Queue)>{});
}
private:
template <size_t... Is>
void lock_impl(index_sequence<Is...>) {
void lock_impl(std::index_sequence<Is...>) {
std::lock(std::get<Is>(tuple_)->mutex_...);
}
template <size_t... Is>
void unlock_impl(index_sequence<Is...>) {
void unlock_impl(std::index_sequence<Is...>) {
(void)std::initializer_list<int>{
(std::get<Is>(tuple_)->mutex_.unlock(), 0)...};
}
@ -96,9 +78,9 @@ template <class T>
struct ThreadedQueue : public BaseThreadQueue {
public:
ThreadedQueue() : total_count_(0) {
owned_waiter_ = MakeUnique<MultiQueueWaiter>();
owned_waiter_ = std::make_unique<MultiQueueWaiter>();
waiter_ = owned_waiter_.get();
owned_waiter1_ = MakeUnique<MultiQueueWaiter>();
owned_waiter1_ = std::make_unique<MultiQueueWaiter>();
waiter1_ = owned_waiter1_.get();
}

View File

@ -111,14 +111,6 @@ struct TextReplacer {
void WriteToFile(const std::string& filename, const std::string& content);
// note: this implementation does not disable this overload for array types
// See
// http://en.cppreference.com/w/cpp/memory/unique_ptr/make_unique#Possible_Implementatiog
template <typename T, typename... Args>
std::unique_ptr<T> MakeUnique(Args&&... args) {
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
template <typename T>
void AddRange(std::vector<T>* dest, const std::vector<T>& to_add) {
dest->insert(dest->end(), to_add.begin(), to_add.end());

View File

@ -478,7 +478,7 @@ WorkingFile* WorkingFiles::OnOpen(const lsTextDocumentItem& open) {
return file;
}
files.push_back(MakeUnique<WorkingFile>(filename, content));
files.push_back(std::make_unique<WorkingFile>(filename, content));
return files[files.size() - 1].get();
}