Code
stringlengths
131
28.2k
Unit Test
stringlengths
40
32.1k
__index_level_0__
int64
0
2.63k
#ifndef TENSORFLOW_TSL_PLATFORM_STACKTRACE_HANDLER_H_ #define TENSORFLOW_TSL_PLATFORM_STACKTRACE_HANDLER_H_ namespace tsl { namespace testing { void InstallStacktraceHandler(); } } #endif #include "tsl/platform/platform.h" #if !defined(IS_MOBILE_PLATFORM) && defined(PLATFORM_POSIX) && \ (defined(__clang__) || defined(__GNUC__)) #define TF_GENERATE_STACKTRACE #endif #if defined(TF_GENERATE_STACKTRACE) #include <errno.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #include <unistd.h> #include <string> #include "tsl/platform/stacktrace.h" #endif namespace tsl { namespace testing { #if defined(TF_GENERATE_STACKTRACE) inline void SafePrintStackTrace() { static const char begin_msg[] = "*** BEGIN MANGLED STACK TRACE ***\n"; (void)!write(STDERR_FILENO, begin_msg, strlen(begin_msg)); int buffer_size = 128; void *trace[128]; buffer_size = backtrace(trace, buffer_size); backtrace_symbols_fd(trace, buffer_size, STDERR_FILENO); static const char end_msg[] = "*** END MANGLED STACK TRACE ***\n\n"; (void)!write(STDERR_FILENO, end_msg, strlen(end_msg)); } static void StacktraceHandler(int sig, siginfo_t *si, void *v) { struct itimerval timer; timer.it_value.tv_sec = 60; timer.it_value.tv_usec = 0; timer.it_interval.tv_sec = 0; timer.it_interval.tv_usec = 0; setitimer(ITIMER_REAL, &timer, 0); struct sigaction sa_timeout; memset(&sa_timeout, 0, sizeof(sa_timeout)); sa_timeout.sa_handler = SIG_DFL; sigaction(SIGALRM, &sa_timeout, 0); char buf[128]; snprintf(buf, sizeof(buf), "*** Received signal %d ***\n", sig); (void)!write(STDERR_FILENO, buf, strlen(buf)); SafePrintStackTrace(); std::string stacktrace = CurrentStackTrace(); (void)!write(STDERR_FILENO, stacktrace.c_str(), stacktrace.length()); struct sigaction sa; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sa.sa_handler = SIG_DFL; sigaction(SIGABRT, &sa, NULL); abort(); } void InstallStacktraceHandler() { int handled_signals[] = {SIGSEGV, SIGABRT, SIGBUS, SIGILL, SIGFPE}; size_t array_limit = sizeof(handled_signals) / sizeof(int); for (size_t i = 0; i < array_limit; i++) { int sig = handled_signals[i]; struct sigaction sa; struct sigaction osa; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_SIGINFO | SA_RESETHAND; sa.sa_sigaction = &StacktraceHandler; if (sigaction(sig, &sa, &osa) != 0) { char buf[128]; snprintf(buf, sizeof(buf), "Warning, can't install backtrace signal handler for signal %d, " "errno:%d \n", sig, errno); (void)!write(STDERR_FILENO, buf, strlen(buf)); } else if (osa.sa_handler != SIG_DFL) { char buf[128]; snprintf(buf, sizeof(buf), "Warning, backtrace signal handler for signal %d overwrote " "previous handler.\n", sig); (void)!write(STDERR_FILENO, buf, strlen(buf)); } } } #else void InstallStacktraceHandler() {} #endif } }
#include <csignal> #include "tsl/platform/logging.h" #include "tsl/platform/test.h" namespace tsl { namespace { TEST(StacktraceHandlerTest, GeneratesStacktrace) { EXPECT_DEATH(raise(SIGABRT), "testing::internal::UnitTestImpl::RunAllTests"); } } }
2,287
#ifndef TENSORFLOW_TSL_PLATFORM_DEFAULT_STACKTRACE_H_ #define TENSORFLOW_TSL_PLATFORM_DEFAULT_STACKTRACE_H_ #include "tsl/platform/platform.h" #if !defined(IS_MOBILE_PLATFORM) && (defined(__clang__) || defined(__GNUC__)) #define TF_HAS_STACKTRACE #endif #if defined(TF_HAS_STACKTRACE) #include <dlfcn.h> #include <execinfo.h> #include <stdio.h> #include <string.h> #include <unistd.h> #endif #include <sstream> #include <string> #include "tsl/platform/abi.h" namespace tsl { inline std::string CurrentStackTrace() { #if defined(TF_HAS_STACKTRACE) std::stringstream ss(""); ss << "*** Begin stack trace ***" << std::endl; int buffer_size = 128; void* trace[128]; buffer_size = backtrace(trace, buffer_size); for (int i = 0; i < buffer_size; ++i) { const char* symbol = ""; Dl_info info; if (dladdr(trace[i], &info)) { if (info.dli_sname != nullptr) { symbol = info.dli_sname; } } std::string demangled = port::MaybeAbiDemangle(symbol); if (demangled.length()) { ss << "\t" << demangled << std::endl; } else { ss << "\t" << symbol << std::endl; } } ss << "*** End stack trace ***" << std::endl; return ss.str(); #else return std::string(); #endif } inline void DebugWriteToString(const char* data, void* arg) { reinterpret_cast<std::string*>(arg)->append(data); } class SavedStackTrace { public: SavedStackTrace() {} void CreateCurrent(int skip_count) {} void Reset() {} typedef void DebugWriter(const char*, void*); void Dump(DebugWriter* writerfn, void* arg) const {} int depth() const { return 0; } void* const* stack() const { return stack_; } private: void* stack_[32]; }; } #endif #include "tsl/platform/windows/stacktrace.h" #include <windows.h> #include <dbghelp.h> #include <string> #include "tsl/platform/mutex.h" #pragma comment(lib, "dbghelp.lib") namespace tsl { static bool SymbolsAreAvailableInit() { SymSetOptions(SYMOPT_UNDNAME | SYMOPT_DEFERRED_LOADS); return SymInitialize(GetCurrentProcess(), NULL, true); } static bool SymbolsAreAvailable() { static bool kSymbolsAvailable = SymbolsAreAvailableInit(); return kSymbolsAvailable; } std::string CurrentStackTrace() { HANDLE current_process = GetCurrentProcess(); static constexpr int kMaxStackFrames = 64; void* trace[kMaxStackFrames]; int num_frames = CaptureStackBackTrace(0, kMaxStackFrames, trace, NULL); static mutex mu(tsl::LINKER_INITIALIZED); std::string stacktrace; for (int i = 0; i < num_frames; ++i) { const char* symbol = "(unknown)"; if (SymbolsAreAvailable()) { char symbol_info_buffer[sizeof(SYMBOL_INFO) + MAX_SYM_NAME * sizeof(TCHAR)]; SYMBOL_INFO* symbol_ptr = reinterpret_cast<SYMBOL_INFO*>(symbol_info_buffer); symbol_ptr->SizeOfStruct = sizeof(SYMBOL_INFO); symbol_ptr->MaxNameLen = MAX_SYM_NAME; mutex_lock lock(mu); if (SymFromAddr(current_process, reinterpret_cast<DWORD64>(trace[i]), 0, symbol_ptr)) { symbol = symbol_ptr->Name; } } char buffer[256]; snprintf(buffer, sizeof(buffer), "0x%p\t%s", trace[i], symbol); stacktrace += buffer; stacktrace += "\n"; } return stacktrace; } }
#include "tsl/platform/stacktrace.h" #include <string> #include "tsl/platform/logging.h" #include "tsl/platform/test.h" namespace tsl { namespace { #if defined(TF_HAS_STACKTRACE) TEST(StacktraceTest, StacktraceWorks) { std::string stacktrace = CurrentStackTrace(); LOG(INFO) << "CurrentStackTrace():\n" << stacktrace; std::string expected_frame = "testing::internal::UnitTestImpl::RunAllTests"; EXPECT_NE(stacktrace.find(expected_frame), std::string::npos); } #endif } }
2,288
#ifndef TENSORFLOW_TSL_PLATFORM_DEFAULT_UNBOUNDED_WORK_QUEUE_H_ #define TENSORFLOW_TSL_PLATFORM_DEFAULT_UNBOUNDED_WORK_QUEUE_H_ #include <deque> #include <memory> #include <vector> #include "tsl/platform/env.h" #include "tsl/platform/mutex.h" #include "tsl/platform/notification.h" namespace tsl { class UnboundedWorkQueue { public: UnboundedWorkQueue(Env* env, const string& thread_name, const ThreadOptions& thread_options = {}); ~UnboundedWorkQueue(); using WorkFunction = std::function<void()>; void Schedule(WorkFunction fn); private: void PooledThreadFunc(); Env* const env_; const string thread_name_; const ThreadOptions thread_options_; mutex work_queue_mu_; condition_variable work_queue_cv_ TF_GUARDED_BY(work_queue_mu_); size_t num_idle_threads_ TF_GUARDED_BY(work_queue_mu_) = 0; bool cancelled_ TF_GUARDED_BY(work_queue_mu_) = false; std::deque<WorkFunction> work_queue_ TF_GUARDED_BY(work_queue_mu_); mutex thread_pool_mu_; std::vector<std::unique_ptr<Thread>> thread_pool_ TF_GUARDED_BY(thread_pool_mu_); }; } #endif #include "tsl/platform/default/unbounded_work_queue.h" #include "absl/memory/memory.h" #include "tsl/platform/env.h" #include "tsl/platform/mutex.h" #include "tsl/platform/numa.h" namespace tsl { UnboundedWorkQueue::UnboundedWorkQueue(Env* env, const string& thread_name, const ThreadOptions& thread_options) : env_(env), thread_name_(thread_name), thread_options_(thread_options) {} UnboundedWorkQueue::~UnboundedWorkQueue() { { mutex_lock l(work_queue_mu_); cancelled_ = true; work_queue_cv_.notify_all(); if (!work_queue_.empty()) { LOG(ERROR) << "UnboundedWorkQueue named \"" << thread_name_ << "\" was " << "deleted with pending work in its queue. This may indicate " << "a potential use-after-free bug."; } } { mutex_lock l(thread_pool_mu_); thread_pool_.clear(); } } void UnboundedWorkQueue::Schedule(WorkFunction fn) { mutex_lock l(work_queue_mu_); work_queue_.push_back(std::move(fn)); work_queue_cv_.notify_one(); if (work_queue_.size() > num_idle_threads_) { Thread* new_thread = env_->StartThread({}, thread_name_, [this]() { PooledThreadFunc(); }); mutex_lock l(thread_pool_mu_); thread_pool_.emplace_back(new_thread); } } void UnboundedWorkQueue::PooledThreadFunc() { if (thread_options_.numa_node != tsl::port::kNUMANoAffinity) { tsl::port::NUMASetThreadNodeAffinity(thread_options_.numa_node); } while (true) { WorkFunction fn; { mutex_lock l(work_queue_mu_); ++num_idle_threads_; while (!cancelled_ && work_queue_.empty()) { work_queue_cv_.wait(l); } if (cancelled_) { return; } fn = std::move(work_queue_.front()); work_queue_.pop_front(); --num_idle_threads_; } fn(); } } }
#include "tsl/platform/unbounded_work_queue.h" #include "absl/memory/memory.h" #include "tsl/platform/random.h" #include "tsl/platform/blocking_counter.h" #include "tsl/platform/env.h" #include "tsl/platform/test.h" namespace tsl { namespace { class UnboundedWorkQueueTest : public ::testing::Test { protected: UnboundedWorkQueueTest() : work_queue_( absl::make_unique<UnboundedWorkQueue>(Env::Default(), "test")) {} ~UnboundedWorkQueueTest() override = default; void RunMultipleCopiesOfClosure(const int num_closures, std::function<void()> fn) { for (int i = 0; i < num_closures; ++i) { work_queue_->Schedule([this, fn]() { fn(); mutex_lock l(mu_); ++closure_count_; cond_var_.notify_all(); }); } } void BlockUntilClosuresDone(const int num_closures) { mutex_lock l(mu_); while (closure_count_ < num_closures) { cond_var_.wait(l); } } void ResetQueue() { work_queue_.reset(); } int NumClosuresExecuted() { mutex_lock l(mu_); return closure_count_; } private: mutex mu_; int closure_count_ TF_GUARDED_BY(mu_) = 0; condition_variable cond_var_; std::unique_ptr<UnboundedWorkQueue> work_queue_; }; TEST_F(UnboundedWorkQueueTest, SingleClosure) { constexpr int num_closures = 1; RunMultipleCopiesOfClosure(num_closures, []() {}); BlockUntilClosuresDone(num_closures); } TEST_F(UnboundedWorkQueueTest, MultipleClosures) { constexpr int num_closures = 10; RunMultipleCopiesOfClosure(num_closures, []() {}); BlockUntilClosuresDone(num_closures); } TEST_F(UnboundedWorkQueueTest, MultipleClosuresSleepingRandomly) { constexpr int num_closures = 1000; RunMultipleCopiesOfClosure(num_closures, []() { Env::Default()->SleepForMicroseconds(random::New64() % 10); }); BlockUntilClosuresDone(num_closures); } TEST_F(UnboundedWorkQueueTest, NestedClosures) { constexpr int num_closures = 10; RunMultipleCopiesOfClosure(num_closures, [=]() { RunMultipleCopiesOfClosure(num_closures, []() {}); }); BlockUntilClosuresDone(num_closures * num_closures + num_closures); } TEST_F(UnboundedWorkQueueTest, RacyDestructor) { constexpr int num_closures = 100; RunMultipleCopiesOfClosure(num_closures, []() {}); ResetQueue(); EXPECT_LE(NumClosuresExecuted(), num_closures); } } }
2,289
#ifndef TENSORFLOW_TSL_PLATFORM_ROCM_ROCDL_PATH_H_ #define TENSORFLOW_TSL_PLATFORM_ROCM_ROCDL_PATH_H_ #include "tsl/platform/types.h" namespace tsl { string RocmRoot(); string RocdlRoot(); } #endif #include "tsl/platform/rocm_rocdl_path.h" #include <stdlib.h> #include "tsl/platform/path.h" #if !defined(PLATFORM_GOOGLE) && TENSORFLOW_USE_ROCM #include "rocm/rocm_config.h" #endif #include "tsl/platform/logging.h" namespace tsl { string RocmRoot() { #if TENSORFLOW_USE_ROCM if (const char* rocm_path_env = std::getenv("ROCM_PATH")) { VLOG(3) << "ROCM root = " << rocm_path_env; return rocm_path_env; } else { VLOG(3) << "ROCM root = " << TF_ROCM_TOOLKIT_PATH; return TF_ROCM_TOOLKIT_PATH; } #else return ""; #endif } string RocdlRoot() { return io::JoinPath(RocmRoot(), "amdgcn/bitcode"); } }
#include "tensorflow/core/platform/rocm_rocdl_path.h" #include "tensorflow/core/lib/core/status_test_util.h" #include "tensorflow/core/platform/env.h" #include "tensorflow/core/platform/path.h" #include "tensorflow/core/platform/test.h" #if !defined(PLATFORM_GOOGLE) && TENSORFLOW_USE_ROCM #include "rocm/rocm_config.h" #endif namespace tensorflow { #if TENSORFLOW_USE_ROCM TEST(RocmRocdlPathTest, ROCDLPath) { VLOG(2) << "ROCm-Device-Libs root = " << RocdlRoot(); std::vector<string> rocdl_files; TF_EXPECT_OK(Env::Default()->GetMatchingPaths( io::JoinPath(RocdlRoot(), "*.bc"), &rocdl_files)); EXPECT_LT(0, rocdl_files.size()); } #endif }
2,290
#ifndef TENSORFLOW_TSL_PLATFORM_DEFAULT_MUTEX_H_ #define TENSORFLOW_TSL_PLATFORM_DEFAULT_MUTEX_H_ namespace tsl { namespace internal { std::cv_status wait_until_system_clock( CVData *cv_data, MuData *mu_data, const std::chrono::system_clock::time_point timeout_time); } template <class Rep, class Period> std::cv_status condition_variable::wait_for( mutex_lock &lock, std::chrono::duration<Rep, Period> dur) { return tsl::internal::wait_until_system_clock( &this->cv_, &lock.mutex()->mu_, std::chrono::system_clock::now() + dur); } } #endif #include "tsl/platform/mutex.h" #include <time.h> #include "nsync_cv.h" #include "nsync_mu.h" #include "nsync_mu_wait.h" #include "nsync_time.h" namespace tsl { static_assert(sizeof(nsync::nsync_mu) <= sizeof(internal::MuData), "tsl::internal::MuData needs to be bigger"); static inline nsync::nsync_mu *mu_cast(internal::MuData *mu) { return reinterpret_cast<nsync::nsync_mu *>(mu); } mutex::mutex() { nsync::nsync_mu_init(mu_cast(&mu_)); } void mutex::lock() { nsync::nsync_mu_lock(mu_cast(&mu_)); } bool mutex::try_lock() { return nsync::nsync_mu_trylock(mu_cast(&mu_)) != 0; }; void mutex::unlock() { nsync::nsync_mu_unlock(mu_cast(&mu_)); } void mutex::lock_shared() { nsync::nsync_mu_rlock(mu_cast(&mu_)); } bool mutex::try_lock_shared() { return nsync::nsync_mu_rtrylock(mu_cast(&mu_)) != 0; }; void mutex::unlock_shared() { nsync::nsync_mu_runlock(mu_cast(&mu_)); } static int EvaluateCondition(const void *vcond) { return static_cast<int>(static_cast<const Condition *>(vcond)->Eval()); } void mutex::Await(const Condition &cond) { nsync::nsync_mu_wait(mu_cast(&mu_), &EvaluateCondition, &cond, nullptr); } bool mutex::AwaitWithDeadline(const Condition &cond, uint64 abs_deadline_ns) { time_t seconds = abs_deadline_ns / (1000 * 1000 * 1000); nsync::nsync_time abs_time = nsync::nsync_time_s_ns( seconds, abs_deadline_ns - seconds * (1000 * 1000 * 1000)); return nsync::nsync_mu_wait_with_deadline(mu_cast(&mu_), &EvaluateCondition, &cond, nullptr, abs_time, nullptr) == 0; } static_assert(sizeof(nsync::nsync_cv) <= sizeof(internal::CVData), "tsl::internal::CVData needs to be bigger"); static inline nsync::nsync_cv *cv_cast(internal::CVData *cv) { return reinterpret_cast<nsync::nsync_cv *>(cv); } condition_variable::condition_variable() { nsync::nsync_cv_init(cv_cast(&cv_)); } void condition_variable::wait(mutex_lock &lock) { nsync::nsync_cv_wait(cv_cast(&cv_), mu_cast(&lock.mutex()->mu_)); } void condition_variable::notify_one() { nsync::nsync_cv_signal(cv_cast(&cv_)); } void condition_variable::notify_all() { nsync::nsync_cv_broadcast(cv_cast(&cv_)); } namespace internal { std::cv_status wait_until_system_clock( CVData *cv_data, MuData *mu_data, const std::chrono::system_clock::time_point timeout_time) { int r = nsync::nsync_cv_wait_with_deadline(cv_cast(cv_data), mu_cast(mu_data), timeout_time, nullptr); return r ? std::cv_status::timeout : std::cv_status::no_timeout; } } }
#include "tsl/platform/mutex.h" #include "tsl/platform/test.h" #include "tsl/platform/threadpool.h" namespace tsl { namespace { class MutexTest : public ::testing::Test { protected: mutex_lock GetLock() TF_NO_THREAD_SAFETY_ANALYSIS { return mutex_lock{mu_}; } tf_shared_lock GetSharedLock() TF_NO_THREAD_SAFETY_ANALYSIS { return tf_shared_lock{mu_}; } bool test_try_lock() { bool test = mu_.try_lock(); if (test) mu_.unlock(); return test; } bool test_try_lock_shared() { bool test = mu_.try_lock_shared(); if (test) mu_.unlock_shared(); return test; } mutex mu_; }; TEST_F(MutexTest, MovableMutexLockTest) { EXPECT_TRUE(test_try_lock()); { mutex_lock lock = GetLock(); EXPECT_FALSE(test_try_lock()); EXPECT_FALSE(test_try_lock_shared()); } EXPECT_TRUE(test_try_lock()); } TEST_F(MutexTest, SharedMutexLockTest) { EXPECT_TRUE(test_try_lock()); { tf_shared_lock lock = GetSharedLock(); EXPECT_FALSE(test_try_lock()); EXPECT_TRUE(test_try_lock_shared()); } EXPECT_TRUE(test_try_lock()); } TEST(ConditionVariableTest, WaitWithPredicate) { constexpr int kNumThreads = 4; mutex mu; condition_variable cv; bool ready = false; int count = 0; tsl::thread::ThreadPool pool(Env::Default(), "condition_variable_test_wait_with_predicate", kNumThreads); for (int i = 0; i < kNumThreads; ++i) { pool.Schedule([&mu, &cv, &ready, &count]() { mutex_lock lock(mu); cv.wait(lock, [&ready] { return ready; }); ++count; cv.notify_one(); }); } { mutex_lock lock(mu); EXPECT_EQ(count, 0); } { mutex_lock lock(mu); ready = true; cv.notify_all(); } { mutex_lock lock(mu); cv.wait(lock, [&count, kNumThreads] { return count == kNumThreads; }); EXPECT_EQ(count, kNumThreads); } } TEST(ConditionVariableTest, WaitWithTruePredicateDoesntBlock) { mutex mu; mutex_lock lock(mu); condition_variable cv; cv.wait(lock, [] { return true; }); EXPECT_TRUE(static_cast<bool>(lock)); } } }
2,291
#ifndef TENSORFLOW_TSL_PROFILER_UTILS_PARSE_ANNOTATION_H_ #define TENSORFLOW_TSL_PROFILER_UTILS_PARSE_ANNOTATION_H_ #include <vector> #include "absl/strings/string_view.h" namespace tsl { namespace profiler { struct Annotation { absl::string_view name; struct Metadata { absl::string_view key; absl::string_view value; }; std::vector<Metadata> metadata; }; Annotation ParseAnnotation(absl::string_view annotation); inline bool HasMetadata(absl::string_view annotation) { constexpr char kUserMetadataMarker = '#'; return !annotation.empty() && annotation.back() == kUserMetadataMarker; } std::vector<Annotation> ParseAnnotationStack( absl::string_view annotation_stack); } } #endif #include "tsl/profiler/utils/parse_annotation.h" #include <stack> #include <string> #include <utility> #include <vector> #include "absl/strings/ascii.h" #include "absl/strings/str_split.h" #include "absl/strings/string_view.h" namespace tsl { namespace profiler { namespace { std::vector<absl::string_view> SplitNameAndMetadata( absl::string_view annotation) { std::vector<absl::string_view> parts; if (!HasMetadata(annotation)) { parts.emplace_back(annotation); } else { annotation.remove_suffix(1); parts = absl::StrSplit(annotation, '#'); if (parts.size() > 2) { parts.resize(2); } } while (parts.size() < 2) { parts.emplace_back(); } return parts; } std::vector<absl::string_view> SplitPairs(absl::string_view metadata) { std::vector<absl::string_view> key_value_pairs; std::stack<char> quotes; size_t start = 0, end = 0; for (; end < metadata.size(); ++end) { char ch = metadata[end]; switch (ch) { case '\"': case '\'': if (quotes.empty() || quotes.top() != ch) { quotes.push(ch); } else { quotes.pop(); } break; case '{': case '(': case '[': quotes.push(ch); break; case '}': if (!quotes.empty() && quotes.top() == '{') { quotes.pop(); } break; case ')': if (!quotes.empty() && quotes.top() == '(') { quotes.pop(); } break; case ']': if (!quotes.empty() && quotes.top() == '[') { quotes.pop(); } break; case ',': if (quotes.empty()) { if (end - start > 1) { key_value_pairs.emplace_back(metadata.data() + start, end - start); } start = end + 1; } break; } } if (end - start > 1) { key_value_pairs.emplace_back(metadata.data() + start, end - start); } return key_value_pairs; } std::vector<std::pair<absl::string_view, absl::string_view>> ParseMetadata( absl::string_view metadata) { std::vector<std::pair<absl::string_view, absl::string_view>> key_values; for (absl::string_view pair : SplitPairs(metadata)) { std::vector<absl::string_view> parts = absl::StrSplit(pair, absl::MaxSplits('=', 1)); if (parts.size() == 2) { absl::string_view key = absl::StripAsciiWhitespace(parts[0]); absl::string_view value = absl::StripAsciiWhitespace(parts[1]); if (!key.empty() && !value.empty()) { key_values.push_back({key, value}); } } } return key_values; } } Annotation ParseAnnotation(absl::string_view annotation) { Annotation result; std::vector<absl::string_view> parts = SplitNameAndMetadata(annotation); if (!parts.empty()) { result.name = absl::StripAsciiWhitespace(parts[0]); for (const auto& key_value : ParseMetadata(parts[1])) { result.metadata.push_back({key_value.first, key_value.second}); } } return result; } std::vector<Annotation> ParseAnnotationStack( absl::string_view annotation_stack) { std::vector<Annotation> annotations; const std::string kAnnotationDelimiter = "::"; for (absl::string_view annotation : absl::StrSplit( annotation_stack, kAnnotationDelimiter, absl::SkipEmpty())) { annotations.emplace_back(ParseAnnotation(annotation)); } return annotations; } } }
#include "tsl/profiler/utils/parse_annotation.h" #include <vector> #include "absl/strings/string_view.h" #include "tsl/platform/test.h" namespace tsl { namespace profiler { namespace { TEST(ParseAnnotationStackTest, EmptyAnnotationStackTest) { std::vector<Annotation> annotations = ParseAnnotationStack(""); ASSERT_TRUE(annotations.empty()); } TEST(ParseAnnotationStackTest, SingleAnnotationStackTest) { std::vector<Annotation> annotations = ParseAnnotationStack("name"); ASSERT_FALSE(annotations.empty()); EXPECT_EQ(annotations.back().name, "name"); EXPECT_TRUE(annotations.back().metadata.empty()); } TEST(ParseAnnotationStackTest, MultiLevelAnnotationStackTest) { std::vector<Annotation> annotations = ParseAnnotationStack("outer::inner"); ASSERT_EQ(annotations.size(), 2); EXPECT_EQ(annotations.front().name, "outer"); EXPECT_TRUE(annotations.front().metadata.empty()); EXPECT_EQ(annotations.back().name, "inner"); EXPECT_TRUE(annotations.back().metadata.empty()); } TEST(ParseAnnotationTest, EmptyAnnotationTest) { Annotation annotation = ParseAnnotation(""); EXPECT_TRUE(annotation.name.empty()); EXPECT_TRUE(annotation.metadata.empty()); } TEST(ParseAnnotationTest, SimpleNameTest) { Annotation annotation = ParseAnnotation("name"); EXPECT_EQ(annotation.name, "name"); EXPECT_TRUE(annotation.metadata.empty()); } TEST(ParseAnnotationTest, SimpleNameWithWhitespaceTest) { Annotation annotation = ParseAnnotation("name "); EXPECT_EQ(annotation.name, "name"); EXPECT_TRUE(annotation.metadata.empty()); } TEST(ParseAnnotationTest, EmptyMetadataTest) { Annotation annotation = ParseAnnotation("name#"); EXPECT_EQ(annotation.name, "name"); EXPECT_TRUE(annotation.metadata.empty()); annotation = ParseAnnotation("name1##"); EXPECT_EQ(annotation.name, "name1"); EXPECT_TRUE(annotation.metadata.empty()); annotation = ParseAnnotation("name2###"); EXPECT_EQ(annotation.name, "name2"); EXPECT_TRUE(annotation.metadata.empty()); } TEST(ParseAnnotationTest, SingleMetadataTest) { Annotation annotation = ParseAnnotation("name#key=value#"); EXPECT_EQ(annotation.name, "name"); ASSERT_EQ(annotation.metadata.size(), 1); EXPECT_EQ(annotation.metadata.at(0).key, "key"); EXPECT_EQ(annotation.metadata.at(0).value, "value"); } TEST(ParseAnnotationTest, MultipleMetadataTest) { Annotation annotation = ParseAnnotation("name#k1=v1,k2=v2,k3=v3#"); EXPECT_EQ(annotation.name, "name"); ASSERT_EQ(annotation.metadata.size(), 3); EXPECT_EQ(annotation.metadata.at(0).key, "k1"); EXPECT_EQ(annotation.metadata.at(0).value, "v1"); EXPECT_EQ(annotation.metadata.at(1).key, "k2"); EXPECT_EQ(annotation.metadata.at(1).value, "v2"); EXPECT_EQ(annotation.metadata.at(2).key, "k3"); EXPECT_EQ(annotation.metadata.at(2).value, "v3"); } TEST(ParseAnnotationTest, MultipleMetadataWithWhitespaceTest) { Annotation annotation = ParseAnnotation("name # k1 = v1, ,k2=v2 #"); EXPECT_EQ(annotation.name, "name"); ASSERT_EQ(annotation.metadata.size(), 2); EXPECT_EQ(annotation.metadata.at(0).key, "k1"); EXPECT_EQ(annotation.metadata.at(0).value, "v1"); EXPECT_EQ(annotation.metadata.at(1).key, "k2"); EXPECT_EQ(annotation.metadata.at(1).value, "v2"); } TEST(ParseAnnotationTest, KeyValueSeparatorTest) { Annotation annotation = ParseAnnotation("name#=v1,k2=,k3==v3,k4=v4=#"); EXPECT_EQ(annotation.name, "name"); ASSERT_EQ(annotation.metadata.size(), 2); EXPECT_EQ(annotation.metadata.at(0).key, "k3"); EXPECT_EQ(annotation.metadata.at(0).value, "=v3"); EXPECT_EQ(annotation.metadata.at(1).key, "k4"); EXPECT_EQ(annotation.metadata.at(1).value, "v4="); } TEST(ParseAnnotationTest, ExtraMetadataSeparatorTest) { Annotation annotation = ParseAnnotation("name##k1=v1#"); EXPECT_EQ(annotation.name, "name"); EXPECT_TRUE(annotation.metadata.empty()); } TEST(ParseAnnotationTest, QuotedMetadata) { Annotation annotation = ParseAnnotation( "name#k1=(v11,v12),k2=[v21,v22,v23],k3={v31,v32}, k4=\"v41,v42\"," "(k51,k52)='v51,v52'#"); EXPECT_EQ(annotation.metadata.at(0).key, "k1"); EXPECT_EQ(annotation.metadata.at(0).value, "(v11,v12)"); EXPECT_EQ(annotation.metadata.at(1).key, "k2"); EXPECT_EQ(annotation.metadata.at(1).value, "[v21,v22,v23]"); EXPECT_EQ(annotation.metadata.at(2).key, "k3"); EXPECT_EQ(annotation.metadata.at(2).value, "{v31,v32}"); EXPECT_EQ(annotation.metadata.at(3).key, "k4"); EXPECT_EQ(annotation.metadata.at(3).value, "\"v41,v42\""); EXPECT_EQ(annotation.metadata.at(4).key, "(k51,k52)"); EXPECT_EQ(annotation.metadata.at(4).value, "'v51,v52'"); } TEST(ParseAnnotationTest, UnmatchedQuotedMetadata) { Annotation annotation = ParseAnnotation("name#k1=v1,k2=(v2,k3=v3#"); EXPECT_EQ(annotation.metadata.at(0).key, "k1"); EXPECT_EQ(annotation.metadata.at(0).value, "v1"); EXPECT_EQ(annotation.metadata.at(1).key, "k2"); EXPECT_EQ(annotation.metadata.at(1).value, "(v2,k3=v3"); } } } }
2,292
#ifndef TENSORFLOW_TSL_PROFILER_UTILS_XPLANE_UTILS_H_ #define TENSORFLOW_TSL_PROFILER_UTILS_XPLANE_UTILS_H_ #include <algorithm> #include <cstdint> #include <optional> #include <vector> #include "absl/algorithm/container.h" #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "absl/strings/string_view.h" #include "tsl/platform/types.h" #include "tsl/profiler/protobuf/xplane.pb.h" #include "tsl/profiler/utils/timespan.h" #include "tsl/profiler/utils/trace_utils.h" #include "tsl/profiler/utils/xplane_visitor.h" namespace tsl { namespace profiler { inline Timespan XEventTimespan(const XEvent& event) { return Timespan(event.offset_ps(), event.duration_ps()); } template <typename F> std::vector<const XPlane*> FindPlanes(const XSpace& space, const F& predicate) { std::vector<const XPlane*> result; for (const XPlane& plane : space.planes()) { if (predicate(plane)) { result.push_back(&plane); } } return result; } template <typename F> std::vector<XPlane*> FindMutablePlanes(XSpace* space, const F& predicate) { std::vector<XPlane*> result; for (XPlane& plane : *space->mutable_planes()) { if (predicate(plane)) { result.push_back(&plane); } } return result; } const XPlane* FindPlaneWithName(const XSpace& space, absl::string_view name); XPlane* FindMutablePlaneWithName(XSpace* space, absl::string_view name); std::vector<const XPlane*> FindPlanesWithNames( const XSpace& space, const std::vector<absl::string_view>& names); XPlane* FindOrAddMutablePlaneWithName(XSpace* space, absl::string_view name); std::vector<const XPlane*> FindPlanesWithPrefix(const XSpace& space, absl::string_view prefix); std::vector<XPlane*> FindMutablePlanesWithPrefix(XSpace* space, absl::string_view prefix); const XLine* FindLineWithId(const XPlane& plane, int64_t id); std::vector<const XLine*> FindLinesWithId(const XPlane& plane, int64_t id); const XLine* FindLineWithName(const XPlane& plane, absl::string_view name); XStat* FindOrAddMutableStat(const XStatMetadata& stat_metadata, XEvent* event); void RemovePlane(XSpace* space, const XPlane* plane); void RemovePlanes(XSpace* space, const std::vector<const XPlane*>& planes); void RemoveLine(XPlane* plane, const XLine* line); void RemoveEvents(XLine* line, const absl::flat_hash_set<const XEvent*>& events); void RemoveEmptyPlanes(XSpace* space); void RemoveEmptyLines(XPlane* plane); template <class Compare> void SortXLinesBy(XPlane* plane, Compare comp) { std::sort(plane->mutable_lines()->pointer_begin(), plane->mutable_lines()->pointer_end(), comp); } class XLinesComparatorByName { public: bool operator()(const XLine* a, const XLine* b) const { auto& line_a = a->display_name().empty() ? a->name() : a->display_name(); auto& line_b = b->display_name().empty() ? b->name() : b->display_name(); return line_a < line_b; } }; void SortXPlane(XPlane* plane); void SortXSpace(XSpace* space); struct XEventsComparator { bool operator()(const XEvent* a, const XEvent* b) const; }; template <typename Event, typename Plane> inline std::vector<Event> GetSortedEvents(Plane& plane, bool include_derived_events = false) { std::vector<Event> events; plane.ForEachLine([&events, include_derived_events](auto line) { if (!include_derived_events && IsDerivedThreadId(line.Id())) return; line.ForEachEvent( [&events](auto event) { events.emplace_back(std::move(event)); }); }); absl::c_sort(events); return events; } void NormalizeTimestamps(XPlane* plane, uint64 start_time_ns); void NormalizeTimestamps(XSpace* space, uint64 start_time_ns); void MergePlanes(const XPlane& src_plane, XPlane* dst_plane); void MergePlanes(const std::vector<const XPlane*>& src_planes, XPlane* dst_plane); int64_t GetStartTimestampNs(const XPlane& plane); bool IsEmpty(const XSpace& space); bool IsXSpaceGrouped(const XSpace& space); void AddFlowsToXplane(int32_t host_id, bool is_host_plane, bool connect_traceme, XPlane* plane); uint64_t GetDevicePlaneFingerprint(const XPlane& plane); template <typename XPlanePointerIterator> void SortPlanesById(XPlanePointerIterator begin, XPlanePointerIterator end) { std::sort(begin, end, [&](const XPlane* a, const XPlane* b) { return a->id() < b->id(); }); } class XEventContextTracker { public: XEventContextTracker(const XPlaneVisitor* plane, const XLine* line) : plane_(plane), line_(line) {} std::optional<XEventVisitor> GetContainingEvent(const Timespan& event); std::optional<XEventVisitor> GetOverlappingEvent(const Timespan& event); private: const XPlaneVisitor* plane_; const XLine* line_; int64_t current_index_ = -1; }; void AggregateXPlane(const XPlane& full_trace, XPlane& aggregated_trace); bool IsCustomPlane(const XPlane& plane); bool IsHostPlane(const XPlane& plane); bool IsDevicePlane(const XPlane& plane); } } #endif #include "tsl/profiler/utils/xplane_utils.h" #include <algorithm> #include <cstdint> #include <limits> #include <optional> #include <set> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "absl/log/log.h" #include "absl/strings/match.h" #include "absl/strings/string_view.h" #include "xla/tsl/util/stats_calculator.h" #include "tsl/platform/fingerprint.h" #include "tsl/platform/types.h" #include "tsl/profiler/lib/context_types.h" #include "tsl/profiler/protobuf/xplane.pb.h" #include "tsl/profiler/utils/math_utils.h" #include "tsl/profiler/utils/tf_xplane_visitor.h" #include "tsl/profiler/utils/timespan.h" #include "tsl/profiler/utils/xplane_builder.h" #include "tsl/profiler/utils/xplane_schema.h" #include "tsl/profiler/utils/xplane_visitor.h" namespace tsl { namespace profiler { namespace { template <typename T, typename Pred> std::vector<int> FindAll(const protobuf::RepeatedPtrField<T>& array, const Pred& pred) { std::vector<int> indices; for (int i = 0; i < array.size(); ++i) { if (pred(&array.Get(i))) indices.push_back(i); } return indices; } template <typename T, typename Pred> int Find(const protobuf::RepeatedPtrField<T>& array, const Pred& pred) { std::vector<int> indices = FindAll(array, pred); if (indices.size() > 1) { LOG(WARNING) << "Found multiple " << T().GetTypeName() << " when only one was expected."; } return indices.empty() ? -1 : indices.front(); } template <typename T> void RemoveAt(protobuf::RepeatedPtrField<T>* array, const std::vector<int>& indices) { if (indices.empty()) return; if (array->size() == indices.size()) { array->Clear(); return; } auto remove_iter = indices.begin(); int i = *(remove_iter++); for (int j = i + 1; j < array->size(); ++j) { if (remove_iter != indices.end() && *remove_iter == j) { ++remove_iter; } else { array->SwapElements(j, i++); } } array->DeleteSubrange(i, array->size() - i); } template <typename T> void Remove(protobuf::RepeatedPtrField<T>* array, const T* elem) { int i = Find(*array, [elem](const T* e) { return elem == e; }); RemoveAt(array, {i}); } template <typename T, typename Pred> void RemoveIf(protobuf::RepeatedPtrField<T>* array, Pred&& pred) { std::vector<int> indices = FindAll(*array, pred); RemoveAt(array, indices); } void CopyEventMetadata(const XEventMetadata& src_event_metadata, const XPlaneVisitor& src_plane, XEventMetadata& dst_event_metadata, XPlaneBuilder& dst_plane) { if (dst_event_metadata.display_name().empty() && !src_event_metadata.display_name().empty()) { dst_event_metadata.set_display_name(src_event_metadata.display_name()); } if (dst_event_metadata.name().empty() && !src_event_metadata.name().empty()) { dst_event_metadata.set_name(src_event_metadata.name()); } if (dst_event_metadata.metadata().empty() && !src_event_metadata.metadata().empty()) { dst_event_metadata.set_metadata(src_event_metadata.metadata()); } if (dst_event_metadata.stats().empty() && !src_event_metadata.stats().empty()) { XEventMetadataVisitor src_event_metadata_visitor(&src_plane, &src_event_metadata); src_event_metadata_visitor.ForEachStat([&](const XStatVisitor& src_stat) { XStatMetadata& metadata = *dst_plane.GetOrCreateStatMetadata(src_stat.Name()); XStat& dst_stat = *dst_event_metadata.add_stats(); dst_stat = src_stat.RawStat(); if (src_stat.ValueCase() == XStat::kRefValue) { XStatMetadata& value_metadata = *dst_plane.GetOrCreateStatMetadata(src_stat.StrOrRefValue()); dst_stat.set_ref_value(value_metadata.id()); } dst_stat.set_metadata_id(metadata.id()); }); } DCHECK_EQ(src_event_metadata.stats_size(), dst_event_metadata.stats_size()); } void CopyEvent(const XEventVisitor& src_event, const XPlaneVisitor& src, const XPlane& src_plane, int64_t time_offset_ps, XPlaneBuilder& dst_plane, XLineBuilder& dst_line) { XEventMetadata* dst_event_metadata = dst_plane.GetOrCreateEventMetadata(src_event.Name()); CopyEventMetadata(*src_event.metadata(), src, *dst_event_metadata, dst_plane); XEventBuilder dst_event = dst_line.AddEvent(*dst_event_metadata); if (src_event.IsAggregatedEvent()) { dst_event.SetNumOccurrences(src_event.NumOccurrences()); } else { dst_event.SetOffsetPs(src_event.OffsetPs() + time_offset_ps); } dst_event.SetDurationPs(src_event.DurationPs()); src_event.ForEachStat([&](const XStatVisitor& stat) { dst_event.AddStat(*dst_plane.GetOrCreateStatMetadata(stat.Name()), stat.RawStat(), src_plane); }); } bool IsOpLineName(absl::string_view line_name) { return line_name == kXlaOpLineName || line_name == kTensorFlowOpLineName; } } const XPlane* FindPlaneWithName(const XSpace& space, absl::string_view name) { int i = Find(space.planes(), [name](const XPlane* plane) { return plane->name() == name; }); return (i != -1) ? &space.planes(i) : nullptr; } std::vector<const XPlane*> FindPlanesWithNames( const XSpace& space, const std::vector<absl::string_view>& names) { absl::flat_hash_set<absl::string_view> names_set(names.begin(), names.end()); std::vector<int> indices = FindAll(space.planes(), [&names_set](const XPlane* plane) { return names_set.contains(plane->name()); }); std::vector<const XPlane*> planes; planes.reserve(indices.size()); for (int i : indices) { planes.push_back(&space.planes(i)); } return planes; } XPlane* FindMutablePlaneWithName(XSpace* space, absl::string_view name) { int i = Find(space->planes(), [name](const XPlane* plane) { return plane->name() == name; }); return (i != -1) ? space->mutable_planes(i) : nullptr; } XPlane* FindOrAddMutablePlaneWithName(XSpace* space, absl::string_view name) { XPlane* plane = FindMutablePlaneWithName(space, name); if (plane == nullptr) { plane = space->add_planes(); plane->set_name(name.data(), name.size()); } return plane; } std::vector<const XPlane*> FindPlanesWithPrefix(const XSpace& space, absl::string_view prefix) { return FindPlanes(space, [&](const XPlane& plane) { return absl::StartsWith(plane.name(), prefix); }); } std::vector<XPlane*> FindMutablePlanesWithPrefix(XSpace* space, absl::string_view prefix) { return FindMutablePlanes(space, [&](XPlane& plane) { return absl::StartsWith(plane.name(), prefix); }); } const XLine* FindLineWithId(const XPlane& plane, int64_t id) { int i = Find(plane.lines(), [id](const XLine* line) { return line->id() == id; }); return (i != -1) ? &plane.lines(i) : nullptr; } std::vector<const XLine*> FindLinesWithId(const XPlane& plane, int64_t id) { std::vector<int> indices = FindAll( plane.lines(), [id](const XLine* line) { return line->id() == id; }); std::vector<const XLine*> lines; lines.reserve(indices.size()); for (int index : indices) { lines.push_back(&plane.lines(index)); } return lines; } const XLine* FindLineWithName(const XPlane& plane, absl::string_view name) { int i = Find(plane.lines(), [name](const XLine* line) { return line->name() == name; }); return (i != -1) ? &plane.lines(i) : nullptr; } XStat* FindOrAddMutableStat(const XStatMetadata& stat_metadata, XEvent* event) { for (auto& stat : *event->mutable_stats()) { if (stat.metadata_id() == stat_metadata.id()) { return &stat; } } XStat* stat = event->add_stats(); stat->set_metadata_id(stat_metadata.id()); return stat; } void RemovePlane(XSpace* space, const XPlane* plane) { DCHECK(plane != nullptr); Remove(space->mutable_planes(), plane); } void RemovePlanes(XSpace* space, const std::vector<const XPlane*>& planes) { absl::flat_hash_set<const XPlane*> planes_set(planes.begin(), planes.end()); RemoveIf(space->mutable_planes(), [&planes_set](const XPlane* plane) { return planes_set.contains(plane); }); } void RemoveLine(XPlane* plane, const XLine* line) { DCHECK(line != nullptr); Remove(plane->mutable_lines(), line); } void RemoveEvents(XLine* line, const absl::flat_hash_set<const XEvent*>& events) { RemoveIf(line->mutable_events(), [&](const XEvent* event) { return events.contains(event); }); } void RemoveEmptyPlanes(XSpace* space) { RemoveIf(space->mutable_planes(), [&](const XPlane* plane) { return plane->lines().empty(); }); } void RemoveEmptyLines(XPlane* plane) { RemoveIf(plane->mutable_lines(), [&](const XLine* line) { return line->events().empty(); }); } bool XEventsComparator::operator()(const XEvent* a, const XEvent* b) const { return XEventTimespan(*a) < XEventTimespan(*b); } void SortXPlane(XPlane* plane) { for (XLine& line : *plane->mutable_lines()) { auto& events = *line.mutable_events(); std::sort(events.pointer_begin(), events.pointer_end(), XEventsComparator()); } } void SortXSpace(XSpace* space) { for (XPlane& plane : *space->mutable_planes()) SortXPlane(&plane); } void NormalizeTimestamps(XPlane* plane, uint64 start_time_ns) { for (XLine& line : *plane->mutable_lines()) { if (line.timestamp_ns() >= static_cast<int64_t>(start_time_ns)) { line.set_timestamp_ns(line.timestamp_ns() - start_time_ns); } } } void NormalizeTimestamps(XSpace* space, uint64 start_time_ns) { for (XPlane& plane : *space->mutable_planes()) { NormalizeTimestamps(&plane, start_time_ns); } } void MergePlanes(const XPlane& src_plane, XPlane* dst_plane) { RemoveEmptyLines(dst_plane); XPlaneVisitor src(&src_plane); XPlaneBuilder dst(dst_plane); src.ForEachStat([&](const XStatVisitor& stat) { XStatMetadata* stat_metadata = dst.GetOrCreateStatMetadata(stat.Name()); dst.SetOrAddStat(*stat_metadata, stat.RawStat(), src_plane); }); src.ForEachLine([&](const XLineVisitor& line) { XLineBuilder dst_line = dst.GetOrCreateLine(line.Id()); int64_t time_offset_ps = 0LL; if (dst_line.NumEvents() == 0) { dst_line.SetTimestampNs(line.TimestampNs()); dst_line.SetName(line.Name()); dst_line.SetDisplayNameIfEmpty(line.DisplayName()); } else { if (line.TimestampNs() <= dst_line.TimestampNs()) { dst_line.SetTimestampNsAndAdjustEventOffsets(line.TimestampNs()); } else { time_offset_ps = NanoToPico(line.TimestampNs() - dst_line.TimestampNs()); } dst_line.SetNameIfEmpty(line.Name()); } line.ForEachEvent([&](const XEventVisitor& event) { CopyEvent(event, src, src_plane, time_offset_ps, dst, dst_line); }); }); } void MergePlanes(const std::vector<const XPlane*>& src_planes, XPlane* dst_plane) { for (const XPlane* src_plane : src_planes) { MergePlanes(*src_plane, dst_plane); } } int64_t GetStartTimestampNs(const XPlane& plane) { if (plane.lines().empty()) return 0LL; int64_t plane_timestamp = std::numeric_limits<int64_t>::max(); for (const auto& line : plane.lines()) { plane_timestamp = std::min(plane_timestamp, line.timestamp_ns()); } return plane_timestamp; } bool IsEmpty(const XSpace& space) { for (const auto& plane : space.planes()) { for (const auto& line : plane.lines()) { if (!line.events().empty()) { return false; } } } return true; } bool IsXSpaceGrouped(const XSpace& space) { for (const auto& plane : space.planes()) { XPlaneVisitor xplane = tsl::profiler::CreateTfXPlaneVisitor(&plane); const XStatMetadata* group_id_stat = xplane.GetStatMetadataByType(StatType::kGroupId); if (group_id_stat) return true; } return false; } void AddFlowsToXplane(int32_t host_id, bool is_host_plane, bool connect_traceme, XPlane* xplane) { if (!xplane) return; XPlaneBuilder plane(xplane); XStatMetadata* correlation_id_stats_metadata = plane.GetStatMetadata(GetStatTypeStr(StatType::kCorrelationId)); XStatMetadata* producer_type_stats_metadata = plane.GetStatMetadata(GetStatTypeStr(StatType::kProducerType)); XStatMetadata* consumer_type_stats_metadata = plane.GetStatMetadata(GetStatTypeStr(StatType::kConsumerType)); XStatMetadata* producer_id_stats_metadata = plane.GetStatMetadata(GetStatTypeStr(StatType::kProducerId)); XStatMetadata* consumer_id_stats_metadata = plane.GetStatMetadata(GetStatTypeStr(StatType::kConsumerId)); XStatMetadata* flow_stats_metadata = plane.GetOrCreateStatMetadata(GetStatTypeStr(StatType::kFlow)); XFlow::FlowDirection direction = is_host_plane ? XFlow::FlowDirection::kFlowOut : XFlow::FlowDirection::kFlowIn; plane.ForEachLine([&](XLineBuilder line) { line.ForEachEvent([&](XEventBuilder event) { std::optional<uint64_t> correlation_id; std::optional<uint64_t> producer_type; std::optional<uint64_t> consumer_type; std::optional<uint64_t> producer_id; std::optional<uint64_t> consumer_id; event.ForEachStat([&](XStat* stat) { if (correlation_id_stats_metadata && stat->metadata_id() == correlation_id_stats_metadata->id()) { correlation_id = stat->uint64_value(); } else if (connect_traceme) { if (producer_type_stats_metadata && stat->metadata_id() == producer_type_stats_metadata->id()) { producer_type = XStatsBuilder<XPlane>::IntOrUintValue(*stat); } else if (consumer_type_stats_metadata && stat->metadata_id() == consumer_type_stats_metadata->id()) { consumer_type = XStatsBuilder<XPlane>::IntOrUintValue(*stat); } else if (producer_id_stats_metadata && stat->metadata_id() == producer_id_stats_metadata->id()) { producer_id = XStatsBuilder<XPlane>::IntOrUintValue(*stat); } else if (consumer_id_stats_metadata && stat->metadata_id() == consumer_id_stats_metadata->id()) { consumer_id = XStatsBuilder<XPlane>::IntOrUintValue(*stat); } } }); if (correlation_id) { XFlow flow(XFlow::GetFlowId(host_id, *correlation_id), direction, ContextType::kGpuLaunch); event.AddStatValue(*flow_stats_metadata, flow.ToStatValue()); } if (connect_traceme) { if (producer_type && producer_id) { auto context_type = GetSafeContextType(*producer_type); XFlow flow(XFlow::GetFlowId(host_id, *producer_id, context_type), XFlow::FlowDirection::kFlowOut, context_type); event.AddStatValue(*flow_stats_metadata, flow.ToStatValue()); } if (consumer_type && consumer_id) { auto context_type = GetSafeContextType(*consumer_type); XFlow flow(XFlow::GetFlowId(host_id, *consumer_id, context_type), XFlow::FlowDirection::kFlowIn, context_type); event.AddStatValue(*flow_stats_metadata, flow.ToStatValue()); } } }); }); } uint64_t GetDevicePlaneFingerprint(const XPlane& plane) { const XLine* xla_module_line = FindLineWithName(plane, kXlaModuleLineName); if (!xla_module_line) return 0ULL; XPlaneVisitor xplane(&plane); XLineVisitor xline(&xplane, xla_module_line); std::set<uint64_t> ordered_module_fps; xline.ForEachEvent([&](const XEventVisitor& xevent) { ordered_module_fps.insert(Fingerprint64(xevent.Name())); }); if (ordered_module_fps.empty()) return 0ULL; uint64_t output = 0ULL; for (const auto& fp : ordered_module_fps) { output = FingerprintCat64(output, fp); } return output; } std::optional<XEventVisitor> XEventContextTracker::GetContainingEvent( const Timespan& event) { if (!line_) return std::nullopt; if (current_index_ != -1) { XEventVisitor current_event(plane_, line_, &line_->events(current_index_)); if (current_event.GetTimespan().Includes(event)) { return current_event; } } for (int i = current_index_ + 1; i < line_->events_size(); ++i) { XEventVisitor current_event(plane_, line_, &line_->events(i)); if (current_event.TimestampPs() > event.end_ps()) break; if (current_event.EndTimestampPs() < event.begin_ps()) continue; current_index_ = i; if (current_event.GetTimespan().Includes(event)) { return current_event; } break; } return std::nullopt; } std::optional<XEventVisitor> XEventContextTracker::GetOverlappingEvent( const Timespan& event) { if (!line_) return std::nullopt; if (current_index_ != -1) { XEventVisitor current_event(plane_, line_, &line_->events(current_index_)); if (current_event.GetTimespan().Overlaps(event)) { return current_event; } } for (int i = current_index_ + 1; i < line_->events_size(); ++i) { XEventVisitor current_event(plane_, line_, &line_->events(i)); if (current_event.TimestampPs() > event.end_ps()) break; if (current_event.EndTimestampPs() < event.begin_ps()) continue; current_index_ = i; if (current_event.GetTimespan().Overlaps(event)) { return current_event; } break; } return std::nullopt; } void AggregateXPlane(const XPlane& full_trace, XPlane& aggregated_trace) { struct EventStat { tsl::Stat<int64_t> stat; int64_t children_duration; }; using StatByEvent = absl::flat_hash_map<int64_t , EventStat>; using StatByGroup = absl::flat_hash_map<int64_t , StatByEvent>; absl::flat_hash_map<int64_t , StatByGroup> stats; const XPlaneVisitor& plane = CreateTfXPlaneVisitor(&full_trace); XPlaneBuilder aggregated_plane(&aggregated_trace); aggregated_plane.SetName(plane.Name()); uint64_t first_op_start_ps = kint64max; uint64_t last_op_end_ps = 0; plane.ForEachLine([&](const XLineVisitor& line) { if (line.Name() == kStepLineName) { XLineBuilder aggregated_line = aggregated_plane.GetOrCreateLine(line.Id()); aggregated_line.SetName(kStepLineName); line.ForEachEvent([&](const XEventVisitor& event) { CopyEvent(event, plane, full_trace, 0LL, aggregated_plane, aggregated_line); }); } if (!IsOpLineName(line.Name())) return; XLineBuilder aggregated_line = aggregated_plane.GetOrCreateLine(line.Id()); aggregated_line.SetName(line.Name()); std::vector<XEventVisitor> event_stack; line.ForEachEvent([&](XEventVisitor event) { first_op_start_ps = first_op_start_ps <= event.TimestampPs() ? first_op_start_ps : event.TimestampPs(); last_op_end_ps = last_op_end_ps >= event.EndTimestampPs() ? last_op_end_ps : event.EndTimestampPs(); const auto& group_stat = event.GetStat(StatType::kGroupId); int64_t group_id = group_stat.has_value() ? group_stat->IntOrUintValue() : kint64max; StatByEvent& line_stats = stats[line.Id()][group_id]; line_stats[event.Id()].stat.UpdateStat(event.DurationPs()); DCHECK(event_stack.empty() || !(event < event_stack.back())); while (!event_stack.empty() && !event_stack.back().GetTimespan().Includes(event.GetTimespan())) { event_stack.pop_back(); } if (!event_stack.empty()) { line_stats[event_stack.back().Id()].children_duration += event.DurationPs(); } event_stack.push_back(std::move(event)); }); }); uint64_t total_time_ps = (last_op_end_ps && last_op_end_ps > first_op_start_ps) ? last_op_end_ps - first_op_start_ps : 0; aggregated_plane.AddStatValue( *aggregated_plane.GetOrCreateStatMetadata( GetStatTypeStr(StatType::kTotalProfileDurationPs)), total_time_ps); XStatMetadata* kMinDurationPs = aggregated_plane.GetOrCreateStatMetadata( GetStatTypeStr(StatType::kMinDurationPs)); XStatMetadata* kSelfDurationPs = aggregated_plane.GetOrCreateStatMetadata( GetStatTypeStr(StatType::kSelfDurationPs)); XStatMetadata* kGroupId = aggregated_plane.GetOrCreateStatMetadata( GetStatTypeStr(StatType::kGroupId)); for (const auto& [line_id, stats_by_group] : stats) { XLineBuilder aggregated_line = aggregated_plane.GetOrCreateLine(line_id); for (const auto& [group_id, stat_by_event] : stats_by_group) { for (const auto& [event_id, event_stat] : stat_by_event) { XEventMetadata& event_metadata = *aggregated_plane.GetOrCreateEventMetadata(event_id); CopyEventMetadata(*plane.GetEventMetadata(event_id), plane, event_metadata, aggregated_plane); XEventBuilder aggregated_event = aggregated_line.AddEvent(event_metadata); aggregated_event.SetNumOccurrences(event_stat.stat.count()); aggregated_event.SetDurationPs(event_stat.stat.sum()); if (group_id != kint64max) { aggregated_event.AddStatValue(*kGroupId, group_id); } if (event_stat.stat.count() > 1) { aggregated_event.AddStatValue(*kMinDurationPs, event_stat.stat.min()); } if (event_stat.children_duration != 0) { aggregated_event.AddStatValue(
#include "tsl/profiler/utils/xplane_utils.h" #include <cstdint> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "tsl/platform/test.h" #include "tsl/platform/types.h" #include "tsl/profiler/protobuf/xplane.pb.h" #include "tsl/profiler/utils/math_utils.h" #include "tsl/profiler/utils/tf_xplane_visitor.h" #include "tsl/profiler/utils/xplane_builder.h" #include "tsl/profiler/utils/xplane_schema.h" #include "tsl/profiler/utils/xplane_visitor.h" namespace tsl { namespace profiler { namespace { using ::testing::Property; using ::testing::SizeIs; using ::testing::UnorderedElementsAre; #if defined(PLATFORM_GOOGLE) using ::testing::EqualsProto; using ::testing::proto::IgnoringRepeatedFieldOrdering; using ::testing::proto::Partially; #endif XEvent CreateEvent(int64_t offset_ps, int64_t duration_ps) { XEvent event; event.set_offset_ps(offset_ps); event.set_duration_ps(duration_ps); return event; } TEST(XPlaneUtilsTest, AddAndRemovePlanes) { XSpace space; auto* p1 = FindOrAddMutablePlaneWithName(&space, "p1"); EXPECT_EQ(p1, FindPlaneWithName(space, "p1")); auto* p2 = FindOrAddMutablePlaneWithName(&space, "p2"); EXPECT_EQ(p2, FindPlaneWithName(space, "p2")); auto* p3 = FindOrAddMutablePlaneWithName(&space, "p3"); EXPECT_EQ(p3, FindPlaneWithName(space, "p3")); RemovePlane(&space, p2); EXPECT_EQ(space.planes_size(), 2); EXPECT_EQ(p1, FindPlaneWithName(space, "p1")); EXPECT_EQ(p3, FindPlaneWithName(space, "p3")); RemovePlane(&space, p1); EXPECT_EQ(space.planes_size(), 1); EXPECT_EQ(p3, FindPlaneWithName(space, "p3")); RemovePlane(&space, p3); EXPECT_EQ(space.planes_size(), 0); } TEST(XPlaneUtilsTest, RemoveEmptyPlanes) { XSpace space; RemoveEmptyPlanes(&space); EXPECT_EQ(space.planes_size(), 0); auto* plane1 = space.add_planes(); plane1->set_name("p1"); plane1->add_lines()->set_name("p1l1"); plane1->add_lines()->set_name("p1l2"); auto* plane2 = space.add_planes(); plane2->set_name("p2"); auto* plane3 = space.add_planes(); plane3->set_name("p3"); plane3->add_lines()->set_name("p3l1"); auto* plane4 = space.add_planes(); plane4->set_name("p4"); RemoveEmptyPlanes(&space); ASSERT_EQ(space.planes_size(), 2); EXPECT_EQ(space.planes(0).name(), "p1"); EXPECT_EQ(space.planes(1).name(), "p3"); } TEST(XPlaneUtilsTest, RemoveEmptyLines) { XPlane plane; RemoveEmptyLines(&plane); EXPECT_EQ(plane.lines_size(), 0); auto* line1 = plane.add_lines(); line1->set_name("l1"); line1->add_events(); line1->add_events(); auto* line2 = plane.add_lines(); line2->set_name("l2"); auto* line3 = plane.add_lines(); line3->set_name("l3"); line3->add_events(); auto* line4 = plane.add_lines(); line4->set_name("l4"); RemoveEmptyLines(&plane); ASSERT_EQ(plane.lines_size(), 2); EXPECT_EQ(plane.lines(0).name(), "l1"); EXPECT_EQ(plane.lines(1).name(), "l3"); } TEST(XPlaneUtilsTest, RemoveLine) { XPlane plane; const XLine* line1 = plane.add_lines(); const XLine* line2 = plane.add_lines(); const XLine* line3 = plane.add_lines(); RemoveLine(&plane, line2); ASSERT_EQ(plane.lines_size(), 2); EXPECT_EQ(&plane.lines(0), line1); EXPECT_EQ(&plane.lines(1), line3); } TEST(XPlaneUtilsTest, RemoveEvents) { XLine line; const XEvent* event1 = line.add_events(); const XEvent* event2 = line.add_events(); const XEvent* event3 = line.add_events(); const XEvent* event4 = line.add_events(); RemoveEvents(&line, {event1, event3}); ASSERT_EQ(line.events_size(), 2); EXPECT_EQ(&line.events(0), event2); EXPECT_EQ(&line.events(1), event4); } TEST(XPlaneUtilsTest, SortXPlaneTest) { XPlane plane; XLine* line = plane.add_lines(); *line->add_events() = CreateEvent(200, 100); *line->add_events() = CreateEvent(100, 100); *line->add_events() = CreateEvent(120, 50); *line->add_events() = CreateEvent(120, 30); SortXPlane(&plane); ASSERT_EQ(plane.lines_size(), 1); ASSERT_EQ(plane.lines(0).events_size(), 4); EXPECT_EQ(plane.lines(0).events(0).offset_ps(), 100); EXPECT_EQ(plane.lines(0).events(0).duration_ps(), 100); EXPECT_EQ(plane.lines(0).events(1).offset_ps(), 120); EXPECT_EQ(plane.lines(0).events(1).duration_ps(), 50); EXPECT_EQ(plane.lines(0).events(2).offset_ps(), 120); EXPECT_EQ(plane.lines(0).events(2).duration_ps(), 30); EXPECT_EQ(plane.lines(0).events(3).offset_ps(), 200); EXPECT_EQ(plane.lines(0).events(3).duration_ps(), 100); } namespace { XLineBuilder CreateXLine(XPlaneBuilder* plane, absl::string_view name, absl::string_view display, int64_t id, int64_t timestamp_ns) { XLineBuilder line = plane->GetOrCreateLine(id); line.SetName(name); line.SetTimestampNs(timestamp_ns); line.SetDisplayNameIfEmpty(display); return line; } XEventBuilder CreateXEvent(XPlaneBuilder* plane, XLineBuilder line, absl::string_view event_name, std::optional<absl::string_view> display, int64_t offset_ns, int64_t duration_ns) { XEventMetadata* event_metadata = plane->GetOrCreateEventMetadata(event_name); if (display) event_metadata->set_display_name(std::string(*display)); XEventBuilder event = line.AddEvent(*event_metadata); event.SetOffsetNs(offset_ns); event.SetDurationNs(duration_ns); return event; } template <typename T, typename V> void CreateXStats(XPlaneBuilder* plane, T* stats_owner, absl::string_view stats_name, V stats_value) { stats_owner->AddStatValue(*plane->GetOrCreateStatMetadata(stats_name), stats_value); } void CheckXLine(const XLine& line, absl::string_view name, absl::string_view display, int64_t start_time_ns, int64_t events_size) { EXPECT_EQ(line.name(), name); EXPECT_EQ(line.display_name(), display); EXPECT_EQ(line.timestamp_ns(), start_time_ns); EXPECT_EQ(line.events_size(), events_size); } void CheckXEvent(const XEvent& event, const XPlane& plane, absl::string_view name, absl::string_view display, int64_t offset_ns, int64_t duration_ns, int64_t stats_size) { const XEventMetadata& event_metadata = plane.event_metadata().at(event.metadata_id()); EXPECT_EQ(event_metadata.name(), name); EXPECT_EQ(event_metadata.display_name(), display); EXPECT_EQ(event.offset_ps(), NanoToPico(offset_ns)); EXPECT_EQ(event.duration_ps(), NanoToPico(duration_ns)); EXPECT_EQ(event.stats_size(), stats_size); } } TEST(XPlaneUtilsTest, MergeXPlaneTest) { XPlane src_plane, dst_plane; constexpr int64_t kLineIdOnlyInSrcPlane = 1LL; constexpr int64_t kLineIdOnlyInDstPlane = 2LL; constexpr int64_t kLineIdInBothPlanes = 3LL; constexpr int64_t kLineIdInBothPlanes2 = 4LL; { XPlaneBuilder src(&src_plane); CreateXStats(&src, &src, "plane_stat1", 1); CreateXStats(&src, &src, "plane_stat3", 3.0); auto l1 = CreateXLine(&src, "l1", "d1", kLineIdOnlyInSrcPlane, 100); auto e1 = CreateXEvent(&src, l1, "event1", "display1", 1, 2); CreateXStats(&src, &e1, "event_stat1", 2.0); auto e2 = CreateXEvent(&src, l1, "event2", std::nullopt, 3, 4); CreateXStats(&src, &e2, "event_stat2", 3); auto l2 = CreateXLine(&src, "l2", "d2", kLineIdInBothPlanes, 200); auto e3 = CreateXEvent(&src, l2, "event3", std::nullopt, 5, 7); CreateXStats(&src, &e3, "event_stat3", 2.0); auto e4 = CreateXEvent(&src, l2, "event4", std::nullopt, 6, 8); CreateXStats(&src, &e4, "event_stat4", 3); CreateXStats(&src, &e4, "event_stat5", 3); auto l5 = CreateXLine(&src, "l5", "d5", kLineIdInBothPlanes2, 700); CreateXEvent(&src, l5, "event51", std::nullopt, 9, 10); CreateXEvent(&src, l5, "event52", std::nullopt, 11, 12); } { XPlaneBuilder dst(&dst_plane); CreateXStats(&dst, &dst, "plane_stat2", 2); CreateXStats(&dst, &dst, "plane_stat3", 4); auto l3 = CreateXLine(&dst, "l3", "d3", kLineIdOnlyInDstPlane, 300); auto e5 = CreateXEvent(&dst, l3, "event5", std::nullopt, 11, 2); CreateXStats(&dst, &e5, "event_stat6", 2.0); auto e6 = CreateXEvent(&dst, l3, "event6", std::nullopt, 13, 4); CreateXStats(&dst, &e6, "event_stat7", 3); auto l2 = CreateXLine(&dst, "l4", "d4", kLineIdInBothPlanes, 400); auto e7 = CreateXEvent(&dst, l2, "event7", std::nullopt, 15, 7); CreateXStats(&dst, &e7, "event_stat8", 2.0); auto e8 = CreateXEvent(&dst, l2, "event8", "display8", 16, 8); CreateXStats(&dst, &e8, "event_stat9", 3); auto l6 = CreateXLine(&dst, "l6", "d6", kLineIdInBothPlanes2, 300); CreateXEvent(&dst, l6, "event61", std::nullopt, 21, 10); CreateXEvent(&dst, l6, "event62", std::nullopt, 22, 12); } MergePlanes(src_plane, &dst_plane); XPlaneVisitor plane(&dst_plane); EXPECT_EQ(dst_plane.lines_size(), 4); EXPECT_EQ(dst_plane.stats_size(), 3); absl::flat_hash_map<absl::string_view, absl::string_view> plane_stats; plane.ForEachStat([&](const XStatVisitor& stat) { if (stat.Name() == "plane_stat1") { EXPECT_EQ(stat.IntValue(), 1); } else if (stat.Name() == "plane_stat2") { EXPECT_EQ(stat.IntValue(), 2); } else if (stat.Name() == "plane_stat3") { EXPECT_EQ(stat.DoubleValue(), 3.0); } else { EXPECT_TRUE(false); } }); EXPECT_EQ(dst_plane.stat_metadata_size(), 12); { const XLine& line = dst_plane.lines(0); CheckXLine(line, "l3", "d3", 300, 2); CheckXEvent(line.events(0), dst_plane, "event5", "", 11, 2, 1); CheckXEvent(line.events(1), dst_plane, "event6", "", 13, 4, 1); } { const XLine& line = dst_plane.lines(1); CheckXLine(line, "l4", "d4", 200, 4); CheckXEvent(line.events(0), dst_plane, "event7", "", 215, 7, 1); CheckXEvent(line.events(1), dst_plane, "event8", "display8", 216, 8, 1); CheckXEvent(line.events(2), dst_plane, "event3", "", 5, 7, 1); CheckXEvent(line.events(3), dst_plane, "event4", "", 6, 8, 2); } { const XLine& line = dst_plane.lines(2); CheckXLine(line, "l6", "d6", 300, 4); CheckXEvent(line.events(0), dst_plane, "event61", "", 21, 10, 0); CheckXEvent(line.events(1), dst_plane, "event62", "", 22, 12, 0); CheckXEvent(line.events(2), dst_plane, "event51", "", 409, 10, 0); CheckXEvent(line.events(3), dst_plane, "event52", "", 411, 12, 0); } { const XLine& line = dst_plane.lines(3); CheckXLine(line, "l1", "d1", 100, 2); CheckXEvent(line.events(0), dst_plane, "event1", "display1", 1, 2, 1); CheckXEvent(line.events(1), dst_plane, "event2", "", 3, 4, 1); } } TEST(XPlaneUtilsTest, FindPlanesWithPrefix) { XSpace xspace; FindOrAddMutablePlaneWithName(&xspace, "test-prefix:0"); FindOrAddMutablePlaneWithName(&xspace, "test-prefix:1"); FindOrAddMutablePlaneWithName(&xspace, "test-prefix:2"); FindOrAddMutablePlaneWithName(&xspace, "test-prefix:3"); XPlane* p4 = FindOrAddMutablePlaneWithName(&xspace, "test-do-not-include:0"); std::vector<const XPlane*> xplanes = FindPlanesWithPrefix(xspace, "test-prefix"); ASSERT_EQ(4, xplanes.size()); for (const XPlane* plane : xplanes) { ASSERT_NE(p4, plane); } } TEST(XplaneUtilsTest, FindMutablePlanesWithPrefix) { XSpace xspace; FindOrAddMutablePlaneWithName(&xspace, "test-prefix:0"); FindOrAddMutablePlaneWithName(&xspace, "test-prefix:1"); FindOrAddMutablePlaneWithName(&xspace, "test-prefix:2"); FindOrAddMutablePlaneWithName(&xspace, "test-prefix:3"); XPlane* p4 = FindOrAddMutablePlaneWithName(&xspace, "test-do-not-include:0"); std::vector<XPlane*> xplanes = FindMutablePlanesWithPrefix(&xspace, "test-prefix"); ASSERT_EQ(4, xplanes.size()); for (XPlane* plane : xplanes) { ASSERT_NE(p4, plane); } } TEST(XplaneUtilsTest, FindPlanesWithPredicate) { XSpace xspace; FindOrAddMutablePlaneWithName(&xspace, "test-prefix:0"); XPlane* p1 = FindOrAddMutablePlaneWithName(&xspace, "test-prefix:1"); std::vector<const XPlane*> xplanes = FindPlanes( xspace, [](const XPlane& xplane) { return xplane.name() == "test-prefix:1"; }); ASSERT_EQ(1, xplanes.size()); ASSERT_EQ(p1, xplanes[0]); } TEST(XplaneUtilsTest, FindMutablePlanesWithPredicate) { XSpace xspace; FindOrAddMutablePlaneWithName(&xspace, "test-prefix:0"); XPlane* p1 = FindOrAddMutablePlaneWithName(&xspace, "test-prefix:1"); std::vector<XPlane*> xplanes = FindMutablePlanes( &xspace, [](XPlane& xplane) { return xplane.name() == "test-prefix:1"; }); ASSERT_EQ(1, xplanes.size()); ASSERT_EQ(p1, xplanes[0]); } TEST(XplaneUtilsTest, TestAggregateXPlanes) { XPlane xplane; XPlaneBuilder builder(&xplane); XEventMetadata* event_metadata1 = builder.GetOrCreateEventMetadata(1); event_metadata1->set_name("EventMetadata1"); XEventMetadata* event_metadata2 = builder.GetOrCreateEventMetadata(2); event_metadata2->set_name("EventMetadata2"); XEventMetadata* event_metadata3 = builder.GetOrCreateEventMetadata(3); event_metadata3->set_name("EventMetadata3"); XEventMetadata* event_metadata4 = builder.GetOrCreateEventMetadata(4); event_metadata4->set_name("EventMetadata4"); XLineBuilder line = builder.GetOrCreateLine(1); line.SetName(kTensorFlowOpLineName); XEventBuilder event1 = line.AddEvent(*event_metadata1); event1.SetOffsetNs(0); event1.SetDurationNs(5); XEventBuilder event3 = line.AddEvent(*event_metadata3); event3.SetOffsetNs(0); event3.SetDurationNs(2); XEventBuilder event2 = line.AddEvent(*event_metadata2); event2.SetOffsetNs(5); event2.SetDurationNs(5); XEventBuilder event4 = line.AddEvent(*event_metadata2); event4.SetOffsetNs(10); event4.SetDurationNs(5); XEventBuilder event5 = line.AddEvent(*event_metadata4); event5.SetOffsetNs(15); event5.SetDurationNs(6); XEventBuilder event6 = line.AddEvent(*event_metadata1); event6.SetOffsetNs(15); event6.SetDurationNs(4); XEventBuilder event7 = line.AddEvent(*event_metadata3); event7.SetOffsetNs(15); event7.SetDurationNs(3); XPlane aggregated_xplane; AggregateXPlane(xplane, aggregated_xplane); #if defined(PLATFORM_GOOGLE) ASSERT_THAT(aggregated_xplane, IgnoringRepeatedFieldOrdering(EqualsProto( R"pb(lines { id: 1 name: "Framework Ops" events { metadata_id: 1 duration_ps: 9000 stats { metadata_id: 2 int64_value: 4000 } stats { metadata_id: 3 int64_value: 4000 } num_occurrences: 2 } events { metadata_id: 3 duration_ps: 5000 stats { metadata_id: 2 int64_value: 2000 } num_occurrences: 2 } events { metadata_id: 4 duration_ps: 6000 stats { metadata_id: 3 int64_value: 2000 } num_occurrences: 1 } events { metadata_id: 2 duration_ps: 10000 stats { metadata_id: 2 int64_value: 5000 } num_occurrences: 2 } } event_metadata { key: 1 value { id: 1 name: "EventMetadata1" } } event_metadata { key: 2 value { id: 2 name: "EventMetadata2" } } event_metadata { key: 3 value { id: 3 name: "EventMetadata3" } } event_metadata { key: 4 value { id: 4 name: "EventMetadata4" } } stat_metadata { key: 1 value { id: 1 name: "total_profile_duration_ps" } } stat_metadata { key: 2 value { id: 2 name: "min_duration_ps" } } stat_metadata { key: 3 value { id: 3 name: "self_duration_ps" } } stat_metadata { key: 4 value { id: 4 name: "group_id" } } stats { metadata_id: 1 uint64_value: 21000 } )pb"))); #endif } TEST(XPlanuUtilsTest, TestInstantEventDoesNotFail) { XPlane xplane; XPlaneBuilder xplane_builder(&xplane); XEventMetadata* event_metadata1 = xplane_builder.GetOrCreateEventMetadata(1); XEventMetadata* event_metadata2 = xplane_builder.GetOrCreateEventMetadata(2); XLineBuilder line = xplane_builder.GetOrCreateLine(1); line.SetName(kTensorFlowOpLineName); XEventBuilder event1 = line.AddEvent(*event_metadata1); XEventBuilder event2 = line.AddEvent(*event_metadata2); event1.SetOffsetNs(1); event1.SetDurationNs(0); event2.SetOffsetNs(1); event2.SetDurationNs(0); XPlane aggregated_xplane; AggregateXPlane(xplane, aggregated_xplane); EXPECT_THAT(aggregated_xplane.lines(), UnorderedElementsAre(Property(&XLine::events, SizeIs(2)))); } TEST(XplaneutilsTest, TestEventMetadataStatsAreCopied) { XPlane xplane; XPlaneBuilder xplane_builder(&xplane); XEventMetadata* event_metadata = xplane_builder.GetOrCreateEventMetadata(1); XStatsBuilder<XEventMetadata> stats(event_metadata, &xplane_builder); stats.AddStatValue( *xplane_builder.GetOrCreateStatMetadata(GetStatTypeStr(StatType::kTfOp)), "TestFunction"); XLineBuilder line = xplane_builder.GetOrCreateLine(1); line.SetName(kTensorFlowOpLineName); XEventBuilder event = line.AddEvent(*event_metadata); event.SetDurationNs(0); event.SetOffsetNs(0); XPlane aggregated_xplane; AggregateXPlane(xplane, aggregated_xplane); XPlaneVisitor visitor = CreateTfXPlaneVisitor(&aggregated_xplane); XEventMetadataVisitor metadata_visitor(&visitor, visitor.GetEventMetadata(1)); std::optional<XStatVisitor> stat = metadata_visitor.GetStat(StatType::kTfOp); ASSERT_TRUE(stat.has_value()); EXPECT_EQ(stat->Name(), "tf_op"); EXPECT_EQ(stat->StrOrRefValue(), "TestFunction"); } TEST(XplaneutilsTest, TestEventMetadataStatsAreCopiedForRefValue) { XPlane xplane; XPlaneBuilder xplane_builder(&xplane); XEventMetadata* event_metadata = xplane_builder.GetOrCreateEventMetadata(1); XStatsBuilder<XEventMetadata> stats(event_metadata, &xplane_builder); stats.AddStatValue( *xplane_builder.GetOrCreateStatMetadata(GetStatTypeStr(StatType::kTfOp)), *xplane_builder.GetOrCreateStatMetadata("TestFunction")); XLineBuilder line = xplane_builder.GetOrCreateLine(1); line.SetName(kTensorFlowOpLineName); XEventBuilder event = line.AddEvent(*event_metadata); event.SetDurationNs(0); event.SetOffsetNs(0); XPlane aggregated_xplane; AggregateXPlane(xplane, aggregated_xplane); XPlaneVisitor visitor = CreateTfXPlaneVisitor(&aggregated_xplane); XEventMetadataVisitor metadata_visitor(&visitor, visitor.GetEventMetadata(1)); std::optional<XStatVisitor> stat = metadata_visitor.GetStat(StatType::kTfOp); ASSERT_TRUE(stat.has_value()); EXPECT_EQ(stat->Name(), "tf_op"); EXPECT_EQ(stat->StrOrRefValue(), "TestFunction"); } TEST(XplaneutilsTest, TestIsXSpaceGrouped) { XSpace space; { XPlaneBuilder p1(space.add_planes()); auto l1 = CreateXLine(&p1, "l1", "d1", 1, 100); auto e1 = CreateXEvent(&p1, l1, "event1", "display1", 1, 2); CreateXStats(&p1, &e1, "event_stat1", 2.0); } EXPECT_FALSE(IsXSpaceGrouped(space)); { XPlaneBuilder p2(space.add_planes()); auto l2 = CreateXLine(&p2, "l2", "d2", 1, 100); auto e2 = CreateXEvent(&p2, l2, "event2", "display2", 1, 2); CreateXStats(&p2, &e2, "group_id", 1); } LOG(ERROR) << space.DebugString(); EXPECT_TRUE(IsXSpaceGrouped(space)); } TEST(XplaneutilsTest, TestIsHostPlane) { XSpace xspace; auto xplane_host_thread = FindOrAddMutablePlaneWithName(&xspace, "/host:CPU"); auto xplane_host_cpu = FindOrAddMutablePlaneWithName(&xspace, "Host CPUs"); auto xplane_tfstreamz = FindOrAddMutablePlaneWithName(&xspace, "/host:tfstreamz"); auto xplane_metadata = FindOrAddMutablePlaneWithName(&xspace, "/host:metadata"); auto xplane_syscalls = FindOrAddMutablePlaneWithName(&xspace, "Syscalls"); auto xplane_python_tracer = FindOrAddMutablePlaneWithName(&xspace, "/host:python-tracer"); auto xplane_custom_prefix = FindOrAddMutablePlaneWithName(&xspace, "/device:CUSTOM:123"); auto xplane_legacy_custom = FindOrAddMutablePlaneWithName(&xspace, "/custom:456"); auto xplane_cupti = FindOrAddMutablePlaneWithName(&xspace, "/host:CUPTI"); EXPECT_TRUE(IsHostPlane(*xplane_host_thread)); EXPECT_TRUE(IsHostPlane(*xplane_host_cpu)); EXPECT_TRUE(IsHostPlane(*xplane_tfstreamz)); EXPECT_TRUE(IsHostPlane(*xplane_metadata)); EXPECT_TRUE(IsHostPlane(*xplane_syscalls)); EXPECT_TRUE(IsHostPlane(*xplane_python_tracer)); EXPECT_FALSE(IsHostPlane(*xplane_custom_prefix)); EXPECT_FALSE(IsHostPlane(*xplane_legacy_custom)); EXPECT_TRUE(IsHostPlane(*xplane_cupti)); } TEST(XplaneutilsTest, TestIsDevicePlane) { XSpace xspace; auto xplane_host_thread = FindOrAddMutablePlaneWithName(&xspace, "/host:CPU"); auto xplane_device_thread = FindOrAddMutablePlaneWithName(&xspace, "/device:TPU"); auto xplane_task_env_thread = FindOrAddMutablePlaneWithName(&xspace, "Task Environment"); auto xplane_custom_prefix = FindOrAddMutablePlaneWithName(&xspace, "/device:CUSTOM:123"); auto xplane_legacy_custom = FindOrAddMutablePlaneWithName(&xspace, "/custom:456"); EXPECT_FALSE(IsDevicePlane(*xplane_host_thread)); EXPECT_FALSE(IsDevicePlane(*xplane_task_env_thread)); EXPECT_TRUE(IsDevicePlane(*xplane_device_thread)); EXPECT_TRUE(IsDevicePlane(*xplane_custom_prefix)); EXPECT_TRUE(IsDevicePlane(*xplane_legacy_custom)); } TEST(XplaneUtilsTest, XPlaneGroupingPropagatesStep) { XPlane xplane; XPlaneBuilder builder(&xplane); XStatMetadata* kGroupId = builder.GetOrCreateStatMetadata(GetStatTypeStr(StatType::kGroupId)); XLineBuilder line = builder.GetOrCreateLine(1); line.SetName(kStepLineName); XEventMetadata* event_metadata = builder.GetOrCreateEventMetadata(1); event_metadata->set_name("Step 1"); XEventBuilder event_builder = line.AddEvent(*event_metadata); event_builder.AddStatValue(*kGroupId, 1); event_builder.SetDurationNs(100); event_builder.SetOffsetNs(100); XEventMetadata* event_metadata2 = builder.GetOrCreateEventMetadata(2); event_metadata2->set_name("Step 2"); XEventBuilder event_builder2 = line.AddEvent(*event_metadata2); event_builder2.AddStatValue(*kGroupId, 2); event_builder2.SetDurationNs(100); event_builder2.SetOffsetNs(300); XPlane aggregated_xplane; AggregateXPlane(xplane, aggregated_xplane); #if defined(PLATFORM_GOOGLE) EXPECT_THAT(aggregated_xplane, Partially(EqualsProto(xplane))); #endif } TEST(XplaneUtilsTest, XPlaneGroupingPropagatesGroupId) { XPlane xplane; XPlaneBuilder builder(&xplane); XEventMetadata* event_metadata1 = builder.GetOrCreateEventMetadata(1); event_metadata1->set_name("EventMetadata1"); XStatMetadata* kGroupId = builder.GetOrCreateStatMetadata(GetStatTypeStr(StatType::kGroupId)); XLineBuilder line = builder.GetOrCreateLine(1); line.SetName(kXlaOpLineName); XEventBuilder event_builder = line.AddEvent(*event_metadata1); event_builder.SetDurationNs(100); event_builder.SetOffsetNs(100); event_builder.AddStatValue(*kGroupId, 1); XEventBuilder event_builder2 = line.AddEvent(*event_metadata1); event_builder2.AddStatValue(*kGroupId, 2); event_builder2.SetDurationNs(100); event_builder2.SetOffsetNs(300); XPlane aggregated_xplane; AggregateXPlane(xplane, aggregated_xplane); EXPECT_THAT(aggregated_xplane.lines(), UnorderedElementsAre(Property(&XLine::events, SizeIs(2)))); XPlaneVisitor visitor = CreateTfXPlaneVisitor(&aggregated_xplane); visitor.ForEachLine([&](const XLineVisitor& line) { line.ForEachEvent([&](const XEventVisitor& event) { EXPECT_TRUE(event.GetStat(StatType::kGroupId).has_value()); }); }); } } } }
2,293
#ifndef TENSORFLOW_TSL_PROFILER_UTILS_TIMESTAMP_UTILS_H_ #define TENSORFLOW_TSL_PROFILER_UTILS_TIMESTAMP_UTILS_H_ #include <cstdint> #include "tsl/profiler/protobuf/xplane.pb.h" namespace tsl { namespace profiler { void SetSessionTimestamps(uint64_t start_walltime_ns, uint64_t stop_walltime_ns, tensorflow::profiler::XSpace& space); } } #endif #include "tsl/profiler/utils/timestamp_utils.h" #include <cstdint> #include "absl/log/log.h" #include "tsl/profiler/protobuf/xplane.pb.h" #include "tsl/profiler/utils/xplane_builder.h" #include "tsl/profiler/utils/xplane_schema.h" #include "tsl/profiler/utils/xplane_utils.h" namespace tsl { namespace profiler { void SetSessionTimestamps(uint64_t start_walltime_ns, uint64_t stop_walltime_ns, tensorflow::profiler::XSpace& space) { if (start_walltime_ns != 0 && stop_walltime_ns != 0) { tsl::profiler::XPlaneBuilder plane( tsl::profiler::FindOrAddMutablePlaneWithName( &space, tsl::profiler::kTaskEnvPlaneName)); plane.AddStatValue(*plane.GetOrCreateStatMetadata( GetTaskEnvStatTypeStr(kEnvProfileStartTime)), start_walltime_ns); plane.AddStatValue(*plane.GetOrCreateStatMetadata( GetTaskEnvStatTypeStr(kEnvProfileStopTime)), stop_walltime_ns); } else { LOG(WARNING) << "Not Setting Session Timestamps, (start_walltime_ns, " "stop_walltime_ns) : " << start_walltime_ns << ", " << stop_walltime_ns; } } } }
#include "tsl/profiler/utils/timestamp_utils.h" #include "tsl/platform/test.h" #include "tsl/profiler/utils/xplane_schema.h" #include "tsl/profiler/utils/xplane_utils.h" #include "tsl/profiler/utils/xplane_visitor.h" namespace tsl { namespace profiler { using ::testing::Eq; TEST(TimestampUtilsTest, StartAndStopTimestampAreAdded) { XSpace xspace; SetSessionTimestamps(1000, 2000, xspace); const XPlane* xplane = FindPlaneWithName(xspace, kTaskEnvPlaneName); XPlaneVisitor visitor(xplane, {}, {FindTaskEnvStatType}); auto start_time = visitor.GetStat(TaskEnvStatType::kEnvProfileStartTime); auto stop_time = visitor.GetStat(TaskEnvStatType::kEnvProfileStopTime); EXPECT_THAT(start_time->IntOrUintValue(), Eq(1000)); EXPECT_THAT(stop_time->IntOrUintValue(), Eq(2000)); } } }
2,294
#ifndef TENSORFLOW_TSL_PROFILER_UTILS_XPLANE_BUILDER_H_ #define TENSORFLOW_TSL_PROFILER_UTILS_XPLANE_BUILDER_H_ #include <stddef.h> #include <cstdint> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/meta/type_traits.h" #include "absl/strings/numbers.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "tsl/platform/macros.h" #include "tsl/platform/protobuf.h" #include "tsl/platform/types.h" #include "tsl/profiler/protobuf/xplane.pb.h" #include "tsl/profiler/utils/math_utils.h" #include "tsl/profiler/utils/timespan.h" namespace tsl { namespace profiler { using tensorflow::profiler::XEvent; using tensorflow::profiler::XEventMetadata; using tensorflow::profiler::XLine; using tensorflow::profiler::XPlane; using tensorflow::profiler::XSpace; using tensorflow::profiler::XStat; using tensorflow::profiler::XStatMetadata; class XPlaneBuilder; template <typename T> class XStatsBuilder { public: explicit XStatsBuilder(T* stats_owner, XPlaneBuilder* stats_metadata_owner) : stats_owner_(stats_owner), stats_metadata_owner_(stats_metadata_owner) {} template <typename ValueT> void AddStatValue(const XStatMetadata& metadata, ValueT&& value) { SetStatValue(std::forward<ValueT>(value), AddStat(metadata)); } template <typename ValueT> void SetOrAddStatValue(const XStatMetadata& metadata, ValueT&& value) { SetStatValue(std::forward<ValueT>(value), FindOrAddStat(metadata)); } void AddStat(const XStatMetadata& metadata, const XStat& src_stat, const XPlane& src_plane) { CopyStatValue(src_stat, src_plane, AddStat(metadata)); } void SetOrAddStat(const XStatMetadata& metadata, const XStat& src_stat, const XPlane& src_plane) { CopyStatValue(src_stat, src_plane, FindOrAddStat(metadata)); } void ParseAndAddStatValue(const XStatMetadata& metadata, absl::string_view value) { int64_t int_value; uint64 uint_value; double double_value; if (absl::SimpleAtoi(value, &int_value)) { AddStatValue(metadata, int_value); } else if (absl::SimpleAtoi(value, &uint_value)) { AddStatValue(metadata, uint_value); } else if (absl::SimpleAtod(value, &double_value)) { AddStatValue(metadata, double_value); } else { AddStatValue(metadata, GetOrCreateStatMetadata(value)); } } void ReserveStats(size_t num_stats) { stats_owner_->mutable_stats()->Reserve(num_stats); } template <typename ForEachStatFunc> void ForEachStat(ForEachStatFunc&& for_each_stat) { for (XStat& stat : *stats_owner_->mutable_stats()) { for_each_stat(&stat); } } const XStat* GetStat(const XStatMetadata& stat_metadata) const { for (auto& stat : *stats_owner_->mutable_stats()) { if (stat.metadata_id() == stat_metadata.id()) { return &stat; } } return nullptr; } static uint64 IntOrUintValue(const XStat& stat) { return stat.value_case() == XStat::kUint64Value ? stat.uint64_value() : stat.int64_value(); } absl::string_view StrOrRefValue(const XStat& stat); private: XStat* AddStat(const XStatMetadata& metadata) { XStat* stat = stats_owner_->add_stats(); stat->set_metadata_id(metadata.id()); return stat; } XStat* FindOrAddStat(const XStatMetadata& metadata) { for (auto& stat : *stats_owner_->mutable_stats()) { if (stat.metadata_id() == metadata.id()) { return &stat; } } return AddStat(metadata); } static void SetStatValue(bool value, XStat* stat) { stat->set_int64_value(value); } template <typename Int, std::enable_if_t<absl::conjunction<std::is_integral<Int>, std::is_signed<Int>>::value, bool> = true> static void SetStatValue(Int value, XStat* stat) { stat->set_int64_value(value); } template <typename UInt, std::enable_if_t< absl::conjunction<std::is_integral<UInt>, absl::negation<std::is_signed<UInt>>>::value, bool> = true> static void SetStatValue(UInt value, XStat* stat) { stat->set_uint64_value(value); } static void SetStatValue(double value, XStat* stat) { stat->set_double_value(value); } static void SetStatValue(const char* value, XStat* stat) { stat->set_str_value(std::string(value)); } static void SetStatValue(absl::string_view value, XStat* stat) { stat->set_str_value(std::string(value)); } static void SetStatValue(std::string&& value, XStat* stat) { stat->set_str_value(std::move(value)); } static void SetStatValue(const XStatMetadata& value, XStat* stat) { stat->set_ref_value(value.id()); } static void SetStatValue(const protobuf::MessageLite& proto, XStat* stat) { auto* bytes = stat->mutable_bytes_value(); proto.SerializeToString(bytes); } void CopyStatValue(const XStat& src_stat, const XPlane& src_plane, XStat* dst_stat) { switch (src_stat.value_case()) { case XStat::VALUE_NOT_SET: break; case XStat::kInt64Value: dst_stat->set_int64_value(src_stat.int64_value()); break; case XStat::kUint64Value: dst_stat->set_uint64_value(src_stat.uint64_value()); break; case XStat::kDoubleValue: dst_stat->set_double_value(src_stat.double_value()); break; case XStat::kStrValue: dst_stat->set_str_value(src_stat.str_value()); break; case XStat::kRefValue: { const auto& stat_metadata_by_id = src_plane.stat_metadata(); const auto it = stat_metadata_by_id.find(src_stat.ref_value()); if (TF_PREDICT_TRUE(it != stat_metadata_by_id.end())) { absl::string_view value = it->second.name(); dst_stat->set_ref_value(GetOrCreateStatMetadata(value).id()); } break; } case XStat::kBytesValue: dst_stat->set_bytes_value(src_stat.bytes_value()); break; } } const XStatMetadata& GetOrCreateStatMetadata(absl::string_view value); T* stats_owner_; XPlaneBuilder* stats_metadata_owner_; }; class XEventBuilder : public XStatsBuilder<XEvent> { public: XEventBuilder(const XLine* line, XPlaneBuilder* plane, XEvent* event) : XStatsBuilder<XEvent>(event, plane), line_(line), event_(event) {} int64_t LineTimestampPs() const { return NanoToPico(line_->timestamp_ns()); } int64_t OffsetPs() const { return event_->offset_ps(); } int64_t TimestampPs() const { return LineTimestampPs() + OffsetPs(); } int64_t DurationPs() const { return event_->duration_ps(); } int64_t MetadataId() const { return event_->metadata_id(); } void SetOffsetPs(int64_t offset_ps) { event_->set_offset_ps(offset_ps); } void SetOffsetNs(int64_t offset_ns) { SetOffsetPs(NanoToPico(offset_ns)); } void SetTimestampPs(int64_t timestamp_ps) { SetOffsetPs(timestamp_ps - LineTimestampPs()); } void SetTimestampNs(int64_t timestamp_ns) { SetOffsetNs(timestamp_ns - line_->timestamp_ns()); } void SetNumOccurrences(int64_t num_occurrences) { event_->set_num_occurrences(num_occurrences); } void SetDurationPs(int64_t duration_ps) { event_->set_duration_ps(duration_ps); } void SetDurationNs(int64_t duration_ns) { SetDurationPs(NanoToPico(duration_ns)); } void SetEndTimestampPs(int64_t end_timestamp_ps) { SetDurationPs(end_timestamp_ps - TimestampPs()); } void SetEndTimestampNs(int64_t end_timestamp_ns) { SetDurationPs(NanoToPico(end_timestamp_ns - line_->timestamp_ns()) - event_->offset_ps()); } Timespan GetTimespan() const { return Timespan(TimestampPs(), DurationPs()); } void SetTimespan(Timespan timespan) { SetTimestampPs(timespan.begin_ps()); SetDurationPs(timespan.duration_ps()); } bool operator<(const XEventBuilder& other) const { return GetTimespan() < other.GetTimespan(); } private: const XLine* line_; XEvent* event_; }; class XLineBuilder { public: explicit XLineBuilder(XLine* line, XPlaneBuilder* plane) : line_(line), plane_(plane) {} XPlaneBuilder* Plane() const { return plane_; } int64_t Id() const { return line_->id(); } void SetId(int64_t id) { line_->set_id(id); } int64_t NumEvents() const { return line_->events_size(); } absl::string_view Name() const { return line_->name(); } void SetName(absl::string_view name) { line_->set_name(std::string(name)); } void SetNameIfEmpty(absl::string_view name) { if (line_->name().empty()) SetName(name); } int64_t TimestampNs() const { return line_->timestamp_ns(); } void SetTimestampNs(int64_t timestamp_ns) { line_->set_timestamp_ns(timestamp_ns); } void SetTimestampNsAndAdjustEventOffsets(int64_t timestamp_ns); void SetDurationPs(int64_t duration_ps) { line_->set_duration_ps(duration_ps); } void ReserveEvents(size_t num_events) { line_->mutable_events()->Reserve(num_events); } void SetDisplayNameIfEmpty(absl::string_view display_name) { if (line_->display_name().empty()) { line_->set_display_name(std::string(display_name)); } } XEventBuilder AddEvent(const XEventMetadata& metadata); XEventBuilder AddEvent(const XEvent& event); template <typename ForEachEventFunc> void ForEachEvent(ForEachEventFunc&& for_each_event) { for (XEvent& event : *line_->mutable_events()) { for_each_event(XEventBuilder(line_, plane_, &event)); } } private: XLine* line_; XPlaneBuilder* plane_; }; class XPlaneBuilder : public XStatsBuilder<XPlane> { public: explicit XPlaneBuilder(XPlane* plane); int64_t Id() const { return plane_->id(); } void SetId(int64_t id) { plane_->set_id(id); } absl::string_view Name() const { return plane_->name(); } void SetName(absl::string_view name) { plane_->set_name(std::string(name)); } void ReserveLines(size_t num_lines) { plane_->mutable_lines()->Reserve(num_lines); } template <typename ForEachLineFunc> void ForEachLine(ForEachLineFunc&& for_each_line) { for (XLine& line : *plane_->mutable_lines()) { for_each_line(XLineBuilder(&line, this)); } } XLineBuilder GetOrCreateLine(int64_t line_id); XEventMetadata* CreateEventMetadata(); XEventMetadata* GetOrCreateEventMetadata(int64_t metadata_id); XEventMetadata* GetOrCreateEventMetadata(absl::string_view name); XEventMetadata* GetOrCreateEventMetadata(std::string&& name); XEventMetadata* GetOrCreateEventMetadata(const char* name) { return GetOrCreateEventMetadata(absl::string_view(name)); } std::vector<XEventMetadata*> GetOrCreateEventsMetadata( const std::vector<absl::string_view>& names); XEventMetadata* GetEventMetadata(absl::string_view name) const; XStatMetadata* GetStatMetadata(absl::string_view name) const; const XStatMetadata* GetStatMetadata(int64_t metadata_id) const; XStatMetadata* CreateStatMetadata(); XStatMetadata* GetOrCreateStatMetadata(int64_t metadata_id); XStatMetadata* GetOrCreateStatMetadata(absl::string_view name); XStatMetadata* GetOrCreateStatMetadata(std::string&& name); XStatMetadata* GetOrCreateStatMetadata(const char* name) { return GetOrCreateStatMetadata(absl::string_view(name)); } private: XPlane* plane_; int64_t last_event_metadata_id_ = 0LL; int64_t last_stat_metadata_id_ = 0LL; absl::flat_hash_map<std::string, XEventMetadata*> event_metadata_by_name_; absl::flat_hash_map<std::string, XStatMetadata*> stat_metadata_by_name_; absl::flat_hash_map<int64_t, XLine*> lines_by_id_; }; template <typename T> const XStatMetadata& XStatsBuilder<T>::GetOrCreateStatMetadata( absl::string_view value) { return *stats_metadata_owner_->GetOrCreateStatMetadata(value); } template <typename T> absl::string_view XStatsBuilder<T>::StrOrRefValue(const XStat& stat) { switch (stat.value_case()) { case XStat::kStrValue: return stat.str_value(); case XStat::kRefValue: { auto* ref_stat = stats_metadata_owner_->GetStatMetadata(stat.ref_value()); return ref_stat ? ref_stat->name() : absl::string_view(); } case XStat::kInt64Value: case XStat::kUint64Value: case XStat::kDoubleValue: case XStat::kBytesValue: case XStat::VALUE_NOT_SET: return absl::string_view(); } } } } #endif #include "tsl/profiler/utils/xplane_builder.h" #include <algorithm> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "tsl/platform/types.h" #include "tsl/profiler/protobuf/xplane.pb.h" #include "tsl/profiler/utils/math_utils.h" namespace tsl { namespace profiler { XPlaneBuilder::XPlaneBuilder(XPlane* plane) : XStatsBuilder<XPlane>(plane, this), plane_(plane) { for (auto& id_and_metadata : *plane->mutable_event_metadata()) { auto& metadata = id_and_metadata.second; last_event_metadata_id_ = std::max<int64_t>(last_event_metadata_id_, metadata.id()); if (!metadata.name().empty()) { event_metadata_by_name_.try_emplace(metadata.name(), &metadata); } } for (auto& id_and_metadata : *plane->mutable_stat_metadata()) { auto& metadata = id_and_metadata.second; last_stat_metadata_id_ = std::max<int64_t>(last_stat_metadata_id_, metadata.id()); if (!metadata.name().empty()) { stat_metadata_by_name_.try_emplace(metadata.name(), &metadata); } } for (XLine& line : *plane->mutable_lines()) { lines_by_id_.try_emplace(line.id(), &line); } } XEventMetadata* XPlaneBuilder::GetOrCreateEventMetadata(int64_t metadata_id) { XEventMetadata& metadata = (*plane_->mutable_event_metadata())[metadata_id]; metadata.set_id(metadata_id); return &metadata; } XEventMetadata* XPlaneBuilder::CreateEventMetadata() { return GetOrCreateEventMetadata(++last_event_metadata_id_); } XEventMetadata* XPlaneBuilder::GetOrCreateEventMetadata( absl::string_view name) { XEventMetadata*& metadata = event_metadata_by_name_[name]; if (metadata == nullptr) { metadata = CreateEventMetadata(); metadata->set_name(std::string(name)); } return metadata; } XEventMetadata* XPlaneBuilder::GetOrCreateEventMetadata(std::string&& name) { XEventMetadata*& metadata = event_metadata_by_name_[name]; if (metadata == nullptr) { metadata = CreateEventMetadata(); metadata->set_name(std::move(name)); } return metadata; } std::vector<XEventMetadata*> XPlaneBuilder::GetOrCreateEventsMetadata( const std::vector<absl::string_view>& names) { std::vector<XEventMetadata*> metadata; metadata.reserve(names.size()); for (absl::string_view name : names) { metadata.push_back(GetOrCreateEventMetadata(name)); } return metadata; } XEventMetadata* XPlaneBuilder::GetEventMetadata(absl::string_view name) const { auto result = event_metadata_by_name_.find(name); if (result == event_metadata_by_name_.end()) return nullptr; return result->second; } XStatMetadata* XPlaneBuilder::GetStatMetadata(absl::string_view name) const { auto result = stat_metadata_by_name_.find(name); if (result == stat_metadata_by_name_.end()) return nullptr; return result->second; } XStatMetadata* XPlaneBuilder::GetOrCreateStatMetadata(int64_t metadata_id) { XStatMetadata& metadata = (*plane_->mutable_stat_metadata())[metadata_id]; metadata.set_id(metadata_id); return &metadata; } const XStatMetadata* XPlaneBuilder::GetStatMetadata(int64_t metadata_id) const { auto result = plane_->stat_metadata().find(metadata_id); if (result == plane_->stat_metadata().end()) return nullptr; return &(result->second); } XStatMetadata* XPlaneBuilder::CreateStatMetadata() { return GetOrCreateStatMetadata(++last_stat_metadata_id_); } XStatMetadata* XPlaneBuilder::GetOrCreateStatMetadata(absl::string_view name) { XStatMetadata*& metadata = stat_metadata_by_name_[name]; if (metadata == nullptr) { metadata = CreateStatMetadata(); metadata->set_name(std::string(name)); } return metadata; } XStatMetadata* XPlaneBuilder::GetOrCreateStatMetadata(std::string&& name) { XStatMetadata*& metadata = stat_metadata_by_name_[name]; if (metadata == nullptr) { metadata = CreateStatMetadata(); metadata->set_name(std::move(name)); } return metadata; } XLineBuilder XPlaneBuilder::GetOrCreateLine(int64_t line_id) { XLine*& line = lines_by_id_[line_id]; if (line == nullptr) { line = plane_->add_lines(); line->set_id(line_id); } return XLineBuilder(line, this); } XEventBuilder XLineBuilder::AddEvent(const XEventMetadata& metadata) { XEvent* event = line_->add_events(); event->set_metadata_id(metadata.id()); return XEventBuilder(line_, plane_, event); } XEventBuilder XLineBuilder::AddEvent(const XEvent& event) { XEvent* new_event = line_->add_events(); *new_event = event; return XEventBuilder(line_, plane_, new_event); } void XLineBuilder::SetTimestampNsAndAdjustEventOffsets(int64_t timestamp_ns) { int64_t offset_ps = NanoToPico(line_->timestamp_ns() - timestamp_ns); line_->set_timestamp_ns(timestamp_ns); if (offset_ps) { for (auto& event : *line_->mutable_events()) { event.set_offset_ps(event.offset_ps() + offset_ps); } } } } }
#include "tsl/profiler/utils/xplane_builder.h" #include <string> #include "absl/strings/string_view.h" #include "tsl/platform/test.h" #include "tsl/profiler/protobuf/xplane.pb.h" #include "tsl/profiler/utils/xplane_visitor.h" namespace tsl { namespace profiler { namespace { TEST(TimespanTests, NonInstantSpanIncludesSingleTimeTests) { XPlane plane; XPlaneBuilder xplane_builder(&plane); XLineBuilder xline_builder = xplane_builder.GetOrCreateLine(0); XEventBuilder event_builder = xline_builder.AddEvent( *xplane_builder.GetOrCreateEventMetadata("1st event")); constexpr auto kBoolStat = true; constexpr auto kInt32Stat = int32_t{1234}; constexpr auto kInt64Stat = int64_t{1234} << 32; constexpr auto kUint32Stat = uint32_t{5678}; constexpr auto kUint64Stat = uint64_t{5678} << 32; constexpr auto kFloatStat = 0.5f; constexpr auto kDoubleStat = 1.0; constexpr auto kStringStat = "abc"; constexpr auto kRefStat = "referenced abc"; event_builder.AddStatValue( *xplane_builder.GetOrCreateStatMetadata("bool stat"), kBoolStat); event_builder.AddStatValue( *xplane_builder.GetOrCreateStatMetadata("int32 stat"), kInt32Stat); event_builder.AddStatValue( *xplane_builder.GetOrCreateStatMetadata("int64 stat"), kInt64Stat); event_builder.AddStatValue( *xplane_builder.GetOrCreateStatMetadata("uint32 stat"), kUint32Stat); event_builder.AddStatValue( *xplane_builder.GetOrCreateStatMetadata("uint64 stat"), kUint64Stat); event_builder.AddStatValue( *xplane_builder.GetOrCreateStatMetadata("string stat"), kStringStat); event_builder.AddStatValue( *xplane_builder.GetOrCreateStatMetadata("float stat"), kFloatStat); event_builder.AddStatValue( *xplane_builder.GetOrCreateStatMetadata("double stat"), kDoubleStat); event_builder.AddStatValue( *xplane_builder.GetOrCreateStatMetadata("ref stat"), *xplane_builder.GetOrCreateStatMetadata(kRefStat)); XPlaneVisitor xplane_visitor(&plane); EXPECT_EQ(xplane_visitor.NumLines(), 1); int num_stats = 0; xplane_visitor.ForEachLine([&](const XLineVisitor& xline) { xline.ForEachEvent([&](const XEventVisitor& xevent) { EXPECT_EQ(xevent.Name(), "1st event"); xevent.ForEachStat([&](const XStatVisitor& stat) { if (stat.Name() == "bool stat") { EXPECT_EQ(stat.BoolValue(), kBoolStat); num_stats++; } else if (stat.Name() == "int32 stat") { EXPECT_EQ(stat.IntValue(), kInt32Stat); EXPECT_EQ(stat.IntOrUintValue(), kInt32Stat); num_stats++; } else if (stat.Name() == "int64 stat") { EXPECT_EQ(stat.IntValue(), kInt64Stat); EXPECT_EQ(stat.IntOrUintValue(), kInt64Stat); num_stats++; } else if (stat.Name() == "uint32 stat") { EXPECT_EQ(stat.UintValue(), kUint32Stat); EXPECT_EQ(stat.IntOrUintValue(), kUint32Stat); num_stats++; } else if (stat.Name() == "uint64 stat") { EXPECT_EQ(stat.UintValue(), kUint64Stat); EXPECT_EQ(stat.IntOrUintValue(), kUint64Stat); num_stats++; } else if (stat.Name() == "string stat") { EXPECT_EQ(stat.StrOrRefValue(), kStringStat); num_stats++; } else if (stat.Name() == "float stat") { EXPECT_EQ(stat.DoubleValue(), kFloatStat); num_stats++; } else if (stat.Name() == "double stat") { EXPECT_EQ(stat.DoubleValue(), kDoubleStat); num_stats++; } else if (stat.Name() == "ref stat") { EXPECT_EQ(stat.StrOrRefValue(), kRefStat); num_stats++; } }); }); }); EXPECT_EQ(num_stats, 9); } } } }
2,295
#ifndef TENSORFLOW_TSL_PROFILER_UTILS_PREPROCESS_XPLANE_H_ #define TENSORFLOW_TSL_PROFILER_UTILS_PREPROCESS_XPLANE_H_ #include <cstdint> #include <memory> #include <optional> #include <tuple> #include <type_traits> #include <utility> #include <variant> #include <vector> #include "absl/hash/hash.h" #include "absl/log/log.h" #include "absl/memory/memory.h" #include "absl/strings/match.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "tsl/profiler/lib/context_types.h" #include "tsl/profiler/protobuf/xplane.pb.h" #include "tsl/profiler/utils/tpu_xplane_utils.h" #include "tsl/profiler/utils/trace_utils.h" #include "tsl/profiler/utils/xplane_builder.h" #include "tsl/profiler/utils/xplane_mutators.h" #include "tsl/profiler/utils/xplane_schema.h" namespace tsl { namespace profiler { static constexpr uint32_t kRunIdMask = (1U << 27) - 1; class XplaneRootEventMutatorFactory : public XplaneEventMutatorFactory { public: static std::unique_ptr<XplaneEventMutatorFactory> CreateFactory( HostEventType event_type, int64_t root_level) { return absl::WrapUnique( new XplaneRootEventMutatorFactory(event_type, root_level)); } std::vector<std::unique_ptr<XplaneEventMutator>> CreateMutators( XPlaneBuilder& xplane) const override { std::vector<std::unique_ptr<XplaneEventMutator>> mutators; if (auto* event_metadata = xplane.GetEventMetadata(GetHostEventTypeStr(event_type_))) { XStatMetadata* root_metadata = xplane.GetOrCreateStatMetadata(GetStatTypeStr(StatType::kIsRoot)); mutators.emplace_back(std::make_unique<XplaneRootEventMutator>( event_metadata, *root_metadata, root_level_)); } return mutators; } private: explicit XplaneRootEventMutatorFactory(HostEventType event_type, int64_t root_level) : event_type_(event_type), root_level_(root_level) {} class XplaneRootEventMutator : public XplaneEventMutator { public: XplaneRootEventMutator(XEventMetadata* event_metadata, XStatMetadata& root_stats_metadata, int64_t root_level) : XplaneEventMutator(event_metadata), root_stats_metadata_(root_stats_metadata), root_level_(root_level) {} void Mutate(XEventBuilder& event_builder) override { event_builder.SetOrAddStatValue(root_stats_metadata_, root_level_); } void MutateEventsInLine(XLineBuilder& line) override { CHECK(false); } private: XStatMetadata& root_stats_metadata_; int64_t root_level_; }; HostEventType event_type_; int64_t root_level_; }; template <typename StatValueType, StatType kStatId> class XContextStatsAccessor { public: using value_type = StatValueType; bool Initialize(XPlaneBuilder& xplane) { stats_metadata_ = xplane.GetStatMetadata(GetStatTypeStr(kStatId)); return stats_metadata_; } std::optional<StatValueType> GetStat(XEventBuilder& event_builder) { if (stats_metadata_ == nullptr) return std::nullopt; auto* stat = event_builder.GetStat(*stats_metadata_); if (stat == nullptr) return std::nullopt; if constexpr (std::is_integral_v<StatValueType>) { return event_builder.IntOrUintValue(*stat); } else { return event_builder.StrOrRefValue(*stat); } } private: XStatMetadata* stats_metadata_ = nullptr; }; template <typename StatValueType, StatType kStatId, StatValueType kDefaultValue> class XContextStatsAccessorWithDefault { public: using value_type = StatValueType; bool Initialize(XPlaneBuilder& xplane) { stats_metadata_ = xplane.GetStatMetadata(GetStatTypeStr(kStatId)); return true; } std::optional<StatValueType> GetStat(XEventBuilder& event_builder) { if (stats_metadata_ == nullptr) return kDefaultValue; auto* stat = event_builder.GetStat(*stats_metadata_); if (stat == nullptr) return kDefaultValue; if constexpr (std::is_integral_v<StatValueType>) { return event_builder.IntOrUintValue(*stat); } else { return event_builder.StrOrRefValue(*stat); } } private: XStatMetadata* stats_metadata_ = nullptr; }; template <std::size_t... Idx> auto make_index_dispatcher(std::index_sequence<Idx...>) { return [](auto&& f) { (f(std::integral_constant<std::size_t, Idx>{}), ...); }; } template <std::size_t N> auto make_index_dispatcher() { return make_index_dispatcher(std::make_index_sequence<N>{}); } template <typename Tuple, typename Func> void for_each(Tuple&& t, Func&& f) { constexpr auto n = std::tuple_size<std::decay_t<Tuple>>::value; auto dispatcher = make_index_dispatcher<n>(); dispatcher([&f, &t](auto idx) { f(std::get<idx>(std::forward<Tuple>(t))); }); } template <HostEventType producer_event, HostEventType consumer_event, ContextType context_type, bool unique_stats, typename... StatsAccessorTypes> class XplaneConnectedEventMutatorFactory : public XplaneEventMutatorFactory { public: static std::unique_ptr<XplaneEventMutatorFactory> CreateFactory() { return absl::WrapUnique(new XplaneConnectedEventMutatorFactory()); } using StatsAccessors = std::tuple<StatsAccessorTypes...>; std::vector<std::unique_ptr<XplaneEventMutator>> CreateMutators( XPlaneBuilder& xplane) const override { StatsAccessors stats_accessors; bool all_required_stats_exist = true; auto check_stats_meta = [&all_required_stats_exist, &xplane](auto&& accessor) { all_required_stats_exist = all_required_stats_exist && accessor.Initialize(xplane); }; for_each(stats_accessors, check_stats_meta); if (!all_required_stats_exist) return {}; XEventMetadata* producer_event_metadata = xplane.GetEventMetadata(GetHostEventTypeStr(producer_event)); XEventMetadata* consumer_event_metadata = xplane.GetEventMetadata(GetHostEventTypeStr(consumer_event)); std::vector<std::unique_ptr<XplaneEventMutator>> mutators; if (producer_event_metadata) { XStatMetadata* context_type_metadata = xplane.GetOrCreateStatMetadata( GetStatTypeStr(StatType::kProducerType)); XStatMetadata* context_id_metadata = xplane.GetOrCreateStatMetadata(GetStatTypeStr(StatType::kProducerId)); mutators.emplace_back(std::make_unique<XplaneConnectedEventMutator>( producer_event_metadata, *context_type_metadata, *context_id_metadata, stats_accessors)); } if (consumer_event_metadata) { XStatMetadata* context_type_metadata = xplane.GetOrCreateStatMetadata( GetStatTypeStr(StatType::kConsumerType)); XStatMetadata* context_id_metadata = xplane.GetOrCreateStatMetadata(GetStatTypeStr(StatType::kConsumerId)); mutators.emplace_back(std::make_unique<XplaneConnectedEventMutator>( consumer_event_metadata, *context_type_metadata, *context_id_metadata, stats_accessors)); } return mutators; } private: XplaneConnectedEventMutatorFactory() = default; class XplaneConnectedEventMutator : public XplaneEventMutator { public: XplaneConnectedEventMutator(XEventMetadata* event_metadata, XStatMetadata& context_type_metadata, XStatMetadata& context_id_metadata, const StatsAccessors& accessors) : XplaneEventMutator(event_metadata), context_type_metadata_(context_type_metadata), context_id_metadata_(context_id_metadata), accessors_(accessors) {} void Mutate(XEventBuilder& event_builder) override { bool all_required_stats_exist = true; std::vector<std::variant<absl::string_view, uint64_t>> required_stats; auto check_stats_meta = [&all_required_stats_exist, &required_stats, &event_builder](auto&& accessor) { if (all_required_stats_exist == false) return; auto stats_data = accessor.GetStat(event_builder); if (!stats_data) { all_required_stats_exist = false; } else { required_stats.emplace_back(*stats_data); } }; for_each(accessors_, check_stats_meta); if (!all_required_stats_exist) return; int64_t context_id; if constexpr (unique_stats) { context_id = absl::HashOf(required_stats); } else { context_id = absl::HashOf(producer_event, consumer_event, required_stats); } event_builder.SetOrAddStatValue(context_type_metadata_, static_cast<int64_t>(context_type)); event_builder.SetOrAddStatValue(context_id_metadata_, context_id); } void MutateEventsInLine(XLineBuilder& line) override { CHECK(false); } private: XStatMetadata& context_type_metadata_; XStatMetadata& context_id_metadata_; StatsAccessors accessors_; }; }; template <HostEventType event_type> class HostRunIdMutatorFactory : public XplaneEventMutatorFactory { public: static std::unique_ptr<XplaneEventMutatorFactory> CreateFactory() { return absl::WrapUnique(new HostRunIdMutatorFactory()); } std::vector<std::unique_ptr<XplaneEventMutator>> CreateMutators( XPlaneBuilder& xplane) const override { std::vector<std::unique_ptr<XplaneEventMutator>> mutators; if (auto* event_metadata = xplane.GetEventMetadata(GetHostEventTypeStr(event_type))) { XContextStatsAccessor<int64_t, StatType::kRunId> run_id_stats_accessor; if (run_id_stats_accessor.Initialize(xplane)) { XStatMetadata* run_id_metadata = xplane.GetOrCreateStatMetadata(GetStatTypeStr(StatType::kRunId)); mutators.emplace_back(std::make_unique<HostRunIdMutator>( event_metadata, run_id_stats_accessor, *run_id_metadata)); } } return mutators; } private: HostRunIdMutatorFactory() = default; class HostRunIdMutator : public XplaneEventMutator { public: HostRunIdMutator( XEventMetadata* event_metadata, XContextStatsAccessor<int64_t, StatType::kRunId> run_id_stats_accessor, XStatMetadata& run_id_metadata) : XplaneEventMutator(event_metadata), run_id_stats_accessor_(run_id_stats_accessor), run_id_metadata_(run_id_metadata) {} void Mutate(XEventBuilder& event_builder) override { auto run_id = run_id_stats_accessor_.GetStat(event_builder); if (!run_id) return; int64_t fixed_run_id = ((uint64_t)run_id.value() & kRunIdMask); event_builder.SetOrAddStatValue(run_id_metadata_, fixed_run_id); } void MutateEventsInLine(XLineBuilder& line) override { CHECK(false); } private: XContextStatsAccessor<int64_t, StatType::kRunId> run_id_stats_accessor_; XStatMetadata& run_id_metadata_; }; }; class TpuModuleLineMutatorFactory : public XplaneEventMutatorFactory { public: static std::unique_ptr<XplaneEventMutatorFactory> CreateFactory() { return absl::WrapUnique(new TpuModuleLineMutatorFactory()); } std::vector<std::unique_ptr<XplaneEventMutator>> CreateMutators( XPlaneBuilder& xplane) const override { std::vector<std::unique_ptr<XplaneEventMutator>> mutators; if (absl::StartsWith(xplane.Name(), kTpuPlanePrefix) && GetTensorCoreId(xplane.Name()).has_value()) { if (auto device_ordinal = ParseDeviceOrdinal(xplane.Name())) { XStatMetadata* context_type_metadata = xplane.GetOrCreateStatMetadata( GetStatTypeStr(StatType::kConsumerType)); XStatMetadata* context_id_metadata = xplane.GetOrCreateStatMetadata( GetStatTypeStr(StatType::kConsumerId)); XContextStatsAccessor<uint64_t, StatType::kQueueId> queue_id_stats_accessor; XContextStatsAccessor<uint64_t, StatType::kRunId> run_id_stats_accessor; XContextStatsAccessorWithDefault<uint64_t, StatType::kCoreType, 0ULL> core_type_stats_accessor; if (queue_id_stats_accessor.Initialize(xplane) && run_id_stats_accessor.Initialize(xplane) && core_type_stats_accessor.Initialize(xplane)) { mutators.emplace_back(std::make_unique<TpuModuleLineMutator>( *device_ordinal, *context_type_metadata, *context_id_metadata, queue_id_stats_accessor, run_id_stats_accessor, core_type_stats_accessor)); } } } return mutators; } private: TpuModuleLineMutatorFactory() = default; class TpuModuleLineMutator : public XplaneEventMutator { public: TpuModuleLineMutator( uint32_t device_ordinal, XStatMetadata& context_type_metadata, XStatMetadata& context_id_metadata, XContextStatsAccessor<uint64_t, StatType::kQueueId> queue_id_stats_accessor, XContextStatsAccessor<uint64_t, StatType::kRunId> run_id_stats_accessor, XContextStatsAccessorWithDefault<uint64_t, StatType::kCoreType, 0ULL> core_type_stats_accessor) : XplaneEventMutator(nullptr), device_ordinal_(device_ordinal), context_type_metadata_(context_type_metadata), context_id_metadata_(context_id_metadata), queue_id_stats_accessor_(queue_id_stats_accessor), run_id_stats_accessor_(run_id_stats_accessor), core_type_stats_accessor_(core_type_stats_accessor) {} void Mutate(XEventBuilder& event_builder) override { CHECK(false); } void MutateEventsInLine(XLineBuilder& line) override { if (line.Name() != kXlaModuleLineName) return; line.ForEachEvent([&](XEventBuilder event) { auto run_id = run_id_stats_accessor_.GetStat(event); auto queue_id = queue_id_stats_accessor_.GetStat(event); auto core_type = core_type_stats_accessor_.GetStat(event); if (!run_id || !queue_id) return; std::vector<std::variant<absl::string_view, uint64_t>> required_stats; required_stats.reserve(4); required_stats.emplace_back(device_ordinal_); required_stats.emplace_back(*queue_id); required_stats.emplace_back(*run_id); required_stats.emplace_back(static_cast<uint64_t>(*core_type)); int64_t context_id = absl::HashOf(required_stats); event.SetOrAddStatValue(context_type_metadata_, static_cast<int64_t>(ContextType::kTpuLaunch)); event.SetOrAddStatValue(context_id_metadata_, context_id); }); } private: uint64_t device_ordinal_; XStatMetadata& context_type_metadata_; XStatMetadata& context_id_metadata_; XContextStatsAccessor<uint64_t, StatType::kQueueId> queue_id_stats_accessor_; XContextStatsAccessor<uint64_t, StatType::kRunId> run_id_stats_accessor_; XContextStatsAccessorWithDefault<uint64_t, StatType::kCoreType, 0ULL> core_type_stats_accessor_; }; }; class ThreadpoolLineMutatorFactory : public XplaneEventMutatorFactory { public: static std::unique_ptr<XplaneEventMutatorFactory> CreateFactory() { return absl::WrapUnique(new ThreadpoolLineMutatorFactory()); } std::vector<std::unique_ptr<XplaneEventMutator>> CreateMutators( XPlaneBuilder& xplane) const override { std::vector<std::unique_ptr<XplaneEventMutator>> mutators; mutators.emplace_back(std::make_unique<ThreadpoolLineMutator>(xplane)); return mutators; } private: ThreadpoolLineMutatorFactory() = default; class ThreadpoolLineMutator : public XplaneEventMutator { public: explicit ThreadpoolLineMutator(XPlaneBuilder& xplane) : XplaneEventMutator(nullptr), xplane_(xplane) { start_region_metadata_ = xplane_.GetEventMetadata(kThreadpoolListenerStartRegion); stop_region_metadata_ = xplane_.GetEventMetadata(kThreadpoolListenerStopRegion); thread_pool_metadata_ = xplane_.GetOrCreateEventMetadata(kThreadpoolListenerRegion); consumer_ = xplane_.GetOrCreateStatMetadata( GetStatTypeStr(StatType::kConsumerId)); consumer_type_ = xplane_.GetOrCreateStatMetadata( GetStatTypeStr(StatType::kConsumerType)); } void Mutate(XEventBuilder& event_builder) override { CHECK(false); } void MutateEventsInLine(XLineBuilder& line) override { if (start_region_metadata_ == nullptr || stop_region_metadata_ == nullptr) { return; } int64_t start_region_timestamp_ps = 0; int64_t region_id; struct EventMetadata { int64_t start_region_timestamp_ps; int64_t region_id; int64_t end_region_timestamp_ps; }; std::vector<EventMetadata> event_metadata; line.ForEachEvent([&](const XEventBuilder& event) { if (event.MetadataId() == start_region_metadata_->id()) { auto consumer_id = event.GetStat(*consumer_); if (!consumer_id) return; start_region_timestamp_ps = event.TimestampPs(); region_id = event.IntOrUintValue(*consumer_id); } else if (event.MetadataId() == stop_region_metadata_->id() && start_region_timestamp_ps != 0) { EventMetadata metadata; metadata.start_region_timestamp_ps = start_region_timestamp_ps; metadata.region_id = region_id; metadata.end_region_timestamp_ps = event.TimestampPs(); event_metadata.emplace_back(metadata); } }); for (const auto& event_metadata : event_metadata) { XEventBuilder region = line.AddEvent(*thread_pool_metadata_); region.SetTimestampPs(event_metadata.start_region_timestamp_ps); region.SetEndTimestampPs(event_metadata.end_region_timestamp_ps); region.SetOrAddStatValue(*consumer_, event_metadata.region_id); region.SetOrAddStatValue( *consumer_type_, static_cast<int64_t>(ContextType::kThreadpoolEvent)); } } private: XStatMetadata* consumer_; XStatMetadata* consumer_type_; XPlaneBuilder& xplane_; XEventMetadata* start_region_metadata_; XEventMetadata* stop_region_metadata_; XEventMetadata* thread_pool_metadata_; }; }; void PreprocessXSpace(XSpace* space); void PreprocessXPlane(XPlane* plane); } } #endif #include "tsl/profiler/utils/preprocess_xplane.h" #include <cstdint> #include <memory> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "tsl/profiler/lib/context_types.h" #include "tsl/profiler/protobuf/xplane.pb.h" #include "tsl/profiler/utils/xplane_builder.h" #include "tsl/profiler/utils/xplane_schema.h" namespace tsl { namespace profiler { namespace { using ::tsl::profiler::HostEventType; using ::tsl::profiler::StatType; using ::tsl::profiler::XEventBuilder; using ::tsl::profiler::XLineBuilder; using ::tsl::profiler::XPlane; using ::tsl::profiler::XPlaneBuilder; using ::tsl::profiler::XSpace; void MutateXPlane(XPlane& plane, const std::vector<std::unique_ptr<XplaneEventMutatorFactory>>& mutator_factories) { XPlaneBuilder plane_builder(&plane); absl::flat_hash_map<int64_t, std::vector<std::unique_ptr<XplaneEventMutator>>> mutators_from_event_metadata_id; std::vector<std::unique_ptr<XplaneEventMutator>> line_mutators; for (const auto& mutator_factory : mutator_factories) { auto mutators = mutator_factory->CreateMutators(plane_builder); for (auto& mutator : mutators) { if (mutator->event_metadata()) { auto id = mutator->event_metadata()->id(); mutators_from_event_metadata_id[id].push_back(std::move(mutator)); } else { line_mutators.push_back(std::move(mutator)); } } } if (mutators_from_event_metadata_id.empty() && line_mutators.empty()) { return; } plane_builder.ForEachLine([&](XLineBuilder line_builder) { for (const auto& mutator : line_mutators) { mutator->MutateEventsInLine(line_builder); } if (mutators_from_event_metadata_id.empty()) return; line_builder.ForEachEvent([&](XEventBuilder event_builder) { auto event_mutators = mutators_from_event_metadata_id.find(event_builder.MetadataId()); if (event_mutators != mutators_from_event_metadata_id.end()) { for (const auto& mutator : event_mutators->second) { mutator->Mutate(event_builder); } } }); }); } std::vector<std::unique_ptr<XplaneEventMutatorFactory>> CreateMutatorFactories() { std::vector<std::unique_ptr<XplaneEventMutatorFactory>> mutator_factories; mutator_factories.push_back(ThreadpoolLineMutatorFactory::CreateFactory()); mutator_factories.push_back(XplaneRootEventMutatorFactory::CreateFactory( HostEventType::kProcessBatch, 2)); mutator_factories.push_back(XplaneRootEventMutatorFactory::CreateFactory( HostEventType::kBatchingSessionRun, 1)); mutator_factories.push_back( XplaneConnectedEventMutatorFactory< HostEventType::kExecutorStateProcess, HostEventType::kTpuExecuteOp, ContextType::kLegacy, false, XContextStatsAccessor<uint64_t, StatType::kStepId>, XContextStatsAccessor<uint64_t, StatType::kIterNum>>::CreateFactory()); #define ADD_QUEUE_CONNECTION(__enque_event__, __deque_event__) \ mutator_factories.push_back( \ XplaneConnectedEventMutatorFactory< \ HostEventType::__enque_event__, HostEventType::__deque_event__, \ ContextType::kTpuStream, true, \ XContextStatsAccessor<uint64, StatType::kRequestId>, \ XContextStatsAccessor<uint64, \ StatType::kQueueAddr>>::CreateFactory()) ADD_QUEUE_CONNECTION(kEnqueueRequestLocked, kRunProgramRequest); ADD_QUEUE_CONNECTION(kEnqueueRequestLocked, kHostCallbackRequest); ADD_QUEUE_CONNECTION(kEnqueueRequestLocked, kTransferH2DRequest); ADD_QUEUE_CONNECTION(kEnqueueRequestLocked, kTransferPreprocessedH2DRequest); ADD_QUEUE_CONNECTION(kEnqueueRequestLocked, kTransferD2HRequest); ADD_QUEUE_CONNECTION(kEnqueueRequestLocked, kOnDeviceSendRequest); ADD_QUEUE_CONNECTION(kEnqueueRequestLocked, kOnDeviceRecvRequest); ADD_QUEUE_CONNECTION(kEnqueueRequestLocked, kOnDeviceSendRecvLocalRequest); ADD_QUEUE_CONNECTION(kEnqueueRequestLocked, kCustomWait); ADD_QUEUE_CONNECTION(kEnqueueRequestLocked, kOnDeviceSendRequestMulti); ADD_QUEUE_CONNECTION(kEnqueueRequestLocked, kOnDeviceRecvRequestMulti); ADD_QUEUE_CONNECTION(kEnqueueRequestLocked, kPjrtAsyncWait); #undef ADD_QUEUE_CONNECTION mutator_factories.push_back( HostRunIdMutatorFactory< HostEventType::kDoEnqueueProgram>::CreateFactory()); mutator_factories.push_back( HostRunIdMutatorFactory< HostEventType::kCompleteCallbacks>::CreateFactory()); mutator_factories.push_back( HostRunIdMutatorFactory< HostEventType::kDoEnqueueContinuationProgram>::CreateFactory()); mutator_factories.push_back( XplaneConnectedEventMutatorFactory< HostEventType::kDoEnqueueProgram, HostEventType::kCompleteCallbacks, ContextType::kTpuLaunch, true, XContextStatsAccessor<uint64_t, StatType::kDeviceOrdinal>, XContextStatsAccessor<uint64_t, StatType::kQueueId>, XContextStatsAccessor<uint64_t, StatType::kRunId>, XContextStatsAccessorWithDefault<uint64_t, StatType::kCoreType, 0ULL>>::CreateFactory()); mutator_factories.push_back(TpuModuleLineMutatorFactory::CreateFactory()); return mutator_factories; } } void PreprocessXPlane(XPlane* plane) { if (plane == nullptr) return; auto mutator_factories = CreateMutatorFactories(); MutateXPlane(*plane, mutator_factories); } void PreprocessXSpace(XSpace* space) { if (space == nullptr) return; auto mutator_factories = CreateMutatorFactories(); for (XPlane& plane : *space->mutable_planes()) { MutateXPlane(plane, mutator_factories); } } } }
#include "tsl/profiler/utils/preprocess_xplane.h" #include <cstdint> #include <memory> #include <optional> #include "absl/container/flat_hash_map.h" #include "absl/hash/hash.h" #include "tsl/platform/test.h" #include "tsl/profiler/lib/connected_traceme.h" #include "tsl/profiler/protobuf/xplane.pb.h" #include "tsl/profiler/utils/tf_xplane_visitor.h" #include "tsl/profiler/utils/xplane_builder.h" #include "tsl/profiler/utils/xplane_schema.h" #include "tsl/profiler/utils/xplane_test_utils.h" #include "tsl/profiler/utils/xplane_visitor.h" namespace tsl { namespace profiler { namespace { using ::tsl::profiler::CreateTfXPlaneVisitor; using ::tsl::profiler::CreateXEvent; using ::tsl::profiler::GetHostEventTypeStr; using ::tsl::profiler::HostEventType; using ::tsl::profiler::StatType; using ::tsl::profiler::XEventVisitor; using ::tsl::profiler::XLineVisitor; using ::tsl::profiler::XPlane; using ::tsl::profiler::XPlaneBuilder; using ::tsl::profiler::XPlaneVisitor; using ::tsl::profiler::XSpace; TEST(PreprocessXPlane, IsRootStatsTest) { XSpace space; XPlane* plane = space.add_planes(); XPlaneBuilder plane_builder(plane); plane_builder.ReserveLines(1); auto line_builder = plane_builder.GetOrCreateLine(0); CreateXEvent(&plane_builder, &line_builder, GetHostEventTypeStr(HostEventType::kProcessBatch), 100, 100); CreateXEvent(&plane_builder, &line_builder, GetHostEventTypeStr(HostEventType::kBatchingSessionRun), 200, 100); PreprocessXSpace(&space); XPlaneVisitor plane_visitor = CreateTfXPlaneVisitor(plane); plane_visitor.ForEachLine([&](const XLineVisitor& line) { line.ForEachEvent([&](const XEventVisitor& event) { ASSERT_TRUE(event.GetStat(StatType::kIsRoot).has_value()); int64_t is_root = event.GetStat(StatType::kIsRoot)->IntValue(); if (event.Type() == HostEventType::kBatchingSessionRun) { EXPECT_EQ(is_root, 1); } else if (event.Type() == HostEventType::kProcessBatch) { EXPECT_EQ(is_root, 2); } else { CHECK(false); } }); }); } TEST(PreprocessXPlane, ProducerConsumerTest) { XSpace space; XPlane* plane = space.add_planes(); XPlaneBuilder plane_builder(plane); plane_builder.ReserveLines(2); auto line_builder = plane_builder.GetOrCreateLine(0); CreateXEvent( &plane_builder, &line_builder, GetHostEventTypeStr(HostEventType::kExecutorStateProcess), 100, 100, {{StatType::kStepId, int64_t{123}}, {StatType::kIterNum, int64_t{456}}}); line_builder = plane_builder.GetOrCreateLine(1); CreateXEvent( &plane_builder, &line_builder, GetHostEventTypeStr(HostEventType::kTpuExecuteOp), 200, 100, {{StatType::kStepId, int64_t{123}}, {StatType::kIterNum, int64_t{456}}}); PreprocessXSpace(&space); std::optional<uint64_t> producer_context_id, consumer_context_id; XPlaneVisitor plane_visitor = CreateTfXPlaneVisitor(plane); plane_visitor.ForEachLine([&](const XLineVisitor& line) { line.ForEachEvent([&](const XEventVisitor& event) { if (event.Type() == HostEventType::kExecutorStateProcess) { auto producer_type = event.GetStat(StatType::kProducerType); ASSERT_TRUE(producer_type.has_value()); EXPECT_EQ(producer_type->IntValue(), static_cast<int64_t>(ContextType::kLegacy)); auto producer_id = event.GetStat(StatType::kProducerId); ASSERT_TRUE(producer_id.has_value()); producer_context_id = producer_id->IntOrUintValue(); } else if (event.Type() == HostEventType::kTpuExecuteOp) { auto consumer_type = event.GetStat(StatType::kConsumerType); ASSERT_TRUE(consumer_type.has_value()); EXPECT_EQ(consumer_type->IntValue(), static_cast<int64_t>(ContextType::kLegacy)); auto consumer_id = event.GetStat(StatType::kConsumerId); ASSERT_TRUE(consumer_id.has_value()); consumer_context_id = consumer_id->IntOrUintValue(); } else { CHECK(false); } }); }); ASSERT_TRUE(producer_context_id && consumer_context_id); ASSERT_EQ(*producer_context_id, *consumer_context_id); } TEST(PreprocessXPlane, ProducerConsumerNotMatchedTest) { XSpace space; XPlane* plane = space.add_planes(); XPlaneBuilder plane_builder(plane); plane_builder.ReserveLines(2); auto line_builder = plane_builder.GetOrCreateLine(0); CreateXEvent(&plane_builder, &line_builder, GetHostEventTypeStr(HostEventType::kExecutorStateProcess), 100, 100, {{StatType::kStepId, int64_t{123}}, {StatType::kIterNum, int64_t{456}}, {StatType::kDeviceOrdinal, int64_t{789}}}); line_builder = plane_builder.GetOrCreateLine(1); CreateXEvent( &plane_builder, &line_builder, GetHostEventTypeStr(HostEventType::kTpuExecuteOp), 200, 100, {{StatType::kStepId, int64_t{123}}, {StatType::kIterNum, int64_t{789}}}); PreprocessXSpace(&space); std::optional<uint64_t> producer_context_id, consumer_context_id; XPlaneVisitor plane_visitor = CreateTfXPlaneVisitor(plane); plane_visitor.ForEachLine([&](const XLineVisitor& line) { line.ForEachEvent([&](const XEventVisitor& event) { if (event.Type() == HostEventType::kExecutorStateProcess) { auto producer_type = event.GetStat(StatType::kProducerType); ASSERT_TRUE(producer_type.has_value()); EXPECT_EQ(producer_type->IntValue(), static_cast<int64_t>(ContextType::kLegacy)); auto producer_id = event.GetStat(StatType::kProducerId); ASSERT_TRUE(producer_id.has_value()); producer_context_id = producer_id->IntOrUintValue(); } else if (event.Type() == HostEventType::kTpuExecuteOp) { auto consumer_type = event.GetStat(StatType::kConsumerType); ASSERT_TRUE(consumer_type.has_value()); EXPECT_EQ(consumer_type->IntValue(), static_cast<int64_t>(ContextType::kLegacy)); auto consumer_id = event.GetStat(StatType::kConsumerId); ASSERT_TRUE(consumer_id.has_value()); consumer_context_id = consumer_id->IntOrUintValue(); } else { CHECK(false); } }); }); ASSERT_TRUE(producer_context_id && consumer_context_id); ASSERT_NE(*producer_context_id, *consumer_context_id); } TEST(PreprocessXPlane, MissingLegacyStatTest) { XSpace space; XPlane* plane = space.add_planes(); XPlaneBuilder plane_builder(plane); plane_builder.ReserveLines(2); auto line_builder = plane_builder.GetOrCreateLine(0); CreateXEvent(&plane_builder, &line_builder, GetHostEventTypeStr(HostEventType::kExecutorStateProcess), 100, 100, {{StatType::kStepId, int64_t{123}}}); line_builder = plane_builder.GetOrCreateLine(1); CreateXEvent(&plane_builder, &line_builder, GetHostEventTypeStr(HostEventType::kTpuExecuteOp), 200, 100, {{StatType::kStepId, int64_t{123}}}); PreprocessXSpace(&space); XPlaneVisitor plane_visitor = CreateTfXPlaneVisitor(plane); plane_visitor.ForEachLine([&](const XLineVisitor& line) { line.ForEachEvent([&](const XEventVisitor& event) { if (event.Type() == HostEventType::kExecutorStateProcess) { auto producer_type = event.GetStat(StatType::kProducerType); ASSERT_FALSE(producer_type.has_value()); auto producer_id = event.GetStat(StatType::kProducerId); ASSERT_FALSE(producer_id.has_value()); } else if (event.Type() == HostEventType::kTpuExecuteOp) { auto consumer_type = event.GetStat(StatType::kConsumerType); ASSERT_FALSE(consumer_type.has_value()); auto consumer_id = event.GetStat(StatType::kConsumerId); ASSERT_FALSE(consumer_id.has_value()); } else { CHECK(false); } }); }); } TEST(PreprocessXPlane, HostRunIdPreprocessorTest) { XSpace space; XPlane* plane = space.add_planes(); XPlaneBuilder plane_builder(plane); plane_builder.ReserveLines(2); auto line_builder = plane_builder.GetOrCreateLine(0); int64_t host_run_id = int64_t{582974244}; int64_t device_run_id = int64_t{46103332}; CreateXEvent( &plane_builder, &line_builder, GetHostEventTypeStr(HostEventType::kDoEnqueueContinuationProgram), 100, 100, {}); CreateXEvent(&plane_builder, &line_builder, GetHostEventTypeStr(HostEventType::kDoEnqueueProgram), 100, 100, {{StatType::kRunId, int64_t{host_run_id}}}); CreateXEvent(&plane_builder, &line_builder, GetHostEventTypeStr(HostEventType::kTpuExecuteOp), 200, 100, {{StatType::kRunId, int64_t{device_run_id}}}); CreateXEvent(&plane_builder, &line_builder, GetHostEventTypeStr(HostEventType::kCompleteCallbacks), 300, 100, {{StatType::kRunId, int64_t{host_run_id}}}); line_builder = plane_builder.GetOrCreateLine(1); PreprocessXSpace(&space); XPlaneVisitor plane_visitor = CreateTfXPlaneVisitor(plane); plane_visitor.ForEachLine([&](const XLineVisitor& line) { line.ForEachEvent([&](const XEventVisitor& event) { if (event.Type() == HostEventType::kDoEnqueueContinuationProgram) { auto run_id = event.GetStat(StatType::kRunId); ASSERT_FALSE(run_id.has_value()); } else if (event.Type() == HostEventType::kDoEnqueueProgram) { auto run_id = event.GetStat(StatType::kRunId); ASSERT_TRUE(run_id.has_value()); ASSERT_EQ(run_id->IntValue(), device_run_id); } else if (event.Type() == HostEventType::kTpuExecuteOp) { auto run_id = event.GetStat(StatType::kRunId); ASSERT_TRUE(run_id.has_value()); ASSERT_EQ(run_id->IntValue(), device_run_id); } else if (event.Type() == HostEventType::kCompleteCallbacks) { auto run_id = event.GetStat(StatType::kRunId); ASSERT_TRUE(run_id.has_value()); ASSERT_EQ(run_id->IntValue(), device_run_id); } else { CHECK(false); } }); }); } TEST(PreprocessXPlane, ThreadPoolPreprocessorTest) { XSpace space; XPlane* plane = space.add_planes(); XPlaneBuilder plane_builder(plane); auto main_line = plane_builder.GetOrCreateLine(0); CreateXEvent(&plane_builder, &main_line, kThreadpoolListenerRecord, 100, 100, {{StatType::kProducerType, static_cast<int64_t>(ContextType::kThreadpoolEvent)}, {StatType::kProducerId, int64_t{123}}}); auto thread_pool_line = plane_builder.GetOrCreateLine(1); CreateXEvent(&plane_builder, &thread_pool_line, kThreadpoolListenerStartRegion, 200, 0, {{StatType::kConsumerType, static_cast<int64_t>(ContextType::kThreadpoolEvent)}, {StatType::kConsumerId, int64_t{123}}}); CreateXEvent(&plane_builder, &thread_pool_line, kThreadpoolListenerStopRegion, 300, 0, {{StatType::kConsumerType, static_cast<int64_t>(ContextType::kThreadpoolEvent)}, {StatType::kConsumerId, int64_t{123}}}); bool new_event_added = false; PreprocessXSpace(&space); XPlaneVisitor plane_visitor = CreateTfXPlaneVisitor(plane); plane_visitor.ForEachLine([&](const XLineVisitor& line) { line.ForEachEvent([&](const XEventVisitor& event) { if (event.Name() == kThreadpoolListenerRegion) { new_event_added = true; EXPECT_EQ(event.DurationPs(), 100); EXPECT_EQ(event.TimestampPs(), 200); auto stat = event.GetStat(StatType::kConsumerId); EXPECT_TRUE(stat.has_value()); EXPECT_EQ(stat->IntOrUintValue(), 123); } }); }); EXPECT_TRUE(new_event_added); } TEST(PreprocessXPlane, XContextStatsAccessorNPETest) { auto xplane = std::make_unique<XPlane>(); XPlaneBuilder xplane_builder(xplane.get()); XLine xline; XLineBuilder xline_builder(&xline, &xplane_builder); XEvent xevent; XEventBuilder xevent_builder(&xline, &xplane_builder, &xevent); XContextStatsAccessor<int64_t, StatType::kRunId> run_id_accessor; ASSERT_FALSE(run_id_accessor.Initialize(xplane_builder)); EXPECT_EQ(run_id_accessor.GetStat(xevent_builder), std::nullopt); } } } }
2,296
#ifndef TENSORFLOW_TSL_PROFILER_UTILS_TF_OP_UTILS_H_ #define TENSORFLOW_TSL_PROFILER_UTILS_TF_OP_UTILS_H_ #include <string> #include <vector> #include "absl/strings/match.h" #include "absl/strings/string_view.h" #include "tsl/platform/macros.h" namespace tsl { namespace profiler { TF_CONST_INIT extern const absl::string_view kUnknownOp; TF_CONST_INIT extern const absl::string_view kDatasetOp; TF_CONST_INIT extern const absl::string_view kMemcpyHToDOp; TF_CONST_INIT extern const absl::string_view kMemcpyDToHOp; TF_CONST_INIT extern const absl::string_view kMemcpyDToDOp; TF_CONST_INIT extern const absl::string_view kMemcpyHToHOp; enum class Category { kUnknown, kTensorFlow, kJax, kTfData, kMemcpyHToD, kMemcpyDToH, kMemcpyDToD, kMemcpyHToH, }; struct TfOp { Category category = Category::kUnknown; absl::string_view name; absl::string_view type; }; TfOp ParseTfOpFullname(absl::string_view tf_op_fullname); std::vector<absl::string_view> ParseTfNameScopes(absl::string_view tf_op_name); std::vector<absl::string_view> ParseTfNameScopes(const TfOp& tf_op); std::string TfOpEventName(const TfOp& tf_op); std::string TfOpEventName(absl::string_view tf_op_fullname); std::string DatasetOpEventName(absl::string_view full_name); std::string IteratorName(absl::string_view full_name); inline bool IsDatasetOp(absl::string_view tf_op_type) { return tf_op_type == kDatasetOp; } inline bool IsDatasetOp(const TfOp& tf_op) { return tf_op.category == Category::kTfData; } inline bool IsInfeedEnqueueOp(absl::string_view tf_op_type) { return absl::StartsWith(tf_op_type, "InfeedEnqueue"); } inline bool IsInfeedEnqueueOp(const TfOp& tf_op) { return tf_op.category == Category::kTensorFlow && IsInfeedEnqueueOp(tf_op.type); } inline bool IsOutsideCompilationOp(absl::string_view tf_op_fullname) { if (absl::EndsWith(tf_op_fullname, ":XlaSendToHost")) return true; if (absl::EndsWith(tf_op_fullname, ":XlaRecvFromHost")) return true; return false; } inline bool IsOutsideCompilationOp(absl::string_view tf_op_fullname, absl::string_view hlo_expression) { if (IsOutsideCompilationOp(tf_op_fullname)) return true; if (absl::StrContains(hlo_expression, "send-done") && absl::StrContains(hlo_expression, "is_host_transfer=true")) return true; return false; } inline bool IsEmbeddingOp(absl::string_view tf_op_fullname) { return absl::StrContains(tf_op_fullname, "Embedding"); } inline bool IsMemcpyHToDOp(absl::string_view tf_op_type) { return tf_op_type == kMemcpyHToDOp; } inline bool IsMemcpyHToDOp(const TfOp& tf_op) { return tf_op.category == Category::kMemcpyHToD; } inline bool IsMemcpyDToHOp(const TfOp& tf_op) { return tf_op.category == Category::kMemcpyDToH; } inline bool IsMemcpyDToDOp(const TfOp& tf_op) { return tf_op.category == Category::kMemcpyDToD; } inline bool IsMemcpyHToHOp(const TfOp& tf_op) { return tf_op.category == Category::kMemcpyHToH; } std::vector<absl::string_view> ParseTensorShapes( absl::string_view tensor_shapes); bool IsTfOpName(absl::string_view op_name); bool IsTfOpType(absl::string_view op_type); bool IsJaxOpType(absl::string_view op_type); bool IsJaxOpNameAndType(absl::string_view op_name, absl::string_view op_type); } } #endif #include "tsl/profiler/utils/tf_op_utils.h" #include <cstdint> #include <optional> #include <string> #include <vector> #include "absl/strings/ascii.h" #include "absl/strings/match.h" #include "absl/strings/numbers.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_split.h" #include "absl/strings/string_view.h" #include "absl/strings/strip.h" #include "tsl/platform/regexp.h" namespace tsl { namespace profiler { namespace { const absl::string_view kIterator = "Iterator"; const absl::string_view kSeparator = "::"; constexpr char kNameScopeSeparator = '/'; constexpr char kOpNameSuffixSeparator = '_'; bool IsInteger(absl::string_view str) { int64_t unused; return absl::SimpleAtoi(str, &unused); } absl::string_view DeriveOpType(absl::string_view full_op_name) { std::vector<absl::string_view> name_scopes_and_op_name = absl::StrSplit(full_op_name, kNameScopeSeparator); absl::string_view op_name = name_scopes_and_op_name.back(); std::vector<absl::string_view> op_type_and_maybe_suffix = absl::StrSplit(op_name, kOpNameSuffixSeparator); absl::string_view maybe_suffix = op_type_and_maybe_suffix.back(); absl::string_view op_type = op_name; if (IsInteger(maybe_suffix)) { op_type = op_name.substr(0, op_name.size() - maybe_suffix.size() - 1); } return op_type; } std::optional<TfOp> GetMemcpyOp(absl::string_view tf_op_fullname) { TfOp tf_op; tf_op.name = tf_op_fullname; if (absl::StartsWithIgnoreCase(tf_op_fullname, "MEMCPYHToD")) { tf_op.category = Category::kMemcpyHToD; tf_op.type = kMemcpyHToDOp; return tf_op; } if (absl::StartsWithIgnoreCase(tf_op_fullname, "MEMCPYDToH")) { tf_op.category = Category::kMemcpyDToH; tf_op.type = kMemcpyDToHOp; return tf_op; } if (absl::StartsWithIgnoreCase(tf_op_fullname, "MEMCPYDToD")) { tf_op.category = Category::kMemcpyDToD; tf_op.type = kMemcpyDToDOp; return tf_op; } else if (absl::StartsWithIgnoreCase(tf_op_fullname, "MEMCPYHToH")) { tf_op.category = Category::kMemcpyHToH; tf_op.type = kMemcpyHToHOp; return tf_op; } return std::nullopt; } } const absl::string_view kUnknownOp = ""; const absl::string_view kDatasetOp = "Dataset"; const absl::string_view kMemcpyHToDOp = "MemcpyHToD"; const absl::string_view kMemcpyDToHOp = "MemcpyDToH"; const absl::string_view kMemcpyDToDOp = "MemcpyDToD"; const absl::string_view kMemcpyHToHOp = "MemcpyHToH"; bool IsTfOpName(absl::string_view op_name) { static const LazyRE2 kTfOpNameRegEx = {"[A-Za-z0-9.][A-Za-z0-9_.\\/>-]*"}; return RE2::FullMatch(op_name, *kTfOpNameRegEx); } bool IsTfOpType(absl::string_view op_type) { static const LazyRE2 kTfOpTypeRegEx = {"[A-Z_][a-zA-Z0-9_]*"}; return RE2::FullMatch(op_type, *kTfOpTypeRegEx); } bool IsJaxOpType(absl::string_view op_type) { static const LazyRE2 kJaxOpTypeRegEx = {"[a-z_][a-z0-9_]*(\\[.*\\])?"}; return RE2::FullMatch(op_type, *kJaxOpTypeRegEx); } bool IsJaxOpNameAndType(absl::string_view op_name, absl::string_view op_type) { if (op_name.empty() || !IsJaxOpType(op_type)) return false; std::vector<absl::string_view> split_result = absl::StrSplit(op_name, kNameScopeSeparator); return absl::StrContains(split_result.back(), op_type); } TfOp ParseTfOpFullname(absl::string_view tf_op_fullname) { TfOp tf_op = {Category::kUnknown, tf_op_fullname, kUnknownOp}; std::vector<absl::string_view> parts = absl::StrSplit(tf_op_fullname, absl::MaxSplits(':', 1)); if (parts.size() != 2) { if (std::optional<TfOp> tfop = GetMemcpyOp(parts[0]); tfop.has_value()) { return *tfop; } return tf_op; } if (parts[0] == kIterator) { tf_op.category = Category::kTfData; tf_op.type = kDatasetOp; return tf_op; } if (IsTfOpName(parts[0]) && IsTfOpType(parts[1])) { tf_op.category = Category::kTensorFlow; tf_op.name = parts[0]; tf_op.type = parts[1]; return tf_op; } absl::string_view op_type = parts[1].empty() ? DeriveOpType(parts[0]) : parts[1]; if (IsJaxOpType(op_type)) { tf_op.category = Category::kJax; tf_op.name = parts[0]; tf_op.type = op_type.substr(0, op_type.find('[')); return tf_op; } if (parts[1].empty()) { tf_op.category = Category::kTensorFlow; tf_op.name = parts[0]; tf_op.type = op_type; return tf_op; } return tf_op; } std::vector<absl::string_view> ParseTfNameScopes(absl::string_view tf_op_name) { std::vector<absl::string_view> name_scopes = absl::StrSplit(tf_op_name, kNameScopeSeparator); if (!name_scopes.empty()) name_scopes.pop_back(); return name_scopes; } std::vector<absl::string_view> ParseTfNameScopes(const TfOp& tf_op) { return ParseTfNameScopes(tf_op.name); } std::string TfOpEventName(const TfOp& tf_op) { std::string event_name; if (tf_op.category == Category::kUnknown) { event_name = std::string(absl::StripTrailingAsciiWhitespace(tf_op.name)); } else if (tf_op.category == Category::kTfData) { event_name = DatasetOpEventName(tf_op.name); } else { event_name = std::string(tf_op.type); } return event_name; } std::string TfOpEventName(absl::string_view tf_op_fullname) { return TfOpEventName(ParseTfOpFullname(tf_op_fullname)); } std::string DatasetOpEventName(absl::string_view full_name) { std::vector<absl::string_view> split_result = absl::StrSplit(full_name, kSeparator); return absl::StrCat(kIterator, kSeparator, split_result.back()); } std::string IteratorName(absl::string_view full_name) { std::vector<absl::string_view> split_result = absl::StrSplit(full_name, kSeparator); return std::string(split_result.back()); } std::vector<absl::string_view> ParseTensorShapes( absl::string_view tensor_shapes) { absl::ConsumePrefix(&tensor_shapes, "("); absl::ConsumeSuffix(&tensor_shapes, ")"); return absl::StrSplit(tensor_shapes, ';'); } } }
#include "tsl/profiler/utils/tf_op_utils.h" #include <vector> #include "absl/strings/string_view.h" #include "tsl/platform/test.h" namespace tsl { namespace profiler { namespace { TEST(TfOpUtilsTest, TfOpTest) { const absl::string_view kName = "OpName:OpType"; TfOp tf_op = ParseTfOpFullname(kName); EXPECT_EQ(tf_op.category, Category::kTensorFlow); EXPECT_EQ(tf_op.name, "OpName"); EXPECT_EQ(tf_op.type, "OpType"); EXPECT_EQ(TfOpEventName(kName), "OpType"); } TEST(TfOpUtilsTest, InternalTfOpTest) { const absl::string_view kName = "OpName:_InternalOpType"; TfOp tf_op = ParseTfOpFullname(kName); EXPECT_EQ(tf_op.category, Category::kTensorFlow); EXPECT_EQ(tf_op.name, "OpName"); EXPECT_EQ(tf_op.type, "_InternalOpType"); EXPECT_EQ(TfOpEventName(kName), "_InternalOpType"); } TEST(TfOpUtilsTest, TfOpWithPathTest) { const absl::string_view kName = "path/to/name:OpType"; TfOp tf_op = ParseTfOpFullname(kName); EXPECT_EQ(tf_op.category, Category::kTensorFlow); EXPECT_EQ(tf_op.name, "path/to/name"); EXPECT_EQ(tf_op.type, "OpType"); EXPECT_EQ(TfOpEventName(kName), "OpType"); } TEST(TfOpUtilsTest, ShortDatasetOpTest) { const absl::string_view kName = "Iterator::Batch"; TfOp tf_op = ParseTfOpFullname(kName); EXPECT_EQ(tf_op.category, Category::kTfData); EXPECT_EQ(tf_op.name, kName); EXPECT_EQ(tf_op.type, kDatasetOp); EXPECT_EQ(TfOpEventName(kName), kName); } TEST(TfOpUtilsTest, LongDatasetOpTest) { const absl::string_view kName = "Iterator::Batch::Map::TfRecord"; TfOp tf_op = ParseTfOpFullname(kName); EXPECT_EQ(tf_op.category, Category::kTfData); EXPECT_EQ(tf_op.name, kName); EXPECT_EQ(tf_op.type, kDatasetOp); EXPECT_EQ(TfOpEventName(kName), "Iterator::TfRecord"); } TEST(TfOpUtilsTest, TraceMeTest) { const absl::string_view kName = "MyTraceMe"; TfOp tf_op = ParseTfOpFullname(kName); EXPECT_EQ(tf_op.category, Category::kUnknown); EXPECT_EQ(tf_op.name, kName); EXPECT_EQ(tf_op.type, kUnknownOp); EXPECT_EQ(TfOpEventName(kName), kName); } TEST(TfOpUtilsTest, TraceMeWithColonTest) { const absl::string_view kName = "RunStep/Server:54635"; TfOp tf_op = ParseTfOpFullname(kName); EXPECT_EQ(tf_op.category, Category::kUnknown); EXPECT_EQ(tf_op.name, kName); EXPECT_EQ(tf_op.type, kUnknownOp); EXPECT_EQ(TfOpEventName(kName), kName); } TEST(TfOpUtilsTest, TraceMeWithDoubleColonTest) { const absl::string_view kName = "XLA::StartProgram"; TfOp tf_op = ParseTfOpFullname(kName); EXPECT_EQ(tf_op.category, Category::kUnknown); EXPECT_EQ(tf_op.name, kName); EXPECT_EQ(tf_op.type, kUnknownOp); EXPECT_EQ(TfOpEventName(kName), kName); } TEST(TfOpUtilsTest, TraceMeWithTrailingWhitespaceTest) { const absl::string_view kName = "SessionRun "; const absl::string_view kNameTrimmed = "SessionRun"; TfOp tf_op = ParseTfOpFullname(kName); EXPECT_EQ(tf_op.category, Category::kUnknown); EXPECT_EQ(tf_op.name, kName); EXPECT_EQ(tf_op.type, kUnknownOp); EXPECT_EQ(TfOpEventName(kName), kNameTrimmed); } TEST(TfOpUtilsTest, InfeedEnqueueTest) { const absl::string_view kName = "input_pipeline_task0/while/body/_1/InfeedQueue/enqueue/" "1:InfeedEnqueueTuple"; TfOp tf_op = ParseTfOpFullname(kName); EXPECT_EQ(tf_op.category, Category::kTensorFlow); EXPECT_EQ(tf_op.name, "input_pipeline_task0/while/body/_1/InfeedQueue/enqueue/1"); EXPECT_EQ(tf_op.type, "InfeedEnqueueTuple"); EXPECT_EQ(TfOpEventName(kName), "InfeedEnqueueTuple"); EXPECT_TRUE(IsInfeedEnqueueOp(tf_op.type)); EXPECT_TRUE(IsInfeedEnqueueOp(tf_op)); } TEST(TfOpUtilsTest, MemcpyHToDTest) { const absl::string_view kName = "MemcpyHToD"; TfOp tf_op = ParseTfOpFullname(kName); EXPECT_EQ(tf_op.category, Category::kMemcpyHToD); EXPECT_EQ(tf_op.name, kName); EXPECT_EQ(tf_op.type, kMemcpyHToDOp); EXPECT_EQ(TfOpEventName(kName), kName); EXPECT_TRUE(IsMemcpyHToDOp(tf_op.type)); EXPECT_TRUE(IsMemcpyHToDOp(tf_op)); } TEST(TfOpUtilsTest, MemcpyDToHTest) { const absl::string_view kName = "MemcpyDToH"; TfOp tf_op = ParseTfOpFullname(kName); EXPECT_EQ(tf_op.category, Category::kMemcpyDToH); EXPECT_EQ(tf_op.name, kName); EXPECT_EQ(tf_op.type, kMemcpyDToHOp); EXPECT_EQ(TfOpEventName(kName), kName); EXPECT_TRUE(IsMemcpyDToHOp(tf_op)); } TEST(TfOpUtilsTest, MemcpyDToDTest) { const absl::string_view kName = "MemcpyDToD"; TfOp tf_op = ParseTfOpFullname(kName); EXPECT_EQ(tf_op.category, Category::kMemcpyDToD); EXPECT_EQ(tf_op.name, kName); EXPECT_EQ(tf_op.type, kMemcpyDToDOp); EXPECT_EQ(TfOpEventName(kName), kName); EXPECT_TRUE(IsMemcpyDToDOp(tf_op)); } TEST(TfOpUtilsTest, MemcpyHToHTest) { const absl::string_view kName = "MemcpyHToH"; TfOp tf_op = ParseTfOpFullname(kName); EXPECT_EQ(tf_op.category, Category::kMemcpyHToH); EXPECT_EQ(tf_op.name, kName); EXPECT_EQ(tf_op.type, kMemcpyHToHOp); EXPECT_EQ(TfOpEventName(kName), kName); EXPECT_TRUE(IsMemcpyHToHOp(tf_op)); } TEST(TfOpUtilsTest, JaxOpTest) { const absl::string_view kName = "op_name:op_type"; TfOp tf_op = ParseTfOpFullname(kName); EXPECT_EQ(tf_op.category, Category::kJax); EXPECT_EQ(tf_op.name, "op_name"); EXPECT_EQ(tf_op.type, "op_type"); EXPECT_EQ(TfOpEventName(kName), "op_type"); } TEST(TfOpUtilsTest, JaxOpWithColonTest) { const absl::string_view kName = "op_name/op_type:"; TfOp tf_op = ParseTfOpFullname(kName); EXPECT_EQ(tf_op.category, Category::kJax); EXPECT_EQ(tf_op.name, "op_name/op_type"); EXPECT_EQ(tf_op.type, "op_type"); EXPECT_EQ(TfOpEventName(kName), "op_type"); } TEST(TfOpUtilsTest, JaxOpNameTest) { const absl::string_view kOpName = "namescope/add"; const absl::string_view kOpType = "add"; EXPECT_TRUE(IsJaxOpNameAndType(kOpName, kOpType)); } TEST(TfOpUtilsTest, JaxOpWithBracketTest) { const absl::string_view kName = "op_name:op_type[array=([])]"; TfOp tf_op = ParseTfOpFullname(kName); EXPECT_EQ(tf_op.category, Category::kJax); EXPECT_EQ(tf_op.name, "op_name"); EXPECT_EQ(tf_op.type, "op_type"); EXPECT_EQ(TfOpEventName(kName), "op_type"); } TEST(TfOpUtilsTest, JaxOpWithBracketAndTrailingColonTest) { const absl::string_view kName = "op_name/op_type[array=([])]:"; TfOp tf_op = ParseTfOpFullname(kName); EXPECT_EQ(tf_op.category, Category::kJax); EXPECT_EQ(tf_op.name, "op_name/op_type[array=([])]"); EXPECT_EQ(tf_op.type, "op_type"); EXPECT_EQ(TfOpEventName(kName), "op_type"); } TEST(TfOpUtilsTest, JaxOpNameWithMetadataTest) { const absl::string_view kOpName = "pmap(<unnamed wrapped function>)/gather[ " "dimension_numbers=GatherDimensionNumbers(offset_dims=(2,), " "collapsed_slice_dims=(0, 1), start_index_map=(0, 1))\n " " slice_sizes=(1, 1, 81) ]:gather"; const absl::string_view kOpType = "gather"; EXPECT_TRUE(IsJaxOpNameAndType(kOpName, kOpType)); } TEST(TfOpUtilsTest, OtherXlaOpTest) { const absl::string_view kName = "namescope.1/namespace__opname2d:namespace__opname2d"; TfOp tf_op = ParseTfOpFullname(kName); EXPECT_EQ(tf_op.category, Category::kJax); EXPECT_EQ(tf_op.name, "namescope.1/namespace__opname2d"); EXPECT_EQ(tf_op.type, "namespace__opname2d"); EXPECT_EQ(TfOpEventName(kName), "namespace__opname2d"); } TEST(TfOpUtilsTest, OtherXlaOpNameTest) { const absl::string_view kOpName = "namescope.1/namespace__opname2d"; const absl::string_view kOpType = "namespace__opname2d"; EXPECT_TRUE(IsJaxOpNameAndType(kOpName, kOpType)); } TEST(TfOpUtilsTest, OpWithoutTypeTest) { const absl::string_view kName = "namescope/OpName_1:"; TfOp tf_op = ParseTfOpFullname(kName); EXPECT_EQ(tf_op.category, Category::kTensorFlow); EXPECT_EQ(tf_op.name, "namescope/OpName_1"); EXPECT_EQ(tf_op.type, "OpName"); EXPECT_EQ(TfOpEventName(kName), "OpName"); } TEST(TfOpUtilsTest, OpTypeWithUnderstslTest) { const absl::string_view kName = "namescope/OpName_a:"; TfOp tf_op = ParseTfOpFullname(kName); EXPECT_EQ(tf_op.category, Category::kTensorFlow); EXPECT_EQ(tf_op.name, "namescope/OpName_a"); EXPECT_EQ(tf_op.type, "OpName_a"); EXPECT_EQ(TfOpEventName(kName), "OpName_a"); } TEST(TfOpUtilsTest, NameScopeTest) { const absl::string_view kName = "scope-1/scope2/OpName:OpType"; TfOp tf_op = ParseTfOpFullname(kName); EXPECT_EQ(tf_op.category, Category::kTensorFlow); EXPECT_EQ(tf_op.name, "scope-1/scope2/OpName"); EXPECT_EQ(tf_op.type, "OpType"); std::vector<absl::string_view> name_scopes = ParseTfNameScopes(tf_op); EXPECT_EQ(name_scopes.size(), 2); EXPECT_EQ(name_scopes[0], "scope-1"); EXPECT_EQ(name_scopes[1], "scope2"); } } } }
2,297
#ifndef TENSORFLOW_TSL_PROFILER_UTILS_BUFFER_POOL_H_ #define TENSORFLOW_TSL_PROFILER_UTILS_BUFFER_POOL_H_ #include <vector> #include "tsl/platform/mutex.h" #include "tsl/platform/thread_annotations.h" namespace tsl { namespace profiler { class BufferPool { public: explicit BufferPool(size_t buffer_size_in_bytes); ~BufferPool(); uint8_t* GetOrCreateBuffer(); void ReclaimBuffer(uint8_t* buffer); void DestroyAllBuffers(); size_t GetBufferSizeInBytes() const; protected: mutex buffers_mutex_; std::vector<uint8_t*> buffers_ TF_GUARDED_BY(buffers_mutex_); size_t buffer_size_in_bytes_; }; } } #endif #include "tsl/profiler/utils/buffer_pool.h" #include <ios> #include "tsl/platform/logging.h" #include "tsl/platform/mem.h" #include "tsl/platform/mutex.h" namespace tsl { namespace profiler { BufferPool::BufferPool(size_t buffer_size_in_bytes) : buffer_size_in_bytes_(buffer_size_in_bytes) {} BufferPool::~BufferPool() { DestroyAllBuffers(); } uint8_t* BufferPool::GetOrCreateBuffer() { { mutex_lock lock(buffers_mutex_); if (!buffers_.empty()) { uint8_t* buffer = buffers_.back(); buffers_.pop_back(); if (!buffer) { LOG(ERROR) << "A reused buffer must not be null!"; return nullptr; } VLOG(3) << "Reused Buffer, buffer=" << std::hex << reinterpret_cast<uintptr_t>(buffer) << std::dec; return buffer; } } constexpr size_t kBufferAlignSize = 8; uint8_t* buffer = reinterpret_cast<uint8_t*>( port::AlignedMalloc(buffer_size_in_bytes_, kBufferAlignSize)); if (buffer == nullptr) { LOG(WARNING) << "Buffer not allocated."; return nullptr; } VLOG(3) << "Allocated Buffer, buffer=" << std::hex << reinterpret_cast<uintptr_t>(buffer) << std::dec << " size=" << buffer_size_in_bytes_; return buffer; } void BufferPool::ReclaimBuffer(uint8_t* buffer) { mutex_lock lock(buffers_mutex_); buffers_.push_back(buffer); VLOG(3) << "Reclaimed Buffer, buffer=" << std::hex << reinterpret_cast<uintptr_t>(buffer) << std::dec; } void BufferPool::DestroyAllBuffers() { mutex_lock lock(buffers_mutex_); for (uint8_t* buffer : buffers_) { VLOG(3) << "Freeing Buffer, buffer:" << std::hex << reinterpret_cast<uintptr_t>(buffer) << std::dec; port::AlignedFree(buffer); } buffers_.clear(); } size_t BufferPool::GetBufferSizeInBytes() const { return buffer_size_in_bytes_; } } }
#include "tsl/profiler/utils/buffer_pool.h" #include "tsl/platform/test.h" namespace tsl { namespace profiler { namespace { TEST(BufferPoolTest, GetOrCreateBufferAlloc) { constexpr size_t kBufferSizeInBytes = 32 * 1024; BufferPool buffer_pool(kBufferSizeInBytes); uint8_t* first_buffer = buffer_pool.GetOrCreateBuffer(); EXPECT_NE(first_buffer, nullptr); uint8_t* second_buffer = buffer_pool.GetOrCreateBuffer(); EXPECT_NE(second_buffer, first_buffer); for (size_t idx = 0; idx < kBufferSizeInBytes; ++idx) { first_buffer[idx] = 0xAB; } buffer_pool.ReclaimBuffer(first_buffer); buffer_pool.ReclaimBuffer(second_buffer); } TEST(BufferPoolTest, GetOrCreateBufferReuse) { constexpr size_t kBufferSizeInBytes = 32 * 1024; BufferPool buffer_pool(kBufferSizeInBytes); uint8_t* buffer = buffer_pool.GetOrCreateBuffer(); EXPECT_NE(buffer, nullptr); buffer[0] = 0xFF; uint8_t* previous_buffer = buffer; buffer_pool.ReclaimBuffer(buffer); uint8_t* reused_buffer = buffer_pool.GetOrCreateBuffer(); EXPECT_EQ(reused_buffer, previous_buffer); for (size_t idx = 0; idx < kBufferSizeInBytes; ++idx) { reused_buffer[idx] = 0xCD; } buffer_pool.ReclaimBuffer(reused_buffer); } TEST(BufferPoolTest, DestroyAllBuffers) { constexpr size_t kBufferSizeInBytes = 32 * 1024; BufferPool buffer_pool(kBufferSizeInBytes); uint8_t* first_buffer = buffer_pool.GetOrCreateBuffer(); EXPECT_NE(first_buffer, nullptr); buffer_pool.DestroyAllBuffers(); for (size_t idx = 0; idx < kBufferSizeInBytes; ++idx) { first_buffer[idx] = 0xEF; } uint8_t* second_buffer = buffer_pool.GetOrCreateBuffer(); for (size_t idx = 0; idx < kBufferSizeInBytes; ++idx) { second_buffer[idx] = 0xAB; } buffer_pool.ReclaimBuffer(first_buffer); buffer_pool.ReclaimBuffer(second_buffer); } } } }
2,298
#ifndef TENSORFLOW_TSL_PROFILER_UTILS_GROUP_EVENTS_H_ #define TENSORFLOW_TSL_PROFILER_UTILS_GROUP_EVENTS_H_ #include <deque> #include <functional> #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "tsl/platform/logging.h" #include "tsl/platform/types.h" #include "tsl/profiler/protobuf/xplane.pb.h" #include "tsl/profiler/utils/xplane_builder.h" #include "tsl/profiler/utils/xplane_visitor.h" namespace tsl { namespace profiler { struct InterThreadConnectInfo { int64_t parent_event_type; int64_t child_event_type; std::vector<int64_t> parent_stat_types; std::vector<int64_t> child_stat_types; }; struct GroupMetadata { std::string name; absl::flat_hash_set<int64_t> parents; absl::flat_hash_set<int64_t> children; }; using GroupMetadataMap = absl::flat_hash_map<int64_t , GroupMetadata>; class EventNode { public: explicit EventNode(XEventVisitor visitor) : visitor_(std::move(visitor)) {} EventNode(const EventNode& event_node) = delete; EventNode& operator=(const EventNode&) = delete; const std::vector<EventNode*>& GetParents() const { return parents_; } const std::vector<EventNode*>& GetChildren() const { return children_; } void AddChild(EventNode* child) { children_.push_back(child); child->parents_.push_back(this); } std::optional<int64_t> GetGroupId() const { return group_id_; } std::string GetGroupName() const; void SetGroupId(int64_t group_id); void PropagateGroupId(int64_t group_id, GroupMetadataMap* group_metadata_map); const XEventVisitor& GetEventVisitor() const { return visitor_; } std::optional<XStatVisitor> GetContextStat(int64_t stat_type) const; void AddStepName(absl::string_view step_name); void SetIsEager(bool is_eager); bool IsEager() const; bool IsNestedIn(EventNode* parent); const EventNode* FindParent(int64_t event_type) const; void SetRootLevel(int root_level) { root_level_ = root_level; } int RootLevel() const { return root_level_; } bool IsCompiledFunc() const; bool operator<(const EventNode& other) const { return GetEventVisitor().TimestampPs() < other.GetEventVisitor().TimestampPs(); } private: XStat* FindOrAddStatByType(int64_t stat_type); XEventVisitor visitor_; std::vector<EventNode*> parents_; std::vector<EventNode*> children_; std::optional<int64_t> group_id_; int root_level_ = 0; }; using EventNodeMap = absl::flat_hash_map<int64_t , std::deque<EventNode>>; using EventList = std::vector<EventNode*>; struct ContextGroup { std::vector<EventNode*> producers; std::vector<EventNode*> consumers; }; using ContextGroupMap = absl::flat_hash_map< int , absl::flat_hash_map<uint64 , ContextGroup>>; class EventForest { public: void AddSpace( std::function<XPlaneVisitor(const tensorflow::profiler::XPlane*)> visitor_factory, tensorflow::profiler::XSpace* space); void AddPlanes( std::function<XPlaneVisitor(const tensorflow::profiler::XPlane*)> visitor_factory, const std::vector<tensorflow::profiler::XPlane*>& planes); void ConnectEvents( const std::vector<InterThreadConnectInfo>& connect_info_list = {}); void ConnectTfDataEvents(); void GroupEvents(); const EventNodeMap& GetEventNodeMap() const { return event_node_map_; } const GroupMetadataMap& GetGroupMetadataMap() const { return group_metadata_map_; } private: void AddPlane( std::function<XPlaneVisitor(const tensorflow::profiler::XPlane*)> visitor_factory, tensorflow::profiler::XPlane* plane); void ConnectIntraThread(tensorflow::profiler::XPlane* plane, XPlaneVisitor* visitor, ContextGroupMap* context_groups); void ConnectInterThread( const std::vector<InterThreadConnectInfo>& connect_info_list); void CreateEventGroups(); void MarkEagerlyExecutedGpuKernels(); void MarkEagerlyExecutedCpuTfOps(); void ProcessTfDataSteps(); void ProcessTensorFlowLoop(); void FindEventNodeAndApply( int64_t event_type, const std::vector<int64_t>& stat_types, const std::function<void(EventNode&, const std::vector<uint64>&)>& cb); EventNodeMap event_node_map_; std::vector<XPlaneVisitor> visitors_; std::deque<std::pair<tensorflow::profiler::XPlane*, XPlaneVisitor>> planes_; absl::flat_hash_set<int64_t> tf_data_step_ids_; EventList tf_loop_root_events_; GroupMetadataMap group_metadata_map_; }; std::vector<InterThreadConnectInfo> CreateInterThreadConnectInfoList(); void GroupTfEvents(tensorflow::profiler::XSpace* space, EventForest* event_forest); void GroupTfEvents(tensorflow::profiler::XSpace* space); bool CheckLoopOp(const tensorflow::profiler::XSpace& space); void AddGroupMetadataToStepEvents(const GroupMetadataMap& group_metadata_map, XLineBuilder& line); void GroupHostAndPlanes( tensorflow::profiler::XSpace* space, const std::vector<tensorflow::profiler::XPlane*>& device_traces, EventForest* event_forest); void GroupXplaneEvents(tensorflow::profiler::XPlane* plane, const GroupMetadataMap& group_metadata_map); void GroupTpuEventsOSS( tensorflow::profiler::XSpace* space, const std::vector<tensorflow::profiler::XPlane*>& device_traces, EventForest* event_forest); } } #endif #include "tsl/profiler/utils/group_events.h" #include <algorithm> #include <cstdint> #include <functional> #include <iterator> #include <map> #include <memory> #include <optional> #include <queue> #include <string> #include <utility> #include <vector> #include "absl/algorithm/container.h" #include "absl/container/flat_hash_map.h" #include "absl/functional/bind_front.h" #include "absl/strings/str_cat.h" #include "tsl/lib/gtl/map_util.h" #include "tsl/platform/dso_loader.h" #include "tsl/platform/env.h" #include "tsl/platform/types.h" #include "tsl/profiler/utils/tf_xplane_visitor.h" #include "tsl/profiler/utils/xplane_builder.h" #include "tsl/profiler/utils/xplane_schema.h" #include "tsl/profiler/utils/xplane_utils.h" #include "tsl/profiler/utils/xplane_visitor.h" namespace tsl { namespace profiler { void CreateStatMetadata(XPlane* plane) { XPlaneBuilder builder(plane); builder.GetOrCreateStatMetadata(GetStatTypeStr(StatType::kGroupId)); builder.GetOrCreateStatMetadata(GetStatTypeStr(StatType::kStepName)); builder.GetOrCreateStatMetadata(GetStatTypeStr(StatType::kIsEager)); } std::optional<int64_t> GetKernelEventType(bool is_host_plane, const XEventVisitor& event) { if (event.GetStat(StatType::kCorrelationId).has_value()) { return is_host_plane ? HostEventType::kKernelLaunch : HostEventType::kKernelExecute; } return std::nullopt; } int64_t GetEventType(bool is_host_plane, const XEventVisitor& event) { if (std::optional<int64_t> event_type = event.Type()) { return *event_type; } else if (std::optional<int64_t> kernel_event_type = GetKernelEventType(is_host_plane, event)) { return *kernel_event_type; } else { return HostEventType::kUnknownHostEventType; } } bool IsLegacyRootEvent(const XEventVisitor& event) { return event.Type() == HostEventType::kTraceContext; } struct GroupingEventStats { explicit GroupingEventStats(const XEventVisitor& event); std::optional<int> producer_type; std::optional<uint64_t> producer_id; std::optional<int> consumer_type; std::optional<uint64_t> consumer_id; std::optional<int> root_level; bool is_async = false; }; GroupingEventStats::GroupingEventStats(const XEventVisitor& event) { std::optional<int64_t> step_id; event.ForEachStat([&](const XStatVisitor& stat) { if (!stat.Type().has_value()) return; switch (*stat.Type()) { case StatType::kProducerType: producer_type = stat.IntValue(); break; case StatType::kProducerId: producer_id = stat.IntOrUintValue(); break; case StatType::kConsumerType: consumer_type = stat.IntValue(); break; case StatType::kConsumerId: consumer_id = stat.IntOrUintValue(); break; case StatType::kIsRoot: root_level = stat.IntValue(); break; case StatType::kIsAsync: is_async = stat.BoolValue(); break; case StatType::kStepId: step_id = stat.IntValue(); break; default: break; } }); if (!root_level.has_value() && IsLegacyRootEvent(event)) { root_level = 1; } } void SetContextGroup(const GroupingEventStats& stats, EventNode* event, ContextGroupMap* context_groups) { if (stats.producer_type.has_value() && stats.producer_id.has_value()) { ((*context_groups)[*stats.producer_type][*stats.producer_id]) .producers.push_back(event); } if (stats.consumer_type.has_value() && stats.consumer_id.has_value()) { ((*context_groups)[*stats.consumer_type][*stats.consumer_id]) .consumers.push_back(event); } } void ConnectContextGroups(const ContextGroupMap& context_groups) { for (auto& type_id_group : context_groups) { for (auto& id_group : type_id_group.second) { const ContextGroup& group = id_group.second; if (group.producers.size() >= 64 && group.consumers.size() >= 64) { LOG_EVERY_N(WARNING, 1000) << "id:" << id_group.first << " producers:" << group.producers.size() << " : " << group.producers[0]->GetEventVisitor().Name() << " consumers:" << group.consumers.size() << " : " << group.consumers[0]->GetEventVisitor().Name(); continue; } for (EventNode* parent : group.producers) { for (EventNode* child : group.consumers) { parent->AddChild(child); } } } } } bool IsImplicitRootEvent(const XEventVisitor& event) { static const auto* const kImplicitRootEvents = new absl::flat_hash_set<int64_t>{ HostEventType::kFunctionRun, HostEventType::kSessionRun, HostEventType::kRunGraph, HostEventType::kExecutorStateProcess}; return event.Type().has_value() && kImplicitRootEvents->contains(*event.Type()); } void ProcessRootEvent(int64_t group_id, EventNode* root_event, GroupMetadataMap* group_metadata_map) { root_event->PropagateGroupId(group_id, group_metadata_map); std::string group_name = root_event->GetGroupName(); if (!IsImplicitRootEvent(root_event->GetEventVisitor())) { root_event->AddStepName(group_name); } (*group_metadata_map)[group_id].name = std::move(group_name); } using Comparator = std::function<bool(const EventNode*)>; const EventNode* FindParentWithComparator(const Comparator& comparator, const EventNode* node, bool include_self) { std::queue<const EventNode*> nodes; absl::flat_hash_set<const EventNode*> seen = {node}; if (include_self) { nodes.push(node); } else { for (const EventNode* parent : node->GetParents()) { nodes.push(parent); seen.insert(parent); } } while (!nodes.empty()) { const EventNode* node = nodes.front(); nodes.pop(); if (comparator(node)) return node; for (const EventNode* parent : node->GetParents()) { if (seen.contains(parent)) continue; nodes.push(parent); seen.insert(parent); } } return nullptr; } bool IsIteratorEventType(std::optional<int64_t> event_type) { return event_type == HostEventType::kIterator || event_type == HostEventType::kDeviceInputPipelineSecondIterator; } bool CheckLoopOp(const XSpace& space) { for (const XPlane& plane : space.planes()) { for (const auto& event_metadata : plane.event_metadata()) { std::optional<int64_t> event_type = FindHostEventType(event_metadata.second.name()); if (!event_type.has_value()) continue; switch (*event_type) { case HostEventType::kWhileOpEvalCond: case HostEventType::kWhileOpStartBody: case HostEventType::kForOp: case HostEventType::kParallelForOp: case HostEventType::kForeverOp: return true; default: break; } } } return false; } std::optional<XStatVisitor> EventNode::GetContextStat(int64_t stat_type) const { std::queue<const EventNode*> nodes; absl::flat_hash_set<const EventNode*> seen = {this}; nodes.push(this); while (!nodes.empty()) { const EventNode* node = nodes.front(); nodes.pop(); if (std::optional<XStatVisitor> stat = node->visitor_.GetStat(stat_type)) { return stat; } for (const EventNode* parent : node->GetParents()) { if (seen.contains(parent)) continue; nodes.push(parent); seen.insert(parent); } } return std::nullopt; } std::string EventNode::GetGroupName() const { std::string name; if (std::optional<XStatVisitor> stat = GetContextStat(StatType::kGraphType)) { absl::StrAppend(&name, stat->StrOrRefValue(), " "); } else if (!(IsImplicitRootEvent(visitor_))) { absl::StrAppend(&name, GetEventVisitor().Name(), " "); } int64_t step_num = group_id_.value_or(0); if (std::optional<XStatVisitor> stat = GetContextStat(StatType::kIterNum)) { step_num = stat->IntValue(); } else if (std::optional<XStatVisitor> stat = GetContextStat(StatType::kStepNum)) { step_num = stat->IntValue(); } absl::StrAppend(&name, step_num); return name; } XStat* EventNode::FindOrAddStatByType(int64_t stat_type) { const XPlaneVisitor& plane = visitor_.Plane(); const XStatMetadata* stat_metadata = plane.GetStatMetadataByType(stat_type); DCHECK(stat_metadata != nullptr); auto* raw_event = const_cast<XEvent*>(&visitor_.RawEvent()); return FindOrAddMutableStat(*stat_metadata, raw_event); } void EventNode::SetGroupId(int64_t group_id) { group_id_ = group_id; FindOrAddStatByType(StatType::kGroupId)->set_int64_value(group_id); } void EventNode::PropagateGroupId(int64_t group_id, GroupMetadataMap* group_metadata_map) { std::queue<EventNode*> nodes; absl::flat_hash_set<EventNode*> seen = {this}; nodes.push(this); while (!nodes.empty()) { EventNode* node = nodes.front(); nodes.pop(); std::optional<int64_t> node_group_id = node->GetGroupId(); if (node_group_id.has_value()) { if (*node_group_id != group_id) { (*group_metadata_map)[group_id].children.insert(*node_group_id); (*group_metadata_map)[*node_group_id].parents.insert(group_id); } } else { node->SetGroupId(group_id); for (EventNode* child : node->GetChildren()) { if (seen.contains(child)) continue; nodes.push(child); seen.insert(child); } } } } void EventNode::AddStepName(absl::string_view step_name) { FindOrAddStatByType(StatType::kStepName) ->set_str_value(step_name.data(), step_name.size()); } void EventNode::SetIsEager(bool is_eager) { FindOrAddStatByType(StatType::kIsEager)->set_int64_value(is_eager ? 1 : 0); } bool EventNode::IsCompiledFunc() const { auto is_func = visitor_.GetStat(StatType::kIsFunc); return !is_func || is_func->IntValue(); } bool EventNode::IsEager() const { const EventNode* node = FindParent(HostEventType::kEagerKernelExecute); if (node == nullptr) { return false; } return !node->IsCompiledFunc(); } const EventNode* EventNode::FindParent(int64_t event_type) const { return FindParentWithComparator( [event_type](const EventNode* node) { return node->GetEventVisitor().Type() == event_type; }, this, true); } void EventForest::FindEventNodeAndApply( const int64_t event_type, const std::vector<int64_t>& stat_types, const std::function<void(EventNode&, const std::vector<uint64>&)>& cb) { if (auto* event_node_list = gtl::FindOrNull(event_node_map_, event_type)) { for (EventNode& event_node : *event_node_list) { std::vector<uint64> stats; for (const auto stat_type : stat_types) { std::optional<XStatVisitor> stat = event_node.GetEventVisitor().GetStat(stat_type); if (!stat) break; stats.push_back(stat->IntOrUintValue()); } if (stats.size() == stat_types.size()) { cb(event_node, stats); } } } } void EventForest::ConnectIntraThread(XPlane* plane, XPlaneVisitor* visitor, ContextGroupMap* context_groups) { bool is_host_plane = (visitor->Name() == kHostThreadsPlaneName); for (auto& line : *plane->mutable_lines()) { std::vector<EventNode*> parent_nodes; for (auto& event : *line.mutable_events()) { XEventVisitor event_visitor(visitor, &line, &event); int64_t event_type = GetEventType(is_host_plane, event_visitor); EventNode* cur_node = &event_node_map_[event_type].emplace_back(std::move(event_visitor)); GroupingEventStats stats(cur_node->GetEventVisitor()); if (stats.root_level.has_value()) { cur_node->SetRootLevel(*stats.root_level); } SetContextGroup(stats, cur_node, context_groups); if (!stats.is_async) { while (!parent_nodes.empty()) { EventNode* parent_node = parent_nodes.back(); if (parent_node->GetEventVisitor().GetTimespan().Includes( cur_node->GetEventVisitor().GetTimespan())) { parent_node->AddChild(cur_node); break; } else { parent_nodes.pop_back(); } } parent_nodes.push_back(cur_node); } } } } void EventForest::ConnectInterThread( const std::vector<InterThreadConnectInfo>& connect_info_list) { for (const auto& connect_info : connect_info_list) { absl::flat_hash_map<std::vector<uint64>, EventNode*> connect_map; const std::vector<int64_t>& parent_stat_types = connect_info.parent_stat_types; const std::vector<int64_t>* child_stat_types = &connect_info.child_stat_types; if (child_stat_types->empty()) { child_stat_types = &parent_stat_types; } FindEventNodeAndApply(connect_info.parent_event_type, parent_stat_types, [&connect_map](EventNode& event_node, const std::vector<uint64>& stats) { connect_map[stats] = &event_node; }); FindEventNodeAndApply( connect_info.child_event_type, *child_stat_types, [&connect_map](EventNode& event_node, const std::vector<uint64>& stats) { if (auto parent_event_node = gtl::FindPtrOrNull(connect_map, stats)) { parent_event_node->AddChild(&event_node); } }); } } bool RootNeedsGrouping(const EventNode* root) { if (root->GetGroupId().has_value()) return false; const EventNode* root_parent = FindParentWithComparator( [root](const EventNode* parent) { return parent->RootLevel() == root->RootLevel(); }, root, false); return root_parent == nullptr; } void SortRootEventList(EventList* event_list) { absl::c_sort(*event_list, [](const EventNode* e1, const EventNode* e2) { return e1->RootLevel() == e2->RootLevel() ? *e1 < *e2 : e1->RootLevel() > e2->RootLevel(); }); } void EventForest::CreateEventGroups() { int64_t group_id = 0; if (!tf_loop_root_events_.empty()) { for (EventNode* root_event : tf_loop_root_events_) { ProcessRootEvent(group_id++, root_event, &group_metadata_map_); } return; } EventList root_events; for (auto& [event_type, events] : event_node_map_) { for (EventNode& event : events) { if (!event.RootLevel()) continue; std::optional<XStatVisitor> step_id_stat = event.GetEventVisitor().GetStat(StatType::kStepId); if (step_id_stat && tf_data_step_ids_.contains(step_id_stat->IntValue())) continue; root_events.push_back(&event); } } SortRootEventList(&root_events); for (EventNode* root_event : root_events) { if (RootNeedsGrouping(root_event)) { ProcessRootEvent(group_id++, root_event, &group_metadata_map_); } } } void EventForest::MarkEagerlyExecutedGpuKernels() { auto kernel_execute_event_node_list = gtl::FindOrNull(event_node_map_, HostEventType::kKernelExecute); if (!kernel_execute_event_node_list) return; for (EventNode& kernel_execute_event_node : *kernel_execute_event_node_list) { kernel_execute_event_node.SetIsEager(kernel_execute_event_node.IsEager()); } } void EventForest::MarkEagerlyExecutedCpuTfOps() { auto tf_op_run_event_node_list = gtl::FindOrNull(event_node_map_, HostEventType::kTfOpRun); if (!tf_op_run_event_node_list) return; for (EventNode& tf_op_run_event_node : *tf_op_run_event_node_list) { tf_op_run_event_node.SetIsEager(tf_op_run_event_node.IsEager()); } } void EventForest::ProcessTfDataSteps() { const int64_t tf_data_event_types[] = { HostEventType::kTfDataCapturedFunctionRun, HostEventType::kTfDataCapturedFunctionRunAsync, HostEventType::kTfDataCapturedFunctionRunInstantiated, HostEventType::kTfDataCapturedFunctionRunWithBorrowedArgs}; for (const int64_t tf_data_event_type : tf_data_event_types) { auto tf_data_events = gtl::FindOrNull(event_node_map_, tf_data_event_type); if (!tf_data_events) continue; for (const EventNode& tf_data_event : *tf_data_events) { std::optional<XStatVisitor> step_id_stat = tf_data_event.GetEventVisitor().GetStat(StatType::kStepId); if (!step_id_stat) continue; tf_data_step_ids_.insert(step_id_stat->IntValue()); } } } void EventForest::ProcessTensorFlowLoop() { struct TensorFlowLoopIteration { EventNode* first_event = nullptr; std::vector<EventNode*> events; }; using TensorFlowLoop = absl::flat_hash_map<int64_t , TensorFlowLoopIteration>; absl::flat_hash_map<int64_t , TensorFlowLoop> tf_loops; auto executor_event_list = gtl::FindOrNull(event_node_map_, HostEventType::kExecutorStateProcess); if (!executor_event_list) return; for (EventNode& executor_event : *executor_event_list) { std::optional<XStatVisitor> step_id_stat = executor_event.GetEventVisitor().GetStat(StatType::kStepId); std::optional<XStatVisitor> iter_num_stat = executor_event.GetEventVisitor().GetStat(StatType::kIterNum); if (!step_id_stat || !iter_num_stat) continue; int64_t step_id = step_id_stat->IntValue(); if (tf_data_step_ids_.contains(step_id)) continue; TensorFlowLoop& tf_loop = tf_loops[step_id]; TensorFlowLoopIteration& iteration = tf_loop[iter_num_stat->IntValue()]; if (!iteration.first_event || executor_event < *iteration.first_event) { iteration.first_event = &executor_event; } iteration.events.push_back(&executor_event); } std::vector<const TensorFlowLoopIteration*> iters; for (const auto& step_id_and_tf_loop : tf_loops) { const TensorFlowLoop& tf_loop = step_id_and_tf_loop.second; if (tf_loop.size() == 1 && tf_loop.contains(0)) continue; for (const auto& iter_num_and_iter : tf_loop) { iters.push_back(&iter_num_and_iter.second); } } absl::c_sort(iters, [](const auto& iter1, const auto& iter2) { return *iter1->first_event < *iter2->first_event; }); for (const TensorFlowLoopIteration* iter : iters) { EventNode* root_event = iter->first_event; tf_loop_root_events_.push_back(root_event); for (EventNode* event : iter->events) { if (event == root_event) continue; root_event->AddChild(event); } } } void EventForest::AddPlane( const std::function<XPlaneVisitor(const XPlane*)> visitor_factory, XPlane* plane) { CreateStatMetadata(plane); planes_.push_back({plane, visitor_factory(plane)}); } void EventForest::AddSpace( const std::function<XPlaneVisitor(const XPlane*)> visitor_factory, XSpace* space) { for (XPlane& plane : *space->mutable_planes()) { AddPlane(visitor_factory, &plane); } } void EventForest::AddPlanes( const std::function<XPlaneVisitor(const XPlane*)> visitor_factory, const std::vector<XPlane*>& planes) { for (XPlane* plane : planes) { AddPlane(visitor_factory, plane); } } void EventForest::ConnectEvents( const std::vector<InterThreadConnectInfo>& connect_info_list) { ContextGroupMap context_groups; for (auto& plane_visitor : planes_) { ConnectIntraThread(plane_visitor.first, &plane_visitor.second, &context_groups); } ConnectInterThread(connect_info_list); ConnectContextGroups(context_groups); } void EventForest::ConnectTfDataEvents() { absl::flat_hash_map< std::pair<int64_t , int64_t >, std::vector<EventNode*>> produce_iterator_map; uint64 num_producers = 0; for (HostEventType event_type : {HostEventType::kPrefetchProduce, HostEventType::kPar
#include "tsl/profiler/utils/group_events.h" #include <optional> #include "absl/container/flat_hash_map.h" #include "absl/strings/string_view.h" #include "tsl/platform/test.h" #include "tsl/platform/types.h" #include "tsl/profiler/protobuf/xplane.pb.h" #include "tsl/profiler/utils/tf_xplane_visitor.h" #include "tsl/profiler/utils/xplane_builder.h" #include "tsl/profiler/utils/xplane_schema.h" #include "tsl/profiler/utils/xplane_test_utils.h" #include "tsl/profiler/utils/xplane_visitor.h" namespace tsl { namespace profiler { namespace { constexpr int64_t kTfExecutor = static_cast<int64_t>(ContextType::kTfExecutor); TEST(GroupEventsTest, GroupGpuTraceLegacyRootTest) { constexpr int64_t kStepNum = 123; constexpr int64_t kStepId = 0; constexpr int64_t kCorrelationId = 100; XSpace space; XPlaneBuilder host_plane_builder(GetOrCreateHostXPlane(&space)); host_plane_builder.ReserveLines(2); auto main_thread = host_plane_builder.GetOrCreateLine(0); CreateXEvent( &host_plane_builder, &main_thread, HostEventType::kTraceContext, 0, 100, {{StatType::kGraphType, "train"}, {StatType::kStepNum, kStepNum}}); CreateXEvent(&host_plane_builder, &main_thread, HostEventType::kFunctionRun, 10, 90, {{StatType::kStepId, kStepId}, {StatType::kProducerType, kTfExecutor}, {StatType::kProducerId, kStepId}}); auto tf_executor_thread = host_plane_builder.GetOrCreateLine(1); CreateXEvent(&host_plane_builder, &tf_executor_thread, HostEventType::kExecutorStateProcess, 20, 80, {{StatType::kStepId, kStepId}, {StatType::kConsumerType, kTfExecutor}, {StatType::kConsumerId, kStepId}}); CreateXEvent(&host_plane_builder, &tf_executor_thread, "matmul", 30, 70, {{StatType::kCorrelationId, kCorrelationId}}); XPlane* device_plane = space.add_planes(); XPlaneBuilder device_plane_builder(device_plane); device_plane_builder.ReserveLines(1); auto stream = device_plane_builder.GetOrCreateLine(0); CreateXEvent(&device_plane_builder, &stream, "matmul", 200, 300, {{StatType::kCorrelationId, kCorrelationId}}); EventForest event_forest; GroupTfEvents(&space, &event_forest); const GroupMetadataMap& group_metadata_map = event_forest.GetGroupMetadataMap(); XPlaneVisitor device_plane_visitor = CreateTfXPlaneVisitor(device_plane); EXPECT_EQ(device_plane->lines(0).events(0).stats_size(), 3); EXPECT_EQ(device_plane_visitor.GetStatType( device_plane->lines(0).events(0).stats(1).metadata_id()), StatType::kGroupId); EXPECT_EQ(group_metadata_map.size(), 1); EXPECT_EQ(group_metadata_map.at(0).name, "train 123"); } TEST(GroupEventsTest, GroupGpuTraceTest) { constexpr int64_t kStepNum = 123; constexpr int64_t kStepId = 0; constexpr int64_t kCorrelationId = 100; XSpace space; XPlaneBuilder host_plane_builder(GetOrCreateHostXPlane(&space)); host_plane_builder.ReserveLines(2); auto main_thread = host_plane_builder.GetOrCreateLine(0); CreateXEvent( &host_plane_builder, &main_thread, "train", 0, 100, {{StatType::kStepNum, kStepNum}, {StatType::kIsRoot, int64_t{1}}}); CreateXEvent(&host_plane_builder, &main_thread, HostEventType::kFunctionRun, 10, 90, {{StatType::kStepId, kStepId}, {StatType::kProducerType, kTfExecutor}, {StatType::kProducerId, kStepId}}); auto tf_executor_thread = host_plane_builder.GetOrCreateLine(1); CreateXEvent(&host_plane_builder, &tf_executor_thread, HostEventType::kExecutorStateProcess, 20, 80, {{StatType::kStepId, kStepId}, {StatType::kConsumerType, kTfExecutor}, {StatType::kConsumerId, kStepId}}); CreateXEvent(&host_plane_builder, &tf_executor_thread, "matmul", 30, 70, {{StatType::kCorrelationId, kCorrelationId}}); XPlane* device_plane = space.add_planes(); XPlaneBuilder device_plane_builder(device_plane); device_plane_builder.ReserveLines(1); auto stream = device_plane_builder.GetOrCreateLine(0); CreateXEvent(&device_plane_builder, &stream, "matmul", 200, 300, {{StatType::kCorrelationId, kCorrelationId}}); EventForest event_forest; GroupTfEvents(&space, &event_forest); const GroupMetadataMap& group_metadata_map = event_forest.GetGroupMetadataMap(); XPlaneVisitor device_plane_visitor = CreateTfXPlaneVisitor(device_plane); EXPECT_EQ(device_plane->lines(0).events(0).stats_size(), 3); EXPECT_EQ(device_plane_visitor.GetStatType( device_plane->lines(0).events(0).stats(1).metadata_id()), StatType::kGroupId); EXPECT_EQ(group_metadata_map.size(), 1); EXPECT_EQ(group_metadata_map.at(0).name, "train 123"); } TEST(GroupEventsTest, GroupTensorFlowLoopTest) { constexpr int64_t kStepId = 0; constexpr int64_t kIterNum = 10; constexpr int64_t kCorrelationId = 100; XSpace space; XPlaneBuilder host_plane_builder(GetOrCreateHostXPlane(&space)); host_plane_builder.ReserveLines(1); auto tf_executor_thread = host_plane_builder.GetOrCreateLine(0); CreateXEvent(&host_plane_builder, &tf_executor_thread, HostEventType::kExecutorStateProcess, 5, 10, {{StatType::kStepId, kStepId}, {StatType::kIterNum, kIterNum}, {StatType::kConsumerType, kTfExecutor}, {StatType::kConsumerId, kStepId}}); CreateXEvent(&host_plane_builder, &tf_executor_thread, HostEventType::kExecutorStateProcess, 20, 80, {{StatType::kStepId, kStepId}, {StatType::kIterNum, kIterNum}, {StatType::kConsumerType, kTfExecutor}, {StatType::kConsumerId, kStepId}}); CreateXEvent(&host_plane_builder, &tf_executor_thread, "matmul", 30, 70, {{StatType::kCorrelationId, kCorrelationId}}); XPlane* device_plane = space.add_planes(); XPlaneBuilder device_plane_builder(device_plane); device_plane_builder.ReserveLines(1); auto stream = device_plane_builder.GetOrCreateLine(0); CreateXEvent(&device_plane_builder, &stream, "matmul", 200, 300, {{StatType::kCorrelationId, kCorrelationId}}); EventForest event_forest; GroupTfEvents(&space, &event_forest); const GroupMetadataMap& group_metadata_map = event_forest.GetGroupMetadataMap(); XPlaneVisitor device_plane_visitor = CreateTfXPlaneVisitor(device_plane); EXPECT_EQ(device_plane->lines(0).events(0).stats_size(), 3); EXPECT_EQ(device_plane_visitor.GetStatType( device_plane->lines(0).events(0).stats(1).metadata_id()), StatType::kGroupId); EXPECT_EQ(device_plane->lines(0).events(0).stats(1).int64_value(), 0); EXPECT_EQ(group_metadata_map.size(), 1); ASSERT_TRUE(group_metadata_map.contains(0)); EXPECT_EQ(group_metadata_map.at(0).name, "10"); } TEST(GroupEventsTest, GroupMultipleTensorFlowLoopsTest) { constexpr int64_t kFirstStepId = 0; constexpr int64_t kSecondStepId = 1; constexpr int64_t kFirstIterNumStart = 10; constexpr int64_t kSecondIterNumStart = 0; XSpace space; XPlaneBuilder host_plane_builder(GetOrCreateHostXPlane(&space)); host_plane_builder.ReserveLines(2); auto first_tf_executor_thread = host_plane_builder.GetOrCreateLine(0); CreateXEvent(&host_plane_builder, &first_tf_executor_thread, HostEventType::kExecutorStateProcess, 220, 80, {{StatType::kStepId, kSecondStepId}, {StatType::kIterNum, kSecondIterNumStart}, {StatType::kConsumerType, kTfExecutor}, {StatType::kConsumerId, kSecondStepId}}); CreateXEvent(&host_plane_builder, &first_tf_executor_thread, HostEventType::kExecutorStateProcess, 320, 80, {{StatType::kStepId, kSecondStepId}, {StatType::kIterNum, kSecondIterNumStart + 1}, {StatType::kConsumerType, kTfExecutor}, {StatType::kConsumerId, kSecondStepId}}); auto second_tf_executor_thread = host_plane_builder.GetOrCreateLine(1); CreateXEvent(&host_plane_builder, &second_tf_executor_thread, HostEventType::kExecutorStateProcess, 20, 80, {{StatType::kStepId, kFirstStepId}, {StatType::kIterNum, kFirstIterNumStart}, {StatType::kConsumerType, kTfExecutor}, {StatType::kConsumerId, kFirstStepId}}); CreateXEvent(&host_plane_builder, &second_tf_executor_thread, HostEventType::kExecutorStateProcess, 120, 80, {{StatType::kStepId, kFirstStepId}, {StatType::kIterNum, kFirstIterNumStart + 1}, {StatType::kConsumerType, kTfExecutor}, {StatType::kConsumerId, kFirstStepId}}); EventForest event_forest; GroupTfEvents(&space, &event_forest); const GroupMetadataMap& group_metadata_map = event_forest.GetGroupMetadataMap(); EXPECT_EQ(group_metadata_map.size(), 4); ASSERT_TRUE(group_metadata_map.contains(0)); EXPECT_EQ(group_metadata_map.at(0).name, "10"); ASSERT_TRUE(group_metadata_map.contains(1)); EXPECT_EQ(group_metadata_map.at(1).name, "11"); ASSERT_TRUE(group_metadata_map.contains(2)); EXPECT_EQ(group_metadata_map.at(2).name, "0"); ASSERT_TRUE(group_metadata_map.contains(3)); EXPECT_EQ(group_metadata_map.at(3).name, "1"); } TEST(GroupEventsTest, EagerOpTest) { XSpace space; XPlane* host_plane = GetOrCreateHostXPlane(&space); XPlaneBuilder host_plane_builder(host_plane); host_plane_builder.ReserveLines(1); auto main_thread = host_plane_builder.GetOrCreateLine(0); XPlane* device_plane = space.add_planes(); XPlaneBuilder device_plane_builder(device_plane); device_plane_builder.ReserveLines(1); auto gpu_stream = device_plane_builder.GetOrCreateLine(0); int64_t correlation_id = 100; const char* kTF1GpuLaunchEvent = "tf1 matmul"; const char* kTF1GpuEvent = "tf1_kernel_matmul"; CreateXEvent(&host_plane_builder, &main_thread, kTF1GpuLaunchEvent, 10, 90, {{StatType::kCorrelationId, correlation_id}}); CreateXEvent(&device_plane_builder, &gpu_stream, kTF1GpuEvent, 200, 300, {{StatType::kCorrelationId, correlation_id}}); ++correlation_id; const char* kLegacyGpuLaunchEvent = "legacy matmul"; const char* kLegacyGpuEvent = "legacy_kernel_matmul"; CreateXEvent(&host_plane_builder, &main_thread, HostEventType::kEagerKernelExecute, 100, 200); CreateXEvent(&host_plane_builder, &main_thread, kLegacyGpuLaunchEvent, 110, 190, {{StatType::kCorrelationId, correlation_id}}); CreateXEvent(&device_plane_builder, &gpu_stream, kLegacyGpuEvent, 300, 400, {{StatType::kCorrelationId, correlation_id}}); ++correlation_id; const char* kEagerOpGpuLaunchEvent = "eager op matmul"; const char* kEagerOpGpuEvent = "eager_op_kernel_matmul"; CreateXEvent(&host_plane_builder, &main_thread, HostEventType::kEagerKernelExecute, 200, 300, {{StatType::kIsFunc, static_cast<int64_t>(0)}}); CreateXEvent(&host_plane_builder, &main_thread, kEagerOpGpuLaunchEvent, 210, 290, {{StatType::kCorrelationId, correlation_id}}); CreateXEvent(&device_plane_builder, &gpu_stream, kEagerOpGpuEvent, 400, 500, {{StatType::kCorrelationId, correlation_id}}); ++correlation_id; const char* kEagerFuncGpuLaunchEvent = "eager func matmul"; const char* kEagerFuncGpuEvent = "eager_func_kernel_matmul"; CreateXEvent(&host_plane_builder, &main_thread, HostEventType::kEagerKernelExecute, 300, 400, {{StatType::kIsFunc, static_cast<int64_t>(1)}}); CreateXEvent(&host_plane_builder, &main_thread, kEagerFuncGpuLaunchEvent, 310, 390, {{StatType::kCorrelationId, correlation_id}}); CreateXEvent(&device_plane_builder, &gpu_stream, kEagerFuncGpuEvent, 500, 600, {{StatType::kCorrelationId, correlation_id}}); ++correlation_id; const char* kEagerOpCpuEvent = "eager_op_cpu_kernel:Matmul"; CreateXEvent(&host_plane_builder, &main_thread, HostEventType::kEagerKernelExecute, 400, 500, {{StatType::kIsFunc, static_cast<int64_t>(0)}}); CreateXEvent(&host_plane_builder, &main_thread, kEagerOpCpuEvent, 410, 490); const char* kEagerFuncCpuEvent = "eager_func_cpu_kernel:Matmul"; CreateXEvent(&host_plane_builder, &main_thread, HostEventType::kEagerKernelExecute, 500, 600, {{StatType::kIsFunc, static_cast<int64_t>(1)}}); CreateXEvent(&host_plane_builder, &main_thread, kEagerFuncCpuEvent, 510, 590); GroupTfEvents(&space); auto is_eager = [](const XEventVisitor& event) { auto eager_stats = event.GetStat(StatType::kIsEager); return eager_stats && eager_stats->IntValue(); }; XPlaneVisitor host_plane_visitor = CreateTfXPlaneVisitor(host_plane); int interested_events_encountered = 0; host_plane_visitor.ForEachLine([&](const XLineVisitor& line) { line.ForEachEvent([&](const XEventVisitor& event) { if (event.Name() == kEagerOpCpuEvent) { interested_events_encountered++; EXPECT_TRUE(is_eager(event)); } else if (event.Name() == kEagerFuncCpuEvent) { interested_events_encountered++; EXPECT_FALSE(is_eager(event)); } }); }); EXPECT_EQ(interested_events_encountered, 2); XPlaneVisitor device_plane_visitor = CreateTfXPlaneVisitor(device_plane); interested_events_encountered = 0; device_plane_visitor.ForEachLine([&](const XLineVisitor& line) { line.ForEachEvent([&](const XEventVisitor& event) { if (event.Name() == kTF1GpuEvent) { interested_events_encountered++; EXPECT_FALSE(is_eager(event)); } else if (event.Name() == kLegacyGpuEvent) { interested_events_encountered++; EXPECT_FALSE(is_eager(event)); } else if (event.Name() == kEagerOpGpuEvent) { interested_events_encountered++; EXPECT_TRUE(is_eager(event)); } else if (event.Name() == kEagerFuncGpuEvent) { interested_events_encountered++; EXPECT_FALSE(is_eager(event)); } }); }); EXPECT_EQ(interested_events_encountered, 4); } TEST(GroupEventsTest, FunctionOpTest) { constexpr int64_t kStepNum = 123; constexpr int64_t kStepId = 0; constexpr int64_t kCorrelationId = 100; XSpace space; XPlane* host_plane = GetOrCreateHostXPlane(&space); XPlaneBuilder host_plane_builder(host_plane); host_plane_builder.ReserveLines(2); auto main_thread = host_plane_builder.GetOrCreateLine(0); CreateXEvent(&host_plane_builder, &main_thread, HostEventType::kTraceContext, 0, 100, {{StatType::kStepNum, kStepNum}}); CreateXEvent(&host_plane_builder, &main_thread, HostEventType::kEagerKernelExecute, 10, 90); CreateXEvent(&host_plane_builder, &main_thread, HostEventType::kFunctionRun, 10, 90, {{StatType::kStepId, kStepId}, {StatType::kProducerType, kTfExecutor}, {StatType::kProducerId, kStepId}}); auto tf_executor_thread = host_plane_builder.GetOrCreateLine(1); CreateXEvent(&host_plane_builder, &tf_executor_thread, HostEventType::kExecutorStateProcess, 20, 80, {{StatType::kStepId, kStepId}, {StatType::kConsumerType, kTfExecutor}, {StatType::kConsumerId, kStepId}}); CreateXEvent(&host_plane_builder, &tf_executor_thread, "matmul", 30, 30, {{StatType::kCorrelationId, kCorrelationId}}); CreateXEvent(&host_plane_builder, &tf_executor_thread, "add:Add", 70, 20); XPlane* device_plane = space.add_planes(); XPlaneBuilder device_plane_builder(device_plane); device_plane_builder.ReserveLines(1); auto stream = device_plane_builder.GetOrCreateLine(0); CreateXEvent(&device_plane_builder, &stream, "matmul", 200, 300, {{StatType::kCorrelationId, kCorrelationId}}); GroupTfEvents(&space); XPlaneVisitor host_plane_visitor = CreateTfXPlaneVisitor(host_plane); const XEvent& cpu_tf_op = host_plane->lines(1).events(2); EXPECT_EQ(cpu_tf_op.stats_size(), 2); EXPECT_EQ(host_plane_visitor.GetStatType(cpu_tf_op.stats(1).metadata_id()), StatType::kIsEager); EXPECT_EQ(cpu_tf_op.stats(1).int64_value(), 0); XPlaneVisitor device_plane_visitor = CreateTfXPlaneVisitor(device_plane); const XEvent& gpu_kernel = device_plane->lines(0).events(0); EXPECT_EQ(gpu_kernel.stats_size(), 3); EXPECT_EQ(device_plane_visitor.GetStatType(gpu_kernel.stats(2).metadata_id()), StatType::kIsEager); EXPECT_EQ(gpu_kernel.stats(2).int64_value(), 0); } TEST(GroupEventsTest, SemanticArgTest) { constexpr int64_t kIsRoot = 1; constexpr int64_t kStepNum = 100; constexpr int64_t kContextType = 123; constexpr uint64 kContextId = 456; XSpace raw_space; XPlane* raw_plane = raw_space.add_planes(); XPlaneBuilder plane(raw_plane); plane.ReserveLines(2); auto root_producer = plane.GetOrCreateLine(0); CreateXEvent(&plane, &root_producer, HostEventType::kTraceContext, 0, 100, {{StatType::kIsRoot, kIsRoot}, {StatType::kStepNum, kStepNum}}); CreateXEvent(&plane, &root_producer, HostEventType::kFunctionRun, 10, 90, {{StatType::kProducerType, kContextType}, {StatType::kProducerId, kContextId}}); auto consumer = plane.GetOrCreateLine(1); CreateXEvent(&plane, &consumer, HostEventType::kExecutorStateProcess, 20, 80, {{StatType::kConsumerType, kContextType}, {StatType::kConsumerId, kContextId}}); GroupTfEvents(&raw_space); int num_events = 0; CreateTfXPlaneVisitor(raw_plane).ForEachLine([&](const XLineVisitor& line) { num_events += line.NumEvents(); line.ForEachEvent([&](const XEventVisitor& event) { std::optional<int64_t> group_id; if (std::optional<XStatVisitor> stat = event.GetStat(StatType::kGroupId)) { group_id = stat->IntValue(); } EXPECT_TRUE(group_id.has_value()); EXPECT_EQ(*group_id, 0); }); }); EXPECT_EQ(num_events, 3); } TEST(GroupEventsTest, SemanticIntArgNoMatchTest) { constexpr int64_t kIsRoot = 1; constexpr int64_t kStepNum = 100; constexpr int64_t kContextType = 123; constexpr uint64 kProducerId = 456; constexpr uint64 kConsumerId = 789; XSpace raw_space; XPlane* raw_plane = raw_space.add_planes(); XPlaneBuilder plane(raw_plane); plane.ReserveLines(2); auto root_producer = plane.GetOrCreateLine(0); CreateXEvent(&plane, &root_producer, HostEventType::kTraceContext, 0, 100, {{StatType::kIsRoot, kIsRoot}, {StatType::kStepNum, kStepNum}}); CreateXEvent(&plane, &root_producer, HostEventType::kFunctionRun, 10, 90, {{StatType::kProducerType, kContextType}, {StatType::kProducerId, kProducerId}}); auto consumer = plane.GetOrCreateLine(1); CreateXEvent(&plane, &consumer, HostEventType::kExecutorStateProcess, 20, 80, {{StatType::kConsumerType, kContextType}, {StatType::kConsumerId, kConsumerId}}); GroupTfEvents(&raw_space); int num_events = 0; CreateTfXPlaneVisitor(raw_plane).ForEachLine([&](const XLineVisitor& line) { num_events += line.NumEvents(); line.ForEachEvent([&](const XEventVisitor& event) { std::optional<int64_t> group_id; if (std::optional<XStatVisitor> stat = event.GetStat(StatType::kGroupId)) { group_id = stat->IntValue(); } if (event.Type() == HostEventType::kExecutorStateProcess) { EXPECT_FALSE(group_id.has_value()); } else { EXPECT_TRUE(group_id.has_value()); EXPECT_EQ(*group_id, 0); } }); }); EXPECT_EQ(num_events, 3); } TEST(GroupEventsTest, SemanticUintArgNoMatchTest) { constexpr int64_t kIsRoot = 1; constexpr int64_t kStepNum = 100; constexpr int64_t kContextType = 123; constexpr uint64 kProducerId = UINT64_MAX; constexpr uint64 kConsumerId = UINT64_MAX - 1; XSpace raw_space; XPlane* raw_plane = raw_space.add_planes(); XPlaneBuilder plane(raw_plane); plane.ReserveLines(2); auto root_producer = plane.GetOrCreateLine(0); CreateXEvent(&plane, &root_producer, HostEventType::kTraceContext, 0, 100, {{StatType::kIsRoot, kIsRoot}, {StatType::kStepNum, kStepNum}}); CreateXEvent(&plane, &root_producer, HostEventType::kFunctionRun, 10, 90, {{StatType::kProducerType, kContextType}, {StatType::kProducerId, kProducerId}}); auto consumer = plane.GetOrCreateLine(1); CreateXEvent(&plane, &consumer, HostEventType::kExecutorStateProcess, 20, 80, {{StatType::kConsumerType, kContextType}, {StatType::kConsumerId, kConsumerId}}); GroupTfEvents(&raw_space); int num_events = 0; CreateTfXPlaneVisitor(raw_plane).ForEachLine([&](const XLineVisitor& line) { num_events += line.NumEvents(); line.ForEachEvent([&](const XEventVisitor& event) { std::optional<int64_t> group_id; if (std::optional<XStatVisitor> stat = event.GetStat(StatType::kGroupId)) { group_id = stat->IntValue(); } if (event.Type() == HostEventType::kExecutorStateProcess) { EXPECT_FALSE(group_id.has_value()); } else { EXPECT_TRUE(group_id.has_value()); EXPECT_EQ(*group_id, 0); } }); }); EXPECT_EQ(num_events, 3); } TEST(GroupEventsTest, AsyncEventTest) { constexpr int64_t kIsRoot = 1; constexpr int64_t kIsAsync = 1; constexpr absl::string_view kParent = "parent"; constexpr absl::string_view kAsync = "async"; constexpr absl::string_view kChild = "child"; XSpace raw_space; XPlane* raw_plane = raw_space.add_planes(); XPlaneBuilder plane(raw_plane); plane.ReserveLines(1); auto line = plane.GetOrCreateLine(0); CreateXEvent(&plane, &line, kParent, 0, 100, {{StatType::kIsRoot, kIsRoot}}); CreateXEvent(&plane, &line, kAsync, 10, 200, {{StatType::kIsAsync, kIsAsync}}); CreateXEvent(&plane, &line, kChild, 20, 80); GroupTfEvents(&raw_space); CreateTfXPlaneVisitor(raw_plane).ForEachLine([&](const XLineVisitor& line) { EXPECT_EQ(line.NumEvents(), 3); line.ForEachEvent([&](const XEventVisitor& event) { std::optional<int64_t> group_id; if (std::optional<XStatVisitor> stat = event.GetStat(StatType::kGroupId)) { group_id = stat->IntValue(); } if (event.Name() == kAsync) { EXPECT_FALSE(group_id.has_value()); } else { EXPECT_TRUE(group_id.has_value()); EXPECT_EQ(*group_id, 0); } }); }); } TEST(GroupEventsTest, BatchingSessionTest) { constexpr absl::string_view kSchedule = "Schedule"; constexpr int64_t kBatchContextType = static_cast<int64_t>(ContextType::kSharedBatchScheduler); constexpr int64_t kBatchContextId = 123; constexpr int64_t kBatchingSessionRunRootLevel = 1; constexpr int64_t kProcessBatchRootLevel = 2; XSpace raw_space; XPlane* raw_plane = raw_space.add_planes(); XPlaneBuilder plane(raw_plane); plane.ReserveLines(2); auto request_thread = plane.GetOrCreateLine(0); CreateXEvent(&plane, &request_thread, HostEventType::kBatchingSessionRun, 0, 100, {{StatType::kIsRoot, kBatchingSessionRunRootLevel}}); CreateXEvent(&plane, &request_thread, kSchedule, 0, 100, {{StatType::kProducerType, kBatchContextType}, {StatType::kProducerId, kBatchContextId}}); CreateXEvent(&plane, &request_thread, HostEventType::kBatchingSessionRun, 200, 100, {{StatType::kIsRoot, kBatchingSessionRunRootLevel}}); CreateXEvent(&plane, &request_thread, kSchedule, 200, 100, {{StatType::kProducerType, kBatchContextType}, {StatType::kProducerId, kBatchContextId}}); auto batch_thread = plane.GetOrCreateLine(1); CreateXEvent(&plane, &batch_thread, HostEventType::kProcessBatch, 200, 100, {{StatType::kConsumerType, kBatchContextType}, {StatType::kConsumerId, kBatchContextId}, {StatType::kIsRoot, kProcessBatchRootLevel}}); EventForest event_forest; GroupTfEvents(&raw_space, &event_forest); const GroupMetadataMap& group_metadata_map = event_forest.GetGroupMetadataMap(); EXPECT_EQ(group_metadata_map.size(), 3); EXPECT_EQ(group_metadata_map.at(0).parents.size(), 2); EXPECT_EQ(group_metadata_map.at(1).children.size(), 1); EXPECT_EQ(group_metadata_map.at(2).children.size(), 1); uint64 num_checked = 0; CreateTfXPlaneVisitor(raw_plane).ForEachLine([&](const XLineVisitor& line) { line.ForEachEvent([&](const XEventVisitor& event) { std::optional<int64_t> group_id; if (std::optional<XStatVisitor> stat = event.GetStat(StatType::kGroupId)) { group_id = stat->IntValue(); } EXPECT_TRUE(group_id.has_value()); if (line.Id() == 0 && event.Type() == HostEventType::kBatchingSessionRun) { ++num_checked; } else if (line.Id() == 1 && event.Type() == HostEventType::kProcessBatch) { ++num_checked; } }); }); EXPECT_EQ(num_checked, 3); } TEST(GroupTPUEventsTest, TpuExecuteOpTest) { tensorflow::profiler::XSpace space; XPlaneBuilder host_plane_builder(GetOrCreateHostXPlane(&space)); host_plane_builder.ReserveLines(1); auto main_thread = host_plane_builder.GetOrCreateLine(0); CreateXEvent( &host_plane_builder, &main_thread, HostEventType::kExecutorStateProcess, 20, 50, {{StatType::kStepId, int64_t{123}}, {StatType::kIterNum, int64_t{456}}}); EventForest event_forest; GroupTpuEventsOSS(&space, {}, &event_forest); EXPECT_EQ(event_forest.GetGroupMetadataMap().size(), 1); XPlaneVisitor host_plane_visitor = CreateTfXPlaneVisitor(&space.planes(0)); host_plane_visitor.ForEachLine([&](const XLineVisitor& line) { line.ForEachEvent([&](const XEventVisitor& event) { EXPECT_TRUE(event.GetStat(StatType::kGroupId).has_value()); }); }); } TEST(GroupTPUEventsTest, TpuRequestTest) { tensorflow::profiler::XSpace space; XPlaneBuilder host_plane_builder(GetOrCreateHostXPlane(&space)); host_plane_builder.ReserveLines(1); auto main_thread = host_plane_builder.GetOrCreateLine(0); CreateXEvent(&host_plane_builder, &main_thread, HostEventType::kSessionRun, 0, 100, {{StatType::kIsRoot, int64_t{1}}}); CreateXEvent(&host_plane_builder, &main_thread, GetHostEventTypeStr(HostEventType::kEnqueueRequestLocked), 20, 50, {{StatType::kQueueAddr, int64_t{123}}, {StatType::kRequestId, int64_t{456}}}); EventForest event_forest; GroupTpuEventsOSS(&space, {}, &event_forest); EXPECT_EQ(event_forest.GetGroupMetadataMap().size(), 1); XPlaneVisitor host_plane_visitor = CreateTfXPlaneVisitor(&space.planes(0)); host_plane_visitor.ForEachLine([&](const XLineVisitor& line) { line.ForEachEvent([&](const XEventVisitor& event) { EXPECT_TRUE(event.GetStat(StatType::kGroupId).has_value()); }); }); } TEST(GroupTPUEventsTest, TpuProgramCallbackTest) { tensorflow::profiler::XSpace space; XPlaneBuilder host_plane_builder(GetOrCreateHostXPlane(&space)); host_plane_builder.ReserveLines(1); auto main_thread = host_plane_builder.GetOrCreateLine(0); CreateXEvent(&host_plane_builder, &main_thread, HostEventType::kSessionRun, 0, 100, {{StatType::kIsRoot, int64_t{1}}}); CreateXEvent(&host_plane_builder, &main_thread, GetHostEventTypeStr(HostEventType::kDoEnqueueProgram), 20, 50, {{StatType::kRunId, int64_t{123}}, {StatType::kQueueId, int64_t{0}}, {StatType::kDeviceOrdinal, int64_t{1}}}); EventForest event_forest; GroupTpuEventsOSS(&space, {}, &event_forest); EXPECT_EQ(event_forest.GetGroupMetadataMap().size(), 1); XPlaneVisitor host_plane_visitor = CreateTfXPlaneVisitor(&space.planes(0)); host_plane_visitor.ForEachLine([&](const XLineVisitor& line) { line.ForEachEvent([&](const XEventVisitor& event) { EXPECT_TRUE(event.GetStat(StatType::kGroupId).has_value()); }); }); } } } }
2,299
#ifndef TENSORFLOW_TSL_PROFILER_UTILS_TPU_XPLANE_UTILS_H_ #define TENSORFLOW_TSL_PROFILER_UTILS_TPU_XPLANE_UTILS_H_ #include <optional> #include <vector> #include "absl/strings/string_view.h" #include "tsl/profiler/protobuf/xplane.pb.h" namespace tsl { namespace profiler { std::vector<const tensorflow::profiler::XPlane*> FindTensorCorePlanes( const tensorflow::profiler::XSpace& xspace); std::vector<tensorflow::profiler::XPlane*> FindMutableTensorCorePlanes( tensorflow::profiler::XSpace* xspace); std::optional<int> GetTensorCoreId(absl::string_view plane_name); } } #endif #include "tsl/profiler/utils/tpu_xplane_utils.h" #include <optional> #include <vector> #include "tsl/platform/regexp.h" #include "tsl/profiler/protobuf/xplane.pb.h" #include "tsl/profiler/utils/xplane_schema.h" #include "tsl/profiler/utils/xplane_utils.h" namespace tsl { namespace profiler { std::vector<const XPlane*> FindTensorCorePlanes(const XSpace& xspace) { return FindPlanes(xspace, [](const XPlane& xplane) { static const LazyRE2 re = {kTpuPlaneRegex}; return RE2::FullMatch(xplane.name(), *re); }); } std::vector<XPlane*> FindMutableTensorCorePlanes(XSpace* xspace) { return FindMutablePlanes(xspace, [](const XPlane& xplane) { static const LazyRE2 re = {kTpuPlaneRegex}; return RE2::FullMatch(xplane.name(), *re); }); } std::optional<int> GetTensorCoreId(absl::string_view plane_name) { int core_id = -1; if (RE2::FullMatch(plane_name, {kTpuPlaneRegex}, &core_id)) { return core_id; } return std::nullopt; } } }
#include "tsl/profiler/utils/tpu_xplane_utils.h" #include <vector> #include "absl/strings/str_cat.h" #include "tsl/platform/test.h" #include "tsl/profiler/protobuf/xplane.pb.h" #include "tsl/profiler/utils/xplane_schema.h" #include "tsl/profiler/utils/xplane_utils.h" namespace tsl { namespace profiler { namespace { using ::testing::UnorderedElementsAre; TEST(TpuXPlaneUtilsTest, GetTensorCoreXPlanesFromXSpace) { XSpace xspace; XPlane* p1 = FindOrAddMutablePlaneWithName(&xspace, TpuPlaneName(0)); XPlane* p2 = FindOrAddMutablePlaneWithName(&xspace, TpuPlaneName(1)); FindOrAddMutablePlaneWithName(&xspace, TpuPlaneName(2) + "Postfix"); std::vector<const XPlane*> xplanes = FindTensorCorePlanes(xspace); EXPECT_THAT(xplanes, UnorderedElementsAre(p1, p2)); } TEST(TpuXPlaneUtilsTest, GetMutableTensorCoreXPlanesFromXSpace) { XSpace xspace; XPlane* p1 = FindOrAddMutablePlaneWithName(&xspace, TpuPlaneName(0)); XPlane* p2 = FindOrAddMutablePlaneWithName(&xspace, TpuPlaneName(1)); FindOrAddMutablePlaneWithName(&xspace, TpuPlaneName(2) + "Postfix"); std::vector<XPlane*> xplanes = FindMutableTensorCorePlanes(&xspace); EXPECT_THAT(xplanes, UnorderedElementsAre(p1, p2)); } TEST(TpuXPlaneUtilsTest, GetTensorCoreIdFromPlaneName) { EXPECT_EQ(GetTensorCoreId(TpuPlaneName(0)), 0); } TEST(TpuXPlaneUtilsTest, IsNotTensorCorePlaneName) { EXPECT_FALSE(GetTensorCoreId("/metadata:0").has_value()); } TEST(TpuXPlaneUtilsTest, IsNotTensorCorePlaneNameWithPrefix) { EXPECT_FALSE( GetTensorCoreId(absl::StrCat("/prefix", TpuPlaneName(0))).has_value()); } } } }
2,300
#ifndef TENSORFLOW_TSL_PROFILER_CONVERT_XPLANE_TO_TRACE_EVENTS_H_ #define TENSORFLOW_TSL_PROFILER_CONVERT_XPLANE_TO_TRACE_EVENTS_H_ #include <string> #include "tsl/platform/types.h" #include "tsl/profiler/convert/trace_container.h" #include "tsl/profiler/protobuf/xplane.pb.h" namespace tsl { namespace profiler { TraceContainer ConvertXSpaceToTraceContainer( const tensorflow::profiler::XSpace& xspace); void ConvertXSpaceToTraceEventsString( const tensorflow::profiler::XSpace& xspace, std::string* content); } } #endif #include "tsl/profiler/convert/xplane_to_trace_events.h" #include <stddef.h> #include <algorithm> #include <string> #include <utility> #include <vector> #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "tsl/platform/types.h" #include "tsl/profiler/protobuf/trace_events.pb.h" #include "tsl/profiler/protobuf/xplane.pb.h" #include "tsl/profiler/utils/tf_xplane_visitor.h" #include "tsl/profiler/utils/trace_utils.h" #include "tsl/profiler/utils/xplane_schema.h" #include "tsl/profiler/utils/xplane_utils.h" #include "tsl/profiler/utils/xplane_visitor.h" namespace tsl { namespace profiler { namespace { using tensorflow::profiler::XSpace; void BuildDeviceAndResources(uint32 device_id, const XPlaneVisitor& plane, Device* device) { device->set_name(std::string(plane.Name())); device->set_device_id(device_id); bool sort_by_ordinal = (device_id == kHostThreadsDeviceId); int ordinal = 0; plane.ForEachLine([&](const XLineVisitor& line) { uint32 resource_id = line.DisplayId(); Resource& resource = (*device->mutable_resources())[resource_id]; resource.set_resource_id(resource_id); resource.set_name(std::string(line.DisplayName())); if (sort_by_ordinal) { resource.set_sort_index(++ordinal); } }); } void ConvertXPlaneToTraceEvents(uint32 device_id, const XPlaneVisitor& xplane, TraceContainer& container) { BuildDeviceAndResources(device_id, xplane, container.MutableDevice(device_id)); xplane.ForEachLine([device_id, &container](const XLineVisitor& xline) { uint32 resource_id = xline.DisplayId(); if (xline.DisplayName() == tsl::profiler::kXlaAsyncOpLineName) { return; } xline.ForEachEvent( [device_id, resource_id, &container](const XEventVisitor& xevent) { int64_t event_type = xevent.Type().value_or(HostEventType::kUnknownHostEventType); if (IsInternalEvent(event_type)) return; TraceEvent* event = container.CreateEvent(); auto& args = *event->mutable_args(); event->set_device_id(device_id); event->set_resource_id(resource_id); if (xevent.HasDisplayName()) { event->set_name(std::string(xevent.DisplayName())); args["long_name"] = std::string(xevent.Name()); } else { event->set_name(std::string(xevent.Name())); } event->set_timestamp_ps(xevent.TimestampPs()); event->set_duration_ps(xevent.DurationPs()); auto for_each_stat = [&](const XStatVisitor& stat) { if (stat.ValueCase() == XStat::VALUE_NOT_SET) return; if (IsInternalStat(stat.Type())) return; if (stat.Type() == StatType::kStepName) { event->set_name(stat.ToString()); } args[std::string(stat.Name())] = stat.ToString(); }; xevent.Metadata().ForEachStat(for_each_stat); xevent.ForEachStat(for_each_stat); }); }); } } uint64 GetTraceViewerMaxEvents() { constexpr uint64 kMaxEvents = 1000000; char* max_events = getenv("TF_PROFILER_TRACE_VIEWER_MAX_EVENTS"); if (max_events != nullptr) { return std::stoull(max_events, nullptr, 10); } else { return kMaxEvents; } } TraceContainer ConvertXSpaceToTraceContainer(const XSpace& xspace) { TraceContainer container; const XPlane* host_plane = FindPlaneWithName(xspace, kHostThreadsPlaneName); if (host_plane != nullptr) { XPlaneVisitor xplane = CreateTfXPlaneVisitor(host_plane); ConvertXPlaneToTraceEvents(kHostThreadsDeviceId, xplane, container); } std::vector<const XPlane*> device_planes = FindPlanesWithPrefix(xspace, kGpuPlanePrefix); if (device_planes.empty()) { device_planes = FindPlanesWithPrefix(xspace, kTpuPlanePrefix); } if (device_planes.empty()) { device_planes = FindPlanesWithPrefix(xspace, kCustomPlanePrefix); } for (const XPlane* device_plane : device_planes) { XPlaneVisitor xplane = CreateTfXPlaneVisitor(device_plane); uint32 device_id = kFirstDeviceId + xplane.Id(); ConvertXPlaneToTraceEvents(device_id, xplane, container); } uint64 viewer_max_events = GetTraceViewerMaxEvents(); container.CapEvents(viewer_max_events); return container; } void ConvertXSpaceToTraceEventsString(const XSpace& xspace, std::string* content) { ConvertXSpaceToTraceContainer(xspace).FlushAndSerializeEvents(content); } } }
#include "tsl/profiler/convert/xplane_to_trace_events.h" #include <limits> #include <utility> #include "tsl/platform/test.h" #include "tsl/profiler/protobuf/trace_events.pb.h" #include "tsl/profiler/protobuf/xplane.pb.h" #include "tsl/profiler/utils/trace_utils.h" #include "tsl/profiler/utils/xplane_builder.h" #include "tsl/profiler/utils/xplane_schema.h" namespace tsl { namespace profiler { namespace { using tensorflow::profiler::XSpace; void CreateXSpace(XSpace* space) { XPlaneBuilder host_plane(space->add_planes()); host_plane.SetName(kHostThreadsPlaneName); XLineBuilder thread1 = host_plane.GetOrCreateLine(10); thread1.SetName("thread1"); XEventBuilder event1 = thread1.AddEvent(*host_plane.GetOrCreateEventMetadata("event1")); event1.SetTimestampNs(150000); event1.SetDurationNs(10000); event1.AddStatValue(*host_plane.GetOrCreateStatMetadata("tf_op"), *host_plane.GetOrCreateStatMetadata("Relu")); XLineBuilder thread2 = host_plane.GetOrCreateLine(20); thread2.SetName("thread2"); XEventBuilder event2 = thread2.AddEvent(*host_plane.GetOrCreateEventMetadata("event2")); event2.SetTimestampNs(160000); event2.SetDurationNs(10000); event2.AddStatValue(*host_plane.GetOrCreateStatMetadata("tf_op"), *host_plane.GetOrCreateStatMetadata("Conv2D")); XPlaneBuilder device_plane(space->add_planes()); device_plane.SetName(GpuPlaneName(0)); device_plane.SetId(0); XLineBuilder stream1 = device_plane.GetOrCreateLine(30); stream1.SetName("gpu stream 1"); XEventBuilder event3 = stream1.AddEvent(*device_plane.GetOrCreateEventMetadata("kernel1")); event3.SetTimestampNs(180000); event3.SetDurationNs(10000); event3.AddStatValue(*device_plane.GetOrCreateStatMetadata("correlation id"), 55); } TEST(ConvertXPlaneToTraceEvents, Convert) { XSpace xspace; CreateXSpace(&xspace); TraceContainer container = ConvertXSpaceToTraceContainer(xspace); ASSERT_EQ(container.trace().devices_size(), 2); EXPECT_EQ( container.trace().devices().at(kHostThreadsDeviceId).resources_size(), 2); EXPECT_EQ(container.trace().devices().at(kFirstDeviceId).resources_size(), 1); EXPECT_EQ(container.UnsortedEvents().size(), 3); } TEST(ConvertXPlaneToTraceEvents, SkipAsyncOps) { XSpace xspace; XPlaneBuilder device_plane(xspace.add_planes()); device_plane.SetName(GpuPlaneName(0)); XLineBuilder async_ops = device_plane.GetOrCreateLine(10); async_ops.SetName(kXlaAsyncOpLineName); XEventBuilder event1 = async_ops.AddEvent(*device_plane.GetOrCreateEventMetadata("event1")); event1.SetTimestampNs(100); event1.SetDurationNs(1); TraceContainer container = ConvertXSpaceToTraceContainer(xspace); ASSERT_THAT(container.UnsortedEvents(), ::testing::IsEmpty()); } } } }
2,301
#ifndef TENSORFLOW_TSL_PROFILER_CONVERT_TRACE_CONTAINER_H_ #define TENSORFLOW_TSL_PROFILER_CONVERT_TRACE_CONTAINER_H_ #include <string> #include <string_view> #include <vector> #include "tsl/profiler/protobuf/trace_events.pb.h" namespace tsl { namespace profiler { using tsl::profiler::Device; using tsl::profiler::Trace; using tsl::profiler::TraceEvent; template <typename Event> class AnyTraceContainer { public: virtual ~AnyTraceContainer() = default; virtual TraceEvent* CreateEvent() = 0; virtual const std::vector<TraceEvent*>& UnsortedEvents() const = 0; }; class TraceContainer : public AnyTraceContainer<TraceEvent> { public: TraceContainer() = default; ~TraceContainer() final { for (const TraceEvent* event : events_) { delete event; } } const Trace& trace() const { return metadata_; } const std::vector<TraceEvent*>& UnsortedEvents() const final { return events_; } void CapEvents(uint32_t max_count); Device* MutableDevice(uint32_t device_id) { return &(*metadata_.mutable_devices())[device_id]; } TraceEvent* CreateEvent() final { TraceEvent* event = new TraceEvent; events_.push_back(event); return event; } void FlushAndSerializeEvents(std::string* output); bool ParseMetadataFromString(const std::string& description); private: Trace metadata_; std::vector<TraceEvent*> events_; }; } } #endif #include "tsl/profiler/convert/trace_container.h" #include <algorithm> #include <string> #include <string_view> #include <vector> #include "tsl/platform/protobuf.h" namespace tsl { namespace profiler { bool TraceContainer::ParseMetadataFromString(const std::string& description) { return protobuf::TextFormat::ParseFromString(description, &metadata_); } void TraceContainer::CapEvents(const uint32_t max_count) { const size_t total_count = events_.size(); if (total_count <= max_count) { return; } const std::vector<TraceEvent*>::iterator end = events_.begin() + max_count; std::partial_sort( events_.begin(), end, events_.end(), [](const TraceEvent* const lhs, const TraceEvent* const rhs) -> bool { return lhs->timestamp_ps() < rhs->timestamp_ps(); }); for (std::vector<TraceEvent*>::iterator i = end; i != events_.end(); ++i) { delete *i; } events_.erase(end, events_.end()); } void TraceContainer::FlushAndSerializeEvents(std::string* const output) { Trace trace = metadata_; for (TraceEvent* const event : events_) { trace.mutable_trace_events()->AddAllocated(event); } events_.clear(); trace.SerializeToString(output); } } }
#include "tsl/profiler/convert/trace_container.h" #include <string> #include "tsl/platform/protobuf.h" #include "tsl/platform/test.h" namespace tsl { namespace profiler { namespace { void PopulateDummyEvent(TraceEvent* const event) { event->set_device_id(1); event->set_resource_id(2); event->set_name("A"); event->set_timestamp_ps(3); event->set_duration_ps(4); } TEST(TraceContainer, TraceEventAllocation) { TraceContainer container; PopulateDummyEvent(container.CreateEvent()); } TEST(TraceContainer, FlushAndSerializeEvents) { TraceContainer container; PopulateDummyEvent(container.CreateEvent()); EXPECT_EQ(container.UnsortedEvents().size(), 1); std::string serialized; container.FlushAndSerializeEvents(&serialized); EXPECT_EQ(container.UnsortedEvents().size(), 0); PopulateDummyEvent(container.CreateEvent()); EXPECT_EQ(container.UnsortedEvents().size(), 1); std::string reserialized; container.FlushAndSerializeEvents(&reserialized); EXPECT_EQ(serialized, reserialized); EXPECT_EQ(container.UnsortedEvents().size(), 0); Trace trace; trace.ParseFromString(reserialized); EXPECT_EQ(trace.trace_events_size(), 1); } TEST(TraceContainer, CapEvents) { TraceContainer container; for (int i = 0; i < 100; i++) { container.CreateEvent()->set_timestamp_ps((100 - i) % 50); } container.CapEvents(101); EXPECT_EQ(container.UnsortedEvents().size(), 100); container.CapEvents(100); EXPECT_EQ(container.UnsortedEvents().size(), 100); container.CapEvents(99); EXPECT_EQ(container.UnsortedEvents().size(), 99); container.CapEvents(50); EXPECT_EQ(container.UnsortedEvents().size(), 50); for (const TraceEvent* const event : container.UnsortedEvents()) { EXPECT_LT(event->timestamp_ps(), 25); } } } } }
2,302
#ifndef TENSORFLOW_TSL_PROFILER_RPC_CLIENT_REMOTE_PROFILER_SESSION_MANAGER_H_ #define TENSORFLOW_TSL_PROFILER_RPC_CLIENT_REMOTE_PROFILER_SESSION_MANAGER_H_ #include <functional> #include <memory> #include <vector> #include "absl/strings/string_view.h" #include "tsl/platform/macros.h" #include "tsl/platform/mutex.h" #include "tsl/platform/status.h" #include "tsl/platform/thread_annotations.h" #include "tsl/platform/types.h" #include "tsl/profiler/rpc/client/profiler_client.h" namespace tsl { namespace profiler { using AddressResolver = std::function<std::string(absl::string_view)>; class RemoteProfilerSessionManager { public: struct Response { std::string service_address; std::unique_ptr<tensorflow::ProfileResponse> profile_response; absl::Status status; }; static std::unique_ptr<RemoteProfilerSessionManager> Create( const tensorflow::RemoteProfilerSessionManagerOptions& options, const tensorflow::ProfileRequest& request, absl::Status& out_status, AddressResolver resolver = nullptr); std::vector<Response> WaitForCompletion(); RemoteProfilerSessionManager(const RemoteProfilerSessionManager&) = delete; RemoteProfilerSessionManager& operator=(const RemoteProfilerSessionManager&) = delete; ~RemoteProfilerSessionManager(); private: explicit RemoteProfilerSessionManager( tensorflow::RemoteProfilerSessionManagerOptions options, tensorflow::ProfileRequest request, AddressResolver resolver); absl::Status Init(); mutex mutex_; tensorflow::RemoteProfilerSessionManagerOptions options_ TF_GUARDED_BY(mutex_); tensorflow::ProfileRequest request_ TF_GUARDED_BY(mutex_); std::vector<std::unique_ptr<RemoteProfilerSession>> clients_ TF_GUARDED_BY(mutex_); AddressResolver resolver_ TF_GUARDED_BY(mutex_); }; } } #endif #include "tsl/profiler/rpc/client/remote_profiler_session_manager.h" #include <cstddef> #include <memory> #include "absl/memory/memory.h" #include "absl/strings/string_view.h" #include "absl/time/clock.h" #include "absl/time/time.h" #include "tsl/platform/env_time.h" #include "tsl/platform/errors.h" #include "tsl/platform/logging.h" #include "tsl/platform/types.h" #include "tsl/profiler/rpc/client/profiler_client.h" #include "tsl/profiler/utils/time_utils.h" namespace tsl { namespace profiler { using tensorflow::ProfileRequest; using tensorflow::RemoteProfilerSessionManagerOptions; std::unique_ptr<RemoteProfilerSessionManager> RemoteProfilerSessionManager::Create( const RemoteProfilerSessionManagerOptions& options, const ProfileRequest& request, absl::Status& out_status, AddressResolver resolver) { VLOG(1) << "Creating a RemoteProfilerSessionManager."; auto session_manager = absl::WrapUnique( new RemoteProfilerSessionManager(options, request, resolver)); out_status = session_manager->Init(); if (!out_status.ok()) { return nullptr; } return session_manager; } RemoteProfilerSessionManager::RemoteProfilerSessionManager( RemoteProfilerSessionManagerOptions options, ProfileRequest request, AddressResolver resolver) : options_(options), request_(request) { if (resolver) { resolver_ = resolver; } else { resolver_ = [](absl::string_view addr) { return std::string(addr); }; } } RemoteProfilerSessionManager::~RemoteProfilerSessionManager() { VLOG(2) << "Destroying RemoteProfilerSessionManager."; } absl::Status RemoteProfilerSessionManager::Init() { mutex_lock lock(mutex_); VLOG(1) << "SessionManager initializing."; const absl::Time session_created_ts = absl::FromUnixNanos(options_.session_creation_timestamp_ns()); const absl::Time deadline = session_created_ts + absl::Milliseconds(options_.max_session_duration_ms()); LOG(INFO) << "Deadline set to " << deadline << " because max_session_duration_ms was " << options_.max_session_duration_ms() << " and session_creation_timestamp_ns was " << options_.session_creation_timestamp_ns() << " [" << session_created_ts << "]"; clients_.reserve(options_.service_addresses_size()); ProfileRequest request = request_; for (auto& service_address : options_.service_addresses()) { std::string resolved_service_address = resolver_(service_address); request.set_host_name(resolved_service_address); auto client = RemoteProfilerSession::Create(resolved_service_address, deadline, request); clients_.push_back(std::move(client)); } LOG(INFO) << "Issued Profile gRPC to " << clients_.size() << " clients"; return absl::OkStatus(); } std::vector<RemoteProfilerSessionManager::Response> RemoteProfilerSessionManager::WaitForCompletion() { mutex_lock lock(mutex_); std::vector<RemoteProfilerSessionManager::Response> remote_responses( clients_.size()); for (int32_t idx = 0; idx < clients_.size(); ++idx) { auto& remote_response = remote_responses[idx]; auto* client = clients_[idx].get(); remote_response.profile_response = client->WaitForCompletion(remote_response.status); remote_response.service_address = std::string(client->GetServiceAddress()); } return remote_responses; } } }
#include "tsl/profiler/rpc/client/remote_profiler_session_manager.h" #include <memory> #include <string> #include <vector> #include "absl/status/status.h" #include "absl/time/clock.h" #include "absl/time/time.h" #include "tsl/platform/errors.h" #include "tsl/platform/status.h" #include "tsl/platform/test.h" #include "tsl/platform/types.h" #include "tsl/profiler/protobuf/profiler_options.pb.h" #include "tsl/profiler/protobuf/profiler_service.pb.h" #include "tsl/profiler/rpc/client/profiler_client_test_util.h" namespace tsl { namespace profiler { namespace { using tensorflow::ProfileRequest; using tensorflow::RemoteProfilerSessionManagerOptions; using ::tsl::profiler::test::DurationApproxLess; using ::tsl::profiler::test::DurationNear; using ::tsl::profiler::test::StartServer; using ::tsl::testing::TmpDir; using Response = tsl::profiler::RemoteProfilerSessionManager::Response; constexpr double kGracePeriodSeconds = 10.0; ProfileRequest PopulateProfileRequest( absl::string_view repository_root, absl::string_view session_id, absl::string_view host_name, const RemoteProfilerSessionManagerOptions& options) { constexpr uint64 kMaxEvents = 1000000; const absl::string_view kXPlanePb = "xplane.pb"; ProfileRequest request; request.set_duration_ms(options.profiler_options().duration_ms()); request.set_max_events(kMaxEvents); request.set_repository_root(repository_root.data(), repository_root.size()); request.set_session_id(session_id.data(), session_id.size()); request.set_host_name(host_name.data(), host_name.size()); request.add_tools(kXPlanePb.data(), kXPlanePb.size()); *request.mutable_opts() = options.profiler_options(); return request; } TEST(RemoteProfilerSessionManagerTest, Simple) { absl::Duration duration = absl::Milliseconds(30); RemoteProfilerSessionManagerOptions options; *options.mutable_profiler_options() = tsl::ProfilerSession::DefaultOptions(); options.mutable_profiler_options()->set_duration_ms( absl::ToInt64Milliseconds(duration)); std::string service_address; auto server = StartServer(duration, &service_address); options.add_service_addresses(service_address); absl::Time approx_start = absl::Now(); absl::Duration grace = absl::Seconds(kGracePeriodSeconds); absl::Duration max_duration = duration + grace; options.set_max_session_duration_ms(absl::ToInt64Milliseconds(max_duration)); options.set_session_creation_timestamp_ns(absl::ToUnixNanos(approx_start)); ProfileRequest request = PopulateProfileRequest(TmpDir(), "session_id", service_address, options); absl::Status status; auto sessions = RemoteProfilerSessionManager::Create(options, request, status); EXPECT_TRUE(status.ok()); std::vector<Response> responses = sessions->WaitForCompletion(); absl::Duration elapsed = absl::Now() - approx_start; ASSERT_EQ(responses.size(), 1); EXPECT_TRUE(responses.back().status.ok()); EXPECT_TRUE(responses.back().profile_response->empty_trace()); EXPECT_EQ(responses.back().profile_response->tool_data_size(), 0); EXPECT_THAT(elapsed, DurationApproxLess(max_duration)); } TEST(RemoteProfilerSessionManagerTest, ExpiredDeadline) { absl::Duration duration = absl::Milliseconds(30); RemoteProfilerSessionManagerOptions options; *options.mutable_profiler_options() = tsl::ProfilerSession::DefaultOptions(); options.mutable_profiler_options()->set_duration_ms( absl::ToInt64Milliseconds(duration)); std::string service_address; auto server = StartServer(duration, &service_address); options.add_service_addresses(service_address); absl::Duration grace = absl::Seconds(kGracePeriodSeconds); absl::Duration max_duration = duration + grace; options.set_max_session_duration_ms(absl::ToInt64Milliseconds(max_duration)); options.set_session_creation_timestamp_ns(0); absl::Time approx_start = absl::Now(); ProfileRequest request = PopulateProfileRequest(TmpDir(), "session_id", service_address, options); absl::Status status; auto sessions = RemoteProfilerSessionManager::Create(options, request, status); EXPECT_TRUE(status.ok()); std::vector<Response> responses = sessions->WaitForCompletion(); absl::Duration elapsed = absl::Now() - approx_start; EXPECT_THAT(elapsed, DurationNear(absl::Seconds(0))); ASSERT_EQ(responses.size(), 1); EXPECT_TRUE(absl::IsDeadlineExceeded(responses.back().status)); EXPECT_TRUE(responses.back().profile_response->empty_trace()); EXPECT_EQ(responses.back().profile_response->tool_data_size(), 0); } TEST(RemoteProfilerSessionManagerTest, LongSession) { absl::Duration duration = absl::Seconds(3); RemoteProfilerSessionManagerOptions options; *options.mutable_profiler_options() = tsl::ProfilerSession::DefaultOptions(); options.mutable_profiler_options()->set_duration_ms( absl::ToInt64Milliseconds(duration)); std::string service_address; auto server = StartServer(duration, &service_address); options.add_service_addresses(service_address); absl::Time approx_start = absl::Now(); absl::Duration grace = absl::Seconds(kGracePeriodSeconds); absl::Duration max_duration = duration + grace; options.set_max_session_duration_ms(absl::ToInt64Milliseconds(max_duration)); options.set_session_creation_timestamp_ns(absl::ToUnixNanos(approx_start)); ProfileRequest request = PopulateProfileRequest(TmpDir(), "session_id", service_address, options); absl::Status status; auto sessions = RemoteProfilerSessionManager::Create(options, request, status); EXPECT_TRUE(status.ok()); std::vector<Response> responses = sessions->WaitForCompletion(); absl::Duration elapsed = absl::Now() - approx_start; ASSERT_EQ(responses.size(), 1); EXPECT_TRUE(responses.back().status.ok()); EXPECT_TRUE(responses.back().profile_response->empty_trace()); EXPECT_EQ(responses.back().profile_response->tool_data_size(), 0); EXPECT_THAT(elapsed, DurationApproxLess(max_duration)); } } } }
2,303
#ifndef TENSORFLOW_TSL_PROFILER_RPC_CLIENT_PROFILER_CLIENT_H_ #define TENSORFLOW_TSL_PROFILER_RPC_CLIENT_PROFILER_CLIENT_H_ #include <memory> #include <string> #include "absl/strings/string_view.h" #include "absl/time/time.h" #include "tsl/platform/status.h" #include "tsl/profiler/protobuf/profiler_analysis.grpc.pb.h" #include "tsl/profiler/protobuf/profiler_service.grpc.pb.h" namespace tsl { namespace profiler { absl::Status ProfileGrpc(const std::string& service_address, const tensorflow::ProfileRequest& request, tensorflow::ProfileResponse* response); absl::Status NewSessionGrpc(const std::string& service_address, const tensorflow::NewProfileSessionRequest& request, tensorflow::NewProfileSessionResponse* response); absl::Status MonitorGrpc(const std::string& service_address, const tensorflow::MonitorRequest& request, tensorflow::MonitorResponse* response); class RemoteProfilerSession { public: static std::unique_ptr<RemoteProfilerSession> Create( const std::string& service_address, absl::Time deadline, const tensorflow::ProfileRequest& profile_request); RemoteProfilerSession(const RemoteProfilerSession&) = delete; RemoteProfilerSession& operator=(const RemoteProfilerSession&) = delete; ~RemoteProfilerSession(); absl::string_view GetServiceAddress() const { return service_address_; } std::unique_ptr<tensorflow::ProfileResponse> WaitForCompletion( absl::Status& out_status); private: explicit RemoteProfilerSession( const std::string& service_addr, absl::Time deadline, const tensorflow::ProfileRequest& profile_request); void ProfileAsync(); absl::Status status_on_completion_; std::unique_ptr<tensorflow::ProfileResponse> response_; std::string service_address_; std::unique_ptr<tensorflow::grpc::ProfilerService::Stub> stub_; absl::Time deadline_; ::grpc::ClientContext grpc_context_; std::unique_ptr< ::grpc::ClientAsyncResponseReader<tensorflow::ProfileResponse>> rpc_; ::grpc::Status grpc_status_ = ::grpc::Status::OK; ::grpc::CompletionQueue cq_; tensorflow::ProfileRequest profile_request_; }; } } #endif #include "tsl/profiler/rpc/client/profiler_client.h" #include <limits> #include <memory> #include "grpcpp/grpcpp.h" #include "absl/memory/memory.h" #include "absl/time/clock.h" #include "absl/time/time.h" #include "tsl/platform/errors.h" #include "tsl/platform/logging.h" #include "tsl/platform/status.h" #include "tsl/platform/types.h" #include "tsl/protobuf/error_codes.pb.h" namespace tsl { namespace profiler { namespace { using tensorflow::MonitorRequest; using tensorflow::MonitorResponse; using tensorflow::NewProfileSessionRequest; using tensorflow::NewProfileSessionResponse; using tensorflow::ProfileRequest; using tensorflow::ProfileResponse; inline absl::Status FromGrpcStatus(const ::grpc::Status& s) { return s.ok() ? absl::OkStatus() : absl::Status(static_cast<absl::StatusCode>(s.error_code()), s.error_message()); } template <typename T> std::unique_ptr<typename T::Stub> CreateStub( const std::string& service_address) { ::grpc::ChannelArguments channel_args; channel_args.SetMaxReceiveMessageSize(std::numeric_limits<int32>::max()); auto channel = ::grpc::CreateCustomChannel( service_address, ::grpc::InsecureChannelCredentials(), channel_args); if (!channel) { LOG(ERROR) << "Unable to create channel" << service_address; return nullptr; } return T::NewStub(channel); } } absl::Status ProfileGrpc(const std::string& service_address, const ProfileRequest& request, ProfileResponse* response) { ::grpc::ClientContext context; std::unique_ptr<tensorflow::grpc::ProfilerService::Stub> stub = CreateStub<tensorflow::grpc::ProfilerService>(service_address); TF_RETURN_IF_ERROR( FromGrpcStatus(stub->Profile(&context, request, response))); return absl::OkStatus(); } absl::Status NewSessionGrpc(const std::string& service_address, const NewProfileSessionRequest& request, NewProfileSessionResponse* response) { ::grpc::ClientContext context; std::unique_ptr<tensorflow::grpc::ProfileAnalysis::Stub> stub = CreateStub<tensorflow::grpc::ProfileAnalysis>(service_address); TF_RETURN_IF_ERROR( FromGrpcStatus(stub->NewSession(&context, request, response))); return absl::OkStatus(); } absl::Status MonitorGrpc(const std::string& service_address, const MonitorRequest& request, MonitorResponse* response) { ::grpc::ClientContext context; std::unique_ptr<tensorflow::grpc::ProfilerService::Stub> stub = CreateStub<tensorflow::grpc::ProfilerService>(service_address); TF_RETURN_IF_ERROR( FromGrpcStatus(stub->Monitor(&context, request, response))); return absl::OkStatus(); } std::unique_ptr<RemoteProfilerSession> RemoteProfilerSession::Create( const std::string& service_address, absl::Time deadline, const ProfileRequest& profile_request) { auto instance = absl::WrapUnique( new RemoteProfilerSession(service_address, deadline, profile_request)); instance->ProfileAsync(); return instance; } RemoteProfilerSession::RemoteProfilerSession( const std::string& service_address, absl::Time deadline, const ProfileRequest& profile_request) : response_(absl::make_unique<ProfileResponse>()), service_address_(service_address), stub_(CreateStub<tensorflow::grpc::ProfilerService>(service_address_)), deadline_(deadline), profile_request_(profile_request) { response_->set_empty_trace(true); } RemoteProfilerSession::~RemoteProfilerSession() { absl::Status dummy; WaitForCompletion(dummy); grpc_context_.TryCancel(); } void RemoteProfilerSession::ProfileAsync() { LOG(INFO) << "Asynchronous gRPC Profile() to " << service_address_; grpc_context_.set_deadline(absl::ToChronoTime(deadline_)); VLOG(1) << "Deadline set to " << deadline_; rpc_ = stub_->AsyncProfile(&grpc_context_, profile_request_, &cq_); rpc_->Finish(response_.get(), &grpc_status_, static_cast<void*>(&status_on_completion_)); VLOG(2) << "Asynchronous gRPC Profile() issued." << absl::Now(); } std::unique_ptr<ProfileResponse> RemoteProfilerSession::WaitForCompletion( absl::Status& out_status) { if (!response_) { out_status = errors::FailedPrecondition( "WaitForCompletion must only be called once."); return nullptr; } LOG(INFO) << "Waiting for completion."; void* got_tag = nullptr; bool ok = false; bool success = cq_.Next(&got_tag, &ok); if (!success || !ok || got_tag == nullptr) { out_status = errors::Internal("Missing or invalid event from completion queue."); return nullptr; } VLOG(1) << "Writing out status."; DCHECK_EQ(got_tag, &status_on_completion_); status_on_completion_.Update(FromGrpcStatus(grpc_status_)); if (status_on_completion_.code() == error::DEADLINE_EXCEEDED) { LOG(WARNING) << status_on_completion_; } else if (!status_on_completion_.ok()) { LOG(ERROR) << status_on_completion_; } out_status = status_on_completion_; return std::move(response_); } } }
#include "tsl/profiler/rpc/client/profiler_client.h" #include <memory> #include <string> #include "absl/time/clock.h" #include "absl/time/time.h" #include "tsl/platform/errors.h" #include "tsl/platform/status.h" #include "tsl/platform/test.h" #include "tsl/platform/types.h" #include "tsl/profiler/protobuf/profiler_service.pb.h" #include "tsl/profiler/rpc/client/profiler_client_test_util.h" namespace tsl { namespace profiler { namespace { using tensorflow::ProfileRequest; using ::tsl::profiler::test::DurationApproxLess; using ::tsl::profiler::test::DurationNear; using ::tsl::profiler::test::StartServer; TEST(RemoteProfilerSession, Simple) { absl::Duration duration = absl::Milliseconds(10); ProfileRequest request; std::string service_addr; auto server = StartServer(duration, &service_addr, &request); absl::Duration grace = absl::Seconds(1); absl::Duration max_duration = duration + grace; absl::Time approx_start = absl::Now(); absl::Time deadline = approx_start + max_duration; auto remote_session = RemoteProfilerSession::Create(service_addr, deadline, request); absl::Status status; auto response = remote_session->WaitForCompletion(status); absl::Duration elapsed = absl::Now() - approx_start; EXPECT_TRUE(status.ok()); EXPECT_TRUE(response->empty_trace()); EXPECT_EQ(response->tool_data_size(), 0); EXPECT_THAT(elapsed, DurationApproxLess(max_duration)); } TEST(RemoteProfilerSession, WaitNotCalled) { absl::Duration duration = absl::Milliseconds(10); ProfileRequest request; std::string service_addr; auto server = StartServer(duration, &service_addr, &request); absl::Duration grace = absl::Seconds(1); absl::Duration max_duration = duration + grace; absl::Time approx_start = absl::Now(); absl::Time deadline = approx_start + max_duration; auto remote_session = RemoteProfilerSession::Create(service_addr, deadline, request); absl::Duration elapsed = absl::Now() - approx_start; EXPECT_THAT(elapsed, DurationApproxLess(max_duration)); } TEST(RemoteProfilerSession, Timeout) { absl::Duration duration = absl::Milliseconds(10); ProfileRequest request; std::string service_addr; auto server = StartServer(duration, &service_addr, &request); auto remote_session = RemoteProfilerSession::Create(service_addr, absl::Now(), request); absl::Status status; auto response = remote_session->WaitForCompletion(status); EXPECT_TRUE(errors::IsDeadlineExceeded(status)); EXPECT_TRUE(response->empty_trace()); EXPECT_EQ(response->tool_data_size(), 0); } TEST(RemoteProfilerSession, LongDeadline) { absl::Duration duration = absl::Milliseconds(10); ProfileRequest request; std::string service_addr; auto server = StartServer(duration, &service_addr, &request); absl::Time approx_start = absl::Now(); absl::Duration grace = absl::Seconds(1000); absl::Duration max_duration = duration + grace; const absl::Time deadline = approx_start + max_duration; auto remote_session = RemoteProfilerSession::Create(service_addr, deadline, request); absl::Status status; auto response = remote_session->WaitForCompletion(status); absl::Duration elapsed = absl::Now() - approx_start; EXPECT_TRUE(status.ok()); EXPECT_TRUE(response->empty_trace()); EXPECT_EQ(response->tool_data_size(), 0); EXPECT_THAT(elapsed, DurationNear(duration)); } TEST(RemoteProfilerSession, LongDuration) { absl::Duration duration = absl::Seconds(3); ProfileRequest request; std::string service_addr; auto server = StartServer(duration, &service_addr, &request); absl::Time approx_start = absl::Now(); absl::Duration grace = absl::Seconds(1); absl::Duration max_duration = duration + grace; const absl::Time deadline = approx_start + max_duration; auto remote_session = RemoteProfilerSession::Create(service_addr, deadline, request); absl::Status status; auto response = remote_session->WaitForCompletion(status); absl::Duration elapsed = absl::Now() - approx_start; EXPECT_TRUE(status.ok()); EXPECT_TRUE(response->empty_trace()); EXPECT_EQ(response->tool_data_size(), 0); EXPECT_THAT(elapsed, DurationApproxLess(max_duration)); } } } }
2,304
#ifndef TENSORFLOW_TSL_PROFILER_BACKENDS_CPU_TRACEME_RECORDER_H_ #define TENSORFLOW_TSL_PROFILER_BACKENDS_CPU_TRACEME_RECORDER_H_ #include <atomic> #include <cstdint> #include <deque> #include <string> #include <vector> #include "tsl/platform/macros.h" #include "tsl/platform/types.h" namespace tsl { namespace profiler { namespace internal { TF_EXPORT extern std::atomic<int> g_trace_level; } class TraceMeRecorder { public: struct Event { bool IsComplete() const { return start_time > 0 && end_time > 0; } bool IsStart() const { return end_time < 0; } bool IsEnd() const { return start_time < 0; } int64_t ActivityId() const { if (IsStart()) return -end_time; if (IsEnd()) return -start_time; return 1; } std::string name; int64_t start_time; int64_t end_time; }; struct ThreadInfo { uint32 tid; std::string name; }; struct ThreadEvents { ThreadInfo thread; std::deque<Event> events; }; using Events = std::vector<ThreadEvents>; static bool Start(int level); static Events Stop(); static inline bool Active(int level = 1) { return internal::g_trace_level.load(std::memory_order_acquire) >= level; } static constexpr int kTracingDisabled = -1; static void Record(Event&& event); static int64_t NewActivityId(); private: TraceMeRecorder() = delete; ~TraceMeRecorder() = delete; static void Clear(); static TF_MUST_USE_RESULT Events Consume(); }; } } #endif #include "tsl/profiler/backends/cpu/traceme_recorder.h" #include <stddef.h> #include <stdint.h> #include <algorithm> #include <atomic> #include <deque> #include <optional> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "tsl/platform/env.h" #include "tsl/platform/logging.h" #include "tsl/platform/macros.h" #include "tsl/platform/types.h" #include "tsl/profiler/utils/lock_free_queue.h" #include "tsl/profiler/utils/per_thread.h" namespace tsl { namespace profiler { namespace internal { #ifdef _WIN32 #define DECL_DLL_EXPORT __declspec(dllexport) #else #define DECL_DLL_EXPORT #endif DECL_DLL_EXPORT std::atomic<int> g_trace_level( TraceMeRecorder::kTracingDisabled); static_assert(ATOMIC_INT_LOCK_FREE == 2, "Assumed atomic<int> was lock free"); } namespace { class SplitEventTracker { public: void AddStart(TraceMeRecorder::Event&& event) { DCHECK(event.IsStart()); start_events_.emplace(event.ActivityId(), std::move(event)); } void AddEnd(TraceMeRecorder::Event* event) { DCHECK(event->IsEnd()); if (!FindStartAndMerge(event)) { end_events_.push_back(event); } } void HandleCrossThreadEvents() { for (auto* event : end_events_) { FindStartAndMerge(event); } } private: bool FindStartAndMerge(TraceMeRecorder::Event* event) { auto iter = start_events_.find(event->ActivityId()); if (iter == start_events_.end()) return false; auto& start_event = iter->second; event->name = std::move(start_event.name); event->start_time = start_event.start_time; start_events_.erase(iter); return true; } absl::flat_hash_map<int64_t, TraceMeRecorder::Event> start_events_; std::vector<TraceMeRecorder::Event*> end_events_; }; class ThreadLocalRecorder { public: ThreadLocalRecorder() { auto* env = Env::Default(); info_.tid = env->GetCurrentThreadId(); env->GetCurrentThreadName(&info_.name); } const TraceMeRecorder::ThreadInfo& Info() const { return info_; } void Record(TraceMeRecorder::Event&& event) { queue_.Push(std::move(event)); } void Clear() { queue_.Clear(); } TF_MUST_USE_RESULT std::deque<TraceMeRecorder::Event> Consume( SplitEventTracker* split_event_tracker) { std::deque<TraceMeRecorder::Event> events; std::optional<TraceMeRecorder::Event> event; while ((event = queue_.Pop())) { if (event->IsStart()) { split_event_tracker->AddStart(*std::move(event)); continue; } events.push_back(*std::move(event)); if (events.back().IsEnd()) { split_event_tracker->AddEnd(&events.back()); } } return events; } private: TraceMeRecorder::ThreadInfo info_; LockFreeQueue<TraceMeRecorder::Event> queue_; }; } void TraceMeRecorder::Clear() { auto recorders = PerThread<ThreadLocalRecorder>::StartRecording(); for (auto& recorder : recorders) { recorder->Clear(); }; } TraceMeRecorder::Events TraceMeRecorder::Consume() { TraceMeRecorder::Events result; SplitEventTracker split_event_tracker; auto recorders = PerThread<ThreadLocalRecorder>::StopRecording(); for (auto& recorder : recorders) { auto events = recorder->Consume(&split_event_tracker); if (!events.empty()) { result.push_back({recorder->Info(), std::move(events)}); } }; split_event_tracker.HandleCrossThreadEvents(); return result; } bool TraceMeRecorder::Start(int level) { level = std::max(0, level); int expected = kTracingDisabled; bool started = internal::g_trace_level.compare_exchange_strong( expected, level, std::memory_order_acq_rel); if (started) { Clear(); } return started; } void TraceMeRecorder::Record(Event&& event) { PerThread<ThreadLocalRecorder>::Get().Record(std::move(event)); } TraceMeRecorder::Events TraceMeRecorder::Stop() { TraceMeRecorder::Events events; if (internal::g_trace_level.exchange( kTracingDisabled, std::memory_order_acq_rel) != kTracingDisabled) { events = Consume(); } return events; } int64_t TraceMeRecorder::NewActivityId() { static std::atomic<int32> thread_counter(1); const thread_local static int32_t thread_id = thread_counter.fetch_add(1, std::memory_order_relaxed); thread_local static uint32 per_thread_activity_id = 0; return static_cast<int64_t>(thread_id) << 32 | per_thread_activity_id++; } } }
#include "tsl/profiler/backends/cpu/traceme_recorder.h" #include <atomic> #include <set> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/strings/numbers.h" #include "absl/strings/str_cat.h" #include "tsl/platform/env.h" #include "tsl/platform/logging.h" #include "tsl/platform/notification.h" #include "tsl/platform/test.h" #include "tsl/platform/threadpool.h" #include "tsl/platform/types.h" #include "tsl/profiler/utils/math_utils.h" #include "tsl/profiler/utils/time_utils.h" namespace tsl { namespace profiler { namespace { using ::testing::ElementsAre; MATCHER_P(Named, name, "") { return arg.name == name; } TEST(RecorderTest, SingleThreaded) { int64_t start_time = GetCurrentTimeNanos(); int64_t end_time = start_time + UniToNano(1); TraceMeRecorder::Record({"before", start_time, end_time}); TraceMeRecorder::Start(1); TraceMeRecorder::Record({"during1", start_time, end_time}); TraceMeRecorder::Record({"during2", start_time, end_time}); auto results = TraceMeRecorder::Stop(); TraceMeRecorder::Record({"after", start_time, end_time}); ASSERT_EQ(results.size(), 1); EXPECT_THAT(results[0].events, ElementsAre(Named("during1"), Named("during2"))); } TEST(RecorderTest, Multithreaded) { constexpr static int kNumThreads = 4; tsl::Notification start; tsl::Notification stop; thread::ThreadPool pool(tsl::Env::Default(), "testpool", kNumThreads); std::atomic<int> thread_count = {0}; for (int i = 0; i < kNumThreads; i++) { pool.Schedule([&start, &stop, &thread_count] { uint64 j = 0; bool was_active = false; auto record_event = [&j]() { int64_t start_time = GetCurrentTimeNanos(); int64_t end_time = start_time + UniToNano(1); TraceMeRecorder::Record( {absl::StrCat(j++), start_time, end_time}); }; thread_count.fetch_add(1, std::memory_order_relaxed); start.WaitForNotification(); while (!stop.HasBeenNotified()) { if (TraceMeRecorder::Active()) { record_event(); was_active = true; } if (was_active && !TraceMeRecorder::Active()) { record_event(); record_event(); was_active = false; } SpinForNanos(10); } }); } struct ThreadState { bool split_session = false; bool overlapping_sessions = false; std::set<uint64> events; }; absl::flat_hash_map<uint32 , ThreadState> thread_state; auto done = [&thread_state] { for (const auto& id_and_thread : thread_state) { auto& t = id_and_thread.second; if (t.events.size() < 2) return false; } return true; }; while (thread_count.load(std::memory_order_relaxed) < kNumThreads) { LOG(INFO) << "Waiting for all threads to spin up..."; SleepForMillis(1); } start.Notify(); constexpr static int kMaxIters = 100; for (int iters = 0; iters < kMaxIters && !done(); ++iters) { LOG(INFO) << "Looping until convergence, iteration: " << iters; TraceMeRecorder::Start(1); SleepForMillis(100); auto results = TraceMeRecorder::Stop(); for (const auto& thread : results) { if (thread.events.empty()) continue; auto& state = thread_state[thread.thread.tid]; std::set<uint64> session_events; uint64 current = 0; for (const auto& event : thread.events) { uint64 activity_id; ASSERT_TRUE(absl::SimpleAtoi(event.name, &activity_id)); session_events.emplace(activity_id); if (current != 0 && activity_id != current + 1) { state.split_session = true; } current = activity_id; } for (const auto& event : session_events) { auto result = state.events.emplace(event); if (!result.second) { state.overlapping_sessions = true; } } } SleepForMillis(1); } stop.Notify(); for (const auto& id_and_thread : thread_state) { auto& thread = id_and_thread.second; EXPECT_FALSE(thread.split_session) << "Expected contiguous events in a session"; EXPECT_FALSE(thread.overlapping_sessions) << "Expected disjoint sessions"; EXPECT_GT(thread.events.size(), 1) << "Expected gaps in thread events between sessions"; } } } } }
2,305
#ifndef TENSORFLOW_TSL_PROFILER_LIB_PROFILER_LOCK_H_ #define TENSORFLOW_TSL_PROFILER_LIB_PROFILER_LOCK_H_ #include <utility> #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "tsl/platform/statusor.h" namespace tsl { namespace profiler { constexpr absl::string_view kProfilerLockContention = "Another profiling session active."; class ProfilerLock { public: static bool HasActiveSession(); static absl::StatusOr<ProfilerLock> Acquire(); ProfilerLock() = default; ProfilerLock(const ProfilerLock&) = delete; ProfilerLock& operator=(const ProfilerLock&) = delete; ProfilerLock(ProfilerLock&& other) : active_(std::exchange(other.active_, false)) {} ProfilerLock& operator=(ProfilerLock&& other) { active_ = std::exchange(other.active_, false); return *this; } ~ProfilerLock() { ReleaseIfActive(); } void ReleaseIfActive(); bool Active() const { return active_; } private: explicit ProfilerLock(bool active) : active_(active) {} bool active_ = false; }; } } #endif #include "tsl/profiler/lib/profiler_lock.h" #include <atomic> #include "absl/status/statusor.h" #include "xla/tsl/util/env_var.h" #include "tsl/platform/errors.h" #include "tsl/platform/macros.h" namespace tsl { namespace profiler { namespace { std::atomic<int> g_session_active = ATOMIC_VAR_INIT(0); static_assert(ATOMIC_INT_LOCK_FREE == 2, "Assumed atomic<int> was lock free"); } bool ProfilerLock::HasActiveSession() { return g_session_active.load(std::memory_order_relaxed) != 0; } absl::StatusOr<ProfilerLock> ProfilerLock::Acquire() { static bool tf_profiler_disabled = [] { bool disabled = false; ReadBoolFromEnvVar("TF_DISABLE_PROFILING", false, &disabled).IgnoreError(); return disabled; }(); if (TF_PREDICT_FALSE(tf_profiler_disabled)) { return errors::AlreadyExists( "TensorFlow Profiler is permanently disabled by env var " "TF_DISABLE_PROFILING."); } int already_active = g_session_active.exchange(1, std::memory_order_acq_rel); if (already_active) { return errors::AlreadyExists(kProfilerLockContention); } return ProfilerLock(true); } void ProfilerLock::ReleaseIfActive() { if (active_) { g_session_active.store(0, std::memory_order_release); active_ = false; } } } }
#include "tsl/profiler/lib/profiler_lock.h" #include <utility> #include "absl/status/statusor.h" #include "tsl/platform/test.h" namespace tsl { namespace profiler { namespace { TEST(ProfilerLockTest, DefaultConstructorCreatesInactiveInstance) { ProfilerLock profiler_lock; EXPECT_FALSE(profiler_lock.Active()); } TEST(ProfilerLockTest, AcquireAndReleaseExplicitly) { absl::StatusOr<ProfilerLock> profiler_lock = ProfilerLock::Acquire(); ASSERT_TRUE(profiler_lock.ok()); EXPECT_TRUE(profiler_lock->Active()); profiler_lock->ReleaseIfActive(); EXPECT_FALSE(profiler_lock->Active()); } TEST(ProfilerLockTest, AcquireAndReleaseOnDestruction) { absl::StatusOr<ProfilerLock> profiler_lock = ProfilerLock::Acquire(); ASSERT_TRUE(profiler_lock.ok()); EXPECT_TRUE(profiler_lock->Active()); } TEST(ProfilerLockTest, ReacquireWithoutReleaseFails) { absl::StatusOr<ProfilerLock> profiler_lock_1 = ProfilerLock::Acquire(); absl::StatusOr<ProfilerLock> profiler_lock_2 = ProfilerLock::Acquire(); ASSERT_TRUE(profiler_lock_1.ok()); EXPECT_TRUE(profiler_lock_1->Active()); EXPECT_FALSE(profiler_lock_2.ok()); } TEST(ProfilerLockTest, ReacquireAfterReleaseSucceeds) { auto profiler_lock_1 = ProfilerLock::Acquire(); ASSERT_TRUE(profiler_lock_1.ok()); ASSERT_TRUE(profiler_lock_1->Active()); profiler_lock_1->ReleaseIfActive(); ASSERT_FALSE(profiler_lock_1->Active()); auto profiler_lock_2 = ProfilerLock::Acquire(); EXPECT_TRUE(profiler_lock_2.ok()); EXPECT_TRUE(profiler_lock_2->Active()); } TEST(ProfilerLockTest, InactiveAfterMove) { absl::StatusOr<ProfilerLock> profiler_lock_1 = ProfilerLock::Acquire(); ASSERT_TRUE(profiler_lock_1.ok()); ASSERT_TRUE(profiler_lock_1->Active()); ProfilerLock profiler_lock_2 = std::move(*profiler_lock_1); EXPECT_FALSE(profiler_lock_1->Active()); EXPECT_TRUE(profiler_lock_2.Active()); } } } }
2,306
#ifndef TENSORFLOW_TSL_PROFILER_LIB_PROFILER_FACTORY_H_ #define TENSORFLOW_TSL_PROFILER_LIB_PROFILER_FACTORY_H_ #include <functional> #include <memory> #include <vector> #include "tsl/profiler/lib/profiler_interface.h" #include "tsl/profiler/protobuf/profiler_options.pb.h" namespace tsl { namespace profiler { using ProfilerFactory = std::function<std::unique_ptr<ProfilerInterface>( const tensorflow::ProfileOptions&)>; void RegisterProfilerFactory(ProfilerFactory factory); std::vector<std::unique_ptr<ProfilerInterface>> CreateProfilers( const tensorflow::ProfileOptions& options); void ClearRegisteredProfilersForTest(); } } #endif #include "tsl/profiler/lib/profiler_factory.h" #include <memory> #include <utility> #include <vector> #include "tsl/platform/mutex.h" #include "tsl/profiler/lib/profiler_controller.h" #include "tsl/profiler/lib/profiler_interface.h" #include "tsl/profiler/protobuf/profiler_options.pb.h" namespace tsl { namespace profiler { namespace { mutex mu(LINKER_INITIALIZED); std::vector<ProfilerFactory>* GetFactories() { static auto factories = new std::vector<ProfilerFactory>(); return factories; } } void RegisterProfilerFactory(ProfilerFactory factory) { mutex_lock lock(mu); GetFactories()->push_back(std::move(factory)); } std::vector<std::unique_ptr<profiler::ProfilerInterface>> CreateProfilers( const tensorflow::ProfileOptions& options) { std::vector<std::unique_ptr<profiler::ProfilerInterface>> result; mutex_lock lock(mu); for (const auto& factory : *GetFactories()) { auto profiler = factory(options); if (profiler == nullptr) continue; result.emplace_back( std::make_unique<ProfilerController>(std::move(profiler))); } return result; } void ClearRegisteredProfilersForTest() { mutex_lock lock(mu); GetFactories()->clear(); } } }
#include "tsl/profiler/lib/profiler_factory.h" #include <functional> #include <utility> #include "absl/memory/memory.h" #include "absl/status/status.h" #include "tsl/platform/macros.h" #include "tsl/platform/test.h" #include "tsl/profiler/lib/profiler_interface.h" #include "tsl/profiler/protobuf/profiler_options.pb.h" #include "tsl/profiler/protobuf/xplane.pb.h" namespace tsl { namespace profiler { namespace { class TestProfiler : public ProfilerInterface { public: absl::Status Start() override { return absl::OkStatus(); } absl::Status Stop() override { return absl::OkStatus(); } absl::Status CollectData(tensorflow::profiler::XSpace*) override { return absl::OkStatus(); } }; std::unique_ptr<ProfilerInterface> TestFactoryFunction( const tensorflow::ProfileOptions& options) { return absl::make_unique<TestProfiler>(); } TEST(ProfilerFactoryTest, FactoryFunctionPointer) { ClearRegisteredProfilersForTest(); RegisterProfilerFactory(&TestFactoryFunction); auto profilers = CreateProfilers(tensorflow::ProfileOptions()); EXPECT_EQ(profilers.size(), 1); } TEST(ProfilerFactoryTest, FactoryLambda) { ClearRegisteredProfilersForTest(); RegisterProfilerFactory([](const tensorflow::ProfileOptions& options) { return absl::make_unique<TestProfiler>(); }); auto profilers = CreateProfilers(tensorflow::ProfileOptions()); EXPECT_EQ(profilers.size(), 1); } std::unique_ptr<ProfilerInterface> NullFactoryFunction( const tensorflow::ProfileOptions& options) { return nullptr; } TEST(ProfilerFactoryTest, FactoryReturnsNull) { ClearRegisteredProfilersForTest(); RegisterProfilerFactory(&NullFactoryFunction); auto profilers = CreateProfilers(tensorflow::ProfileOptions()); EXPECT_TRUE(profilers.empty()); } class FactoryClass { public: explicit FactoryClass(void* ptr) : ptr_(ptr) {} FactoryClass(const FactoryClass&) = default; FactoryClass(FactoryClass&&) = default; std::unique_ptr<ProfilerInterface> CreateProfiler( const tensorflow::ProfileOptions& options) const { return absl::make_unique<TestProfiler>(); } private: void* ptr_ TF_ATTRIBUTE_UNUSED = nullptr; }; TEST(ProfilerFactoryTest, FactoryClassCapturedByLambda) { ClearRegisteredProfilersForTest(); static int token = 42; FactoryClass factory(&token); RegisterProfilerFactory([factory = std::move(factory)]( const tensorflow::ProfileOptions& options) { return factory.CreateProfiler(options); }); auto profilers = CreateProfilers(tensorflow::ProfileOptions()); EXPECT_EQ(profilers.size(), 1); } } } }
2,307
#ifndef TENSORFLOW_TSL_LIB_MONITORING_SAMPLER_H_ #define TENSORFLOW_TSL_LIB_MONITORING_SAMPLER_H_ #include "tsl/platform/platform.h" #ifdef IS_MOBILE_PLATFORM #include <memory> #include "tsl/lib/monitoring/metric_def.h" #include "tsl/platform/macros.h" #include "tsl/platform/status.h" #include "tsl/platform/types.h" #include "tsl/protobuf/histogram.pb.h" namespace tsl { namespace monitoring { using tensorflow::HistogramProto; class SamplerCell { public: SamplerCell() {} ~SamplerCell() {} void Add(double value) {} HistogramProto value() const { return HistogramProto(); } private: SamplerCell(const SamplerCell&) = delete; void operator=(const SamplerCell&) = delete; }; class Buckets { public: Buckets() = default; ~Buckets() = default; static std::unique_ptr<Buckets> Explicit( std::initializer_list<double> bucket_limits) { return std::unique_ptr<Buckets>(new Buckets()); } static std::unique_ptr<Buckets> Exponential(double scale, double growth_factor, int bucket_count) { return std::unique_ptr<Buckets>(new Buckets()); } const std::vector<double>& explicit_bounds() const { return explicit_bounds_; } private: std::vector<double> explicit_bounds_; Buckets(const Buckets&) = delete; void operator=(const Buckets&) = delete; }; template <int NumLabels> class Sampler { public: ~Sampler() {} template <typename... MetricDefArgs> static Sampler* New(const MetricDef<MetricKind::kCumulative, HistogramProto, NumLabels>& metric_def, std::unique_ptr<Buckets> buckets) { return new Sampler<NumLabels>(std::move(buckets)); } template <typename... Labels> SamplerCell* GetCell(const Labels&... labels) { return &default_sampler_cell_; } Status GetStatus() { return OkStatus(); } private: Sampler(std::unique_ptr<Buckets> buckets) : buckets_(std::move(buckets)) {} SamplerCell default_sampler_cell_; std::unique_ptr<Buckets> buckets_; Sampler(const Sampler&) = delete; void operator=(const Sampler&) = delete; }; } } #else #include <float.h> #include <map> #include <memory> #include <tuple> #include <utility> #include <vector> #include "tsl/lib/histogram/histogram.h" #include "tsl/lib/monitoring/collection_registry.h" #include "tsl/lib/monitoring/metric_def.h" #include "tsl/platform/macros.h" #include "tsl/platform/mutex.h" #include "tsl/platform/status.h" #include "tsl/platform/thread_annotations.h" #include "tsl/protobuf/histogram.pb.h" namespace tsl { namespace monitoring { using tensorflow::HistogramProto; class SamplerCell { public: explicit SamplerCell(const std::vector<double>& bucket_limits) : histogram_(bucket_limits) {} ~SamplerCell() {} void Add(double sample); HistogramProto value() const; private: histogram::ThreadSafeHistogram histogram_; SamplerCell(const SamplerCell&) = delete; void operator=(const SamplerCell&) = delete; }; class Buckets { public: virtual ~Buckets() = default; static std::unique_ptr<Buckets> Exponential(double scale, double growth_factor, int bucket_count); static std::unique_ptr<Buckets> Explicit( std::initializer_list<double> bucket_limits); static std::unique_ptr<Buckets> Explicit(std::vector<double> bucket_limits); virtual const std::vector<double>& explicit_bounds() const = 0; }; template <int NumLabels> class Sampler { public: ~Sampler() { registration_handle_.reset(); } static Sampler* New(const MetricDef<MetricKind::kCumulative, HistogramProto, NumLabels>& metric_def, std::unique_ptr<Buckets> buckets); template <typename... Labels> SamplerCell* GetCell(const Labels&... labels) TF_LOCKS_EXCLUDED(mu_); absl::Status GetStatus() { return status_; } private: friend class SamplerCell; Sampler(const MetricDef<MetricKind::kCumulative, HistogramProto, NumLabels>& metric_def, std::unique_ptr<Buckets> buckets) : metric_def_(metric_def), buckets_(std::move(buckets)), registration_handle_(CollectionRegistry::Default()->Register( &metric_def_, [&](MetricCollectorGetter getter) { auto metric_collector = getter.Get(&metric_def_); tf_shared_lock l(mu_); for (const auto& cell : cells_) { metric_collector.CollectValue(cell.first, cell.second.value()); } })) { if (registration_handle_) { status_ = absl::OkStatus(); } else { status_ = absl::Status(absl::StatusCode::kAlreadyExists, "Another metric with the same name already exists."); } } mutable mutex mu_; absl::Status status_; using LabelArray = std::array<string, NumLabels>; std::map<LabelArray, SamplerCell> cells_ TF_GUARDED_BY(mu_); const MetricDef<MetricKind::kCumulative, HistogramProto, NumLabels> metric_def_; std::unique_ptr<Buckets> buckets_; std::unique_ptr<CollectionRegistry::RegistrationHandle> registration_handle_; Sampler(const Sampler&) = delete; void operator=(const Sampler&) = delete; }; inline void SamplerCell::Add(const double sample) { histogram_.Add(sample); } inline HistogramProto SamplerCell::value() const { HistogramProto pb; histogram_.EncodeToProto(&pb, true ); return pb; } template <int NumLabels> Sampler<NumLabels>* Sampler<NumLabels>::New( const MetricDef<MetricKind::kCumulative, HistogramProto, NumLabels>& metric_def, std::unique_ptr<Buckets> buckets) { return new Sampler<NumLabels>(metric_def, std::move(buckets)); } template <int NumLabels> template <typename... Labels> SamplerCell* Sampler<NumLabels>::GetCell(const Labels&... labels) TF_LOCKS_EXCLUDED(mu_) { static_assert(sizeof...(Labels) == NumLabels, "Mismatch between Sampler<NumLabels> and number of labels " "provided in GetCell(...)."); const LabelArray& label_array = {{labels...}}; { tf_shared_lock l(mu_); const auto found_it = cells_.find(label_array); if (found_it != cells_.end()) { return &(found_it->second); } } mutex_lock l(mu_); return &(cells_ .emplace(std::piecewise_construct, std::forward_as_tuple(label_array), std::forward_as_tuple(buckets_->explicit_bounds())) .first->second); } } } #endif #endif #include "tsl/lib/monitoring/sampler.h" #include "tsl/platform/platform.h" #ifdef IS_MOBILE_PLATFORM #else namespace tsl { namespace monitoring { namespace { class ExplicitBuckets : public Buckets { public: ~ExplicitBuckets() override = default; explicit ExplicitBuckets(std::vector<double> bucket_limits) : bucket_limits_(std::move(bucket_limits)) { CHECK_GT(bucket_limits_.size(), 0); for (size_t i = 1; i < bucket_limits_.size(); i++) { CHECK_GT(bucket_limits_[i], bucket_limits_[i - 1]); } if (bucket_limits_.back() != DBL_MAX) { bucket_limits_.push_back(DBL_MAX); } } const std::vector<double>& explicit_bounds() const override { return bucket_limits_; } private: std::vector<double> bucket_limits_; ExplicitBuckets(const ExplicitBuckets&) = delete; void operator=(const ExplicitBuckets&) = delete; }; class ExponentialBuckets : public Buckets { public: ~ExponentialBuckets() override = default; ExponentialBuckets(double scale, double growth_factor, int bucket_count) : explicit_buckets_( ComputeBucketLimits(scale, growth_factor, bucket_count)) {} const std::vector<double>& explicit_bounds() const override { return explicit_buckets_.explicit_bounds(); } private: static std::vector<double> ComputeBucketLimits(double scale, double growth_factor, int bucket_count) { CHECK_GT(bucket_count, 0); std::vector<double> bucket_limits; double bound = scale; for (int i = 0; i < bucket_count; i++) { bucket_limits.push_back(bound); bound *= growth_factor; } return bucket_limits; } ExplicitBuckets explicit_buckets_; ExponentialBuckets(const ExponentialBuckets&) = delete; void operator=(const ExponentialBuckets&) = delete; }; } std::unique_ptr<Buckets> Buckets::Explicit(std::vector<double> bucket_limits) { return std::unique_ptr<Buckets>( new ExplicitBuckets(std::move(bucket_limits))); } std::unique_ptr<Buckets> Buckets::Explicit( std::initializer_list<double> bucket_limits) { return std::unique_ptr<Buckets>(new ExplicitBuckets(bucket_limits)); } std::unique_ptr<Buckets> Buckets::Exponential(double scale, double growth_factor, int bucket_count) { return std::unique_ptr<Buckets>( new ExponentialBuckets(scale, growth_factor, bucket_count)); } } } #endif
#include "tensorflow/core/lib/monitoring/sampler.h" #include "tensorflow/core/platform/test.h" namespace tensorflow { namespace monitoring { namespace { using histogram::Histogram; void EqHistograms(const Histogram& expected, const HistogramProto& actual_proto) { Histogram actual; ASSERT_TRUE(actual.DecodeFromProto(actual_proto)); EXPECT_EQ(expected.ToString(), actual.ToString()); } auto* sampler_with_labels = Sampler<1>::New({"/tensorflow/test/sampler_with_labels", "Sampler with one label.", "MyLabel"}, Buckets::Explicit({10.0, 20.0})); TEST(LabeledSamplerTest, InitializedEmpty) { Histogram empty; EqHistograms(empty, sampler_with_labels->GetCell("Empty")->value()); } TEST(LabeledSamplerTest, ExplicitBucketBoundaries) { Histogram expected({10.0, 20.0, DBL_MAX}); auto* cell = sampler_with_labels->GetCell("BucketBoundaries"); sampler_with_labels->GetCell("AddedToCheckPreviousCellValidity"); cell->Add(-1.0); expected.Add(-1.0); cell->Add(10.0); expected.Add(10.0); cell->Add(20.0); expected.Add(20.0); cell->Add(31.0); expected.Add(31.0); EqHistograms(expected, cell->value()); } auto* init_sampler_without_labels = Sampler<0>::New({"/tensorflow/test/init_sampler_without_labels", "Sampler without labels initialized as empty."}, Buckets::Explicit(std::vector<double>{1.5, 2.8})); TEST(UnlabeledSamplerTest, InitializedEmpty) { Histogram empty; EqHistograms(empty, init_sampler_without_labels->GetCell()->value()); } auto* sampler_without_labels = Sampler<0>::New({"/tensorflow/test/sampler_without_labels", "Sampler without labels initialized as empty."}, Buckets::Explicit({1.5, 2.8})); TEST(UnlabeledSamplerTest, ExplicitBucketBoundaries) { Histogram expected({1.5, 2.8, DBL_MAX}); auto* cell = sampler_without_labels->GetCell(); cell->Add(-1.0); expected.Add(-1.0); cell->Add(2.0); expected.Add(2.0); cell->Add(31.0); expected.Add(31.0); EqHistograms(expected, cell->value()); } auto* sampler_with_exponential = Sampler<1>::New({"/tensorflow/test/sampler_with_exponential", "Sampler with exponential buckets.", "MyLabel"}, Buckets::Exponential(1, 2, 3)); TEST(ExponentialSamplerTest, ExponentialBucketBoundaries) { Histogram expected({1.0, 2.0, 4.0, DBL_MAX}); auto* cell = sampler_with_exponential->GetCell("BucketBoundaries"); sampler_with_exponential->GetCell("AddedToCheckPreviousCellValidity"); cell->Add(-1.0); expected.Add(-1.0); cell->Add(0.5); expected.Add(0.5); cell->Add(1.001); expected.Add(1.001); cell->Add(3.999); expected.Add(3.999); cell->Add(6.0); expected.Add(6.0); EqHistograms(expected, cell->value()); } TEST(ExplicitSamplerTest, SameName) { auto* same_sampler = Sampler<1>::New({"/tensorflow/test/sampler_with_labels", "Sampler with one label.", "MyLabel"}, Buckets::Explicit({10.0, 20.0})); EXPECT_TRUE(sampler_with_labels->GetStatus().ok()); EXPECT_TRUE(same_sampler->GetStatus().ok()); delete same_sampler; } } } }
2,308
#ifndef TENSORFLOW_TSL_LIB_MONITORING_COLLECTION_REGISTRY_H_ #define TENSORFLOW_TSL_LIB_MONITORING_COLLECTION_REGISTRY_H_ namespace tensorflow { namespace monitoring { namespace test_util { class CollectionRegistryTestAccess; } } } #include "tsl/platform/platform.h" #ifdef IS_MOBILE_PLATFORM #include <functional> #include <map> #include <memory> #include "tsl/lib/monitoring/metric_def.h" #include "tsl/platform/macros.h" namespace tsl { namespace monitoring { template <MetricKind metric_kind, typename Value, int NumLabels> class MetricCollector { public: ~MetricCollector() = default; void CollectValue(const std::array<std::string, NumLabels>& labels, Value value) {} private: friend class MetricCollectorGetter; MetricCollector() {} }; class MetricCollectorGetter { public: template <MetricKind metric_kind, typename Value, int NumLabels> MetricCollector<metric_kind, Value, NumLabels> Get( const MetricDef<metric_kind, Value, NumLabels>* const metric_def) { return MetricCollector<metric_kind, Value, NumLabels>(); } private: MetricCollectorGetter() {} }; class CollectionRegistry { public: ~CollectionRegistry() = default; static CollectionRegistry* Default() { return new CollectionRegistry(); } using CollectionFunction = std::function<void(MetricCollectorGetter getter)>; class RegistrationHandle { public: RegistrationHandle() {} ~RegistrationHandle() {} }; std::unique_ptr<RegistrationHandle> Register( const AbstractMetricDef* metric_def, const CollectionFunction& collection_function) { return std::unique_ptr<RegistrationHandle>(new RegistrationHandle()); } private: CollectionRegistry() {} CollectionRegistry(const CollectionRegistry&) = delete; void operator=(const CollectionRegistry&) = delete; }; } } #else #include <functional> #include <map> #include <memory> #include <utility> #include "tsl/lib/monitoring/collected_metrics.h" #include "tsl/lib/monitoring/metric_def.h" #include "tsl/lib/monitoring/types.h" #include "tsl/platform/env.h" #include "tsl/platform/logging.h" #include "tsl/platform/macros.h" #include "tsl/platform/mutex.h" #include "tsl/platform/stringpiece.h" #include "tsl/platform/thread_annotations.h" #include "tsl/platform/types.h" #include "tsl/protobuf/histogram.pb.h" namespace tsl { namespace monitoring { namespace internal { class Collector; } template <MetricKind metric_kind, typename Value, int NumLabels> class MetricCollector { public: ~MetricCollector() = default; void CollectValue(const std::array<std::string, NumLabels>& labels, Value value); private: friend class internal::Collector; MetricCollector( const MetricDef<metric_kind, Value, NumLabels>* const metric_def, const uint64 registration_time_millis, internal::Collector* const collector, PointSet* const point_set) : metric_def_(metric_def), registration_time_millis_(registration_time_millis), collector_(collector), point_set_(point_set) { point_set_->metric_name = std::string(metric_def->name()); } const MetricDef<metric_kind, Value, NumLabels>* const metric_def_; const uint64 registration_time_millis_; internal::Collector* const collector_; PointSet* const point_set_; }; class MetricCollectorGetter { public: template <MetricKind metric_kind, typename Value, int NumLabels> MetricCollector<metric_kind, Value, NumLabels> Get( const MetricDef<metric_kind, Value, NumLabels>* const metric_def); private: friend class internal::Collector; MetricCollectorGetter(internal::Collector* const collector, const AbstractMetricDef* const allowed_metric_def, const uint64 registration_time_millis) : collector_(collector), allowed_metric_def_(allowed_metric_def), registration_time_millis_(registration_time_millis) {} internal::Collector* const collector_; const AbstractMetricDef* const allowed_metric_def_; const uint64 registration_time_millis_; }; class CollectionRegistry { public: ~CollectionRegistry() = default; static CollectionRegistry* Default(); using CollectionFunction = std::function<void(MetricCollectorGetter getter)>; class RegistrationHandle; std::unique_ptr<RegistrationHandle> Register( const AbstractMetricDef* metric_def, const CollectionFunction& collection_function) TF_LOCKS_EXCLUDED(mu_) TF_MUST_USE_RESULT; struct CollectMetricsOptions { CollectMetricsOptions() {} bool collect_metric_descriptors = true; }; std::unique_ptr<CollectedMetrics> CollectMetrics( const CollectMetricsOptions& options) const; private: friend class ::tensorflow::monitoring::test_util:: CollectionRegistryTestAccess; friend class internal::Collector; explicit CollectionRegistry(Env* env); void Unregister(const AbstractMetricDef* metric_def) TF_LOCKS_EXCLUDED(mu_); Env* const env_; mutable mutex mu_; struct CollectionInfo { const AbstractMetricDef* const metric_def; CollectionFunction collection_function; uint64 registration_time_millis; }; std::map<StringPiece, CollectionInfo> registry_ TF_GUARDED_BY(mu_); CollectionRegistry(const CollectionRegistry&) = delete; void operator=(const CollectionRegistry&) = delete; }; class CollectionRegistry::RegistrationHandle { public: RegistrationHandle(CollectionRegistry* const export_registry, const AbstractMetricDef* const metric_def) : export_registry_(export_registry), metric_def_(metric_def) {} ~RegistrationHandle() { export_registry_->Unregister(metric_def_); } private: CollectionRegistry* const export_registry_; const AbstractMetricDef* const metric_def_; }; namespace internal { template <typename Value> void CollectValue(Value value, Point* point); template <> inline void CollectValue(int64_t value, Point* const point) { point->value_type = ValueType::kInt64; point->int64_value = value; } template <> inline void CollectValue(std::function<int64_t()> value_fn, Point* const point) { point->value_type = ValueType::kInt64; point->int64_value = value_fn(); } template <> inline void CollectValue(std::string value, Point* const point) { point->value_type = ValueType::kString; point->string_value = std::move(value); } template <> inline void CollectValue(std::function<std::string()> value_fn, Point* const point) { point->value_type = ValueType::kString; point->string_value = value_fn(); } template <> inline void CollectValue(bool value, Point* const point) { point->value_type = ValueType::kBool; point->bool_value = value; } template <> inline void CollectValue(std::function<bool()> value_fn, Point* const point) { point->value_type = ValueType::kBool; point->bool_value = value_fn(); } template <> inline void CollectValue(HistogramProto value, Point* const point) { point->value_type = ValueType::kHistogram; point->histogram_value = std::move(value); } template <> inline void CollectValue(Percentiles value, Point* const point) { point->value_type = ValueType::kPercentiles; point->percentiles_value = std::move(value); } template <> inline void CollectValue(double value, Point* const point) { point->value_type = ValueType::kDouble; point->double_value = value; } template <> inline void CollectValue(std::function<double()> value_fn, Point* const point) { point->value_type = ValueType::kDouble; point->double_value = value_fn(); } class Collector { public: explicit Collector(const uint64 collection_time_millis) : collected_metrics_(new CollectedMetrics()), collection_time_millis_(collection_time_millis) {} template <MetricKind metric_kind, typename Value, int NumLabels> MetricCollector<metric_kind, Value, NumLabels> GetMetricCollector( const MetricDef<metric_kind, Value, NumLabels>* const metric_def, const uint64 registration_time_millis, internal::Collector* const collector) TF_LOCKS_EXCLUDED(mu_) { auto* const point_set = [&]() { mutex_lock l(mu_); return collected_metrics_->point_set_map .insert(std::make_pair(std::string(metric_def->name()), std::unique_ptr<PointSet>(new PointSet()))) .first->second.get(); }(); return MetricCollector<metric_kind, Value, NumLabels>( metric_def, registration_time_millis, collector, point_set); } uint64 collection_time_millis() const { return collection_time_millis_; } void CollectMetricDescriptor(const AbstractMetricDef* const metric_def) TF_LOCKS_EXCLUDED(mu_); void CollectMetricValues( const CollectionRegistry::CollectionInfo& collection_info); std::unique_ptr<CollectedMetrics> ConsumeCollectedMetrics() TF_LOCKS_EXCLUDED(mu_); private: mutable mutex mu_; std::unique_ptr<CollectedMetrics> collected_metrics_ TF_GUARDED_BY(mu_); const uint64 collection_time_millis_; Collector(const Collector&) = delete; void operator=(const Collector&) = delete; }; template <MetricKind kind> void WriteTimestamps(const uint64 registration_time_millis, const uint64 collection_time_millis, Point* const point); template <> inline void WriteTimestamps<MetricKind::kGauge>( const uint64 registration_time_millis, const uint64 collection_time_millis, Point* const point) { point->start_timestamp_millis = collection_time_millis; point->end_timestamp_millis = collection_time_millis; } template <> inline void WriteTimestamps<MetricKind::kCumulative>( const uint64 registration_time_millis, const uint64 collection_time_millis, Point* const point) { point->start_timestamp_millis = registration_time_millis; point->end_timestamp_millis = registration_time_millis < collection_time_millis ? collection_time_millis : registration_time_millis; } } template <MetricKind metric_kind, typename Value, int NumLabels> void MetricCollector<metric_kind, Value, NumLabels>::CollectValue( const std::array<std::string, NumLabels>& labels, Value value) { point_set_->points.emplace_back(new Point()); auto* const point = point_set_->points.back().get(); const std::vector<std::string> label_descriptions = metric_def_->label_descriptions(); point->labels.reserve(NumLabels); for (int i = 0; i < NumLabels; ++i) { point->labels.push_back({}); auto* const label = &point->labels.back(); label->name = label_descriptions[i]; label->value = labels[i]; } internal::CollectValue(std::move(value), point); internal::WriteTimestamps<metric_kind>( registration_time_millis_, collector_->collection_time_millis(), point); } template <MetricKind metric_kind, typename Value, int NumLabels> MetricCollector<metric_kind, Value, NumLabels> MetricCollectorGetter::Get( const MetricDef<metric_kind, Value, NumLabels>* const metric_def) { if (allowed_metric_def_ != metric_def) { LOG(FATAL) << "Expected collection for: " << allowed_metric_def_->name() << " but instead got: " << metric_def->name(); } return collector_->GetMetricCollector(metric_def, registration_time_millis_, collector_); } class Exporter { public: virtual ~Exporter() {} virtual void PeriodicallyExportMetrics() = 0; virtual void ExportMetrics() = 0; }; namespace exporter_registration { class ExporterRegistration { public: explicit ExporterRegistration(Exporter* exporter) : exporter_(exporter) { exporter_->PeriodicallyExportMetrics(); } private: Exporter* exporter_; }; } #define REGISTER_TF_METRICS_EXPORTER(exporter) \ REGISTER_TF_METRICS_EXPORTER_UNIQ_HELPER(__COUNTER__, exporter) #define REGISTER_TF_METRICS_EXPORTER_UNIQ_HELPER(ctr, exporter) \ REGISTER_TF_METRICS_EXPORTER_UNIQ(ctr, exporter) #define REGISTER_TF_METRICS_EXPORTER_UNIQ(ctr, exporter) \ static ::tsl::monitoring::exporter_registration::ExporterRegistration \ exporter_registration_##ctr(new exporter()) } } #endif #endif #include "tsl/lib/monitoring/collection_registry.h" #ifndef IS_MOBILE_PLATFORM #include "tsl/platform/logging.h" namespace tsl { namespace monitoring { namespace internal { void Collector::CollectMetricValues( const CollectionRegistry::CollectionInfo& info) { info.collection_function(MetricCollectorGetter( this, info.metric_def, info.registration_time_millis)); } std::unique_ptr<CollectedMetrics> Collector::ConsumeCollectedMetrics() { mutex_lock l(mu_); return std::move(collected_metrics_); } void Collector::CollectMetricDescriptor( const AbstractMetricDef* const metric_def) { auto* const metric_descriptor = [&]() { mutex_lock l(mu_); return collected_metrics_->metric_descriptor_map .insert(std::make_pair( string(metric_def->name()), std::unique_ptr<MetricDescriptor>(new MetricDescriptor()))) .first->second.get(); }(); metric_descriptor->name = string(metric_def->name()); metric_descriptor->description = string(metric_def->description()); for (const StringPiece label_name : metric_def->label_descriptions()) { metric_descriptor->label_names.emplace_back(label_name); } metric_descriptor->metric_kind = metric_def->kind(); metric_descriptor->value_type = metric_def->value_type(); } } CollectionRegistry* CollectionRegistry::Default() { static CollectionRegistry* default_registry = new CollectionRegistry(Env::Default()); return default_registry; } CollectionRegistry::CollectionRegistry(Env* const env) : env_(env) {} std::unique_ptr<CollectionRegistry::RegistrationHandle> CollectionRegistry::Register(const AbstractMetricDef* const metric_def, const CollectionFunction& collection_function) { CHECK(collection_function) << "Requires collection_function to contain an implementation."; mutex_lock l(mu_); const auto found_it = registry_.find(metric_def->name()); if (found_it != registry_.end()) { LOG(WARNING) << "Trying to register 2 metrics with the same name: " << metric_def->name() << ". The old value will be erased in order to register a new one. " "Please check if you link the metric more than once, or " "if the name is already used by other metrics."; registry_.erase(found_it); } registry_.insert( {metric_def->name(), {metric_def, collection_function, env_->NowMicros() / 1000}}); return std::unique_ptr<RegistrationHandle>( new RegistrationHandle(this, metric_def)); } void CollectionRegistry::Unregister(const AbstractMetricDef* const metric_def) { mutex_lock l(mu_); registry_.erase(metric_def->name()); } std::unique_ptr<CollectedMetrics> CollectionRegistry::CollectMetrics( const CollectMetricsOptions& options) const { internal::Collector collector(env_->NowMicros() / 1000); mutex_lock l(mu_); for (const auto& registration : registry_) { if (options.collect_metric_descriptors) { collector.CollectMetricDescriptor(registration.second.metric_def); } collector.CollectMetricValues(registration.second ); } return collector.ConsumeCollectedMetrics(); } } } #endif
#include "tensorflow/core/lib/monitoring/collection_registry.h" #include <memory> #include "tensorflow/core/lib/monitoring/counter.h" #include "tensorflow/core/lib/monitoring/gauge.h" #include "tensorflow/core/lib/monitoring/percentile_sampler.h" #include "tensorflow/core/lib/monitoring/sampler.h" #include "tensorflow/core/lib/strings/strcat.h" #include "tensorflow/core/platform/protobuf.h" #include "tensorflow/core/platform/test.h" namespace tensorflow { namespace monitoring { using histogram::Histogram; namespace test_util { class CollectionRegistryTestAccess { public: static std::unique_ptr<CollectionRegistry> CreateRegistry(Env* const env) { return std::unique_ptr<CollectionRegistry>(new CollectionRegistry(env)); } }; } namespace { void EmptyCollectionFunction(MetricCollectorGetter getter) {} TEST(CollectionRegistryTest, RegistrationUnregistration) { auto* collection_registry = CollectionRegistry::Default(); const MetricDef<MetricKind::kCumulative, int64_t, 0> metric_def0( "/tensorflow/metric0", "An example metric with no labels."); const MetricDef<MetricKind::kGauge, HistogramProto, 1> metric_def1( "/tensorflow/metric1", "An example metric with one label.", "LabelName"); { std::unique_ptr<CollectionRegistry::RegistrationHandle> handle0 = collection_registry->Register(&metric_def0, EmptyCollectionFunction); std::unique_ptr<CollectionRegistry::RegistrationHandle> handle1 = collection_registry->Register(&metric_def1, EmptyCollectionFunction); handle0.reset(); handle0 = collection_registry->Register(&metric_def0, EmptyCollectionFunction); } } TEST(CollectionRegistryDeathTest, DuplicateRegistration) { auto* collection_registry = CollectionRegistry::Default(); const MetricDef<MetricKind::kCumulative, int64_t, 0> metric_def( "/tensorflow/metric", "An example metric with no labels."); auto handle = collection_registry->Register(&metric_def, EmptyCollectionFunction); auto duplicate_handle = collection_registry->Register(&metric_def, EmptyCollectionFunction); EXPECT_NE(duplicate_handle, nullptr); } TEST(CollectMetricsTest, Counter) { auto counter_with_labels = std::unique_ptr<Counter<2>>( Counter<2>::New("/tensorflow/test/counter_with_labels", "Counter with labels.", "MyLabel0", "MyLabel1")); auto counter_without_labels = std::unique_ptr<Counter<0>>(Counter<0>::New( "/tensorflow/test/counter_without_labels", "Counter without labels.")); counter_with_labels->GetCell("Label00", "Label10")->IncrementBy(42); counter_with_labels->GetCell("Label01", "Label11")->IncrementBy(58); counter_without_labels->GetCell()->IncrementBy(7); for (const bool collect_metric_descriptors : {true, false}) { SCOPED_TRACE(strings::StrCat("collect_metric_descriptors: ", collect_metric_descriptors)); auto* collection_registry = CollectionRegistry::Default(); CollectionRegistry::CollectMetricsOptions options; options.collect_metric_descriptors = collect_metric_descriptors; const std::unique_ptr<CollectedMetrics> collected_metrics = collection_registry->CollectMetrics(options); if (collect_metric_descriptors) { ASSERT_GE(collected_metrics->metric_descriptor_map.size(), 2); const MetricDescriptor& ld = *collected_metrics->metric_descriptor_map.at( "/tensorflow/test/counter_with_labels"); EXPECT_EQ("/tensorflow/test/counter_with_labels", ld.name); EXPECT_EQ("Counter with labels.", ld.description); ASSERT_EQ(2, ld.label_names.size()); EXPECT_EQ("MyLabel0", ld.label_names[0]); EXPECT_EQ("MyLabel1", ld.label_names[1]); EXPECT_EQ(MetricKind::kCumulative, ld.metric_kind); EXPECT_EQ(ValueType::kInt64, ld.value_type); const MetricDescriptor& ud = *collected_metrics->metric_descriptor_map.at( "/tensorflow/test/counter_without_labels"); EXPECT_EQ("/tensorflow/test/counter_without_labels", ud.name); EXPECT_EQ("Counter without labels.", ud.description); ASSERT_EQ(0, ud.label_names.size()); EXPECT_EQ(MetricKind::kCumulative, ud.metric_kind); EXPECT_EQ(ValueType::kInt64, ud.value_type); } else { EXPECT_EQ(0, collected_metrics->metric_descriptor_map.size()); } ASSERT_GE(collected_metrics->point_set_map.size(), 2); const PointSet& lps = *collected_metrics->point_set_map.at( "/tensorflow/test/counter_with_labels"); EXPECT_EQ("/tensorflow/test/counter_with_labels", lps.metric_name); ASSERT_EQ(2, lps.points.size()); ASSERT_EQ(2, lps.points[0]->labels.size()); EXPECT_EQ("MyLabel0", lps.points[0]->labels[0].name); EXPECT_EQ("Label00", lps.points[0]->labels[0].value); EXPECT_EQ("MyLabel1", lps.points[0]->labels[1].name); EXPECT_EQ("Label10", lps.points[0]->labels[1].value); EXPECT_EQ(ValueType::kInt64, lps.points[0]->value_type); EXPECT_EQ(42, lps.points[0]->int64_value); EXPECT_LT(0, lps.points[0]->start_timestamp_millis); EXPECT_LT(0, lps.points[0]->end_timestamp_millis); EXPECT_GE(lps.points[0]->end_timestamp_millis, lps.points[0]->start_timestamp_millis); ASSERT_EQ(2, lps.points[1]->labels.size()); EXPECT_EQ("MyLabel0", lps.points[1]->labels[0].name); EXPECT_EQ("Label01", lps.points[1]->labels[0].value); EXPECT_EQ("MyLabel1", lps.points[1]->labels[1].name); EXPECT_EQ("Label11", lps.points[1]->labels[1].value); EXPECT_EQ(ValueType::kInt64, lps.points[1]->value_type); EXPECT_EQ(58, lps.points[1]->int64_value); EXPECT_LT(0, lps.points[1]->start_timestamp_millis); EXPECT_LT(0, lps.points[1]->end_timestamp_millis); EXPECT_GE(lps.points[1]->end_timestamp_millis, lps.points[1]->start_timestamp_millis); const PointSet& ups = *collected_metrics->point_set_map.at( "/tensorflow/test/counter_without_labels"); EXPECT_EQ("/tensorflow/test/counter_without_labels", ups.metric_name); ASSERT_EQ(1, ups.points.size()); EXPECT_EQ(0, ups.points[0]->labels.size()); EXPECT_EQ(ValueType::kInt64, ups.points[0]->value_type); EXPECT_EQ(7, ups.points[0]->int64_value); EXPECT_LT(0, ups.points[0]->start_timestamp_millis); EXPECT_LT(0, ups.points[0]->end_timestamp_millis); EXPECT_GE(ups.points[0]->end_timestamp_millis, ups.points[0]->start_timestamp_millis); } } TEST(CollectMetricsTest, Gauge) { auto string_gauge_with_labels = std::unique_ptr<Gauge<string, 2>>(Gauge<string, 2>::New( "/tensorflow/test/string_gauge_with_labels", "String gauge with labels.", "MyLabel0", "MyLabel1")); auto inteter_gauge_without_labels = std::unique_ptr<Gauge<int64_t, 0>>( Gauge<int64_t, 0>::New("/tensorflow/test/integer_gauge_without_labels", "Integer gauge without labels.")); string_gauge_with_labels->GetCell("Label00", "Label10")->Set("test1"); string_gauge_with_labels->GetCell("Label01", "Label11")->Set("test2"); inteter_gauge_without_labels->GetCell()->Set(7); for (const bool collect_metric_descriptors : {true, false}) { SCOPED_TRACE(strings::StrCat("collect_metric_descriptors: ", collect_metric_descriptors)); auto* collection_registry = CollectionRegistry::Default(); CollectionRegistry::CollectMetricsOptions options; options.collect_metric_descriptors = collect_metric_descriptors; const std::unique_ptr<CollectedMetrics> collected_metrics = collection_registry->CollectMetrics(options); if (collect_metric_descriptors) { ASSERT_GE(collected_metrics->metric_descriptor_map.size(), 2); const MetricDescriptor& ld = *collected_metrics->metric_descriptor_map.at( "/tensorflow/test/string_gauge_with_labels"); EXPECT_EQ("/tensorflow/test/string_gauge_with_labels", ld.name); EXPECT_EQ("String gauge with labels.", ld.description); ASSERT_EQ(2, ld.label_names.size()); EXPECT_EQ("MyLabel0", ld.label_names[0]); EXPECT_EQ("MyLabel1", ld.label_names[1]); EXPECT_EQ(MetricKind::kGauge, ld.metric_kind); EXPECT_EQ(ValueType::kString, ld.value_type); const MetricDescriptor& ud = *collected_metrics->metric_descriptor_map.at( "/tensorflow/test/integer_gauge_without_labels"); EXPECT_EQ("/tensorflow/test/integer_gauge_without_labels", ud.name); EXPECT_EQ("Integer gauge without labels.", ud.description); ASSERT_EQ(0, ud.label_names.size()); EXPECT_EQ(MetricKind::kGauge, ud.metric_kind); EXPECT_EQ(ValueType::kInt64, ud.value_type); } else { EXPECT_EQ(0, collected_metrics->metric_descriptor_map.size()); } ASSERT_GE(collected_metrics->point_set_map.size(), 2); const PointSet& lps = *collected_metrics->point_set_map.at( "/tensorflow/test/string_gauge_with_labels"); EXPECT_EQ("/tensorflow/test/string_gauge_with_labels", lps.metric_name); ASSERT_EQ(2, lps.points.size()); ASSERT_EQ(2, lps.points[0]->labels.size()); EXPECT_EQ("MyLabel0", lps.points[0]->labels[0].name); EXPECT_EQ("Label00", lps.points[0]->labels[0].value); EXPECT_EQ("MyLabel1", lps.points[0]->labels[1].name); EXPECT_EQ("Label10", lps.points[0]->labels[1].value); EXPECT_EQ(ValueType::kString, lps.points[0]->value_type); EXPECT_EQ("test1", lps.points[0]->string_value); EXPECT_LT(0, lps.points[0]->start_timestamp_millis); EXPECT_LT(0, lps.points[0]->end_timestamp_millis); EXPECT_GE(lps.points[0]->end_timestamp_millis, lps.points[0]->start_timestamp_millis); ASSERT_EQ(2, lps.points[1]->labels.size()); EXPECT_EQ("MyLabel0", lps.points[1]->labels[0].name); EXPECT_EQ("Label01", lps.points[1]->labels[0].value); EXPECT_EQ("MyLabel1", lps.points[1]->labels[1].name); EXPECT_EQ("Label11", lps.points[1]->labels[1].value); EXPECT_EQ(ValueType::kString, lps.points[1]->value_type); EXPECT_EQ("test2", lps.points[1]->string_value); EXPECT_LT(0, lps.points[1]->start_timestamp_millis); EXPECT_LT(0, lps.points[1]->end_timestamp_millis); EXPECT_GE(lps.points[1]->end_timestamp_millis, lps.points[1]->start_timestamp_millis); const PointSet& ups = *collected_metrics->point_set_map.at( "/tensorflow/test/integer_gauge_without_labels"); EXPECT_EQ("/tensorflow/test/integer_gauge_without_labels", ups.metric_name); ASSERT_EQ(1, ups.points.size()); EXPECT_EQ(0, ups.points[0]->labels.size()); EXPECT_EQ(ValueType::kInt64, ups.points[0]->value_type); EXPECT_EQ(7, ups.points[0]->int64_value); EXPECT_LT(0, ups.points[0]->start_timestamp_millis); EXPECT_LT(0, ups.points[0]->end_timestamp_millis); EXPECT_GE(ups.points[0]->end_timestamp_millis, ups.points[0]->start_timestamp_millis); } } void EqHistograms(const Histogram& expected, const HistogramProto& actual_proto) { Histogram actual; ASSERT_TRUE(actual.DecodeFromProto(actual_proto)); EXPECT_EQ(expected.ToString(), actual.ToString()); } TEST(CollectMetricsTest, Sampler) { auto sampler_with_labels = std::unique_ptr<Sampler<2>>( Sampler<2>::New({"/tensorflow/test/sampler_with_labels", "Sampler with labels.", "MyLabel0", "MyLabel1"}, Buckets::Explicit({1.0, 2.0}))); auto sampler_without_labels = std::unique_ptr<Sampler<0>>(Sampler<0>::New( {"/tensorflow/test/sampler_without_labels", "Sampler without labels."}, Buckets::Explicit({0.0}))); Histogram with_labels0({1.0, 2.0, DBL_MAX}); sampler_with_labels->GetCell("Label00", "Label10")->Add(0.7); with_labels0.Add(0.7); Histogram with_labels1({1.0, 2.0, DBL_MAX}); sampler_with_labels->GetCell("Label01", "Label11")->Add(1.5); with_labels1.Add(1.5); Histogram without_labels({0.0, DBL_MAX}); sampler_without_labels->GetCell()->Add(0.5); without_labels.Add(0.5); for (const bool collect_metric_descriptors : {true, false}) { SCOPED_TRACE(strings::StrCat("collect_metric_descriptors: ", collect_metric_descriptors)); auto* collection_registry = CollectionRegistry::Default(); CollectionRegistry::CollectMetricsOptions options; options.collect_metric_descriptors = collect_metric_descriptors; const std::unique_ptr<CollectedMetrics> collected_metrics = collection_registry->CollectMetrics(options); if (collect_metric_descriptors) { ASSERT_GE(collected_metrics->metric_descriptor_map.size(), 2); const MetricDescriptor& ld = *collected_metrics->metric_descriptor_map.at( "/tensorflow/test/sampler_with_labels"); EXPECT_EQ("/tensorflow/test/sampler_with_labels", ld.name); EXPECT_EQ("Sampler with labels.", ld.description); ASSERT_EQ(2, ld.label_names.size()); EXPECT_EQ("MyLabel0", ld.label_names[0]); EXPECT_EQ("MyLabel1", ld.label_names[1]); EXPECT_EQ(MetricKind::kCumulative, ld.metric_kind); EXPECT_EQ(ValueType::kHistogram, ld.value_type); const MetricDescriptor& ud = *collected_metrics->metric_descriptor_map.at( "/tensorflow/test/sampler_without_labels"); EXPECT_EQ("/tensorflow/test/sampler_without_labels", ud.name); EXPECT_EQ("Sampler without labels.", ud.description); ASSERT_EQ(0, ud.label_names.size()); EXPECT_EQ(MetricKind::kCumulative, ud.metric_kind); EXPECT_EQ(ValueType::kHistogram, ud.value_type); } else { EXPECT_EQ(0, collected_metrics->metric_descriptor_map.size()); } ASSERT_GE(collected_metrics->point_set_map.size(), 2); const PointSet& lps = *collected_metrics->point_set_map.at( "/tensorflow/test/sampler_with_labels"); EXPECT_EQ("/tensorflow/test/sampler_with_labels", lps.metric_name); ASSERT_EQ(2, lps.points.size()); ASSERT_EQ(2, lps.points[0]->labels.size()); EXPECT_EQ("MyLabel0", lps.points[0]->labels[0].name); EXPECT_EQ("Label00", lps.points[0]->labels[0].value); EXPECT_EQ("MyLabel1", lps.points[0]->labels[1].name); EXPECT_EQ("Label10", lps.points[0]->labels[1].value); EXPECT_EQ(ValueType::kHistogram, lps.points[0]->value_type); EqHistograms(with_labels0, lps.points[0]->histogram_value); EXPECT_LT(0, lps.points[0]->start_timestamp_millis); EXPECT_LT(0, lps.points[0]->end_timestamp_millis); EXPECT_GE(lps.points[0]->end_timestamp_millis, lps.points[0]->start_timestamp_millis); ASSERT_EQ(2, lps.points[1]->labels.size()); EXPECT_EQ("MyLabel0", lps.points[1]->labels[0].name); EXPECT_EQ("Label01", lps.points[1]->labels[0].value); EXPECT_EQ("MyLabel1", lps.points[1]->labels[1].name); EXPECT_EQ("Label11", lps.points[1]->labels[1].value); EXPECT_EQ(ValueType::kHistogram, lps.points[1]->value_type); EqHistograms(with_labels1, lps.points[1]->histogram_value); EXPECT_LT(0, lps.points[1]->start_timestamp_millis); EXPECT_LT(0, lps.points[1]->end_timestamp_millis); EXPECT_GE(lps.points[1]->end_timestamp_millis, lps.points[1]->start_timestamp_millis); const PointSet& ups = *collected_metrics->point_set_map.at( "/tensorflow/test/sampler_without_labels"); EXPECT_EQ("/tensorflow/test/sampler_without_labels", ups.metric_name); ASSERT_EQ(1, ups.points.size()); EXPECT_EQ(0, ups.points[0]->labels.size()); EXPECT_EQ(ValueType::kHistogram, ups.points[0]->value_type); EqHistograms(without_labels, ups.points[0]->histogram_value); EXPECT_LT(0, ups.points[0]->start_timestamp_millis); EXPECT_LT(0, ups.points[0]->end_timestamp_millis); EXPECT_GE(ups.points[0]->end_timestamp_millis, ups.points[0]->start_timestamp_millis); } } TEST(CollectMetricsTest, PercentileSampler) { auto sampler_with_labels = std::unique_ptr<PercentileSampler<2>>(PercentileSampler<2>::New( {"/tensorflow/test/pctsampler_with_labels", "Percentile sampler with labels.", "MyLabel0", "MyLabel1"}, {25.0, 50.0, 75.0}, 1024, UnitOfMeasure::kNumber)); auto sampler_without_labels = std::unique_ptr<PercentileSampler<0>>(PercentileSampler<0>::New( {"/tensorflow/test/pctsampler_without_labels", "Percentile sampler without labels."}, {25.0, 50.0, 75.0}, 1024, UnitOfMeasure::kNumber)); sampler_with_labels->GetCell("Label00", "Label10")->Add(0.7); sampler_with_labels->GetCell("Label01", "Label11")->Add(1.5); sampler_without_labels->GetCell()->Add(0.5); for (const bool collect_metric_descriptors : {true, false}) { SCOPED_TRACE(strings::StrCat("collect_metric_descriptors: ", collect_metric_descriptors)); auto* collection_registry = CollectionRegistry::Default(); CollectionRegistry::CollectMetricsOptions options; options.collect_metric_descriptors = collect_metric_descriptors; const std::unique_ptr<CollectedMetrics> collected_metrics = collection_registry->CollectMetrics(options); if (collect_metric_descriptors) { ASSERT_GE(collected_metrics->metric_descriptor_map.size(), 2); const MetricDescriptor& ld = *collected_metrics->metric_descriptor_map.at( "/tensorflow/test/pctsampler_with_labels"); EXPECT_EQ("/tensorflow/test/pctsampler_with_labels", ld.name); EXPECT_EQ("Percentile sampler with labels.", ld.description); ASSERT_EQ(2, ld.label_names.size()); EXPECT_EQ("MyLabel0", ld.label_names[0]); EXPECT_EQ("MyLabel1", ld.label_names[1]); EXPECT_EQ(MetricKind::kCumulative, ld.metric_kind); EXPECT_EQ(ValueType::kPercentiles, ld.value_type); const MetricDescriptor& ud = *collected_metrics->metric_descriptor_map.at( "/tensorflow/test/pctsampler_without_labels"); EXPECT_EQ("/tensorflow/test/pctsampler_without_labels", ud.name); EXPECT_EQ("Percentile sampler without labels.", ud.description); ASSERT_EQ(0, ud.label_names.size()); EXPECT_EQ(MetricKind::kCumulative, ud.metric_kind); EXPECT_EQ(ValueType::kPercentiles, ud.value_type); } else { EXPECT_EQ(0, collected_metrics->metric_descriptor_map.size()); } ASSERT_GE(collected_metrics->point_set_map.size(), 2); const PointSet& lps = *collected_metrics->point_set_map.at( "/tensorflow/test/pctsampler_with_labels"); EXPECT_EQ("/tensorflow/test/pctsampler_with_labels", lps.metric_name); ASSERT_EQ(2, lps.points.size()); ASSERT_EQ(2, lps.points[0]->labels.size()); EXPECT_EQ("MyLabel0", lps.points[0]->labels[0].name); EXPECT_EQ("Label00", lps.points[0]->labels[0].value); EXPECT_EQ("MyLabel1", lps.points[0]->labels[1].name); EXPECT_EQ("Label10", lps.points[0]->labels[1].value); EXPECT_EQ(ValueType::kPercentiles, lps.points[0]->value_type); EXPECT_LT(0, lps.points[0]->start_timestamp_millis); EXPECT_LT(0, lps.points[0]->end_timestamp_millis); EXPECT_GE(lps.points[0]->end_timestamp_millis, lps.points[0]->start_timestamp_millis); ASSERT_EQ(2, lps.points[1]->labels.size()); EXPECT_EQ("MyLabel0", lps.points[1]->labels[0].name); EXPECT_EQ("Label01", lps.points[1]->labels[0].value); EXPECT_EQ("MyLabel1", lps.points[1]->labels[1].name); EXPECT_EQ("Label11", lps.points[1]->labels[1].value); EXPECT_EQ(ValueType::kPercentiles, lps.points[1]->value_type); EXPECT_LT(0, lps.points[1]->start_timestamp_millis); EXPECT_LT(0, lps.points[1]->end_timestamp_millis); EXPECT_GE(lps.points[1]->end_timestamp_millis, lps.points[1]->start_timestamp_millis); const PointSet& ups = *collected_metrics->point_set_map.at( "/tensorflow/test/pctsampler_without_labels"); EXPECT_EQ("/tensorflow/test/pctsampler_without_labels", ups.metric_name); ASSERT_EQ(1, ups.points.size()); EXPECT_EQ(0, ups.points[0]->labels.size()); EXPECT_EQ(ValueType::kPercentiles, ups.points[0]->value_type); EXPECT_LT(0, ups.points[0]->start_timestamp_millis); EXPECT_LT(0, ups.points[0]->end_timestamp_millis); EXPECT_GE(ups.points[0]->end_timestamp_millis, ups.points[0]->start_timestamp_millis); } } class FakeClockEnv : public EnvWrapper { public: FakeClockEnv() : EnvWrapper(Env::Default()), current_millis_(0) {} void AdvanceByMillis(const uint64 millis) { current_millis_ += millis; } uint64 NowMicros() const override { return current_millis_ * 1000; } private: uint64 current_millis_; }; TEST(CollectionRegistryTest, WriteTimestamps) { FakeClockEnv fake_clock_env; auto collection_registry = test_util::CollectionRegistryTestAccess::CreateRegistry(&fake_clock_env); fake_clock_env.AdvanceByMillis(25); { const MetricDef<MetricKind::kCumulative, int64_t, 0> cumulative_metric( "/tensorflow/cumulative/metric", "An example metric with no labels."); auto handle = collection_registry->Register( &cumulative_metric, [&](MetricCollectorGetter getter) { auto metric_collector = getter.Get(&cumulative_metric); metric_collector.CollectValue({}, 42); }); fake_clock_env.AdvanceByMillis(75); const std::unique_ptr<CollectedMetrics> collected_metrics = collection_registry->CollectMetrics({}); const PointSet& point_set = *collected_metrics->point_set_map.at("/tensorflow/cumulative/metric"); ASSERT_EQ(1, point_set.points.size()); EXPECT_EQ(25, point_set.points[0]->start_timestamp_millis); EXPECT_EQ(100, point_set.points[0]->end_timestamp_millis); } { const MetricDef<MetricKind::kGauge, int64_t, 0> gauge_metric( "/tensorflow/gauge/metric", "An example metric with no labels."); auto handle = collection_registry->Register( &gauge_metric, [&](MetricCollectorGetter getter) { auto metric_collector = getter.Get(&gauge_metric); metric_collector.CollectValue({}, 42); }); fake_clock_env.AdvanceByMillis(75); const std::unique_ptr<CollectedMetrics> collected_metrics = collection_registry->CollectMetrics({}); const PointSet& point_set = *collected_metrics->point_set_map.at("/tensorflow/gauge/metric"); ASSERT_EQ(1, point_set.points.size()); EXPECT_EQ(175, point_set.points[0]->start_timestamp_millis); EXPECT_EQ(175, point_set.points[0]->end_timestamp_millis); } } } } }
2,309
#ifndef TENSORFLOW_TSL_LIB_MONITORING_PERCENTILE_SAMPLER_H_ #define TENSORFLOW_TSL_LIB_MONITORING_PERCENTILE_SAMPLER_H_ #include "tsl/platform/platform.h" #ifdef IS_MOBILE_PLATFORM #include "tsl/platform/status.h" #include "tsl/lib/monitoring/collection_registry.h" #include "tsl/lib/monitoring/metric_def.h" #include "tsl/lib/monitoring/types.h" #include "tsl/platform/macros.h" namespace tsl { namespace monitoring { class PercentileSamplerCell { public: void Add(double sample) {} Percentiles value() const { return Percentiles(); } }; template <int NumLabels> class PercentileSampler { public: static PercentileSampler* New( const MetricDef<MetricKind::kCumulative, Percentiles, NumLabels>& metric_def, std::vector<double> percentiles, size_t max_samples, UnitOfMeasure unit_of_measure); template <typename... Labels> PercentileSamplerCell* GetCell(const Labels&... labels) { return &default_cell_; } Status GetStatus() { return tsl::OkStatus(); } private: PercentileSamplerCell default_cell_; PercentileSampler() = default; PercentileSampler(const PercentileSampler&) = delete; void operator=(const PercentileSampler&) = delete; }; template <int NumLabels> PercentileSampler<NumLabels>* PercentileSampler<NumLabels>::New( const MetricDef<MetricKind::kCumulative, Percentiles, NumLabels>& , std::vector<double> , size_t , UnitOfMeasure ) { return new PercentileSampler<NumLabels>(); } } } #else #include <cmath> #include <map> #include "tsl/platform/status.h" #include "tsl/lib/monitoring/collection_registry.h" #include "tsl/lib/monitoring/metric_def.h" #include "tsl/lib/monitoring/types.h" #include "tsl/platform/macros.h" #include "tsl/platform/mutex.h" #include "tsl/platform/thread_annotations.h" namespace tsl { namespace monitoring { class PercentileSamplerCell { public: PercentileSamplerCell(UnitOfMeasure unit_of_measure, std::vector<double> percentiles, size_t max_samples) : unit_of_measure_(unit_of_measure), percentiles_(std::move(percentiles)), samples_(max_samples), num_samples_(0), next_position_(0), total_samples_(0), accumulator_(0.0) {} void Add(double sample); Percentiles value() const; private: struct Sample { bool operator<(const Sample& rhs) const { return value < rhs.value; } uint64 nstime = 0; double value = NAN; }; std::vector<Sample> GetSamples(size_t* total_samples, long double* accumulator) const; mutable mutex mu_; UnitOfMeasure unit_of_measure_; const std::vector<double> percentiles_; std::vector<Sample> samples_ TF_GUARDED_BY(mu_); size_t num_samples_ TF_GUARDED_BY(mu_); size_t next_position_ TF_GUARDED_BY(mu_); size_t total_samples_ TF_GUARDED_BY(mu_); long double accumulator_ TF_GUARDED_BY(mu_); PercentileSamplerCell(const PercentileSamplerCell&) = delete; void operator=(const PercentileSamplerCell&) = delete; }; template <int NumLabels> class PercentileSampler { public: ~PercentileSampler() { registration_handle_.reset(); } static PercentileSampler* New( const MetricDef<MetricKind::kCumulative, Percentiles, NumLabels>& metric_def, std::vector<double> percentiles, size_t max_samples, UnitOfMeasure unit_of_measure); template <typename... Labels> PercentileSamplerCell* GetCell(const Labels&... labels) TF_LOCKS_EXCLUDED(mu_); absl::Status GetStatus() { return status_; } private: friend class PercentileSamplerCell; PercentileSampler(const MetricDef<MetricKind::kCumulative, Percentiles, NumLabels>& metric_def, std::vector<double> percentiles, size_t max_samples, UnitOfMeasure unit_of_measure) : metric_def_(metric_def), unit_of_measure_(unit_of_measure), percentiles_(std::move(percentiles)), max_samples_(max_samples), registration_handle_(CollectionRegistry::Default()->Register( &metric_def_, [&](MetricCollectorGetter getter) { auto metric_collector = getter.Get(&metric_def_); mutex_lock l(mu_); for (const auto& cell : cells_) { metric_collector.CollectValue(cell.first, cell.second.value()); } })) { if (registration_handle_) { for (size_t i = 0; i < percentiles_.size(); ++i) { if (percentiles_[i] < 0.0 || percentiles_[i] > 100.0) { status_ = absl::Status(absl::StatusCode::kInvalidArgument, "Percentile values must be in [0, 100] range."); break; } if (i + 1 < percentiles_.size() && percentiles_[i] >= percentiles_[i + 1]) { status_ = absl::Status( absl::StatusCode::kInvalidArgument, "Percentile values must be in strictly ascending order."); break; } } } else { status_ = absl::Status(absl::StatusCode::kAlreadyExists, "Another metric with the same name already exists."); } } mutable mutex mu_; absl::Status status_; using LabelArray = std::array<string, NumLabels>; std::map<LabelArray, PercentileSamplerCell> cells_ TF_GUARDED_BY(mu_); const MetricDef<MetricKind::kCumulative, Percentiles, NumLabels> metric_def_; UnitOfMeasure unit_of_measure_ = UnitOfMeasure::kNumber; const std::vector<double> percentiles_; const size_t max_samples_ = 0; std::unique_ptr<CollectionRegistry::RegistrationHandle> registration_handle_; PercentileSampler(const PercentileSampler&) = delete; void operator=(const PercentileSampler&) = delete; }; template <int NumLabels> PercentileSampler<NumLabels>* PercentileSampler<NumLabels>::New( const MetricDef<MetricKind::kCumulative, Percentiles, NumLabels>& metric_def, std::vector<double> percentiles, size_t max_samples, UnitOfMeasure unit_of_measure) { return new PercentileSampler<NumLabels>(metric_def, std::move(percentiles), max_samples, unit_of_measure); } template <int NumLabels> template <typename... Labels> PercentileSamplerCell* PercentileSampler<NumLabels>::GetCell( const Labels&... labels) TF_LOCKS_EXCLUDED(mu_) { static_assert( sizeof...(Labels) == NumLabels, "Mismatch between PercentileSampler<NumLabels> and number of labels " "provided in GetCell(...)."); const LabelArray& label_array = {{labels...}}; mutex_lock l(mu_); const auto found_it = cells_.find(label_array); if (found_it != cells_.end()) { return &(found_it->second); } return &(cells_ .emplace(std::piecewise_construct, std::forward_as_tuple(label_array), std::forward_as_tuple(unit_of_measure_, percentiles_, max_samples_)) .first->second); } } } #endif #endif #include "tsl/lib/monitoring/percentile_sampler.h" #include <algorithm> #include <cmath> #include <vector> #ifdef IS_MOBILE_PLATFORM #else namespace tsl { namespace monitoring { void PercentileSamplerCell::Add(double sample) { uint64 nstime = EnvTime::NowNanos(); mutex_lock l(mu_); samples_[next_position_] = {nstime, sample}; ++next_position_; if (TF_PREDICT_FALSE(next_position_ >= samples_.size())) { next_position_ = 0; } if (TF_PREDICT_FALSE(num_samples_ < samples_.size())) { ++num_samples_; } ++total_samples_; accumulator_ += sample; } Percentiles PercentileSamplerCell::value() const { Percentiles pct_samples; pct_samples.unit_of_measure = unit_of_measure_; size_t total_samples; long double accumulator; std::vector<Sample> samples = GetSamples(&total_samples, &accumulator); if (!samples.empty()) { pct_samples.num_samples = samples.size(); pct_samples.total_samples = total_samples; pct_samples.accumulator = accumulator; pct_samples.start_nstime = samples.front().nstime; pct_samples.end_nstime = samples.back().nstime; long double total = 0.0; for (auto& sample : samples) { total += sample.value; } pct_samples.mean = total / pct_samples.num_samples; long double total_sigma = 0.0; for (auto& sample : samples) { double delta = sample.value - pct_samples.mean; total_sigma += delta * delta; } pct_samples.stddev = std::sqrt(total_sigma / pct_samples.num_samples); std::sort(samples.begin(), samples.end()); pct_samples.min_value = samples.front().value; pct_samples.max_value = samples.back().value; for (auto percentile : percentiles_) { size_t index = std::min<size_t>( static_cast<size_t>(percentile * pct_samples.num_samples / 100.0), pct_samples.num_samples - 1); PercentilePoint pct = {percentile, samples[index].value}; pct_samples.points.push_back(pct); } } return pct_samples; } std::vector<PercentileSamplerCell::Sample> PercentileSamplerCell::GetSamples( size_t* total_samples, long double* accumulator) const { mutex_lock l(mu_); std::vector<Sample> samples; if (num_samples_ == samples_.size()) { samples.insert(samples.end(), samples_.begin() + next_position_, samples_.end()); } samples.insert(samples.end(), samples_.begin(), samples_.begin() + next_position_); *total_samples = total_samples_; *accumulator = accumulator_; return samples; } } } #endif
#include "tensorflow/core/lib/monitoring/percentile_sampler.h" #include "tensorflow/core/platform/test.h" namespace tensorflow { namespace monitoring { namespace { auto* pctsampler_with_labels = PercentileSampler<1>::New( {"/tensorflow/test/percentile_sampler_with_labels", "Percentile sampler with one label.", "MyLabel"}, {25.0, 50.0, 90.0, 99.0}, 1024, UnitOfMeasure::kNumber); auto* pctsampler_without_labels = PercentileSampler<0>::New( {"/tensorflow/test/percentile_sampler_without_labels", "Percentile sampler without labels initialized as empty."}, {25.0, 50.0, 90.0, 99.0}, 1024, UnitOfMeasure::kNumber); TEST(LabeledPercentileSamplerTest, FixedPercentilesValues) { auto* cell = pctsampler_with_labels->GetCell("MyLabel"); cell->Add(10.0); cell->Add(4.0); cell->Add(1.0); cell->Add(0.6); auto value = cell->value(); EXPECT_EQ(value.min_value, 0.6); EXPECT_EQ(value.max_value, 10.0); EXPECT_EQ(value.num_samples, 4); EXPECT_EQ(value.points[0].value, 1.0); EXPECT_EQ(value.points[1].value, 4.0); EXPECT_EQ(value.points[2].value, 10.0); EXPECT_EQ(value.points[3].value, 10.0); } TEST(UnlabeledPercentileSamplerTest, FixedPercentilesValues) { auto* cell = pctsampler_without_labels->GetCell(); cell->Add(10.0); cell->Add(4.0); cell->Add(1.0); cell->Add(0.6); auto value = cell->value(); EXPECT_EQ(value.min_value, 0.6); EXPECT_EQ(value.max_value, 10.0); EXPECT_EQ(value.num_samples, 4); EXPECT_EQ(value.points[0].value, 1.0); EXPECT_EQ(value.points[1].value, 4.0); EXPECT_EQ(value.points[2].value, 10.0); EXPECT_EQ(value.points[3].value, 10.0); } } } }
2,310
#ifndef TENSORFLOW_TSL_LIB_RANDOM_WEIGHTED_PICKER_H_ #define TENSORFLOW_TSL_LIB_RANDOM_WEIGHTED_PICKER_H_ #include <assert.h> #include "tsl/platform/logging.h" #include "tsl/platform/macros.h" #include "tsl/platform/types.h" namespace tsl { namespace random { class SimplePhilox; class WeightedPicker { public: explicit WeightedPicker(int N); ~WeightedPicker(); int Pick(SimplePhilox* rnd) const; int PickAt(int32_t weight_index) const; int32 get_weight(int index) const; void set_weight(int index, int32_t weight); int32 total_weight() const; int num_elements() const; void SetAllWeights(int32_t weight); void SetWeightsFromArray(int N, const int32* weights); void Resize(int N); void Append(int32_t weight); private: int N_; int num_levels_; int32** level_; static int LevelSize(int level) { return 1 << level; } void RebuildTreeWeights(); WeightedPicker(const WeightedPicker&) = delete; void operator=(const WeightedPicker&) = delete; }; inline int32 WeightedPicker::get_weight(int index) const { DCHECK_GE(index, 0); DCHECK_LT(index, N_); return level_[num_levels_ - 1][index]; } inline int32 WeightedPicker::total_weight() const { return level_[0][0]; } inline int WeightedPicker::num_elements() const { return N_; } } } #endif #include "tsl/lib/random/weighted_picker.h" #include <string.h> #include <algorithm> #include "tsl/lib/random/simple_philox.h" namespace tsl { namespace random { WeightedPicker::WeightedPicker(int N) { CHECK_GE(N, 0); N_ = N; num_levels_ = 1; while (LevelSize(num_levels_ - 1) < N) { num_levels_++; } level_ = new int32*[num_levels_]; for (int l = 0; l < num_levels_; l++) { level_[l] = new int32[LevelSize(l)]; } SetAllWeights(1); } WeightedPicker::~WeightedPicker() { for (int l = 0; l < num_levels_; l++) { delete[] level_[l]; } delete[] level_; } static int32 UnbiasedUniform(SimplePhilox* r, int32_t n) { CHECK_LE(0, n); const uint32 range = ~static_cast<uint32>(0); if (n == 0) { return r->Rand32() * n; } else if (0 == (n & (n - 1))) { return r->Rand32() & (n - 1); } else { uint32 rem = (range % n) + 1; uint32 rnd; do { rnd = r->Rand32(); } while (rnd < rem); return rnd % n; } } int WeightedPicker::Pick(SimplePhilox* rnd) const { if (total_weight() == 0) return -1; return PickAt(UnbiasedUniform(rnd, total_weight())); } int WeightedPicker::PickAt(int32_t weight_index) const { if (weight_index < 0 || weight_index >= total_weight()) return -1; int32_t position = weight_index; int index = 0; for (int l = 1; l < num_levels_; l++) { const int32_t left_weight = level_[l][2 * index]; if (position < left_weight) { index = 2 * index; } else { index = 2 * index + 1; position -= left_weight; } } CHECK_GE(index, 0); CHECK_LT(index, N_); CHECK_LE(position, level_[num_levels_ - 1][index]); return index; } void WeightedPicker::set_weight(int index, int32_t weight) { assert(index >= 0); assert(index < N_); const int32_t delta = weight - get_weight(index); for (int l = num_levels_ - 1; l >= 0; l--) { level_[l][index] += delta; index >>= 1; } } void WeightedPicker::SetAllWeights(int32_t weight) { int32* leaves = level_[num_levels_ - 1]; for (int i = 0; i < N_; i++) leaves[i] = weight; for (int i = N_; i < LevelSize(num_levels_ - 1); i++) leaves[i] = 0; RebuildTreeWeights(); } void WeightedPicker::SetWeightsFromArray(int N, const int32* weights) { Resize(N); int32* leaves = level_[num_levels_ - 1]; for (int i = 0; i < N_; i++) leaves[i] = weights[i]; for (int i = N_; i < LevelSize(num_levels_ - 1); i++) leaves[i] = 0; RebuildTreeWeights(); } void WeightedPicker::RebuildTreeWeights() { for (int l = num_levels_ - 2; l >= 0; l--) { int32* level = level_[l]; int32* children = level_[l + 1]; for (int i = 0; i < LevelSize(l); i++) { level[i] = children[2 * i] + children[2 * i + 1]; } } } void WeightedPicker::Append(int32_t weight) { Resize(num_elements() + 1); set_weight(num_elements() - 1, weight); } void WeightedPicker::Resize(int new_size) { CHECK_GE(new_size, 0); if (new_size <= LevelSize(num_levels_ - 1)) { for (int i = new_size; i < N_; i++) { set_weight(i, 0); } N_ = new_size; return; } assert(new_size > N_); WeightedPicker new_picker(new_size); int32* dst = new_picker.level_[new_picker.num_levels_ - 1]; int32* src = this->level_[this->num_levels_ - 1]; memcpy(dst, src, sizeof(dst[0]) * N_); memset(dst + N_, 0, sizeof(dst[0]) * (new_size - N_)); new_picker.RebuildTreeWeights(); std::swap(new_picker.N_, this->N_); std::swap(new_picker.num_levels_, this->num_levels_); std::swap(new_picker.level_, this->level_); assert(this->N_ == new_size); } } }
#include "tsl/lib/random/weighted_picker.h" #include <string.h> #include <vector> #include "tsl/lib/random/simple_philox.h" #include "tsl/platform/logging.h" #include "tsl/platform/macros.h" #include "tsl/platform/test.h" #include "tsl/platform/test_benchmark.h" #include "tsl/platform/types.h" namespace tsl { namespace random { static void TestPicker(SimplePhilox* rnd, int size); static void CheckUniform(SimplePhilox* rnd, WeightedPicker* picker, int trials); static void CheckSkewed(SimplePhilox* rnd, WeightedPicker* picker, int trials); static void TestPickAt(int items, const int32* weights); TEST(WeightedPicker, Simple) { PhiloxRandom philox(testing::RandomSeed(), 17); SimplePhilox rnd(&philox); { VLOG(0) << "======= Zero-length picker"; WeightedPicker picker(0); EXPECT_EQ(picker.Pick(&rnd), -1); } { VLOG(0) << "======= Singleton picker"; WeightedPicker picker(1); EXPECT_EQ(picker.Pick(&rnd), 0); EXPECT_EQ(picker.Pick(&rnd), 0); EXPECT_EQ(picker.Pick(&rnd), 0); } { VLOG(0) << "======= Grown picker"; WeightedPicker picker(0); for (int i = 0; i < 10; i++) { picker.Append(1); } CheckUniform(&rnd, &picker, 100000); } { VLOG(0) << "======= Grown picker with zero weights"; WeightedPicker picker(1); picker.Resize(10); EXPECT_EQ(picker.Pick(&rnd), 0); EXPECT_EQ(picker.Pick(&rnd), 0); EXPECT_EQ(picker.Pick(&rnd), 0); } { VLOG(0) << "======= Shrink picker and check weights"; WeightedPicker picker(1); picker.Resize(10); EXPECT_EQ(picker.Pick(&rnd), 0); EXPECT_EQ(picker.Pick(&rnd), 0); EXPECT_EQ(picker.Pick(&rnd), 0); for (int i = 0; i < 10; i++) { picker.set_weight(i, i); } EXPECT_EQ(picker.total_weight(), 45); picker.Resize(5); EXPECT_EQ(picker.total_weight(), 10); picker.Resize(2); EXPECT_EQ(picker.total_weight(), 1); picker.Resize(1); EXPECT_EQ(picker.total_weight(), 0); } } TEST(WeightedPicker, BigWeights) { PhiloxRandom philox(testing::RandomSeed() + 1, 17); SimplePhilox rnd(&philox); VLOG(0) << "======= Check uniform with big weights"; WeightedPicker picker(2); picker.SetAllWeights(2147483646L / 3); CheckUniform(&rnd, &picker, 100000); } TEST(WeightedPicker, Deterministic) { VLOG(0) << "======= Testing deterministic pick"; static const int32 weights[] = {1, 0, 200, 5, 42}; TestPickAt(TF_ARRAYSIZE(weights), weights); } TEST(WeightedPicker, Randomized) { PhiloxRandom philox(testing::RandomSeed() + 10, 17); SimplePhilox rnd(&philox); TestPicker(&rnd, 1); TestPicker(&rnd, 2); TestPicker(&rnd, 3); TestPicker(&rnd, 4); TestPicker(&rnd, 7); TestPicker(&rnd, 8); TestPicker(&rnd, 9); TestPicker(&rnd, 10); TestPicker(&rnd, 100); } static void TestPicker(SimplePhilox* rnd, int size) { VLOG(0) << "======= Testing size " << size; { WeightedPicker picker(size); picker.SetAllWeights(0); for (int i = 0; i < 100; i++) EXPECT_EQ(picker.Pick(rnd), -1); } std::vector<int32> weights(size); for (int elem = 0; elem < size; elem++) { weights[elem] = 0; } for (int elem = 0; elem < size; elem++) { WeightedPicker picker(size); picker.SetAllWeights(0); picker.set_weight(elem, elem + 1); for (int i = 0; i < 100; i++) EXPECT_EQ(picker.Pick(rnd), elem); weights[elem] = 10; picker.SetWeightsFromArray(size, &weights[0]); for (int i = 0; i < 100; i++) EXPECT_EQ(picker.Pick(rnd), elem); weights[elem] = 0; } { WeightedPicker picker(size); CheckUniform(rnd, &picker, 100000); } if (size / 3 > 0) { WeightedPicker picker(size / 3); while (picker.num_elements() != size) { picker.Append(1); } CheckUniform(rnd, &picker, 100000); } if (size <= 10) { WeightedPicker picker(size); int32_t weight = 1; for (int elem = 0; elem < size; elem++) { picker.set_weight(elem, weight); weights[elem] = weight; weight *= 2; } CheckSkewed(rnd, &picker, 1000000); WeightedPicker array_picker(0); array_picker.SetWeightsFromArray(size, &weights[0]); CheckSkewed(rnd, &array_picker, 1000000); } } static void CheckUniform(SimplePhilox* rnd, WeightedPicker* picker, int trials) { const int size = picker->num_elements(); int* count = new int[size]; memset(count, 0, sizeof(count[0]) * size); for (int i = 0; i < size * trials; i++) { const int elem = picker->Pick(rnd); EXPECT_GE(elem, 0); EXPECT_LT(elem, size); count[elem]++; } const int expected_min = int(0.9 * trials); const int expected_max = int(1.1 * trials); for (int i = 0; i < size; i++) { EXPECT_GE(count[i], expected_min); EXPECT_LE(count[i], expected_max); } delete[] count; } static void CheckSkewed(SimplePhilox* rnd, WeightedPicker* picker, int trials) { const int size = picker->num_elements(); int* count = new int[size]; memset(count, 0, sizeof(count[0]) * size); for (int i = 0; i < size * trials; i++) { const int elem = picker->Pick(rnd); EXPECT_GE(elem, 0); EXPECT_LT(elem, size); count[elem]++; } for (int i = 0; i < size - 1; i++) { LOG(INFO) << i << ": " << count[i]; const float ratio = float(count[i + 1]) / float(count[i]); EXPECT_GE(ratio, 1.6f); EXPECT_LE(ratio, 2.4f); } delete[] count; } static void TestPickAt(int items, const int32* weights) { WeightedPicker picker(items); picker.SetWeightsFromArray(items, weights); int weight_index = 0; for (int i = 0; i < items; ++i) { for (int j = 0; j < weights[i]; ++j) { int pick = picker.PickAt(weight_index); EXPECT_EQ(pick, i); ++weight_index; } } EXPECT_EQ(weight_index, picker.total_weight()); } static void BM_Create(::testing::benchmark::State& state) { int arg = state.range(0); for (auto s : state) { WeightedPicker p(arg); } } BENCHMARK(BM_Create)->Range(1, 1024); static void BM_CreateAndSetWeights(::testing::benchmark::State& state) { int arg = state.range(0); std::vector<int32> weights(arg); for (int i = 0; i < arg; i++) { weights[i] = i * 10; } for (auto s : state) { WeightedPicker p(arg); p.SetWeightsFromArray(arg, &weights[0]); } } BENCHMARK(BM_CreateAndSetWeights)->Range(1, 1024); static void BM_Pick(::testing::benchmark::State& state) { int arg = state.range(0); PhiloxRandom philox(301, 17); SimplePhilox rnd(&philox); WeightedPicker p(arg); int result = 0; for (auto s : state) { result += p.Pick(&rnd); } VLOG(4) << result; } BENCHMARK(BM_Pick)->Range(1, 1024); } }
2,311
#ifndef TENSORFLOW_TSL_LIB_RANDOM_RANDOM_DISTRIBUTIONS_H_ #define TENSORFLOW_TSL_LIB_RANDOM_RANDOM_DISTRIBUTIONS_H_ #include <algorithm> #include <cmath> #include <type_traits> #include "unsupported/Eigen/CXX11/Tensor" #include "tsl/lib/random/philox_random.h" #include "tsl/lib/random/random_distributions_utils.h" #include "tsl/platform/types.h" namespace tsl { namespace random { PHILOX_DEVICE_INLINE Eigen::half Uint16ToHalf(uint16 x); PHILOX_DEVICE_INLINE bfloat16 Uint16ToGfloat16(uint16 x); template <typename Int> PHILOX_DEVICE_INLINE Int SignedAdd(Int a, typename std::make_unsigned<Int>::type b) { auto b_div_2 = b >> 1; return a + static_cast<Int>(b_div_2) + static_cast<Int>(b - b_div_2); } template <class Generator, typename RealType> class UniformDistribution; template <class Generator> class UniformDistribution<Generator, Eigen::half> { public: static constexpr int kResultElementCount = Generator::kResultElementCount; static constexpr int kElementCost = 3; static constexpr bool kVariableSamplesPerOutput = false; typedef Array<Eigen::half, kResultElementCount> ResultType; typedef Eigen::half ResultElementType; PHILOX_DEVICE_INLINE ResultType operator()(Generator* gen) { typename Generator::ResultType sample = (*gen)(); ResultType result; for (int i = 0; i < kResultElementCount; ++i) { result[i] = Uint16ToHalf(sample[i]); } return result; } }; template <class Generator> class UniformDistribution<Generator, bfloat16> { public: static constexpr int kResultElementCount = Generator::kResultElementCount; static constexpr int kElementCost = 3; static constexpr bool kVariableSamplesPerOutput = false; typedef Array<bfloat16, kResultElementCount> ResultType; typedef bfloat16 ResultElementType; PHILOX_DEVICE_INLINE ResultType operator()(Generator* gen) { typename Generator::ResultType sample = (*gen)(); ResultType result; for (int i = 0; i < kResultElementCount; ++i) { result[i] = Uint16ToGfloat16(sample[i]); } return result; } }; template <class Generator> class UniformDistribution<Generator, float> { public: static constexpr int kResultElementCount = Generator::kResultElementCount; static constexpr int kElementCost = 3; static constexpr bool kVariableSamplesPerOutput = false; typedef Array<float, kResultElementCount> ResultType; typedef float ResultElementType; PHILOX_DEVICE_INLINE ResultType operator()(Generator* gen) { typename Generator::ResultType sample = (*gen)(); ResultType result; for (int i = 0; i < kResultElementCount; ++i) { result[i] = Uint32ToFloat(sample[i]); } return result; } }; template <class Generator> class UniformDistribution<Generator, double> { public: static constexpr int kResultElementCount = Generator::kResultElementCount / 2; static constexpr int kElementCost = 3; static constexpr bool kVariableSamplesPerOutput = false; typedef Array<double, kResultElementCount> ResultType; typedef double ResultElementType; PHILOX_DEVICE_INLINE ResultType operator()(Generator* gen) { typename Generator::ResultType sample = (*gen)(); ResultType result; for (int i = 0; i < kResultElementCount; ++i) { result[i] = Uint64ToDouble(sample[2 * i], sample[2 * i + 1]); } return result; } }; template <class Generator> class UniformDistribution<Generator, int32> { public: static constexpr int kResultElementCount = Generator::kResultElementCount; static constexpr int kElementCost = 3; static constexpr bool kVariableSamplesPerOutput = false; typedef Array<int32, kResultElementCount> ResultType; typedef int32 ResultElementType; UniformDistribution(int32_t lo, int32_t hi) : lo_(lo), range_(static_cast<uint32>(hi) - static_cast<uint32>(lo)) {} PHILOX_DEVICE_INLINE ResultType operator()(Generator* gen) { typename Generator::ResultType sample = (*gen)(); ResultType result; for (int i = 0; i < kResultElementCount; ++i) { result[i] = SignedAdd(lo_, sample[i] % range_); } return result; } private: int32 lo_; uint32 range_; }; template <class Generator> class UniformDistribution<Generator, int64_t> { public: static constexpr int kResultElementCount = Generator::kResultElementCount / 2; static constexpr int kElementCost = 3; static constexpr bool kVariableSamplesPerOutput = false; typedef Array<int64_t, kResultElementCount> ResultType; typedef int64_t ResultElementType; UniformDistribution(int64_t lo, int64_t hi) : lo_(lo), range_(static_cast<uint64>(hi) - static_cast<uint64>(lo)) {} PHILOX_DEVICE_INLINE ResultType operator()(Generator* gen) { typename Generator::ResultType sample = (*gen)(); ResultType result; for (int i = 0; i < kResultElementCount; ++i) { auto bits = sample[2 * i] | static_cast<uint64>(sample[2 * i + 1]) << 32; result[i] = SignedAdd(lo_, bits % range_); } return result; } private: int64_t lo_; uint64 range_; }; template <typename Generator, typename IntType> class UniformFullIntDistribution; template <typename Generator, typename IntType> class UniformFullIntDistribution32 { public: static constexpr int kResultElementCount = Generator::kResultElementCount; static constexpr int kElementCost = 3; static constexpr bool kVariableSamplesPerOutput = false; typedef Array<IntType, kResultElementCount> ResultType; typedef IntType ResultElementType; PHILOX_DEVICE_INLINE ResultType operator()(Generator* gen) { typename Generator::ResultType sample = (*gen)(); ResultType result; for (int i = 0; i < kResultElementCount; ++i) { result[i] = sample[i]; } return result; } }; template <typename Generator, typename IntType> class UniformFullIntDistribution64 { public: static constexpr int kResultElementCount = Generator::kResultElementCount / 2; static constexpr int kElementCost = 3; static constexpr bool kVariableSamplesPerOutput = false; typedef Array<IntType, kResultElementCount> ResultType; typedef IntType ResultElementType; PHILOX_DEVICE_INLINE ResultType operator()(Generator* gen) { typename Generator::ResultType sample = (*gen)(); ResultType result; for (int i = 0; i < kResultElementCount; ++i) { result[i] = sample[2 * i] | static_cast<uint64>(sample[2 * i + 1]) << 32; } return result; } }; template <typename Generator> class UniformFullIntDistribution<Generator, int32> : public UniformFullIntDistribution32<Generator, int32> {}; template <typename Generator> class UniformFullIntDistribution<Generator, uint32> : public UniformFullIntDistribution32<Generator, uint32> {}; template <typename Generator> class UniformFullIntDistribution<Generator, int64_t> : public UniformFullIntDistribution64<Generator, int64_t> {}; template <typename Generator> class UniformFullIntDistribution<Generator, uint64> : public UniformFullIntDistribution64<Generator, uint64> {}; template <class Generator> class SingleSampleAdapter { public: static constexpr int kResultElementCount = 1; static constexpr int kNativeElementCount = Generator::kResultElementCount; typedef typename Generator::ResultElementType ResultType; typedef typename Generator::ResultElementType ResultElementType; PHILOX_DEVICE_INLINE explicit SingleSampleAdapter(Generator* gen) : generator_(gen), used_result_index_(Generator::kResultElementCount) {} PHILOX_DEVICE_INLINE ResultType operator()() { if (used_result_index_ == Generator::kResultElementCount) { unused_results_ = (*generator_)(); used_result_index_ = 0; } return unused_results_[used_result_index_++]; } PHILOX_DEVICE_INLINE void Skip(uint64 num_skips) { if (!num_skips) { return; } int num_unused_results = kNativeElementCount - used_result_index_; if (num_skips <= num_unused_results) { used_result_index_ += num_skips; return; } num_skips -= num_unused_results; used_result_index_ = kNativeElementCount; SkipFromGenerator(num_skips / kNativeElementCount); num_skips = num_skips % kNativeElementCount; if (num_skips) { unused_results_ = (*generator_)(); used_result_index_ = num_skips; } } private: PHILOX_DEVICE_INLINE void SkipFromGenerator(uint64 num_skips) { while (num_skips--) { (*generator_)(); } } Generator* generator_; typename Generator::ResultType unused_results_; int used_result_index_; }; template <class Generator, typename RealType> class NormalDistribution; PHILOX_DEVICE_INLINE void BoxMullerDouble(uint32 x0, uint32 x1, uint32 x2, uint32 x3, double* d0, double* d1); template <class Generator> class NormalDistribution<Generator, Eigen::half> { public: static constexpr int kResultElementCount = Generator::kResultElementCount; static constexpr int kElementCost = 70; static constexpr bool kVariableSamplesPerOutput = false; typedef Array<Eigen::half, kResultElementCount> ResultType; typedef Eigen::half ResultElementType; PHILOX_DEVICE_INLINE ResultType operator()(Generator* gen) { typename Generator::ResultType sample = (*gen)(); ResultType result; for (int i = 0; i < kResultElementCount; i += 2) { float f[2]; BoxMullerFloat(sample[i], sample[i + 1], &f[0], &f[1]); result[i] = Eigen::half(f[0]); result[i + 1] = Eigen::half(f[1]); } return result; } }; template <class Generator> class NormalDistribution<Generator, bfloat16> { public: static constexpr int kResultElementCount = Generator::kResultElementCount; static constexpr int kElementCost = 70; static constexpr bool kVariableSamplesPerOutput = false; typedef Array<bfloat16, kResultElementCount> ResultType; typedef bfloat16 ResultElementType; PHILOX_DEVICE_INLINE ResultType operator()(Generator* gen) { typename Generator::ResultType sample = (*gen)(); ResultType result; static_assert(kResultElementCount % 2 == 0, "kResultElementCount should be an even number"); for (int i = 0; i < kResultElementCount; i += 2) { float f[2]; BoxMullerFloat(sample[i], sample[i + 1], &f[0], &f[1]); result[i] = bfloat16(f[0]); result[i + 1] = bfloat16(f[1]); } return result; } }; template <class Generator> class NormalDistribution<Generator, float> { public: static constexpr int kResultElementCount = Generator::kResultElementCount; static constexpr int kElementCost = 70; static constexpr bool kVariableSamplesPerOutput = false; typedef Array<float, kResultElementCount> ResultType; typedef float ResultElementType; PHILOX_DEVICE_INLINE ResultType operator()(Generator* gen) { typename Generator::ResultType sample = (*gen)(); ResultType result; for (int i = 0; i < kResultElementCount; i += 2) { BoxMullerFloat(sample[i], sample[i + 1], &result[i], &result[i + 1]); } return result; } }; template <class Generator> class NormalDistribution<Generator, double> { public: static constexpr int kResultElementCount = Generator::kResultElementCount / 2; static constexpr int kElementCost = 70; static constexpr bool kVariableSamplesPerOutput = false; typedef Array<double, kResultElementCount> ResultType; typedef double ResultElementType; PHILOX_DEVICE_INLINE ResultType operator()(Generator* gen) { typename Generator::ResultType sample = (*gen)(); ResultType result; for (int i = 0; i < kResultElementCount; i += 2) { const int i2 = 2 * i; BoxMullerDouble(sample[i2], sample[i2 + 1], sample[i2 + 2], sample[i2 + 3], &result[i], &result[i + 1]); } return result; } }; template <class SingleSampleGenerator, typename RealType> class TruncatedNormalDistribution; template <class SingleSampleGenerator> class TruncatedNormalDistribution<SingleSampleGenerator, Eigen::half> { public: static constexpr int kResultElementCount = SingleSampleGenerator::kNativeElementCount; static constexpr int kElementCost = 90; static constexpr bool kVariableSamplesPerOutput = true; const float kTruncateValue = 2.0f; typedef Array<Eigen::half, kResultElementCount> ResultType; typedef Eigen::half ResultElementType; PHILOX_DEVICE_INLINE ResultType operator()(SingleSampleGenerator* gen) { ResultType results; int index = 0; while (true) { const uint32 x0 = (*gen)(); const uint32 x1 = (*gen)(); float f[2]; BoxMullerFloat(x0, x1, &f[0], &f[1]); if (Eigen::numext::abs(f[0]) < kTruncateValue) { results[index++] = Eigen::half(f[0]); if (index >= kResultElementCount) { return results; } } if (Eigen::numext::abs(f[1]) < kTruncateValue) { results[index++] = Eigen::half(f[1]); if (index >= kResultElementCount) { return results; } } } } }; template <class SingleSampleGenerator> class TruncatedNormalDistribution<SingleSampleGenerator, bfloat16> { public: static constexpr int kResultElementCount = SingleSampleGenerator::kNativeElementCount; static constexpr int kElementCost = 90; static constexpr bool kVariableSamplesPerOutput = true; const float kTruncateValue = 2.0f; typedef Array<bfloat16, kResultElementCount> ResultType; typedef bfloat16 ResultElementType; PHILOX_DEVICE_INLINE ResultType operator()(SingleSampleGenerator* gen) { ResultType results; int index = 0; while (true) { const uint32 x0 = (*gen)(); const uint32 x1 = (*gen)(); float f[2]; BoxMullerFloat(x0, x1, &f[0], &f[1]); if (Eigen::numext::abs(f[0]) < kTruncateValue) { results[index++] = bfloat16(f[0]); if (index >= kResultElementCount) { return results; } } if (Eigen::numext::abs(f[1]) < kTruncateValue) { results[index++] = bfloat16(f[1]); if (index >= kResultElementCount) { return results; } } } } }; template <class SingleSampleGenerator> class TruncatedNormalDistribution<SingleSampleGenerator, float> { public: static constexpr int kResultElementCount = SingleSampleGenerator::kNativeElementCount; static constexpr int kElementCost = 90; static constexpr bool kVariableSamplesPerOutput = true; const float kTruncateValue = 2.0f; typedef Array<float, kResultElementCount> ResultType; typedef float ResultElementType; PHILOX_DEVICE_INLINE ResultType operator()(SingleSampleGenerator* gen) { ResultType results; int index = 0; while (true) { const uint32 x0 = (*gen)(); const uint32 x1 = (*gen)(); float f[2]; BoxMullerFloat(x0, x1, &f[0], &f[1]); if (Eigen::numext::abs(f[0]) < kTruncateValue) { results[index++] = f[0]; if (index >= kResultElementCount) { return results; } } if (Eigen::numext::abs(f[1]) < kTruncateValue) { results[index++] = f[1]; if (index >= kResultElementCount) { return results; } } } } }; template <class SingleSampleGenerator> class TruncatedNormalDistribution<SingleSampleGenerator, double> { public: static constexpr int kResultElementCount = (SingleSampleGenerator::kNativeElementCount > 1) ? SingleSampleGenerator::kNativeElementCount / 2 : 1; static constexpr int kElementCost = 90; static constexpr bool kVariableSamplesPerOutput = true; typedef Array<double, kResultElementCount> ResultType; typedef double ResultElementType; const double kTruncateValue = 2.0; PHILOX_DEVICE_INLINE ResultType operator()(SingleSampleGenerator* gen) { ResultType results; int index = 0; while (true) { const uint32 x0 = (*gen)(); const uint32 x1 = (*gen)(); const uint32 x2 = (*gen)(); const uint32 x3 = (*gen)(); double d[2]; BoxMullerDouble(x0, x1, x2, x3, &d[0], &d[1]); if (Eigen::numext::abs(d[0]) < kTruncateValue) { results[index++] = d[0]; if (index >= kResultElementCount) { return results; } } if (Eigen::numext::abs(d[1]) < kTruncateValue) { results[index++] = d[1]; if (index >= kResultElementCount) { return results; } } } } }; PHILOX_DEVICE_INLINE void BoxMullerDouble(uint32 x0, uint32 x1, uint32 x2, uint32 x3, double* d0, double* d1) { const double epsilon = 1.0e-7; double u1 = Uint64ToDouble(x0, x1); if (u1 < epsilon) { u1 = epsilon; } const double v1 = 2 * M_PI * Uint64ToDouble(x2, x3); const double u2 = Eigen::numext::sqrt(-2.0 * Eigen::numext::log(u1)); #if !defined(__linux__) *d0 = Eigen::numext::sin(v1); *d1 = Eigen::numext::cos(v1); #else sincos(v1, d0, d1); #endif *d0 *= u2; *d1 *= u2; } PHILOX_DEVICE_INLINE Eigen::half Uint16ToHalf(uint16 x) { const uint16 man = x & 0x3ffu; const uint16 exp = static_cast<uint16>(15); const uint16 val = (exp << 10) | man; Eigen::half result = Eigen::numext::bit_cast<Eigen::half>(val); return result - Eigen::half(1.0); } PHILOX_DEVICE_INLINE bfloat16 Uint16ToGfloat16(uint16 x) { const uint16 man = x & 0x7fu; const uint16 exp = static_cast<uint16>(127); const uint16 val = (exp << 7) | man; bfloat16 result; memcpy(&result, &val, sizeof(val)); return result - bfloat16(1.0); } } } #endif #include "tsl/lib/random/distribution_sampler.h" #include "tsl/lib/random/philox_random.h" namespace tsl { namespace random { template <> void SingleSampleAdapter<PhiloxRandom>::SkipFromGenerator(uint64 num_skips) { generator_->Skip(num_skips); } } }
#include "tsl/lib/random/random_distributions.h" #include <algorithm> #include <cmath> #include <functional> #include <numeric> #include <unordered_map> #include <vector> #include "tsl/lib/math/math_util.h" #include "tsl/lib/random/philox_random.h" #include "tsl/lib/random/philox_random_test_utils.h" #include "tsl/platform/logging.h" #include "tsl/platform/random.h" #include "tsl/platform/test.h" namespace tsl { namespace random { namespace { static constexpr float kZLimit = 6.0; static constexpr float kZLimitBfloat16 = 20.0; template <class Distribution> void FillRandomsWithSingles(PhiloxRandom gen, typename Distribution::ResultElementType* p, int64_t size) { int granularity = Distribution::kResultElementCount; CHECK(size % granularity == 0) << " size: " << size << " granularity: " << granularity; SingleSampleAdapter<PhiloxRandom> single_samples(&gen); Distribution dist; for (int i = 0; i < size; i += granularity) { auto sample = dist(&single_samples); std::copy(&sample[0], &sample[0] + granularity, &p[i]); } } template <typename T> bool CheckSamplesMoments(const std::vector<T>& samples, const std::function<double(int)>& theoretical_moments, int max_moments, int stride, T z_limit) { const T* const samples_data = &samples[0]; const int samples_size = samples.size(); std::vector<double> moments(max_moments + 1); double* const moments_data = &moments[0]; std::vector<int> moments_sample_count(max_moments + 1); int* const moments_sample_count_data = &moments_sample_count[0]; for (int k = 0; k < samples_size; ++k) { double moment = 1.; for (int i = 0; i <= max_moments; ++i) { int index = k + i * stride; if (index >= samples_size) { break; } moments_data[i] += moment; ++moments_sample_count_data[i]; moment *= static_cast<double>(samples_data[index]); } } for (int i = 0; i <= max_moments; ++i) { moments[i] /= moments_sample_count[i]; } bool status = true; for (int i = 1; i <= max_moments; ++i) { const double moments_i_mean = (stride == 0) ? theoretical_moments(i) : MathUtil::IPow(theoretical_moments(1), i); const double moments_i_squared = (stride == 0) ? theoretical_moments(2 * i) : MathUtil::IPow(theoretical_moments(2), i); const double moments_i_var = moments_i_squared - moments_i_mean * moments_i_mean; static const double kNumericalError = 1e-6; const double error_per_moment = i * kNumericalError; const double total_variance = moments_i_var / moments_sample_count[i] + error_per_moment; const double z_test = fabs((moments[i] - moments_i_mean) / sqrt(total_variance)); if (z_test > static_cast<double>(z_limit)) { LOG(ERROR) << "failing z_test:" << " moment: " << i << " stride: " << stride << " z_test: " << z_test << " z_limit: " << z_limit << " measured moments: " << moments[i] << " theoretical mean of the moments: " << moments_i_mean << " theoretical var of the moments: " << moments_i_var << " sample count: " << moments_sample_count[i]; status = false; } } return status; } template <typename T> void UniformMomentsTest(int count, int max_moments, const std::vector<int>& strides, T z_limit) { auto uniform_moments = [](int n) -> double { return 1. / (n + 1); }; std::vector<T> v1(count); uint64 seed = GetTestSeed(); PhiloxRandom gen(seed); FillRandoms<UniformDistribution<PhiloxRandom, T> >(gen, &v1[0], v1.size()); for (int stride : strides) { bool status = CheckSamplesMoments(v1, uniform_moments, max_moments, stride, z_limit); ASSERT_TRUE(status) << " UniformMomentsTest failing. seed: " << seed; } } template <typename T> void NormalMomentsTest(int count, int max_moments, const std::vector<int>& strides, T z_limit) { auto normal_moments = [](int n) -> double { if (n % 2 == 1) { return 0.; } else { double v = 1.; for (int i = n - 1; i >= 1; i -= 2) { v *= i; } return v; } }; std::vector<T> v1(count); uint64 seed = GetTestSeed(); PhiloxRandom gen(seed); FillRandoms<NormalDistribution<PhiloxRandom, T> >(gen, &v1[0], v1.size()); for (int stride : strides) { bool status = CheckSamplesMoments(v1, normal_moments, max_moments, stride, z_limit); ASSERT_TRUE(status) << " NormalMomentsTest failing. seed: " << seed; } } class TruncatedNormalMoments { public: double operator()(int n) { if (n == 0) { return 1; } if (n % 2 == 1) { return 0.; } auto iter = cached_results_.find(n); if (iter != cached_results_.end()) { return iter->second; } double bias = 2.0 * MathUtil::IPow(kV, n - 1) * kFV / (2.0 * kPhiV - 1.0); double moment_n_minus_2 = (*this)(n - 2); double moment_n = (n - 1) * moment_n_minus_2 - bias; cached_results_[n] = moment_n; return moment_n; } private: const double kV = 2.0; const double kFV = 1.0 / sqrt(2.0 * M_PI) * exp(-kV * kV / 2.0); const double kPhiV = 0.977249868051821; std::unordered_map<int, double> cached_results_; }; template <typename T> void RandomParametersMomentsTest(int count, int max_moments, const std::vector<int>& strides, T z_limit) { std::vector<T> v1(count); uint64 seed = GetTestSeed(); PhiloxRandom gen(seed); FillRandomsWithSingles< TruncatedNormalDistribution<SingleSampleAdapter<PhiloxRandom>, T> >( gen, &v1[0], v1.size()); for (int stride : strides) { bool status = CheckSamplesMoments(v1, TruncatedNormalMoments(), max_moments, stride, z_limit); ASSERT_TRUE(status) << " NormalMomentsTest failing. seed: " << seed; } } TEST(PhiloxRandomTest, UniformBfloat16MomentsTest) { const std::vector<int> strides = {0, 1, 4, 17}; UniformMomentsTest<bfloat16>(1 << 20, 40, strides, bfloat16(kZLimitBfloat16)); } TEST(PhiloxRandomTest, NormalBfloat16MomentsTest) { const std::vector<int> strides = {0, 1, 4, 17}; NormalMomentsTest<bfloat16>(8 << 20, 25, strides, bfloat16(kZLimitBfloat16)); } TEST(PhiloxRandomTest, RandomParametersBfloat16MomentsTest) { const std::vector<int> strides = {0, 1, 4, 17}; RandomParametersMomentsTest<bfloat16>(1 << 20, 40, strides, bfloat16(kZLimitBfloat16)); } TEST(PhiloxRandomTest, UniformFloatMomentsTest) { const std::vector<int> strides = {0, 1, 4, 17}; UniformMomentsTest<float>(1 << 20, 40, strides, kZLimit); } TEST(PhiloxRandomTest, NormalFloatMomentsTest) { const std::vector<int> strides = {0, 1, 4, 17}; NormalMomentsTest<float>(8 << 20, 25, strides, kZLimit); } TEST(PhiloxRandomTest, RandomParametersFloatMomentsTest) { const std::vector<int> strides = {0, 1, 4, 17}; RandomParametersMomentsTest<float>(1 << 20, 40, strides, kZLimit); } TEST(PhiloxRandomTest, UniformDoubleMomentsTest) { const std::vector<int> strides = {0, 1, 4, 17}; UniformMomentsTest<double>(1 << 20, 40, strides, kZLimit); } TEST(PhiloxRandomTest, NormalDoubleMomentsTest) { const std::vector<int> strides = {0, 1, 4, 17}; NormalMomentsTest<double>(8 << 20, 25, strides, kZLimit); } TEST(PhiloxRandomTest, RandomParametersDoubleMomentsTest) { const std::vector<int> strides = {0, 1, 4, 17}; RandomParametersMomentsTest<double>(1 << 20, 40, strides, kZLimit); } class MockGenerator { public: explicit MockGenerator(uint64 seed) : counter_(seed) {} using ResultType = std::vector<uint32>; using ResultElementType = uint32; static constexpr int kResultElementCount = 1; ResultType operator()() { ResultType result; result.push_back(counter_++); return result; } private: uint32 counter_; }; template <typename T> void SingleSampleAdapterSkipTest() { std::vector<uint64> skips(10); std::vector<uint64> skip_afters(10); std::iota(skips.begin(), skips.end(), 0); std::iota(skip_afters.begin(), skip_afters.end(), 0); uint64 total_samples = 100; uint64 seed = GetTestSeed(); for (uint64 skip : skips) { for (uint64 skip_after : skip_afters) { T parent_gen(seed); SingleSampleAdapter<T> gen(&parent_gen); T parent_gen_to_skip(seed); SingleSampleAdapter<T> gen_to_skip(&parent_gen_to_skip); int cur = 0; for (; cur < skip_after; cur++) { gen(); gen_to_skip(); } for (; cur < skip_after + skip; cur++) { gen(); } gen_to_skip.Skip(skip); for (; cur < total_samples; cur++) { ASSERT_EQ(gen(), gen_to_skip()); } } } } TEST(SingleSampleAdapterTest, PhiloxRandomSkip) { SingleSampleAdapterSkipTest<PhiloxRandom>(); } TEST(SingleSampleAdapterTest, MockGeneratorSkip) { SingleSampleAdapterSkipTest<MockGenerator>(); } } } }
2,312
#ifndef TENSORFLOW_TSL_LIB_RANDOM_DISTRIBUTION_SAMPLER_H_ #define TENSORFLOW_TSL_LIB_RANDOM_DISTRIBUTION_SAMPLER_H_ #include <memory> #include <utility> #include "absl/types/span.h" #include "tsl/lib/random/simple_philox.h" #include "tsl/platform/logging.h" #include "tsl/platform/macros.h" #include "tsl/platform/types.h" namespace tsl { namespace random { class DistributionSampler { public: explicit DistributionSampler(const absl::Span<const float> weights); ~DistributionSampler() {} int Sample(SimplePhilox* rand) const { float r = rand->RandFloat(); int idx = rand->Uniform(num_); if (r < prob(idx)) return idx; DCHECK_NE(-1, alt(idx)); return alt(idx); } int num() const { return num_; } private: float prob(int idx) const { DCHECK_LT(idx, num_); return data_[idx].first; } int alt(int idx) const { DCHECK_LT(idx, num_); return data_[idx].second; } void set_prob(int idx, float f) { DCHECK_LT(idx, num_); data_[idx].first = f; } void set_alt(int idx, int val) { DCHECK_LT(idx, num_); data_[idx].second = val; } int num_; std::unique_ptr<std::pair<float, int>[]> data_; DistributionSampler(const DistributionSampler&) = delete; void operator=(const DistributionSampler&) = delete; }; } } #endif #include "tsl/lib/random/distribution_sampler.h" #include <memory> #include <vector> #include "absl/types/span.h" namespace tsl { namespace random { DistributionSampler::DistributionSampler( const absl::Span<const float> weights) { DCHECK(!weights.empty()); int n = weights.size(); num_ = n; data_.reset(new std::pair<float, int>[n]); std::unique_ptr<double[]> pr(new double[n]); double sum = 0.0; for (int i = 0; i < n; i++) { sum += weights[i]; set_alt(i, -1); } std::vector<int> high; high.reserve(n); std::vector<int> low; low.reserve(n); for (int i = 0; i < n; i++) { double p = (weights[i] * n) / sum; pr[i] = p; if (p < 1.0) { low.push_back(i); } else { high.push_back(i); } } while (!high.empty() && !low.empty()) { int l = low.back(); low.pop_back(); int h = high.back(); high.pop_back(); set_alt(l, h); DCHECK_GE(pr[h], 1.0); double remaining = pr[h] - (1.0 - pr[l]); pr[h] = remaining; if (remaining < 1.0) { low.push_back(h); } else { high.push_back(h); } } for (int i = 0; i < n; i++) { set_prob(i, pr[i]); } for (size_t i = 0; i < high.size(); i++) { int idx = high[i]; set_prob(idx, 1.0); set_alt(idx, idx); } for (size_t i = 0; i < low.size(); i++) { int idx = low[i]; set_prob(idx, 1.0); set_alt(idx, idx); } } } }
#include "tsl/lib/random/distribution_sampler.h" #include <string.h> #include <memory> #include <vector> #include "tsl/lib/random/simple_philox.h" #include "tsl/platform/macros.h" #include "tsl/platform/test.h" #include "tsl/platform/test_benchmark.h" #include "tsl/platform/types.h" namespace tsl { namespace random { class DistributionSamplerTest : public ::testing::Test { protected: float TestWeights(const std::vector<float>& weights, int trials_per_bin) { int iters = weights.size() * trials_per_bin; std::unique_ptr<float[]> counts(new float[weights.size()]); memset(counts.get(), 0, sizeof(float) * weights.size()); DistributionSampler sampler(weights); PhiloxRandom philox(testing::RandomSeed(), 17); SimplePhilox random(&philox); for (int i = 0; i < iters; i++) { int r = sampler.Sample(&random); EXPECT_LT(r, weights.size()); EXPECT_GE(r, 0); counts[r] += 1.0; } float chi2 = 0.0; for (size_t i = 0; i < weights.size(); i++) { counts[i] /= iters; float err = (counts[i] - weights[i]); chi2 += (err * err) / weights[i]; } return chi2; } void TestDistribution(float* arr, int n) { std::vector<float> w; w.reserve(n); for (int i = 0; i < n; i++) { w.push_back(arr[i]); } float var = TestWeights(w, 1000); if (var < 0.001) return; var = TestWeights(w, 100000); if (var < 0.001) return; EXPECT_TRUE(false) << "Chi2 is " << var << " in " << n * 100000 << "iterations"; } }; TEST_F(DistributionSamplerTest, KnownDistribution) { float kEven2[] = {0.5, 0.5}; float kEven3[] = {0.33333333, 0.33333333, 0.33333333}; float kEven4[] = {0.25, 0.25, 0.25, 0.25}; float kDist1[] = {0.8, 0.15, 0.05}; TestDistribution(kEven2, TF_ARRAYSIZE(kEven2)); TestDistribution(kEven3, TF_ARRAYSIZE(kEven3)); TestDistribution(kEven4, TF_ARRAYSIZE(kEven4)); TestDistribution(kDist1, TF_ARRAYSIZE(kDist1)); } static void BM_DistributionSampler(::testing::benchmark::State& state) { const int n = state.range(0); PhiloxRandom philox(173, 371); SimplePhilox rand(&philox); std::vector<float> weights(n, 0); for (int i = 0; i < n; i++) { weights[i] = rand.Uniform(100); } DistributionSampler picker(weights); int r = 0; for (auto s : state) { r |= picker.Sample(&rand); } CHECK_NE(r, kint32max); } BENCHMARK(BM_DistributionSampler)->Arg(10)->Arg(100)->Arg(1000); } }
2,313
#ifndef TENSORFLOW_TSL_LIB_RANDOM_SIMPLE_PHILOX_H_ #define TENSORFLOW_TSL_LIB_RANDOM_SIMPLE_PHILOX_H_ #include <math.h> #include <string.h> #include <algorithm> #include "tsl/lib/random/philox_random.h" #include "tsl/lib/random/random_distributions.h" namespace tsl { namespace random { class SimplePhilox { public: PHILOX_DEVICE_INLINE explicit SimplePhilox(PhiloxRandom* gen) : single_(gen) {} PHILOX_DEVICE_INLINE uint32 Rand32() { return single_(); } PHILOX_DEVICE_INLINE uint64 Rand64() { const uint32 lo = single_(), hi = single_(); return lo | static_cast<uint64>(hi) << 32; } PHILOX_DEVICE_INLINE float RandFloat() { return Uint32ToFloat(single_()); } PHILOX_DEVICE_INLINE double RandDouble() { const uint32 x0 = single_(), x1 = single_(); return Uint64ToDouble(x0, x1); } uint32 Uniform(uint32 n); uint64 Uniform64(uint64 n); bool OneIn(uint32 n) { return Uniform(n) == 0; } uint32 Skewed(int max_log); private: SingleSampleAdapter<PhiloxRandom> single_; }; } } #endif #include "tsl/lib/random/simple_philox.h" #include "tsl/lib/random/exact_uniform_int.h" #include "tsl/platform/logging.h" namespace tsl { namespace random { uint32 SimplePhilox::Uniform(uint32 n) { return ExactUniformInt<uint32>(n, [this]() { return Rand32(); }); } uint64 SimplePhilox::Uniform64(uint64 n) { return ExactUniformInt<uint64>(n, [this]() { return Rand64(); }); } uint32 SimplePhilox::Skewed(int max_log) { CHECK(0 <= max_log && max_log <= 32); const int shift = Rand32() % (max_log + 1); const uint32 mask = shift == 32 ? ~static_cast<uint32>(0) : (1 << shift) - 1; return Rand32() & mask; } } }
#include "tsl/lib/random/simple_philox.h" #include <set> #include <string> #include "tsl/platform/logging.h" #include "tsl/platform/test.h" #include "tsl/platform/types.h" namespace tsl { namespace random { namespace { TEST(SimplePhiloxTest, FloatTest) { PhiloxRandom philox(7, 7); SimplePhilox gen(&philox); static const int kIters = 1000000; for (int i = 0; i < kIters; ++i) { float f = gen.RandFloat(); EXPECT_LE(0.0f, f); EXPECT_GT(1.0f, f); } for (int i = 0; i < kIters; ++i) { double d = gen.RandDouble(); EXPECT_LE(0.0, d); EXPECT_GT(1.0, d); } } static void DifferenceTest(const char *names, SimplePhilox *gen1, SimplePhilox *gen2) { static const int kIters = 100; bool different = false; for (int i = 0; i < kIters; ++i) { if (gen1->Rand32() != gen2->Rand32()) { different = true; break; } } CHECK(different) << "different seeds but same output!"; } TEST(SimplePhiloxTest, DifferenceTest) { PhiloxRandom philox1(1, 1), philox2(17, 17); SimplePhilox gen1(&philox1), gen2(&philox2); DifferenceTest("SimplePhilox: different seeds", &gen1, &gen2); } TEST(SimplePhiloxTest, DifferenceTestCloseSeeds) { PhiloxRandom philox1(1, 1), philox2(2, 1); SimplePhilox gen1(&philox1), gen2(&philox2); DifferenceTest("SimplePhilox: close seeds", &gen1, &gen2); } TEST(SimplePhiloxTest, Regression_CloseSeedsAreDifferent) { const int kCount = 1000; PhiloxRandom philox1(0, 1), philox2(1, 1); SimplePhilox gen1(&philox1), gen2(&philox2); std::set<uint32> first; std::set<uint32> all; for (int i = 0; i < kCount; ++i) { uint32 v = gen1.Rand32(); first.insert(v); all.insert(v); all.insert(gen2.Rand32()); } EXPECT_EQ(kCount, first.size()); EXPECT_EQ(2 * kCount, all.size()); } TEST(SimplePhiloxTest, TestUniform) { PhiloxRandom philox(17, 17); SimplePhilox gen(&philox); uint32 range = 3 * (1L << 29); uint32 threshold = 1L << 30; size_t count = 0; static const int kTrials = 100000; for (int i = 0; i < kTrials; ++i) { uint32 rnd = gen.Uniform(range); if (rnd < threshold) { ++count; } } EXPECT_LT(fabs((threshold + 0.0) / range - (count + 0.0) / kTrials), 0.005); } TEST(SimplePhiloxTest, TestUniform64) { PhiloxRandom philox(17, 17); SimplePhilox gen(&philox); uint64 range = 3 * (1LL << 59); uint64 threshold = 1LL << 60; size_t count = 0; static const int kTrials = 100000; for (int i = 0; i < kTrials; ++i) { uint64 rnd = gen.Uniform64(range); if (rnd < threshold) { ++count; } } EXPECT_LT(fabs((threshold + 0.0) / range - (count + 0.0) / kTrials), 0.005); } } } }
2,314
#ifndef TENSORFLOW_TSL_LIB_STRINGS_PROTO_SERIALIZATION_H_ #define TENSORFLOW_TSL_LIB_STRINGS_PROTO_SERIALIZATION_H_ #include "tsl/platform/protobuf.h" namespace tsl { bool SerializeToStringDeterministic(const protobuf::MessageLite& msg, string* result); bool SerializeToBufferDeterministic(const protobuf::MessageLite& msg, char* buffer, size_t size); bool AreSerializedProtosEqual(const protobuf::MessageLite& x, const protobuf::MessageLite& y); uint64 DeterministicProtoHash64(const protobuf::MessageLite& proto); uint64 DeterministicProtoHash64(const protobuf::MessageLite& proto, uint64 seed); } #endif #include "tsl/lib/strings/proto_serialization.h" #include <cstring> #include <memory> #include "absl/memory/memory.h" #include "absl/strings/string_view.h" #include "tsl/lib/gtl/inlined_vector.h" #include "tsl/platform/hash.h" #include "tsl/platform/logging.h" #include "tsl/platform/macros.h" namespace tsl { namespace { class DeterministicSerializer { public: explicit DeterministicSerializer(const protobuf::MessageLite& msg) : DeterministicSerializer(msg, msg.ByteSizeLong()) {} DeterministicSerializer(const protobuf::MessageLite& msg, size_t size) : size_(size) { char* ptr = space_; if (size_ > sizeof(space_)) { ptr = new char[size_]; alloc_.reset(ptr); } bool ok = SerializeToBufferDeterministic(msg, ptr, size_); DCHECK(ok); } size_t size() const { return size_; } const char* data() const { return alloc_ == nullptr ? space_ : alloc_.get(); } private: static constexpr int kInlinedBufferSize = 256; const size_t size_; std::unique_ptr<char[]> alloc_; char space_[kInlinedBufferSize]; }; } bool SerializeToStringDeterministic(const protobuf::MessageLite& msg, string* result) { const size_t size = msg.ByteSizeLong(); DCHECK_LE(size, static_cast<size_t>(INT_MAX)); *result = string(size, '\0'); return SerializeToBufferDeterministic(msg, const_cast<char*>(result->data()), result->size()); } bool SerializeToBufferDeterministic(const protobuf::MessageLite& msg, char* buffer, size_t size) { DCHECK(msg.ByteSizeLong() == size && size <= static_cast<size_t>(INT_MAX)); protobuf::io::ArrayOutputStream array_stream(buffer, size); protobuf::io::CodedOutputStream output_stream(&array_stream); output_stream.SetSerializationDeterministic(true); msg.SerializeWithCachedSizes(&output_stream); return !output_stream.HadError() && size == static_cast<size_t>(output_stream.ByteCount()); } bool AreSerializedProtosEqual(const protobuf::MessageLite& x, const protobuf::MessageLite& y) { const size_t size = x.ByteSizeLong(); if (size != y.ByteSizeLong()) return false; if (size == 0) return true; DeterministicSerializer x_serialized(x, size); DeterministicSerializer y_serialized(y, size); return memcmp(x_serialized.data(), y_serialized.data(), size) == 0; } uint64 DeterministicProtoHash64(const protobuf::MessageLite& proto, uint64 seed) { DeterministicSerializer serialized(proto); return Hash64(serialized.data(), serialized.size(), seed); } uint64 DeterministicProtoHash64(const protobuf::MessageLite& proto) { DeterministicSerializer serialized(proto); return Hash64(serialized.data(), serialized.size()); } }
#include "tensorflow/core/lib/strings/proto_serialization.h" #include <string> #include "absl/memory/memory.h" #include "tensorflow/core/framework/attr_value.pb.h" #include "tensorflow/core/framework/graph.pb.h" #include "tensorflow/core/framework/node_def.pb.h" #include "tensorflow/core/lib/gtl/inlined_vector.h" #include "tensorflow/core/lib/strings/strcat.h" #include "tensorflow/core/platform/test.h" #include "tensorflow/core/platform/test_benchmark.h" namespace tensorflow { namespace { GraphDef MakeGraphDef(int num_nodes) { GraphDef graph_def; for (int i = 0; i < num_nodes; ++i) { NodeDef* node = graph_def.add_node(); node->set_name(strings::StrCat("node", i)); node->set_op(strings::StrCat("op", i % 10)); (*node->mutable_attr())["foo"].set_f(3.14f); (*node->mutable_attr())["bar"].set_s("baz"); } return graph_def; } } static void BM_ProtoSerializationToString(::testing::benchmark::State& state) { int num_nodes = state.range(0); GraphDef graph_def = MakeGraphDef(num_nodes); for (auto i : state) { string serialized; testing::DoNotOptimize( SerializeToStringDeterministic(graph_def, &serialized)); } } BENCHMARK(BM_ProtoSerializationToString)->Range(1, 10000); static void BM_ProtoSerializationToBuffer(::testing::benchmark::State& state) { int num_nodes = state.range(0); GraphDef graph_def = MakeGraphDef(num_nodes); const size_t size = graph_def.ByteSizeLong(); for (auto i : state) { gtl::InlinedVector<char, 1024> buf(size); testing::DoNotOptimize( SerializeToBufferDeterministic(graph_def, buf.data(), size)); } } BENCHMARK(BM_ProtoSerializationToBuffer)->Range(1, 10000); static void BM_DeterministicProtoHash64(::testing::benchmark::State& state) { int num_nodes = state.range(0); GraphDef graph_def = MakeGraphDef(num_nodes); for (auto i : state) { testing::DoNotOptimize(DeterministicProtoHash64(graph_def)); } } BENCHMARK(BM_DeterministicProtoHash64)->Range(1, 10000); static void BM_AreSerializedProtosEqual(::testing::benchmark::State& state) { int num_nodes = state.range(0); GraphDef graph_def_a = MakeGraphDef(num_nodes); GraphDef graph_def_b = MakeGraphDef(num_nodes); graph_def_b.mutable_node(0)->mutable_name()[0] = 'l'; for (auto i : state) { testing::DoNotOptimize(AreSerializedProtosEqual(graph_def_a, graph_def_a)); } } BENCHMARK(BM_AreSerializedProtosEqual)->Range(1, 10000); }
2,315
#ifndef TENSORFLOW_TSL_LIB_HISTOGRAM_HISTOGRAM_H_ #define TENSORFLOW_TSL_LIB_HISTOGRAM_HISTOGRAM_H_ #include <string> #include <vector> #include "tsl/platform/macros.h" #include "tsl/platform/mutex.h" #include "tsl/platform/thread_annotations.h" #include "tsl/platform/types.h" namespace tensorflow { class HistogramProto; } namespace tsl { using tensorflow::HistogramProto; namespace histogram { class Histogram { public: Histogram(); explicit Histogram(absl::Span<const double> custom_bucket_limits); bool DecodeFromProto(const HistogramProto& proto); ~Histogram() {} void Clear(); void Add(double value); void EncodeToProto(HistogramProto* proto, bool preserve_zero_buckets) const; double Median() const; double Percentile(double p) const; double Average() const; double StandardDeviation() const; std::string ToString() const; private: double min_; double max_; double num_; double sum_; double sum_squares_; std::vector<double> custom_bucket_limits_; absl::Span<const double> bucket_limits_; std::vector<double> buckets_; double Remap(double x, double x0, double x1, double y0, double y1) const; Histogram(const Histogram&) = delete; void operator=(const Histogram&) = delete; }; class ThreadSafeHistogram { public: ThreadSafeHistogram() {} explicit ThreadSafeHistogram(absl::Span<const double> custom_bucket_limits) : histogram_(custom_bucket_limits) {} bool DecodeFromProto(const HistogramProto& proto); ~ThreadSafeHistogram() {} void Clear(); void Add(double value); void EncodeToProto(HistogramProto* proto, bool preserve_zero_buckets) const; double Median() const; double Percentile(double p) const; double Average() const; double StandardDeviation() const; std::string ToString() const; private: mutable mutex mu_; Histogram histogram_ TF_GUARDED_BY(mu_); }; } } #endif #include "tsl/lib/histogram/histogram.h" #include <float.h> #include <math.h> #include <vector> #include "tsl/platform/logging.h" #include "tsl/platform/mutex.h" #include "tsl/platform/types.h" #include "tsl/protobuf/histogram.pb.h" namespace tsl { namespace histogram { static std::vector<double>* InitDefaultBucketsInner() { std::vector<double> buckets; std::vector<double> neg_buckets; double v = 1.0e-12; while (v < 1.0e20) { buckets.push_back(v); neg_buckets.push_back(-v); v *= 1.1; } buckets.push_back(DBL_MAX); neg_buckets.push_back(-DBL_MAX); std::reverse(neg_buckets.begin(), neg_buckets.end()); std::vector<double>* result = new std::vector<double>; result->insert(result->end(), neg_buckets.begin(), neg_buckets.end()); result->push_back(0.0); result->insert(result->end(), buckets.begin(), buckets.end()); return result; } static absl::Span<const double> InitDefaultBuckets() { static std::vector<double>* default_bucket_limits = InitDefaultBucketsInner(); return *default_bucket_limits; } Histogram::Histogram() : bucket_limits_(InitDefaultBuckets()) { Clear(); } Histogram::Histogram(absl::Span<const double> custom_bucket_limits) : custom_bucket_limits_(custom_bucket_limits.begin(), custom_bucket_limits.end()), bucket_limits_(custom_bucket_limits_) { #ifndef NDEBUG DCHECK_GT(bucket_limits_.size(), size_t{0}); for (size_t i = 1; i < bucket_limits_.size(); i++) { DCHECK_GT(bucket_limits_[i], bucket_limits_[i - 1]); } #endif Clear(); } bool Histogram::DecodeFromProto(const HistogramProto& proto) { if ((proto.bucket_size() != proto.bucket_limit_size()) || (proto.bucket_size() == 0)) { return false; } min_ = proto.min(); max_ = proto.max(); num_ = proto.num(); sum_ = proto.sum(); sum_squares_ = proto.sum_squares(); custom_bucket_limits_.clear(); custom_bucket_limits_.insert(custom_bucket_limits_.end(), proto.bucket_limit().begin(), proto.bucket_limit().end()); bucket_limits_ = custom_bucket_limits_; buckets_.clear(); buckets_.insert(buckets_.end(), proto.bucket().begin(), proto.bucket().end()); return true; } void Histogram::Clear() { min_ = bucket_limits_[bucket_limits_.size() - 1]; max_ = -DBL_MAX; num_ = 0; sum_ = 0; sum_squares_ = 0; buckets_.resize(bucket_limits_.size()); for (size_t i = 0; i < bucket_limits_.size(); i++) { buckets_[i] = 0; } } void Histogram::Add(double value) { int b = std::upper_bound(bucket_limits_.begin(), bucket_limits_.end(), value) - bucket_limits_.begin(); buckets_[b] += 1.0; if (min_ > value) min_ = value; if (max_ < value) max_ = value; num_++; sum_ += value; sum_squares_ += (value * value); } double Histogram::Median() const { return Percentile(50.0); } double Histogram::Remap(double x, double x0, double x1, double y0, double y1) const { return y0 + (x - x0) / (x1 - x0) * (y1 - y0); } double Histogram::Percentile(double p) const { if (num_ == 0.0) return 0.0; double threshold = num_ * (p / 100.0); double cumsum_prev = 0; for (size_t i = 0; i < buckets_.size(); i++) { double cumsum = cumsum_prev + buckets_[i]; if (cumsum >= threshold) { if (cumsum == cumsum_prev) { continue; } double lhs = (i == 0 || cumsum_prev == 0) ? min_ : bucket_limits_[i - 1]; lhs = std::max(lhs, min_); double rhs = bucket_limits_[i]; rhs = std::min(rhs, max_); double weight = Remap(threshold, cumsum_prev, cumsum, lhs, rhs); return weight; } cumsum_prev = cumsum; } return max_; } double Histogram::Average() const { if (num_ == 0.0) return 0; return sum_ / num_; } double Histogram::StandardDeviation() const { if (num_ == 0.0) return 0; double variance = (sum_squares_ * num_ - sum_ * sum_) / (num_ * num_); return sqrt(variance); } std::string Histogram::ToString() const { std::string r; char buf[200]; snprintf(buf, sizeof(buf), "Count: %.0f Average: %.4f StdDev: %.2f\n", num_, Average(), StandardDeviation()); r.append(buf); snprintf(buf, sizeof(buf), "Min: %.4f Median: %.4f Max: %.4f\n", (num_ == 0.0 ? 0.0 : min_), Median(), max_); r.append(buf); r.append("------------------------------------------------------\n"); const double mult = num_ > 0 ? 100.0 / num_ : 0.0; double sum = 0; for (size_t b = 0; b < buckets_.size(); b++) { if (buckets_[b] <= 0.0) continue; sum += buckets_[b]; snprintf(buf, sizeof(buf), "[ %10.2g, %10.2g ) %7.0f %7.3f%% %7.3f%% ", ((b == 0) ? -DBL_MAX : bucket_limits_[b - 1]), bucket_limits_[b], buckets_[b], mult * buckets_[b], mult * sum); r.append(buf); int marks = static_cast<int>(20 * (buckets_[b] / num_) + 0.5); r.append(marks, '#'); r.push_back('\n'); } return r; } void Histogram::EncodeToProto(HistogramProto* proto, bool preserve_zero_buckets) const { proto->Clear(); proto->set_min(min_); proto->set_max(max_); proto->set_num(num_); proto->set_sum(sum_); proto->set_sum_squares(sum_squares_); for (size_t i = 0; i < buckets_.size();) { double end = bucket_limits_[i]; double count = buckets_[i]; i++; if (!preserve_zero_buckets && count <= 0.0) { while (i < buckets_.size() && buckets_[i] <= 0.0) { end = bucket_limits_[i]; count = buckets_[i]; i++; } } proto->add_bucket_limit(end); proto->add_bucket(count); } if (proto->bucket_size() == 0.0) { proto->add_bucket_limit(DBL_MAX); proto->add_bucket(0.0); } } bool ThreadSafeHistogram::DecodeFromProto(const HistogramProto& proto) { mutex_lock l(mu_); return histogram_.DecodeFromProto(proto); } void ThreadSafeHistogram::Clear() { mutex_lock l(mu_); histogram_.Clear(); } void ThreadSafeHistogram::Add(double value) { mutex_lock l(mu_); histogram_.Add(value); } void ThreadSafeHistogram::EncodeToProto(HistogramProto* proto, bool preserve_zero_buckets) const { mutex_lock l(mu_); histogram_.EncodeToProto(proto, preserve_zero_buckets); } double ThreadSafeHistogram::Median() const { mutex_lock l(mu_); return histogram_.Median(); } double ThreadSafeHistogram::Percentile(double p) const { mutex_lock l(mu_); return histogram_.Percentile(p); } double ThreadSafeHistogram::Average() const { mutex_lock l(mu_); return histogram_.Average(); } double ThreadSafeHistogram::StandardDeviation() const { mutex_lock l(mu_); return histogram_.StandardDeviation(); } std::string ThreadSafeHistogram::ToString() const { mutex_lock l(mu_); return histogram_.ToString(); } } }
#include "tsl/lib/histogram/histogram.h" #include <float.h> #include "tsl/platform/logging.h" #include "tsl/platform/test.h" #include "tsl/protobuf/histogram.pb.h" namespace tsl { namespace histogram { static void Validate(const Histogram& h) { string s1 = h.ToString(); LOG(ERROR) << s1; HistogramProto proto_with_zeroes; h.EncodeToProto(&proto_with_zeroes, true); Histogram h2; EXPECT_TRUE(h2.DecodeFromProto(proto_with_zeroes)); string s2 = h2.ToString(); LOG(ERROR) << s2; EXPECT_EQ(s1, s2); HistogramProto proto_no_zeroes; h.EncodeToProto(&proto_no_zeroes, false); LOG(ERROR) << proto_no_zeroes.DebugString(); Histogram h3; EXPECT_TRUE(h3.DecodeFromProto(proto_no_zeroes)); string s3 = h3.ToString(); LOG(ERROR) << s3; EXPECT_EQ(s1, s3); } TEST(Histogram, Empty) { Histogram h; Validate(h); } TEST(Histogram, SingleValue) { Histogram h; h.Add(-3.0); Validate(h); } TEST(Histogram, CustomBuckets) { Histogram h({-10, -5, 0, 5, 10, 100, 1000, 10000, DBL_MAX}); h.Add(-3.0); h.Add(4.99); h.Add(5.0); h.Add(1000.0); Validate(h); } TEST(Histogram, Median) { Histogram h({0, 10, 100, DBL_MAX}); h.Add(-2); h.Add(-2); h.Add(0); double median = h.Median(); EXPECT_EQ(median, -0.5); } TEST(Histogram, Percentile) { Histogram h({1, 2, 3, 4}); h.Add(-1.0); h.Add(1.5); h.Add(1.5); h.Add(1.5); h.Add(2.5); h.Add(2.5); h.Add(2.5); h.Add(2.5); h.Add(3.5); h.Add(3.9); EXPECT_EQ(h.Percentile(0), -1.0); EXPECT_EQ(h.Percentile(25), 1.5); EXPECT_EQ(h.Percentile(50), 2.25); EXPECT_EQ(h.Percentile(75), 2.875); EXPECT_EQ(h.Percentile(90), 3.45); EXPECT_EQ(h.Percentile(100), 3.9); } TEST(Histogram, Basic) { Histogram h; for (int i = 0; i < 100; i++) { h.Add(i); } for (int i = 1000; i < 100000; i += 1000) { h.Add(i); } Validate(h); } TEST(ThreadSafeHistogram, Basic) { Histogram h; for (int i = 0; i < 100; i++) { h.Add(i); } ThreadSafeHistogram tsh; for (int i = 0; i < 100; i++) { tsh.Add(i); } for (int i = 0; i < 2; ++i) { bool preserve_zero_buckets = (i == 0); HistogramProto h_proto; h.EncodeToProto(&h_proto, preserve_zero_buckets); HistogramProto tsh_proto; tsh.EncodeToProto(&tsh_proto, preserve_zero_buckets); Histogram h2; EXPECT_TRUE(h2.DecodeFromProto(tsh_proto)); ThreadSafeHistogram tsh2; EXPECT_TRUE(tsh2.DecodeFromProto(h_proto)); EXPECT_EQ(h2.ToString(), tsh2.ToString()); } EXPECT_EQ(h.Median(), tsh.Median()); EXPECT_EQ(h.Percentile(40.0), tsh.Percentile(40.0)); EXPECT_EQ(h.Average(), tsh.Average()); EXPECT_EQ(h.StandardDeviation(), tsh.StandardDeviation()); EXPECT_EQ(h.ToString(), tsh.ToString()); } } }
2,316
#ifndef TENSORFLOW_TSL_LIB_HASH_CRC32C_H_ #define TENSORFLOW_TSL_LIB_HASH_CRC32C_H_ #include <stddef.h> #include "absl/crc/crc32c.h" #include "absl/strings/string_view.h" #include "tsl/platform/cord.h" #include "tsl/platform/platform.h" #include "tsl/platform/types.h" namespace tsl { namespace crc32c { inline uint32 Extend(uint32 init_crc, const char* buf, size_t size) { return static_cast<uint32>(absl::ExtendCrc32c( static_cast<absl::crc32c_t>(init_crc), absl::string_view(buf, size))); } #if defined(TF_CORD_SUPPORT) extern uint32 Extend(uint32 init_crc, const absl::Cord& cord); #endif inline uint32 Value(const char* data, size_t n) { return Extend(0, data, n); } #if defined(TF_CORD_SUPPORT) inline uint32 Value(const absl::Cord& cord) { return Extend(0, cord); } #endif static const uint32 kMaskDelta = 0xa282ead8ul; inline uint32 Mask(uint32 crc) { return ((crc >> 15) | (crc << 17)) + kMaskDelta; } inline uint32 Unmask(uint32 masked_crc) { uint32 rot = masked_crc - kMaskDelta; return ((rot >> 17) | (rot << 15)); } } } #endif #include "tsl/lib/hash/crc32c.h" #include <stdint.h> #include "absl/strings/cord.h" #include "absl/strings/string_view.h" #include "tsl/platform/types.h" namespace tsl { namespace crc32c { #if defined(TF_CORD_SUPPORT) uint32 Extend(uint32 crc, const absl::Cord &cord) { for (absl::string_view fragment : cord.Chunks()) { crc = Extend(crc, fragment.data(), fragment.size()); } return crc; } #endif } }
#include "tsl/lib/hash/crc32c.h" #include <string> #include "absl/strings/cord.h" #include "tsl/platform/logging.h" #include "tsl/platform/test.h" #include "tsl/platform/test_benchmark.h" #include "tsl/platform/types.h" namespace tsl { namespace crc32c { TEST(CRC, StandardResults) { char buf[32]; memset(buf, 0, sizeof(buf)); ASSERT_EQ(0x8a9136aa, Value(buf, sizeof(buf))); memset(buf, 0xff, sizeof(buf)); ASSERT_EQ(0x62a8ab43, Value(buf, sizeof(buf))); for (int i = 0; i < 32; i++) { buf[i] = i; } ASSERT_EQ(0x46dd794e, Value(buf, sizeof(buf))); for (int i = 0; i < 32; i++) { buf[i] = 31 - i; } ASSERT_EQ(0x113fdb5c, Value(buf, sizeof(buf))); unsigned char data[48] = { 0x01, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x18, 0x28, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; ASSERT_EQ(0xd9963a56, Value(reinterpret_cast<char*>(data), sizeof(data))); ASSERT_EQ(0xdd1b19be, Value(reinterpret_cast<char*>(data), sizeof(data) - 7)); ASSERT_EQ(0x4930c4b1, Value(reinterpret_cast<char*>(data) + 1, sizeof(data) - 4)); } TEST(CRC, Values) { ASSERT_NE(Value("a", 1), Value("foo", 3)); } TEST(CRC, Extend) { ASSERT_EQ(Value("hello world", 11), Extend(Value("hello ", 6), "world", 5)); } TEST(CRC, Mask) { uint32 crc = Value("foo", 3); ASSERT_NE(crc, Mask(crc)); ASSERT_NE(crc, Mask(Mask(crc))); ASSERT_EQ(crc, Unmask(Mask(crc))); ASSERT_EQ(crc, Unmask(Unmask(Mask(Mask(crc))))); } #if defined(PLATFORM_GOOGLE) TEST(CRC, ValuesWithCord) { ASSERT_NE(Value(absl::Cord("a")), Value(absl::Cord("foo"))); } TEST(CRC, ExtendWithCord) { ASSERT_EQ(Value(absl::Cord("hello world")), Extend(Value(absl::Cord("hello ")), absl::Cord("world"))); } #endif static void BM_CRC(::testing::benchmark::State& state) { int len = state.range(0); std::string input(len, 'x'); uint32 h = 0; for (auto s : state) { h = Extend(h, input.data() + 1, len - 1); } state.SetBytesProcessed(state.iterations() * len); VLOG(1) << h; } BENCHMARK(BM_CRC)->Range(1, 256 * 1024); } }
2,317
#ifndef TENSORFLOW_TSL_LIB_CORE_BITMAP_H_ #define TENSORFLOW_TSL_LIB_CORE_BITMAP_H_ #include <string> #include "tsl/platform/logging.h" namespace tsl { namespace core { class Bitmap { public: Bitmap(); explicit Bitmap(size_t n); ~Bitmap(); Bitmap(const Bitmap&) = delete; Bitmap& operator=(const Bitmap&) = delete; size_t bits() const; void Reset(size_t n); bool get(size_t i) const; void set(size_t i); void clear(size_t i); size_t FirstUnset(size_t start) const; std::string ToString() const; private: typedef uint32_t Word; static constexpr size_t kBits = 32; static size_t NumWords(size_t n) { return (n + kBits - 1) / kBits; } static Word Mask(size_t i) { return 1ull << i; } size_t nbits_; Word* word_; }; inline Bitmap::Bitmap() : nbits_(0), word_(nullptr) {} inline Bitmap::Bitmap(size_t n) : Bitmap() { Reset(n); } inline Bitmap::~Bitmap() { delete[] word_; } inline size_t Bitmap::bits() const { return nbits_; } inline bool Bitmap::get(size_t i) const { DCHECK_LT(i, nbits_); return word_[i / kBits] & Mask(i % kBits); } inline void Bitmap::set(size_t i) { DCHECK_LT(i, nbits_); word_[i / kBits] |= Mask(i % kBits); } inline void Bitmap::clear(size_t i) { DCHECK_LT(i, nbits_); word_[i / kBits] &= ~Mask(i % kBits); } } } #endif #include "tsl/lib/core/bitmap.h" #include <cstddef> #include <cstdint> #include <cstring> #include <string> #include "absl/numeric/bits.h" namespace tsl { namespace core { void Bitmap::Reset(size_t n) { const size_t num_words = NumWords(n); if (num_words != NumWords(nbits_)) { Word* w = new Word[num_words]; delete[] word_; word_ = w; } memset(word_, 0, sizeof(word_[0]) * num_words); nbits_ = n; } static size_t FindFirstSet(uint32_t w) { return w == 0 ? 0 : absl::countr_zero(w) + 1; } size_t Bitmap::FirstUnset(size_t start) const { if (start >= nbits_) { return nbits_; } size_t mask = (1ull << (start % kBits)) - 1; const size_t nwords = NumWords(nbits_); for (size_t i = start / kBits; i < nwords; i++) { Word word = word_[i] | mask; mask = 0; size_t r = FindFirstSet(~word); if (r) { size_t result = i * kBits + (r - 1); if (result > nbits_) result = nbits_; return result; } } return nbits_; } std::string Bitmap::ToString() const { std::string result; result.resize(bits()); for (size_t i = 0; i < nbits_; i++) { result[i] = get(i) ? '1' : '0'; } return result; } } }
#include "tsl/lib/core/bitmap.h" #include "tsl/lib/random/simple_philox.h" #include "tsl/platform/macros.h" #include "tsl/platform/test.h" namespace tsl { namespace core { namespace { size_t NextSize(size_t n) { return n + ((n < 75) ? 1 : 25); } static void MakeRandomBitmap(random::SimplePhilox* rnd, Bitmap* bitmap) { size_t n = rnd->Uniform(200); bitmap->Reset(n); for (size_t i = 0; i < n; i++) { if (rnd->OneIn(2)) bitmap->set(i); } } TEST(BitmapTest, Basic) { for (size_t n = 0; n < 200; n = NextSize(n)) { Bitmap bits(n); for (size_t i = 0; i < n; i++) { EXPECT_FALSE(bits.get(i)) << n << " " << i << " " << bits.ToString(); bits.set(i); EXPECT_TRUE(bits.get(i)) << n << " " << i << " " << bits.ToString(); bits.clear(i); EXPECT_FALSE(bits.get(i)) << n << " " << i << " " << bits.ToString(); } } } TEST(BitmapTest, ToString) { Bitmap bits(10); bits.set(1); bits.set(3); EXPECT_EQ(bits.ToString(), "0101000000"); } TEST(BitmapTest, FirstUnset) { for (size_t n = 0; n < 200; n = NextSize(n)) { for (size_t p = 0; p <= 100; p++) { for (size_t q = 0; q <= 100; q++) { Bitmap bitmap(n); int one_count = 0; size_t i = 0; while (i < p && i < n) { one_count++; bitmap.set(i); i++; } while (i < n) { i++; for (size_t j = 0; j < q && i < n; j++, i++) { one_count++; bitmap.set(i); } } int seen = 0; size_t pos = 0; while (true) { pos = bitmap.FirstUnset(pos); if (pos == n) break; ASSERT_FALSE(bitmap.get(pos)) << pos << " " << bitmap.ToString(); seen++; pos++; } EXPECT_EQ(seen, n - one_count) << " " << bitmap.ToString(); } } } } TEST(BitmapTest, FirstUnsetRandom) { random::PhiloxRandom philox(301, 17); random::SimplePhilox rnd(&philox); for (int iter = 0; iter < 10000; iter++) { Bitmap bitmap; MakeRandomBitmap(&rnd, &bitmap); size_t zero_bits = 0; for (size_t i = 0; i < bitmap.bits(); i++) { if (!bitmap.get(i)) zero_bits++; } int seen = 0; size_t pos = 0; while (true) { pos = bitmap.FirstUnset(pos); if (pos == bitmap.bits()) break; ASSERT_FALSE(bitmap.get(pos)) << pos << " " << bitmap.ToString(); seen++; pos++; } EXPECT_EQ(seen, zero_bits) << " " << bitmap.ToString(); } } } } }
2,318
#ifndef TENSORFLOW_TSL_LIB_IO_RANDOM_INPUTSTREAM_H_ #define TENSORFLOW_TSL_LIB_IO_RANDOM_INPUTSTREAM_H_ #include "tsl/lib/io/inputstream_interface.h" #include "tsl/platform/cord.h" #include "tsl/platform/file_system.h" namespace tsl { namespace io { class RandomAccessInputStream : public InputStreamInterface { public: RandomAccessInputStream(RandomAccessFile* file, bool owns_file = false); ~RandomAccessInputStream() override; absl::Status ReadNBytes(int64_t bytes_to_read, tstring* result) override; #if defined(TF_CORD_SUPPORT) absl::Status ReadNBytes(int64_t bytes_to_read, absl::Cord* result) override; #endif absl::Status SkipNBytes(int64_t bytes_to_skip) override; int64_t Tell() const override; absl::Status Seek(int64_t position) { pos_ = position; return absl::OkStatus(); } absl::Status Reset() override { return Seek(0); } private: RandomAccessFile* file_; int64_t pos_ = 0; bool owns_file_ = false; }; } } #endif #include "tsl/lib/io/random_inputstream.h" #include <memory> namespace tsl { namespace io { RandomAccessInputStream::RandomAccessInputStream(RandomAccessFile* file, bool owns_file) : file_(file), owns_file_(owns_file) {} RandomAccessInputStream::~RandomAccessInputStream() { if (owns_file_) { delete file_; } } absl::Status RandomAccessInputStream::ReadNBytes(int64_t bytes_to_read, tstring* result) { if (bytes_to_read < 0) { return errors::InvalidArgument("Cannot read negative number of bytes"); } result->clear(); result->resize_uninitialized(bytes_to_read); char* result_buffer = &(*result)[0]; StringPiece data; absl::Status s = file_->Read(pos_, bytes_to_read, &data, result_buffer); if (data.data() != result_buffer) { memmove(result_buffer, data.data(), data.size()); } result->resize(data.size()); if (s.ok() || errors::IsOutOfRange(s)) { pos_ += data.size(); } return s; } #if defined(TF_CORD_SUPPORT) absl::Status RandomAccessInputStream::ReadNBytes(int64_t bytes_to_read, absl::Cord* result) { if (bytes_to_read < 0) { return errors::InvalidArgument("Cannot read negative number of bytes"); } int64_t current_size = result->size(); absl::Status s = file_->Read(pos_, bytes_to_read, result); if (s.ok() || errors::IsOutOfRange(s)) { pos_ += result->size() - current_size; } return s; } #endif static constexpr int64_t kMaxSkipSize = 8 * 1024 * 1024; absl::Status RandomAccessInputStream::SkipNBytes(int64_t bytes_to_skip) { if (bytes_to_skip < 0) { return errors::InvalidArgument("Can't skip a negative number of bytes"); } std::unique_ptr<char[]> scratch(new char[kMaxSkipSize]); if (bytes_to_skip > 0) { StringPiece data; absl::Status s = file_->Read(pos_ + bytes_to_skip - 1, 1, &data, scratch.get()); if ((s.ok() || errors::IsOutOfRange(s)) && data.size() == 1) { pos_ += bytes_to_skip; return absl::OkStatus(); } } while (bytes_to_skip > 0) { int64_t bytes_to_read = std::min<int64_t>(kMaxSkipSize, bytes_to_skip); StringPiece data; absl::Status s = file_->Read(pos_, bytes_to_read, &data, scratch.get()); if (s.ok() || errors::IsOutOfRange(s)) { pos_ += data.size(); } else { return s; } if (data.size() < static_cast<size_t>(bytes_to_read)) { return errors::OutOfRange("reached end of file"); } bytes_to_skip -= bytes_to_read; } return absl::OkStatus(); } int64_t RandomAccessInputStream::Tell() const { return pos_; } } }
#include "tsl/lib/io/random_inputstream.h" #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/env.h" #include "tsl/platform/test.h" namespace tsl { namespace io { namespace { TEST(RandomInputStream, ReadNBytes) { Env* env = Env::Default(); string fname = testing::TmpDir() + "/random_inputbuffer_test"; TF_ASSERT_OK(WriteStringToFile(env, fname, "0123456789")); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); tstring read; RandomAccessInputStream in(file.get()); TF_ASSERT_OK(in.ReadNBytes(3, &read)); EXPECT_EQ(read, "012"); EXPECT_EQ(3, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(0, &read)); EXPECT_EQ(read, ""); EXPECT_EQ(3, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(5, &read)); EXPECT_EQ(read, "34567"); EXPECT_EQ(8, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(0, &read)); EXPECT_EQ(read, ""); EXPECT_EQ(8, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.ReadNBytes(20, &read))); EXPECT_EQ(read, "89"); EXPECT_EQ(10, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(0, &read)); EXPECT_EQ(read, ""); EXPECT_EQ(10, in.Tell()); } #if defined(TF_CORD_SUPPORT) TEST(RandomInputStream, ReadNBytesWithCords) { Env* env = Env::Default(); string fname = testing::TmpDir() + "/random_inputbuffer_test"; TF_ASSERT_OK(WriteStringToFile(env, fname, "0123456789")); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); absl::Cord read; RandomAccessInputStream in(file.get()); TF_ASSERT_OK(in.ReadNBytes(3, &read)); EXPECT_EQ(read, "012"); EXPECT_EQ(3, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(0, &read)); EXPECT_EQ(read, "012"); EXPECT_EQ(3, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(5, &read)); EXPECT_EQ(read, "01234567"); EXPECT_EQ(8, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(0, &read)); EXPECT_EQ(read, "01234567"); EXPECT_EQ(8, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.ReadNBytes(20, &read))); EXPECT_EQ(read, "0123456789"); EXPECT_EQ(10, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(0, &read)); EXPECT_EQ(read, "0123456789"); EXPECT_EQ(10, in.Tell()); } #endif TEST(RandomInputStream, SkipNBytes) { Env* env = Env::Default(); string fname = testing::TmpDir() + "/random_inputbuffer_test"; TF_ASSERT_OK(WriteStringToFile(env, fname, "0123456789")); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); tstring read; RandomAccessInputStream in(file.get()); TF_ASSERT_OK(in.SkipNBytes(3)); EXPECT_EQ(3, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(0, &read)); EXPECT_EQ(read, ""); EXPECT_EQ(3, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(4, &read)); EXPECT_EQ(read, "3456"); EXPECT_EQ(7, in.Tell()); TF_ASSERT_OK(in.SkipNBytes(0)); EXPECT_EQ(7, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(2, &read)); EXPECT_EQ(read, "78"); EXPECT_EQ(9, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.SkipNBytes(20))); EXPECT_EQ(10, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.ReadNBytes(5, &read))); EXPECT_EQ(read, ""); EXPECT_EQ(10, in.Tell()); } TEST(RandomInputStream, Seek) { Env* env = Env::Default(); string fname = testing::TmpDir() + "/random_inputbuffer_seek_test"; TF_ASSERT_OK(WriteStringToFile(env, fname, "0123456789")); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); tstring read; RandomAccessInputStream in(file.get()); TF_ASSERT_OK(in.Seek(3)); EXPECT_EQ(3, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(4, &read)); EXPECT_EQ(read, "3456"); EXPECT_EQ(7, in.Tell()); TF_ASSERT_OK(in.Seek(1)); TF_ASSERT_OK(in.ReadNBytes(4, &read)); EXPECT_EQ(read, "1234"); EXPECT_EQ(5, in.Tell()); } } } }
2,319
#ifndef TENSORFLOW_TSL_LIB_IO_BUFFERED_INPUTSTREAM_H_ #define TENSORFLOW_TSL_LIB_IO_BUFFERED_INPUTSTREAM_H_ #include <string> #include "tsl/lib/io/inputstream_interface.h" #include "tsl/platform/file_system.h" namespace tsl { namespace io { class BufferedInputStream : public InputStreamInterface { public: BufferedInputStream(InputStreamInterface* input_stream, size_t buffer_bytes, bool owns_input_stream = false); BufferedInputStream(RandomAccessFile* file, size_t buffer_bytes); ~BufferedInputStream() override; absl::Status ReadNBytes(int64_t bytes_to_read, tstring* result) override; absl::Status SkipNBytes(int64_t bytes_to_skip) override; int64_t Tell() const override; absl::Status Seek(int64_t position); absl::Status ReadLine(std::string* result); absl::Status ReadLine(tstring* result); std::string ReadLineAsString(); absl::Status SkipLine(); template <typename T> absl::Status ReadAll(T* result); absl::Status Reset() override; private: absl::Status FillBuffer(); template <typename StringType> absl::Status ReadLineHelper(StringType* result, bool include_eol); InputStreamInterface* input_stream_; size_t size_; tstring buf_; size_t pos_ = 0; size_t limit_ = 0; bool owns_input_stream_ = false; absl::Status file_status_ = absl::OkStatus(); BufferedInputStream(const BufferedInputStream&) = delete; void operator=(const BufferedInputStream&) = delete; }; #ifndef SWIG extern template Status BufferedInputStream::ReadAll<std::string>( std::string* result); extern template Status BufferedInputStream::ReadAll<tstring>(tstring* result); #endif } } #endif #include "tsl/lib/io/buffered_inputstream.h" #include "absl/status/status.h" #include "tsl/lib/io/random_inputstream.h" namespace tsl { namespace io { BufferedInputStream::BufferedInputStream(InputStreamInterface* input_stream, size_t buffer_bytes, bool owns_input_stream) : input_stream_(input_stream), size_(buffer_bytes), owns_input_stream_(owns_input_stream) { buf_.reserve(size_); } BufferedInputStream::BufferedInputStream(RandomAccessFile* file, size_t buffer_bytes) : BufferedInputStream(new RandomAccessInputStream(file), buffer_bytes, true) {} BufferedInputStream::~BufferedInputStream() { if (owns_input_stream_) { delete input_stream_; } } absl::Status BufferedInputStream::FillBuffer() { if (!file_status_.ok()) { pos_ = 0; limit_ = 0; return file_status_; } absl::Status s = input_stream_->ReadNBytes(size_, &buf_); pos_ = 0; limit_ = buf_.size(); if (!s.ok()) { file_status_ = s; } return s; } template <typename StringType> absl::Status BufferedInputStream::ReadLineHelper(StringType* result, bool include_eol) { result->clear(); absl::Status s; size_t start_pos = pos_; while (true) { if (pos_ == limit_) { result->append(buf_.data() + start_pos, pos_ - start_pos); s = FillBuffer(); if (limit_ == 0) { break; } start_pos = pos_; } char c = buf_[pos_]; if (c == '\n') { result->append(buf_.data() + start_pos, pos_ - start_pos); if (include_eol) { result->append(1, c); } pos_++; return absl::OkStatus(); } if (c == '\r') { result->append(buf_.data() + start_pos, pos_ - start_pos); start_pos = pos_ + 1; } pos_++; } if (absl::IsOutOfRange(s) && !result->empty()) { return absl::OkStatus(); } return s; } absl::Status BufferedInputStream::ReadNBytes(int64_t bytes_to_read, tstring* result) { if (bytes_to_read < 0) { return errors::InvalidArgument("Can't read a negative number of bytes: ", bytes_to_read); } result->clear(); if (pos_ == limit_ && !file_status_.ok() && bytes_to_read > 0) { return file_status_; } result->reserve(bytes_to_read); absl::Status s; while (result->size() < static_cast<size_t>(bytes_to_read)) { if (pos_ == limit_) { s = FillBuffer(); if (limit_ == 0) { DCHECK(!s.ok()); file_status_ = s; break; } } const int64_t bytes_to_copy = std::min<int64_t>(limit_ - pos_, bytes_to_read - result->size()); result->insert(result->size(), buf_, pos_, bytes_to_copy); pos_ += bytes_to_copy; } if (absl::IsOutOfRange(s) && (result->size() == static_cast<size_t>(bytes_to_read))) { return absl::OkStatus(); } return s; } absl::Status BufferedInputStream::SkipNBytes(int64_t bytes_to_skip) { if (bytes_to_skip < 0) { return errors::InvalidArgument("Can only skip forward, not ", bytes_to_skip); } if (pos_ + bytes_to_skip < limit_) { pos_ += bytes_to_skip; } else { absl::Status s = input_stream_->SkipNBytes(bytes_to_skip - (limit_ - pos_)); pos_ = 0; limit_ = 0; if (absl::IsOutOfRange(s)) { file_status_ = s; } return s; } return absl::OkStatus(); } int64_t BufferedInputStream::Tell() const { return input_stream_->Tell() - (limit_ - pos_); } absl::Status BufferedInputStream::Seek(int64_t position) { if (position < 0) { return errors::InvalidArgument("Seeking to a negative position: ", position); } const int64_t buf_lower_limit = input_stream_->Tell() - limit_; if (position < buf_lower_limit) { TF_RETURN_IF_ERROR(Reset()); return SkipNBytes(position); } if (position < Tell()) { pos_ -= Tell() - position; return absl::OkStatus(); } return SkipNBytes(position - Tell()); } template <typename T> absl::Status BufferedInputStream::ReadAll(T* result) { result->clear(); absl::Status status; while (status.ok()) { status = FillBuffer(); if (limit_ == 0) { break; } result->append(buf_); pos_ = limit_; } if (absl::IsOutOfRange(status)) { file_status_ = status; return absl::OkStatus(); } return status; } template Status BufferedInputStream::ReadAll<std::string>(std::string* result); template Status BufferedInputStream::ReadAll<tstring>(tstring* result); absl::Status BufferedInputStream::Reset() { TF_RETURN_IF_ERROR(input_stream_->Reset()); pos_ = 0; limit_ = 0; file_status_ = absl::OkStatus(); return absl::OkStatus(); } absl::Status BufferedInputStream::ReadLine(std::string* result) { return ReadLineHelper(result, false); } absl::Status BufferedInputStream::ReadLine(tstring* result) { return ReadLineHelper(result, false); } std::string BufferedInputStream::ReadLineAsString() { std::string result; ReadLineHelper(&result, true).IgnoreError(); return result; } absl::Status BufferedInputStream::SkipLine() { absl::Status s; bool skipped = false; while (true) { if (pos_ == limit_) { s = FillBuffer(); if (limit_ == 0) { break; } } char c = buf_[pos_++]; skipped = true; if (c == '\n') { return absl::OkStatus(); } } if (absl::IsOutOfRange(s) && skipped) { return absl::OkStatus(); } return s; } } }
#include "tsl/lib/io/buffered_inputstream.h" #include "tsl/lib/core/status_test_util.h" #include "tsl/lib/io/random_inputstream.h" #include "tsl/platform/env.h" #include "tsl/platform/test.h" #include "tsl/platform/test_benchmark.h" namespace tsl { namespace io { namespace { static std::vector<int> BufferSizes() { return {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 65536}; } class ReadOnceInputStream : public InputStreamInterface { public: ReadOnceInputStream() : start_(true) {} virtual absl::Status ReadNBytes(int64_t bytes_to_read, tstring* result) { if (bytes_to_read < 11) { return errors::InvalidArgument("Not reading all bytes: ", bytes_to_read); } if (start_) { *result = "0123456789"; start_ = false; return errors::OutOfRange("Out of range."); } return errors::InvalidArgument( "Redudant call to ReadNBytes after an OutOfRange error."); } int64_t Tell() const override { return start_ ? 0 : 10; } absl::Status Reset() override { start_ = true; return absl::OkStatus(); } private: bool start_; }; TEST(BufferedInputStream, ReadLine_Empty) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK(WriteStringToFile(env, fname, "")); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessInputStream> input_stream( new RandomAccessInputStream(file.get())); BufferedInputStream in(input_stream.get(), buf_size); string line; EXPECT_TRUE(errors::IsOutOfRange(in.ReadLine(&line))); } } TEST(BufferedInputStream, ReadLine1) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK( WriteStringToFile(env, fname, "line one\nline two\nline three\n")); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessInputStream> input_stream( new RandomAccessInputStream(file.get())); BufferedInputStream in(input_stream.get(), buf_size); string line; TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line one"); TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line two"); TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line three"); EXPECT_TRUE(errors::IsOutOfRange(in.ReadLine(&line))); EXPECT_TRUE(errors::IsOutOfRange(in.ReadLine(&line))); } } TEST(BufferedInputStream, ReadLine_NoTrailingNewLine) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK(WriteStringToFile(env, fname, "line one\nline two\nline three")); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessInputStream> input_stream( new RandomAccessInputStream(file.get())); BufferedInputStream in(input_stream.get(), buf_size); string line; TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line one"); TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line two"); TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line three"); EXPECT_TRUE(errors::IsOutOfRange(in.ReadLine(&line))); EXPECT_TRUE(errors::IsOutOfRange(in.ReadLine(&line))); } } TEST(BufferedInputStream, ReadLine_EmptyLines) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK( WriteStringToFile(env, fname, "line one\n\n\nline two\nline three")); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessInputStream> input_stream( new RandomAccessInputStream(file.get())); BufferedInputStream in(input_stream.get(), buf_size); string line; TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line one"); TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, ""); TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, ""); TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line two"); TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line three"); EXPECT_TRUE(errors::IsOutOfRange(in.ReadLine(&line))); EXPECT_TRUE(errors::IsOutOfRange(in.ReadLine(&line))); } } TEST(BufferedInputStream, ReadLine_CRLF) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK(WriteStringToFile(env, fname, "line one\r\n\r\n\r\nline two\r\nline three")); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessInputStream> input_stream( new RandomAccessInputStream(file.get())); BufferedInputStream in(input_stream.get(), buf_size); string line; TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line one"); TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, ""); TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, ""); TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line two"); TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line three"); EXPECT_TRUE(errors::IsOutOfRange(in.ReadLine(&line))); EXPECT_TRUE(errors::IsOutOfRange(in.ReadLine(&line))); } } TEST(BufferedInputStream, SkipLine1) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK( WriteStringToFile(env, fname, "line one\nline two\nline three\n")); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessInputStream> input_stream( new RandomAccessInputStream(file.get())); BufferedInputStream in(input_stream.get(), buf_size); string line; TF_ASSERT_OK(in.SkipLine()); TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line two"); TF_ASSERT_OK(in.SkipLine()); EXPECT_TRUE(errors::IsOutOfRange(in.SkipLine())); EXPECT_TRUE(errors::IsOutOfRange(in.SkipLine())); } } TEST(BufferedInputStream, SkipLine_NoTrailingNewLine) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK(WriteStringToFile(env, fname, "line one\nline two\nline three")); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessInputStream> input_stream( new RandomAccessInputStream(file.get())); BufferedInputStream in(input_stream.get(), buf_size); string line; TF_ASSERT_OK(in.SkipLine()); TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line two"); TF_ASSERT_OK(in.SkipLine()); EXPECT_TRUE(errors::IsOutOfRange(in.SkipLine())); EXPECT_TRUE(errors::IsOutOfRange(in.SkipLine())); } } TEST(BufferedInputStream, SkipLine_EmptyLines) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK(WriteStringToFile(env, fname, "line one\n\n\nline two")); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessInputStream> input_stream( new RandomAccessInputStream(file.get())); BufferedInputStream in(input_stream.get(), buf_size); string line; TF_ASSERT_OK(in.SkipLine()); TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, ""); TF_ASSERT_OK(in.SkipLine()); TF_ASSERT_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line two"); } } TEST(BufferedInputStream, ReadNBytes) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK(WriteStringToFile(env, fname, "0123456789")); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessInputStream> input_stream( new RandomAccessInputStream(file.get())); tstring read; BufferedInputStream in(input_stream.get(), buf_size); EXPECT_EQ(0, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(3, &read)); EXPECT_EQ(read, "012"); EXPECT_EQ(3, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(0, &read)); EXPECT_EQ(read, ""); EXPECT_EQ(3, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(4, &read)); EXPECT_EQ(read, "3456"); EXPECT_EQ(7, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(0, &read)); EXPECT_EQ(read, ""); EXPECT_EQ(7, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.ReadNBytes(5, &read))); EXPECT_EQ(read, "789"); EXPECT_EQ(10, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.ReadNBytes(5, &read))); EXPECT_EQ(read, ""); EXPECT_EQ(10, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(0, &read)); EXPECT_EQ(read, ""); EXPECT_EQ(10, in.Tell()); } } TEST(BufferedInputStream, OutOfRangeCache) { for (auto buf_size : BufferSizes()) { if (buf_size < 11) { continue; } ReadOnceInputStream input_stream; tstring read; BufferedInputStream in(&input_stream, buf_size); EXPECT_EQ(0, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(3, &read)); EXPECT_EQ(read, "012"); EXPECT_EQ(3, in.Tell()); TF_ASSERT_OK((in.ReadNBytes(7, &read))); EXPECT_EQ(read, "3456789"); EXPECT_EQ(10, in.Tell()); absl::Status s = in.ReadNBytes(5, &read); EXPECT_EQ(error::OUT_OF_RANGE, s.code()) << s; EXPECT_EQ(read, ""); TF_ASSERT_OK(in.ReadNBytes(0, &read)); EXPECT_EQ(read, ""); } } TEST(BufferedInputStream, SkipNBytes) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK(WriteStringToFile(env, fname, "0123456789")); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessInputStream> input_stream( new RandomAccessInputStream(file.get())); tstring read; BufferedInputStream in(input_stream.get(), buf_size); EXPECT_EQ(0, in.Tell()); TF_ASSERT_OK(in.SkipNBytes(3)); EXPECT_EQ(3, in.Tell()); TF_ASSERT_OK(in.SkipNBytes(0)); EXPECT_EQ(3, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(2, &read)); EXPECT_EQ(read, "34"); EXPECT_EQ(5, in.Tell()); TF_ASSERT_OK(in.SkipNBytes(0)); EXPECT_EQ(5, in.Tell()); TF_ASSERT_OK(in.SkipNBytes(2)); EXPECT_EQ(7, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(1, &read)); EXPECT_EQ(read, "7"); EXPECT_EQ(8, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.SkipNBytes(5))); EXPECT_EQ(10, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.SkipNBytes(5))); EXPECT_EQ(10, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.ReadNBytes(5, &read))); EXPECT_EQ(read, ""); EXPECT_EQ(10, in.Tell()); } } TEST(BufferedInputStream, ReadNBytesRandomAccessFile) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK(WriteStringToFile(env, fname, "0123456789")); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); for (auto buf_size : BufferSizes()) { tstring read; BufferedInputStream in(file.get(), buf_size); EXPECT_EQ(0, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(3, &read)); EXPECT_EQ(read, "012"); EXPECT_EQ(3, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(0, &read)); EXPECT_EQ(read, ""); EXPECT_EQ(3, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(4, &read)); EXPECT_EQ(read, "3456"); EXPECT_EQ(7, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(0, &read)); EXPECT_EQ(read, ""); EXPECT_EQ(7, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.ReadNBytes(5, &read))); EXPECT_EQ(read, "789"); EXPECT_EQ(10, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.ReadNBytes(5, &read))); EXPECT_EQ(read, ""); EXPECT_EQ(10, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(0, &read)); EXPECT_EQ(read, ""); EXPECT_EQ(10, in.Tell()); } } TEST(BufferedInputStream, SkipNBytesRandomAccessFile) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK(WriteStringToFile(env, fname, "0123456789")); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); for (auto buf_size : BufferSizes()) { tstring read; BufferedInputStream in(file.get(), buf_size); EXPECT_EQ(0, in.Tell()); TF_ASSERT_OK(in.SkipNBytes(3)); EXPECT_EQ(3, in.Tell()); TF_ASSERT_OK(in.SkipNBytes(0)); EXPECT_EQ(3, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(2, &read)); EXPECT_EQ(read, "34"); EXPECT_EQ(5, in.Tell()); TF_ASSERT_OK(in.SkipNBytes(0)); EXPECT_EQ(5, in.Tell()); TF_ASSERT_OK(in.SkipNBytes(2)); EXPECT_EQ(7, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(1, &read)); EXPECT_EQ(read, "7"); EXPECT_EQ(8, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.SkipNBytes(5))); EXPECT_EQ(10, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.SkipNBytes(5))); EXPECT_EQ(10, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.ReadNBytes(5, &read))); EXPECT_EQ(read, ""); EXPECT_EQ(10, in.Tell()); } } TEST(BufferedInputStream, Seek) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK(WriteStringToFile(env, fname, "0123456789")); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessInputStream> input_stream( new RandomAccessInputStream(file.get())); tstring read; BufferedInputStream in(input_stream.get(), buf_size); TF_ASSERT_OK(in.Seek(3)); EXPECT_EQ(3, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(4, &read)); EXPECT_EQ(read, "3456"); EXPECT_EQ(7, in.Tell()); TF_ASSERT_OK(in.Seek(1)); TF_ASSERT_OK(in.ReadNBytes(4, &read)); EXPECT_EQ(read, "1234"); EXPECT_EQ(5, in.Tell()); } } TEST(BufferedInputStream, Seek_NotReset) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK(WriteStringToFile(env, fname, "0123456789")); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); std::unique_ptr<RandomAccessInputStream> input_stream( new RandomAccessInputStream(file.get())); tstring read; BufferedInputStream in(input_stream.get(), 3); TF_ASSERT_OK(in.ReadNBytes(4, &read)); int before_tell = input_stream.get()->Tell(); EXPECT_EQ(before_tell, 6); TF_ASSERT_OK(in.Seek(3)); int after_tell = input_stream.get()->Tell(); EXPECT_EQ(before_tell, after_tell); } TEST(BufferedInputStream, ReadAll_Empty) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); const string expected = ""; TF_ASSERT_OK(WriteStringToFile(env, fname, expected)); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); for (auto buf_size : BufferSizes()) { RandomAccessInputStream input_stream(file.get()); BufferedInputStream in(&input_stream, buf_size); string contents; TF_ASSERT_OK(in.ReadAll(&contents)); EXPECT_EQ(expected, contents); } } TEST(BufferedInputStream, ReadAll_Text) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); const string expected = "line one\nline two\nline three"; TF_ASSERT_OK(WriteStringToFile(env, fname, expected)); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); for (auto buf_size : BufferSizes()) { RandomAccessInputStream input_stream(file.get()); BufferedInputStream in(&input_stream, buf_size); string contents; TF_ASSERT_OK(in.ReadAll(&contents)); EXPECT_EQ(expected, contents); } } void BM_BufferedReaderSmallReads(::testing::benchmark::State& state) { const int buff_size = state.range(0); const int file_size = state.range(1); Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); const string file_elem = "0123456789"; std::unique_ptr<WritableFile> write_file; TF_ASSERT_OK(env->NewWritableFile(fname, &write_file)); for (int i = 0; i < file_size; ++i) { TF_ASSERT_OK(write_file->Append(file_elem)); } TF_ASSERT_OK(write_file->Close()); std::unique_ptr<RandomAccessFile> file; TF_ASSERT_OK(env->NewRandomAccessFile(fname, &file)); tstring result; int itr = 0; for (auto s : state) { BufferedInputStream in(file.get(), buff_size); for (int64_t i = 0; i < 10 * file_size; ++i) { TF_ASSERT_OK(in.ReadNBytes(1, &result)) << "i: " << i << " itr: " << itr << " buff_size: " << buff_size << " file size: " << file_size; } ++itr; } } BENCHMARK(BM_BufferedReaderSmallReads) ->ArgPair(1, 5) ->ArgPair(1, 1024) ->ArgPair(10, 5) ->ArgPair(10, 1024) ->ArgPair(1024, 1024) ->ArgPair(1024 * 1024, 1024) ->ArgPair(1024 * 1024, 1024 * 1024) ->ArgPair(256 * 1024 * 1024, 1024); } } }
2,320
#ifndef TENSORFLOW_TSL_LIB_IO_INPUTBUFFER_H_ #define TENSORFLOW_TSL_LIB_IO_INPUTBUFFER_H_ #include <string> #include "tsl/platform/coding.h" #include "tsl/platform/env.h" #include "tsl/platform/macros.h" #include "tsl/platform/status.h" #include "tsl/platform/types.h" namespace tsl { namespace io { class InputBuffer { public: InputBuffer(RandomAccessFile* file, size_t buffer_bytes); ~InputBuffer(); template <typename T> absl::Status ReadLine(T* result); absl::Status ReadNBytes(int64_t bytes_to_read, std::string* result); absl::Status ReadNBytes(int64_t bytes_to_read, char* result, size_t* bytes_read); absl::Status ReadVarint32(uint32* result); absl::Status ReadVarint64(uint64* result); absl::Status SkipNBytes(int64_t bytes_to_skip); absl::Status Seek(int64_t position); absl::Status Hint(int64_t bytes_to_read); int64_t Tell() const { return file_pos_ - (limit_ - pos_); } RandomAccessFile* file() const { return file_; } private: absl::Status FillBuffer(); absl::Status ReadVarint32Fallback(uint32* result); absl::Status ReadVarint64Fallback(uint64* result); template <typename T> absl::Status ReadVarintFallback(T* result, int max_bytes); RandomAccessFile* file_; int64_t file_pos_; size_t size_; char* buf_; char* pos_; char* limit_; InputBuffer(const InputBuffer&) = delete; void operator=(const InputBuffer&) = delete; }; extern template Status InputBuffer::ReadLine<std::string>(std::string* result); extern template Status InputBuffer::ReadLine<tstring>(tstring* result); inline absl::Status InputBuffer::ReadVarint32(uint32* result) { if (pos_ + core::kMaxVarint32Bytes <= limit_) { const char* offset = core::GetVarint32Ptr(pos_, limit_, result); if (offset == nullptr) return errors::OutOfRange("Parsed past limit."); pos_ = const_cast<char*>(offset); return absl::OkStatus(); } else { return ReadVarint32Fallback(result); } } inline absl::Status InputBuffer::ReadVarint64(uint64* result) { if (pos_ + core::kMaxVarint64Bytes <= limit_) { const char* offset = core::GetVarint64Ptr(pos_, limit_, result); if (offset == nullptr) return errors::OutOfRange("Parsed past limit."); pos_ = const_cast<char*>(offset); return absl::OkStatus(); } else { return ReadVarint64Fallback(result); } } } } #endif #include "tsl/lib/io/inputbuffer.h" #include <algorithm> #include "tsl/platform/errors.h" #include "tsl/platform/logging.h" namespace tsl { namespace io { InputBuffer::InputBuffer(RandomAccessFile* file, size_t buffer_bytes) : file_(file), file_pos_(0), size_(buffer_bytes), buf_(new char[size_]), pos_(buf_), limit_(buf_) {} InputBuffer::~InputBuffer() { delete[] buf_; } absl::Status InputBuffer::FillBuffer() { StringPiece data; absl::Status s = file_->Read(file_pos_, size_, &data, buf_); if (data.data() != buf_) { memmove(buf_, data.data(), data.size()); } pos_ = buf_; limit_ = pos_ + data.size(); file_pos_ += data.size(); return s; } template <typename T> absl::Status InputBuffer::ReadLine(T* result) { result->clear(); absl::Status s; do { size_t buf_remain = limit_ - pos_; char* newline = static_cast<char*>(memchr(pos_, '\n', buf_remain)); if (newline != nullptr) { size_t result_len = newline - pos_; result->append(pos_, result_len); pos_ = newline + 1; if (!result->empty() && result->back() == '\r') { result->resize(result->size() - 1); } return absl::OkStatus(); } if (buf_remain > 0) result->append(pos_, buf_remain); s = FillBuffer(); DCHECK_EQ(pos_, buf_); } while (limit_ != buf_); if (!result->empty() && result->back() == '\r') { result->resize(result->size() - 1); } if (errors::IsOutOfRange(s) && !result->empty()) { return absl::OkStatus(); } return s; } template Status InputBuffer::ReadLine<std::string>(std::string* result); template Status InputBuffer::ReadLine<tstring>(tstring* result); absl::Status InputBuffer::ReadNBytes(int64_t bytes_to_read, std::string* result) { result->clear(); if (bytes_to_read < 0) { return errors::InvalidArgument("Can't read a negative number of bytes: ", bytes_to_read); } result->resize(bytes_to_read); size_t bytes_read = 0; absl::Status status = ReadNBytes(bytes_to_read, &(*result)[0], &bytes_read); if (bytes_read < bytes_to_read) result->resize(bytes_read); return status; } absl::Status InputBuffer::ReadNBytes(int64_t bytes_to_read, char* result, size_t* bytes_read) { if (bytes_to_read < 0) { return errors::InvalidArgument("Can't read a negative number of bytes: ", bytes_to_read); } absl::Status status; *bytes_read = 0; while (*bytes_read < static_cast<size_t>(bytes_to_read)) { if (pos_ == limit_) { status = FillBuffer(); if (limit_ == buf_) { break; } } const int64_t bytes_to_copy = std::min<int64_t>(limit_ - pos_, bytes_to_read - *bytes_read); memcpy(result + *bytes_read, pos_, bytes_to_copy); pos_ += bytes_to_copy; *bytes_read += bytes_to_copy; } if (errors::IsOutOfRange(status) && (*bytes_read == static_cast<size_t>(bytes_to_read))) { return absl::OkStatus(); } return status; } absl::Status InputBuffer::ReadVarint32Fallback(uint32* result) { absl::Status s = ReadVarintFallback(result, core::kMaxVarint32Bytes); if (errors::IsDataLoss(s)) { return errors::DataLoss("Stored data is too large to be a varint32."); } return s; } absl::Status InputBuffer::ReadVarint64Fallback(uint64* result) { absl::Status s = ReadVarintFallback(result, core::kMaxVarint64Bytes); if (errors::IsDataLoss(s)) { return errors::DataLoss("Stored data is too large to be a varint64."); } return s; } template <typename T> absl::Status InputBuffer::ReadVarintFallback(T* result, int max_bytes) { uint8 scratch = 0; auto* p = reinterpret_cast<char*>(&scratch); size_t unused_bytes_read = 0; *result = 0; for (int index = 0; index < max_bytes; index++) { int shift = 7 * index; TF_RETURN_IF_ERROR(ReadNBytes(1, p, &unused_bytes_read)); *result |= (static_cast<T>(scratch) & 127) << shift; if (!(scratch & 128)) return absl::OkStatus(); } return errors::DataLoss("Stored data longer than ", max_bytes, " bytes."); } absl::Status InputBuffer::SkipNBytes(int64_t bytes_to_skip) { if (bytes_to_skip < 0) { return errors::InvalidArgument("Can only skip forward, not ", bytes_to_skip); } int64_t bytes_skipped = 0; absl::Status s; while (bytes_skipped < bytes_to_skip) { if (pos_ == limit_) { s = FillBuffer(); if (limit_ == buf_) { break; } } const int64_t bytes_to_advance = std::min<int64_t>(limit_ - pos_, bytes_to_skip - bytes_skipped); bytes_skipped += bytes_to_advance; pos_ += bytes_to_advance; } if (errors::IsOutOfRange(s) && bytes_skipped == bytes_to_skip) { return absl::OkStatus(); } return s; } absl::Status InputBuffer::Seek(int64_t position) { if (position < 0) { return errors::InvalidArgument("Seeking to a negative position: ", position); } const int64_t bufpos = file_pos_ - static_cast<int64_t>(limit_ - buf_); if (position >= bufpos && position < file_pos_) { pos_ = buf_ + (position - bufpos); DCHECK(pos_ >= buf_ && pos_ < limit_); } else { pos_ = limit_ = buf_; file_pos_ = position; } return absl::OkStatus(); } absl::Status InputBuffer::Hint(int64_t bytes_to_read) { if (bytes_to_read < 0) { return errors::InvalidArgument("Can't read a negative number of bytes: ", bytes_to_read); } if (bytes_to_read > size_) { return absl::OkStatus(); } const int64_t bytes_remain_in_buf = static_cast<int64_t>(limit_ - pos_); if (bytes_to_read <= bytes_remain_in_buf) { return absl::OkStatus(); } memmove(buf_, pos_, bytes_remain_in_buf); pos_ = buf_; limit_ = buf_ + bytes_remain_in_buf; bytes_to_read -= bytes_remain_in_buf; StringPiece data; absl::Status s = file_->Read(file_pos_, bytes_to_read, &data, limit_); if (data.data() != limit_) { memmove(limit_, data.data(), data.size()); } limit_ += data.size(); file_pos_ += data.size(); if (errors::IsOutOfRange(s) && data.size() == bytes_to_read) { return absl::OkStatus(); } else { return s; } } } }
#include "tsl/lib/io/inputbuffer.h" #include <vector> #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/coding.h" #include "tsl/platform/env.h" #include "tsl/platform/errors.h" #include "tsl/platform/logging.h" #include "tsl/platform/status.h" #include "tsl/platform/str_util.h" #include "tsl/platform/strcat.h" #include "tsl/platform/test.h" namespace tsl { namespace { static std::vector<int> BufferSizes() { return {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 65536}; } TEST(InputBuffer, ReadLine_Empty) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK(WriteStringToFile(env, fname, "")); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessFile> file; TF_CHECK_OK(env->NewRandomAccessFile(fname, &file)); string line; io::InputBuffer in(file.get(), buf_size); EXPECT_TRUE(errors::IsOutOfRange(in.ReadLine(&line))); } } TEST(InputBuffer, ReadLine1) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_CHECK_OK( WriteStringToFile(env, fname, "line one\nline two\nline three\n")); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessFile> file; TF_CHECK_OK(env->NewRandomAccessFile(fname, &file)); string line; io::InputBuffer in(file.get(), buf_size); TF_CHECK_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line one"); TF_CHECK_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line two"); TF_CHECK_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line three"); EXPECT_TRUE(errors::IsOutOfRange(in.ReadLine(&line))); EXPECT_TRUE(errors::IsOutOfRange(in.ReadLine(&line))); } } TEST(InputBuffer, ReadLine_NoTrailingNewLine) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK(WriteStringToFile(env, fname, "line one\nline two\nline three")); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessFile> file; TF_CHECK_OK(env->NewRandomAccessFile(fname, &file)); string line; io::InputBuffer in(file.get(), buf_size); TF_CHECK_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line one"); TF_CHECK_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line two"); TF_CHECK_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line three"); EXPECT_TRUE(errors::IsOutOfRange(in.ReadLine(&line))); EXPECT_TRUE(errors::IsOutOfRange(in.ReadLine(&line))); } } TEST(InputBuffer, ReadLine_EmptyLines) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_CHECK_OK( WriteStringToFile(env, fname, "line one\n\n\nline two\nline three")); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessFile> file; TF_CHECK_OK(env->NewRandomAccessFile(fname, &file)); string line; io::InputBuffer in(file.get(), buf_size); TF_CHECK_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line one"); TF_CHECK_OK(in.ReadLine(&line)); EXPECT_EQ(line, ""); TF_CHECK_OK(in.ReadLine(&line)); EXPECT_EQ(line, ""); TF_CHECK_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line two"); TF_CHECK_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line three"); EXPECT_TRUE(errors::IsOutOfRange(in.ReadLine(&line))); EXPECT_TRUE(errors::IsOutOfRange(in.ReadLine(&line))); } } TEST(InputBuffer, ReadLine_CRLF) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK(WriteStringToFile(env, fname, "line one\r\n\r\n\r\nline two\r\nline three")); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessFile> file; TF_CHECK_OK(env->NewRandomAccessFile(fname, &file)); string line; io::InputBuffer in(file.get(), buf_size); TF_CHECK_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line one"); TF_CHECK_OK(in.ReadLine(&line)); EXPECT_EQ(line, ""); TF_CHECK_OK(in.ReadLine(&line)); EXPECT_EQ(line, ""); TF_CHECK_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line two"); TF_CHECK_OK(in.ReadLine(&line)); EXPECT_EQ(line, "line three"); EXPECT_TRUE(errors::IsOutOfRange(in.ReadLine(&line))); EXPECT_TRUE(errors::IsOutOfRange(in.ReadLine(&line))); } } TEST(InputBuffer, ReadNBytes) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK(WriteStringToFile(env, fname, "0123456789")); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessFile> file; TF_CHECK_OK(env->NewRandomAccessFile(fname, &file)); string read; io::InputBuffer in(file.get(), buf_size); EXPECT_EQ(0, in.Tell()); TF_CHECK_OK(in.ReadNBytes(3, &read)); EXPECT_EQ(read, "012"); EXPECT_EQ(3, in.Tell()); TF_CHECK_OK(in.ReadNBytes(0, &read)); EXPECT_EQ(read, ""); EXPECT_EQ(3, in.Tell()); TF_CHECK_OK(in.ReadNBytes(4, &read)); EXPECT_EQ(read, "3456"); EXPECT_EQ(7, in.Tell()); TF_CHECK_OK(in.ReadNBytes(0, &read)); EXPECT_EQ(read, ""); EXPECT_EQ(7, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.ReadNBytes(5, &read))); EXPECT_EQ(read, "789"); EXPECT_EQ(10, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.ReadNBytes(5, &read))); EXPECT_EQ(read, ""); EXPECT_EQ(10, in.Tell()); TF_CHECK_OK(in.ReadNBytes(0, &read)); EXPECT_EQ(read, ""); EXPECT_EQ(10, in.Tell()); } size_t bytes_read; for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessFile> file; TF_CHECK_OK(env->NewRandomAccessFile(fname, &file)); char read[5]; io::InputBuffer in(file.get(), buf_size); EXPECT_EQ(0, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(3, read, &bytes_read)); EXPECT_EQ(StringPiece(read, 3), "012"); EXPECT_EQ(3, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(0, read, &bytes_read)); EXPECT_EQ(StringPiece(read, 3), "012"); EXPECT_EQ(3, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(4, read, &bytes_read)); EXPECT_EQ(StringPiece(read, 4), "3456"); EXPECT_EQ(7, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(0, read, &bytes_read)); EXPECT_EQ(StringPiece(read, 4), "3456"); EXPECT_EQ(7, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.ReadNBytes(5, read, &bytes_read))); EXPECT_EQ(StringPiece(read, 3), "789"); EXPECT_EQ(10, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.ReadNBytes(5, read, &bytes_read))); EXPECT_EQ(StringPiece(read, 3), "789"); EXPECT_EQ(10, in.Tell()); TF_ASSERT_OK(in.ReadNBytes(0, read, &bytes_read)); EXPECT_EQ(StringPiece(read, 3), "789"); EXPECT_EQ(10, in.Tell()); } } TEST(InputBuffer, SkipNBytes) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK(WriteStringToFile(env, fname, "0123456789")); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessFile> file; TF_CHECK_OK(env->NewRandomAccessFile(fname, &file)); string read; io::InputBuffer in(file.get(), buf_size); EXPECT_EQ(0, in.Tell()); TF_CHECK_OK(in.SkipNBytes(3)); EXPECT_EQ(3, in.Tell()); TF_CHECK_OK(in.SkipNBytes(0)); EXPECT_EQ(3, in.Tell()); TF_CHECK_OK(in.ReadNBytes(2, &read)); EXPECT_EQ(read, "34"); EXPECT_EQ(5, in.Tell()); TF_CHECK_OK(in.SkipNBytes(0)); EXPECT_EQ(5, in.Tell()); TF_CHECK_OK(in.SkipNBytes(2)); EXPECT_EQ(7, in.Tell()); TF_CHECK_OK(in.ReadNBytes(1, &read)); EXPECT_EQ(read, "7"); EXPECT_EQ(8, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.SkipNBytes(5))); EXPECT_EQ(10, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.SkipNBytes(5))); EXPECT_EQ(10, in.Tell()); EXPECT_TRUE(errors::IsOutOfRange(in.ReadNBytes(5, &read))); EXPECT_EQ(read, ""); EXPECT_EQ(10, in.Tell()); } } TEST(InputBuffer, Seek) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK(WriteStringToFile(env, fname, "0123456789")); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessFile> file; TF_CHECK_OK(env->NewRandomAccessFile(fname, &file)); string read; io::InputBuffer in(file.get(), buf_size); TF_CHECK_OK(in.ReadNBytes(3, &read)); EXPECT_EQ(read, "012"); TF_CHECK_OK(in.ReadNBytes(3, &read)); EXPECT_EQ(read, "345"); TF_CHECK_OK(in.Seek(0)); TF_CHECK_OK(in.ReadNBytes(3, &read)); EXPECT_EQ(read, "012"); TF_CHECK_OK(in.Seek(3)); TF_CHECK_OK(in.ReadNBytes(4, &read)); EXPECT_EQ(read, "3456"); TF_CHECK_OK(in.Seek(4)); TF_CHECK_OK(in.ReadNBytes(4, &read)); EXPECT_EQ(read, "4567"); TF_CHECK_OK(in.Seek(1 << 25)); EXPECT_TRUE(errors::IsOutOfRange(in.ReadNBytes(1, &read))); EXPECT_TRUE(absl::StrContains(in.Seek(-1).ToString(), "negative position")); } } TEST(InputBuffer, ReadVarint32) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); std::vector<uint32> data; uint32 i = 0; for (; i < (1U << 10); i += 1) data.push_back(i); for (; i < (1U << 15); i += 5) data.push_back(i); for (; i < (1U << 31); i += 132817) data.push_back(i); data.push_back(std::numeric_limits<uint32>::max()); { std::unique_ptr<WritableFile> file; TF_CHECK_OK(env->NewWritableFile(fname, &file)); string varint; for (uint32 number : data) { varint.clear(); core::PutVarint32(&varint, number); TF_CHECK_OK(file->Append(StringPiece(varint))); } } for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessFile> file; TF_CHECK_OK(env->NewRandomAccessFile(fname, &file)); io::InputBuffer in(file.get(), buf_size); uint32 result = 0; for (uint32 expected : data) { TF_ASSERT_OK(in.ReadVarint32(&result)); EXPECT_EQ(expected, result); } EXPECT_TRUE(errors::IsOutOfRange(in.ReadVarint32(&result))); } } TEST(InputBuffer, ReadVarint64) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); std::vector<uint64> data; uint64 i = 0; for (; i < (1U << 10); i += 1) data.push_back(i); for (; i < (1U << 15); i += 5) data.push_back(i); for (; i < (1U << 31); i += 164817) data.push_back(i); for (; i < (1ULL << 63); i += 16481797854795663UL) data.push_back(i); data.push_back(std::numeric_limits<uint64>::max()); { std::unique_ptr<WritableFile> file; TF_CHECK_OK(env->NewWritableFile(fname, &file)); string varint; for (uint64 number : data) { varint.clear(); core::PutVarint64(&varint, number); TF_CHECK_OK(file->Append(StringPiece(varint))); } } for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessFile> file; TF_CHECK_OK(env->NewRandomAccessFile(fname, &file)); io::InputBuffer in(file.get(), buf_size); uint64 result = 0; for (uint64 expected : data) { TF_ASSERT_OK(in.ReadVarint64(&result)); EXPECT_EQ(expected, result); } EXPECT_TRUE(errors::IsOutOfRange(in.ReadVarint64(&result))); } } TEST(InputBuffer, Hint) { Env* env = Env::Default(); string fname; ASSERT_TRUE(env->LocalTempFilename(&fname)); TF_ASSERT_OK(WriteStringToFile(env, fname, "0123456789")); for (auto buf_size : BufferSizes()) { std::unique_ptr<RandomAccessFile> file; TF_CHECK_OK(env->NewRandomAccessFile(fname, &file)); string read; io::InputBuffer in(file.get(), buf_size); TF_CHECK_OK(in.ReadNBytes(3, &read)); EXPECT_EQ(read, "012"); TF_CHECK_OK(in.Hint(4)); TF_CHECK_OK(in.ReadNBytes(3, &read)); EXPECT_EQ(read, "345"); TF_CHECK_OK(in.Hint(1)); TF_CHECK_OK(in.ReadNBytes(3, &read)); EXPECT_EQ(read, "678"); TF_CHECK_OK(in.Seek(0)); TF_CHECK_OK(in.Hint(7)); TF_CHECK_OK(in.ReadNBytes(3, &read)); EXPECT_EQ(read, "012"); TF_CHECK_OK(in.ReadNBytes(4, &read)); EXPECT_EQ(read, "3456"); TF_CHECK_OK(in.Hint(2)); TF_CHECK_OK(in.Seek(4)); TF_CHECK_OK(in.ReadNBytes(4, &read)); EXPECT_EQ(read, "4567"); TF_CHECK_OK(in.Seek(0)); TF_CHECK_OK(in.Hint(1 << 25)); TF_CHECK_OK(in.Seek(1 << 25)); EXPECT_TRUE(errors::IsOutOfRange(in.Hint(1))); EXPECT_TRUE(errors::IsInvalidArgument(in.Hint(-1))); } } } }
2,321
#ifndef TENSORFLOW_TSL_LIB_IO_CACHE_H_ #define TENSORFLOW_TSL_LIB_IO_CACHE_H_ #include <cstdint> #include "tsl/platform/stringpiece.h" namespace tsl { using Slice = StringPiece; namespace table { class Cache; Cache* NewLRUCache(size_t capacity); class Cache { public: Cache() = default; Cache(const Cache&) = delete; Cache& operator=(const Cache&) = delete; virtual ~Cache(); struct Handle {}; virtual Handle* Insert(const Slice& key, void* value, size_t charge, void (*deleter)(const Slice& key, void* value)) = 0; virtual Handle* Lookup(const Slice& key) = 0; virtual void Release(Handle* handle) = 0; virtual void* Value(Handle* handle) = 0; virtual void Erase(const Slice& key) = 0; virtual uint64_t NewId() = 0; virtual void Prune() {} virtual size_t TotalCharge() const = 0; private: void LRU_Remove(Handle* e); void LRU_Append(Handle* e); void Unref(Handle* e); struct Rep; Rep* rep_; }; } } #endif #include "tsl/lib/io/cache.h" #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "tsl/platform/mutex.h" #include "tsl/platform/raw_coding.h" namespace tsl { namespace table { Cache::~Cache() {} namespace { struct LRUHandle { void* value; void (*deleter)(const Slice&, void* value); LRUHandle* next_hash; LRUHandle* next; LRUHandle* prev; size_t charge; size_t key_length; bool in_cache; uint32_t refs; uint32_t hash; char key_data[1]; Slice key() const { assert(next != this); return Slice(key_data, key_length); } }; class HandleTable { public: HandleTable() : length_(0), elems_(0), list_(nullptr) { Resize(); } ~HandleTable() { delete[] list_; } LRUHandle* Lookup(const Slice& key, uint32_t hash) { return *FindPointer(key, hash); } LRUHandle* Insert(LRUHandle* h) { LRUHandle** ptr = FindPointer(h->key(), h->hash); LRUHandle* old = *ptr; h->next_hash = (old == nullptr ? nullptr : old->next_hash); *ptr = h; if (old == nullptr) { ++elems_; if (elems_ > length_) { Resize(); } } return old; } LRUHandle* Remove(const Slice& key, uint32_t hash) { LRUHandle** ptr = FindPointer(key, hash); LRUHandle* result = *ptr; if (result != nullptr) { *ptr = result->next_hash; --elems_; } return result; } private: uint32_t length_; uint32_t elems_; LRUHandle** list_; LRUHandle** FindPointer(const Slice& key, uint32_t hash) { LRUHandle** ptr = &list_[hash & (length_ - 1)]; while (*ptr != nullptr && ((*ptr)->hash != hash || key != (*ptr)->key())) { ptr = &(*ptr)->next_hash; } return ptr; } void Resize() { uint32_t new_length = 4; while (new_length < elems_) { new_length *= 2; } LRUHandle** new_list = new LRUHandle*[new_length]; memset(new_list, 0, sizeof(new_list[0]) * new_length); uint32_t count = 0; for (uint32_t i = 0; i < length_; i++) { LRUHandle* h = list_[i]; while (h != nullptr) { LRUHandle* next = h->next_hash; uint32_t hash = h->hash; LRUHandle** ptr = &new_list[hash & (new_length - 1)]; h->next_hash = *ptr; *ptr = h; h = next; count++; } } assert(elems_ == count); delete[] list_; list_ = new_list; length_ = new_length; } }; class LRUCache { public: LRUCache(); ~LRUCache(); void SetCapacity(size_t capacity) { capacity_ = capacity; } Cache::Handle* Insert(const Slice& key, uint32_t hash, void* value, size_t charge, void (*deleter)(const Slice& key, void* value)); Cache::Handle* Lookup(const Slice& key, uint32_t hash); void Release(Cache::Handle* handle); void Erase(const Slice& key, uint32_t hash); void Prune(); size_t TotalCharge() const { mutex_lock l(mutex_); return usage_; } private: void LRU_Remove(LRUHandle* e); void LRU_Append(LRUHandle* list, LRUHandle* e); void Ref(LRUHandle* e); void Unref(LRUHandle* e); bool FinishErase(LRUHandle* e) TF_EXCLUSIVE_LOCKS_REQUIRED(mutex_); size_t capacity_; mutable mutex mutex_; size_t usage_ TF_GUARDED_BY(mutex_); LRUHandle lru_ TF_GUARDED_BY(mutex_); LRUHandle in_use_ TF_GUARDED_BY(mutex_); HandleTable table_ TF_GUARDED_BY(mutex_); }; LRUCache::LRUCache() : capacity_(0), usage_(0) { lru_.next = &lru_; lru_.prev = &lru_; in_use_.next = &in_use_; in_use_.prev = &in_use_; } LRUCache::~LRUCache() { assert(in_use_.next == &in_use_); for (LRUHandle* e = lru_.next; e != &lru_;) { LRUHandle* next = e->next; assert(e->in_cache); e->in_cache = false; assert(e->refs == 1); Unref(e); e = next; } } void LRUCache::Ref(LRUHandle* e) { if (e->refs == 1 && e->in_cache) { LRU_Remove(e); LRU_Append(&in_use_, e); } e->refs++; } void LRUCache::Unref(LRUHandle* e) { assert(e->refs > 0); e->refs--; if (e->refs == 0) { assert(!e->in_cache); (*e->deleter)(e->key(), e->value); free(e); } else if (e->in_cache && e->refs == 1) { LRU_Remove(e); LRU_Append(&lru_, e); } } void LRUCache::LRU_Remove(LRUHandle* e) { e->next->prev = e->prev; e->prev->next = e->next; } void LRUCache::LRU_Append(LRUHandle* list, LRUHandle* e) { e->next = list; e->prev = list->prev; e->prev->next = e; e->next->prev = e; } Cache::Handle* LRUCache::Lookup(const Slice& key, uint32_t hash) { mutex_lock l(mutex_); LRUHandle* e = table_.Lookup(key, hash); if (e != nullptr) { Ref(e); } return reinterpret_cast<Cache::Handle*>(e); } void LRUCache::Release(Cache::Handle* handle) { mutex_lock l(mutex_); Unref(reinterpret_cast<LRUHandle*>(handle)); } Cache::Handle* LRUCache::Insert(const Slice& key, uint32_t hash, void* value, size_t charge, void (*deleter)(const Slice& key, void* value)) { mutex_lock l(mutex_); LRUHandle* e = reinterpret_cast<LRUHandle*>(malloc(sizeof(LRUHandle) - 1 + key.size())); e->value = value; e->deleter = deleter; e->charge = charge; e->key_length = key.size(); e->hash = hash; e->in_cache = false; e->refs = 1; memcpy(e->key_data, key.data(), key.size()); if (capacity_ > 0) { e->refs++; e->in_cache = true; LRU_Append(&in_use_, e); usage_ += charge; FinishErase(table_.Insert(e)); } else { e->next = nullptr; } while (usage_ > capacity_ && lru_.next != &lru_) { LRUHandle* old = lru_.next; assert(old->refs == 1); bool erased = FinishErase(table_.Remove(old->key(), old->hash)); if (!erased) { assert(erased); } } return reinterpret_cast<Cache::Handle*>(e); } bool LRUCache::FinishErase(LRUHandle* e) { if (e != nullptr) { assert(e->in_cache); LRU_Remove(e); e->in_cache = false; usage_ -= e->charge; Unref(e); } return e != nullptr; } void LRUCache::Erase(const Slice& key, uint32_t hash) { mutex_lock l(mutex_); FinishErase(table_.Remove(key, hash)); } void LRUCache::Prune() { mutex_lock l(mutex_); while (lru_.next != &lru_) { LRUHandle* e = lru_.next; assert(e->refs == 1); bool erased = FinishErase(table_.Remove(e->key(), e->hash)); if (!erased) { assert(erased); } } } static const int kNumShardBits = 4; static const int kNumShards = 1 << kNumShardBits; class ShardedLRUCache : public Cache { private: LRUCache shard_[kNumShards]; mutex id_mutex_; uint64_t last_id_; static inline uint32_t HashSlice(const Slice& s) { return Hash(s.data(), s.size(), 0); } static uint32_t Shard(uint32_t hash) { return hash >> (32 - kNumShardBits); } public: explicit ShardedLRUCache(size_t capacity) : last_id_(0) { const size_t per_shard = (capacity + (kNumShards - 1)) / kNumShards; for (int s = 0; s < kNumShards; s++) { shard_[s].SetCapacity(per_shard); } } ~ShardedLRUCache() override {} Handle* Insert(const Slice& key, void* value, size_t charge, void (*deleter)(const Slice& key, void* value)) override { const uint32_t hash = HashSlice(key); return shard_[Shard(hash)].Insert(key, hash, value, charge, deleter); } Handle* Lookup(const Slice& key) override { const uint32_t hash = HashSlice(key); return shard_[Shard(hash)].Lookup(key, hash); } void Release(Handle* handle) override { LRUHandle* h = reinterpret_cast<LRUHandle*>(handle); shard_[Shard(h->hash)].Release(handle); } void Erase(const Slice& key) override { const uint32_t hash = HashSlice(key); shard_[Shard(hash)].Erase(key, hash); } void* Value(Handle* handle) override { return reinterpret_cast<LRUHandle*>(handle)->value; } uint64_t NewId() override { mutex_lock l(id_mutex_); return ++(last_id_); } void Prune() override { for (int s = 0; s < kNumShards; s++) { shard_[s].Prune(); } } size_t TotalCharge() const override { size_t total = 0; for (int s = 0; s < kNumShards; s++) { total += shard_[s].TotalCharge(); } return total; } private: static uint32_t Hash(const char* data, size_t n, uint32_t seed) { const uint32_t m = 0xc6a4a793; const uint32_t r = 24; const char* limit = data + n; uint32_t h = seed ^ (n * m); while (data + 4 <= limit) { uint32_t w = core::DecodeFixed32(data); data += 4; h += w; h *= m; h ^= (h >> 16); } switch (limit - data) { case 3: h += static_cast<uint8_t>(data[2]) << 16; ABSL_FALLTHROUGH_INTENDED; case 2: h += static_cast<uint8_t>(data[1]) << 8; ABSL_FALLTHROUGH_INTENDED; case 1: h += static_cast<uint8_t>(data[0]); h *= m; h ^= (h >> r); break; } return h; } }; } Cache* NewLRUCache(size_t capacity) { return new ShardedLRUCache(capacity); } } }
#include "tsl/lib/io/cache.h" #include <string> #include <vector> #include "tsl/platform/coding.h" #include "tsl/platform/raw_coding.h" #include "tsl/platform/test.h" namespace tsl { namespace table { static std::string EncodeKey(int k) { std::string result; core::PutFixed32(&result, k); return result; } static int DecodeKey(const Slice& k) { assert(k.size() == 4); return core::DecodeFixed32(k.data()); } static void* EncodeValue(uintptr_t v) { return reinterpret_cast<void*>(v); } static int DecodeValue(void* v) { return reinterpret_cast<uintptr_t>(v); } class CacheTest : public ::testing::Test { public: static void Deleter(const Slice& key, void* v) { current_->deleted_keys_.push_back(DecodeKey(key)); current_->deleted_values_.push_back(DecodeValue(v)); } static constexpr int kCacheSize = 1000; std::vector<int> deleted_keys_; std::vector<int> deleted_values_; Cache* cache_; CacheTest() : cache_(NewLRUCache(kCacheSize)) { current_ = this; } ~CacheTest() { delete cache_; } int Lookup(int key) { Cache::Handle* handle = cache_->Lookup(EncodeKey(key)); const int r = (handle == nullptr) ? -1 : DecodeValue(cache_->Value(handle)); if (handle != nullptr) { cache_->Release(handle); } return r; } void Insert(int key, int value, int charge = 1) { cache_->Release(cache_->Insert(EncodeKey(key), EncodeValue(value), charge, &CacheTest::Deleter)); } Cache::Handle* InsertAndReturnHandle(int key, int value, int charge = 1) { return cache_->Insert(EncodeKey(key), EncodeValue(value), charge, &CacheTest::Deleter); } void Erase(int key) { cache_->Erase(EncodeKey(key)); } static CacheTest* current_; }; CacheTest* CacheTest::current_; TEST_F(CacheTest, HitAndMiss) { ASSERT_EQ(-1, Lookup(100)); Insert(100, 101); ASSERT_EQ(101, Lookup(100)); ASSERT_EQ(-1, Lookup(200)); ASSERT_EQ(-1, Lookup(300)); Insert(200, 201); ASSERT_EQ(101, Lookup(100)); ASSERT_EQ(201, Lookup(200)); ASSERT_EQ(-1, Lookup(300)); Insert(100, 102); ASSERT_EQ(102, Lookup(100)); ASSERT_EQ(201, Lookup(200)); ASSERT_EQ(-1, Lookup(300)); ASSERT_EQ(1, deleted_keys_.size()); ASSERT_EQ(100, deleted_keys_[0]); ASSERT_EQ(101, deleted_values_[0]); } TEST_F(CacheTest, Erase) { Erase(200); ASSERT_EQ(0, deleted_keys_.size()); Insert(100, 101); Insert(200, 201); Erase(100); ASSERT_EQ(-1, Lookup(100)); ASSERT_EQ(201, Lookup(200)); ASSERT_EQ(1, deleted_keys_.size()); ASSERT_EQ(100, deleted_keys_[0]); ASSERT_EQ(101, deleted_values_[0]); Erase(100); ASSERT_EQ(-1, Lookup(100)); ASSERT_EQ(201, Lookup(200)); ASSERT_EQ(1, deleted_keys_.size()); } TEST_F(CacheTest, EntriesArePinned) { Insert(100, 101); Cache::Handle* h1 = cache_->Lookup(EncodeKey(100)); ASSERT_EQ(101, DecodeValue(cache_->Value(h1))); Insert(100, 102); Cache::Handle* h2 = cache_->Lookup(EncodeKey(100)); ASSERT_EQ(102, DecodeValue(cache_->Value(h2))); ASSERT_EQ(0, deleted_keys_.size()); cache_->Release(h1); ASSERT_EQ(1, deleted_keys_.size()); ASSERT_EQ(100, deleted_keys_[0]); ASSERT_EQ(101, deleted_values_[0]); Erase(100); ASSERT_EQ(-1, Lookup(100)); ASSERT_EQ(1, deleted_keys_.size()); cache_->Release(h2); ASSERT_EQ(2, deleted_keys_.size()); ASSERT_EQ(100, deleted_keys_[1]); ASSERT_EQ(102, deleted_values_[1]); } TEST_F(CacheTest, EvictionPolicy) { Insert(100, 101); Insert(200, 201); Insert(300, 301); Cache::Handle* h = cache_->Lookup(EncodeKey(300)); for (int i = 0; i < kCacheSize + 100; i++) { Insert(1000 + i, 2000 + i); ASSERT_EQ(2000 + i, Lookup(1000 + i)); ASSERT_EQ(101, Lookup(100)); } ASSERT_EQ(101, Lookup(100)); ASSERT_EQ(-1, Lookup(200)); ASSERT_EQ(301, Lookup(300)); cache_->Release(h); } TEST_F(CacheTest, UseExceedsCacheSize) { std::vector<Cache::Handle*> h; for (int i = 0; i < kCacheSize + 100; i++) { h.push_back(InsertAndReturnHandle(1000 + i, 2000 + i)); } for (int i = 0; i < h.size(); i++) { ASSERT_EQ(2000 + i, Lookup(1000 + i)); } for (int i = 0; i < h.size(); i++) { cache_->Release(h[i]); } } TEST_F(CacheTest, HeavyEntries) { const int kLight = 1; const int kHeavy = 10; int added = 0; int index = 0; while (added < 2 * kCacheSize) { const int weight = (index & 1) ? kLight : kHeavy; Insert(index, 1000 + index, weight); added += weight; index++; } int cached_weight = 0; for (int i = 0; i < index; i++) { const int weight = (i & 1 ? kLight : kHeavy); int r = Lookup(i); if (r >= 0) { cached_weight += weight; ASSERT_EQ(1000 + i, r); } } ASSERT_LE(cached_weight, kCacheSize + kCacheSize / 10); } TEST_F(CacheTest, NewId) { uint64_t a = cache_->NewId(); uint64_t b = cache_->NewId(); ASSERT_NE(a, b); } TEST_F(CacheTest, Prune) { Insert(1, 100); Insert(2, 200); Cache::Handle* handle = cache_->Lookup(EncodeKey(1)); ASSERT_TRUE(handle); cache_->Prune(); cache_->Release(handle); ASSERT_EQ(100, Lookup(1)); ASSERT_EQ(-1, Lookup(2)); } TEST_F(CacheTest, ZeroSizeCache) { delete cache_; cache_ = NewLRUCache(0); Insert(1, 100); ASSERT_EQ(-1, Lookup(1)); } } }
2,322
#ifndef TENSORFLOW_TSL_LIB_IO_INPUTSTREAM_INTERFACE_H_ #define TENSORFLOW_TSL_LIB_IO_INPUTSTREAM_INTERFACE_H_ #include <string> #include "tsl/platform/cord.h" #include "tsl/platform/errors.h" #include "tsl/platform/status.h" #include "tsl/platform/types.h" namespace tsl { namespace io { class InputStreamInterface { public: InputStreamInterface() {} virtual ~InputStreamInterface() {} virtual absl::Status ReadNBytes(int64_t bytes_to_read, tstring* result) = 0; #if defined(TF_CORD_SUPPORT) virtual absl::Status ReadNBytes(int64_t bytes_to_read, absl::Cord* cord) { return errors::Unimplemented( "ReadNBytes(int64, absl::Cord*) is not implemented."); } #endif virtual absl::Status SkipNBytes(int64_t bytes_to_skip); virtual int64_t Tell() const = 0; virtual absl::Status Reset() = 0; }; } } #endif #include "tsl/lib/io/inputstream_interface.h" #include "tsl/platform/errors.h" namespace tsl { namespace io { static constexpr int64_t kMaxSkipSize = 8 * 1024 * 1024; absl::Status InputStreamInterface::SkipNBytes(int64_t bytes_to_skip) { if (bytes_to_skip < 0) { return errors::InvalidArgument("Can't skip a negative number of bytes"); } tstring unused; while (bytes_to_skip > 0) { int64_t bytes_to_read = std::min<int64_t>(kMaxSkipSize, bytes_to_skip); TF_RETURN_IF_ERROR(ReadNBytes(bytes_to_read, &unused)); bytes_to_skip -= bytes_to_read; } return absl::OkStatus(); } } }
#include "tsl/lib/io/inputstream_interface.h" #include "tsl/lib/core/status_test_util.h" #include "tsl/platform/errors.h" #include "tsl/platform/test.h" namespace tsl { namespace io { namespace { class TestStringStream : public InputStreamInterface { public: explicit TestStringStream(const string& content) : content_(content) {} absl::Status ReadNBytes(int64_t bytes_to_read, tstring* result) override { result->clear(); if (pos_ + bytes_to_read > content_.size()) { return errors::OutOfRange("limit reached"); } *result = content_.substr(pos_, bytes_to_read); pos_ += bytes_to_read; return absl::OkStatus(); } int64_t Tell() const override { return pos_; } absl::Status Reset() override { pos_ = 0; return absl::OkStatus(); } private: string content_; int64_t pos_ = 0; }; TEST(InputStreamInterface, Basic) { TestStringStream ss("This is a test string"); tstring res; TF_ASSERT_OK(ss.ReadNBytes(4, &res)); EXPECT_EQ("This", res); TF_ASSERT_OK(ss.SkipNBytes(6)); TF_ASSERT_OK(ss.ReadNBytes(11, &res)); EXPECT_EQ("test string", res); EXPECT_TRUE(errors::IsOutOfRange(ss.SkipNBytes(1))); TF_ASSERT_OK(ss.Reset()); TF_ASSERT_OK(ss.ReadNBytes(4, &res)); EXPECT_EQ("This", res); } } } }
2,323
#include "sample1.h" int Factorial(int n) { int result = 1; for (int i = 1; i <= n; i++) { result *= i; } return result; } bool IsPrime(int n) { if (n <= 1) return false; if (n % 2 == 0) return n == 2; for (int i = 3;; i += 2) { if (i > n / i) break; if (n % i == 0) return false; } return true; }
#include "sample1.h" #include <limits.h> #include "gtest/gtest.h" namespace { TEST(FactorialTest, Negative) { EXPECT_EQ(1, Factorial(-5)); EXPECT_EQ(1, Factorial(-1)); EXPECT_GT(Factorial(-10), 0); } TEST(FactorialTest, Zero) { EXPECT_EQ(1, Factorial(0)); } TEST(FactorialTest, Positive) { EXPECT_EQ(1, Factorial(1)); EXPECT_EQ(2, Factorial(2)); EXPECT_EQ(6, Factorial(3)); EXPECT_EQ(40320, Factorial(8)); } TEST(IsPrimeTest, Negative) { EXPECT_FALSE(IsPrime(-1)); EXPECT_FALSE(IsPrime(-2)); EXPECT_FALSE(IsPrime(INT_MIN)); } TEST(IsPrimeTest, Trivial) { EXPECT_FALSE(IsPrime(0)); EXPECT_FALSE(IsPrime(1)); EXPECT_TRUE(IsPrime(2)); EXPECT_TRUE(IsPrime(3)); } TEST(IsPrimeTest, Positive) { EXPECT_FALSE(IsPrime(4)); EXPECT_TRUE(IsPrime(5)); EXPECT_FALSE(IsPrime(6)); EXPECT_TRUE(IsPrime(23)); } }
2,324
#include "sample4.h" #include <stdio.h> int Counter::Increment() { return counter_++; } int Counter::Decrement() { if (counter_ == 0) { return counter_; } else { return counter_--; } } void Counter::Print() const { printf("%d", counter_); }
#include "sample4.h" #include "gtest/gtest.h" namespace { TEST(Counter, Increment) { Counter c; EXPECT_EQ(0, c.Decrement()); EXPECT_EQ(0, c.Increment()); EXPECT_EQ(1, c.Increment()); EXPECT_EQ(2, c.Increment()); EXPECT_EQ(3, c.Decrement()); } }
2,325
#include "sample2.h" #include <string.h> const char* MyString::CloneCString(const char* a_c_string) { if (a_c_string == nullptr) return nullptr; const size_t len = strlen(a_c_string); char* const clone = new char[len + 1]; memcpy(clone, a_c_string, len + 1); return clone; } void MyString::Set(const char* a_c_string) { const char* const temp = MyString::CloneCString(a_c_string); delete[] c_string_; c_string_ = temp; }
#include "sample2.h" #include "gtest/gtest.h" namespace { TEST(MyString, DefaultConstructor) { const MyString s; EXPECT_STREQ(nullptr, s.c_string()); EXPECT_EQ(0u, s.Length()); } const char kHelloString[] = "Hello, world!"; TEST(MyString, ConstructorFromCString) { const MyString s(kHelloString); EXPECT_EQ(0, strcmp(s.c_string(), kHelloString)); EXPECT_EQ(sizeof(kHelloString) / sizeof(kHelloString[0]) - 1, s.Length()); } TEST(MyString, CopyConstructor) { const MyString s1(kHelloString); const MyString s2 = s1; EXPECT_EQ(0, strcmp(s2.c_string(), kHelloString)); } TEST(MyString, Set) { MyString s; s.Set(kHelloString); EXPECT_EQ(0, strcmp(s.c_string(), kHelloString)); s.Set(s.c_string()); EXPECT_EQ(0, strcmp(s.c_string(), kHelloString)); s.Set(nullptr); EXPECT_STREQ(nullptr, s.c_string()); } }
2,326
#include <cstdio> #include "gtest/gtest.h" #if defined(GTEST_OS_ESP8266) || defined(GTEST_OS_ESP32) || \ (defined(GTEST_OS_NRF52) && defined(ARDUINO)) #ifdef GTEST_OS_ESP8266 extern "C" { #endif void setup() { testing::InitGoogleTest(); } void loop() { RUN_ALL_TESTS(); } #ifdef GTEST_OS_ESP8266 } #endif #elif defined(GTEST_OS_QURT) GTEST_API_ int main() { printf("Running main() from %s\n", __FILE__); testing::InitGoogleTest(); return RUN_ALL_TESTS(); } #else GTEST_API_ int main(int argc, char **argv) { printf("Running main() from %s\n", __FILE__); testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } #endif
#include "gtest/gtest.h" namespace { TEST(GTestMainTest, ShouldSucceed) {} }
2,327
#include "gtest/gtest-typed-test.h" #include <set> #include <string> #include <vector> #include "gtest/gtest.h" namespace testing { namespace internal { static const char* SkipSpaces(const char* str) { while (IsSpace(*str)) str++; return str; } static std::vector<std::string> SplitIntoTestNames(const char* src) { std::vector<std::string> name_vec; src = SkipSpaces(src); for (; src != nullptr; src = SkipComma(src)) { name_vec.push_back(StripTrailingSpaces(GetPrefixUntilComma(src))); } return name_vec; } const char* TypedTestSuitePState::VerifyRegisteredTestNames( const char* test_suite_name, const char* file, int line, const char* registered_tests) { RegisterTypeParameterizedTestSuite(test_suite_name, CodeLocation(file, line)); typedef RegisteredTestsMap::const_iterator RegisteredTestIter; registered_ = true; std::vector<std::string> name_vec = SplitIntoTestNames(registered_tests); Message errors; std::set<std::string> tests; for (std::vector<std::string>::const_iterator name_it = name_vec.begin(); name_it != name_vec.end(); ++name_it) { const std::string& name = *name_it; if (tests.count(name) != 0) { errors << "Test " << name << " is listed more than once.\n"; continue; } if (registered_tests_.count(name) != 0) { tests.insert(name); } else { errors << "No test named " << name << " can be found in this test suite.\n"; } } for (RegisteredTestIter it = registered_tests_.begin(); it != registered_tests_.end(); ++it) { if (tests.count(it->first) == 0) { errors << "You forgot to list test " << it->first << ".\n"; } } const std::string& errors_str = errors.GetString(); if (!errors_str.empty()) { fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(), errors_str.c_str()); fflush(stderr); posix::Abort(); } return registered_tests; } } }
#include "test/gtest-typed-test_test.h" #include <set> #include <string> #include <type_traits> #include <vector> #include "gtest/gtest.h" GTEST_DISABLE_MSC_WARNINGS_PUSH_(4127 ) using testing::Test; template <typename T> class CommonTest : public Test { public: static void SetUpTestSuite() { shared_ = new T(5); } static void TearDownTestSuite() { delete shared_; shared_ = nullptr; } protected: typedef std::vector<T> Vector; typedef std::set<int> IntSet; CommonTest() : value_(1) {} ~CommonTest() override { EXPECT_EQ(3, value_); } void SetUp() override { EXPECT_EQ(1, value_); value_++; } void TearDown() override { EXPECT_EQ(2, value_); value_++; } T value_; static T* shared_; }; template <typename T> T* CommonTest<T>::shared_ = nullptr; using testing::Types; typedef Types<char, int> TwoTypes; TYPED_TEST_SUITE(CommonTest, TwoTypes); TYPED_TEST(CommonTest, ValuesAreCorrect) { EXPECT_EQ(5, *TestFixture::shared_); typename TestFixture::Vector empty; EXPECT_EQ(0U, empty.size()); typename TestFixture::IntSet empty2; EXPECT_EQ(0U, empty2.size()); EXPECT_EQ(2, this->value_); } TYPED_TEST(CommonTest, ValuesAreStillCorrect) { ASSERT_TRUE(this->shared_ != nullptr); EXPECT_EQ(5, *this->shared_); EXPECT_EQ(static_cast<TypeParam>(2), this->value_); } template <typename T> class TypedTest1 : public Test {}; TYPED_TEST_SUITE(TypedTest1, int); TYPED_TEST(TypedTest1, A) {} template <typename T> class TypedTest2 : public Test {}; TYPED_TEST_SUITE(TypedTest2, Types<int>); TYPED_TEST(TypedTest2, A) {} namespace library1 { template <typename T> class NumericTest : public Test {}; typedef Types<int, long> NumericTypes; TYPED_TEST_SUITE(NumericTest, NumericTypes); TYPED_TEST(NumericTest, DefaultIsZero) { EXPECT_EQ(0, TypeParam()); } } template <typename T> class TypedTestWithNames : public Test {}; class TypedTestNames { public: template <typename T> static std::string GetName(int i) { if (std::is_same<T, char>::value) { return std::string("char") + ::testing::PrintToString(i); } if (std::is_same<T, int>::value) { return std::string("int") + ::testing::PrintToString(i); } } }; TYPED_TEST_SUITE(TypedTestWithNames, TwoTypes, TypedTestNames); TYPED_TEST(TypedTestWithNames, TestSuiteName) { if (std::is_same<TypeParam, char>::value) { EXPECT_STREQ(::testing::UnitTest::GetInstance() ->current_test_info() ->test_suite_name(), "TypedTestWithNames/char0"); } if (std::is_same<TypeParam, int>::value) { EXPECT_STREQ(::testing::UnitTest::GetInstance() ->current_test_info() ->test_suite_name(), "TypedTestWithNames/int1"); } } using testing::Types; using testing::internal::TypedTestSuitePState; class TypedTestSuitePStateTest : public Test { protected: void SetUp() override { state_.AddTestName("foo.cc", 0, "FooTest", "A"); state_.AddTestName("foo.cc", 0, "FooTest", "B"); state_.AddTestName("foo.cc", 0, "FooTest", "C"); } TypedTestSuitePState state_; }; TEST_F(TypedTestSuitePStateTest, SucceedsForMatchingList) { const char* tests = "A, B, C"; EXPECT_EQ(tests, state_.VerifyRegisteredTestNames("Suite", "foo.cc", 1, tests)); } TEST_F(TypedTestSuitePStateTest, IgnoresOrderAndSpaces) { const char* tests = "A,C, B"; EXPECT_EQ(tests, state_.VerifyRegisteredTestNames("Suite", "foo.cc", 1, tests)); } using TypedTestSuitePStateDeathTest = TypedTestSuitePStateTest; TEST_F(TypedTestSuitePStateDeathTest, DetectsDuplicates) { EXPECT_DEATH_IF_SUPPORTED( state_.VerifyRegisteredTestNames("Suite", "foo.cc", 1, "A, B, A, C"), "foo\\.cc.1.?: Test A is listed more than once\\."); } TEST_F(TypedTestSuitePStateDeathTest, DetectsExtraTest) { EXPECT_DEATH_IF_SUPPORTED( state_.VerifyRegisteredTestNames("Suite", "foo.cc", 1, "A, B, C, D"), "foo\\.cc.1.?: No test named D can be found in this test suite\\."); } TEST_F(TypedTestSuitePStateDeathTest, DetectsMissedTest) { EXPECT_DEATH_IF_SUPPORTED( state_.VerifyRegisteredTestNames("Suite", "foo.cc", 1, "A, C"), "foo\\.cc.1.?: You forgot to list test B\\."); } TEST_F(TypedTestSuitePStateDeathTest, DetectsTestAfterRegistration) { state_.VerifyRegisteredTestNames("Suite", "foo.cc", 1, "A, B, C"); EXPECT_DEATH_IF_SUPPORTED( state_.AddTestName("foo.cc", 2, "FooTest", "D"), "foo\\.cc.2.?: Test D must be defined before REGISTER_TYPED_TEST_SUITE_P" "\\(FooTest, \\.\\.\\.\\)\\."); } template <typename T> class DerivedTest : public CommonTest<T> {}; TYPED_TEST_SUITE_P(DerivedTest); TYPED_TEST_P(DerivedTest, ValuesAreCorrect) { EXPECT_EQ(5, *TestFixture::shared_); EXPECT_EQ(2, this->value_); } TYPED_TEST_P(DerivedTest, ValuesAreStillCorrect) { ASSERT_TRUE(this->shared_ != nullptr); EXPECT_EQ(5, *this->shared_); EXPECT_EQ(2, this->value_); } REGISTER_TYPED_TEST_SUITE_P(DerivedTest, ValuesAreCorrect, ValuesAreStillCorrect); typedef Types<short, long> MyTwoTypes; INSTANTIATE_TYPED_TEST_SUITE_P(My, DerivedTest, MyTwoTypes); template <typename T> class TypeParametrizedTestWithNames : public Test {}; TYPED_TEST_SUITE_P(TypeParametrizedTestWithNames); TYPED_TEST_P(TypeParametrizedTestWithNames, TestSuiteName) { if (std::is_same<TypeParam, char>::value) { EXPECT_STREQ(::testing::UnitTest::GetInstance() ->current_test_info() ->test_suite_name(), "CustomName/TypeParametrizedTestWithNames/parChar0"); } if (std::is_same<TypeParam, int>::value) { EXPECT_STREQ(::testing::UnitTest::GetInstance() ->current_test_info() ->test_suite_name(), "CustomName/TypeParametrizedTestWithNames/parInt1"); } } REGISTER_TYPED_TEST_SUITE_P(TypeParametrizedTestWithNames, TestSuiteName); class TypeParametrizedTestNames { public: template <typename T> static std::string GetName(int i) { if (std::is_same<T, char>::value) { return std::string("parChar") + ::testing::PrintToString(i); } if (std::is_same<T, int>::value) { return std::string("parInt") + ::testing::PrintToString(i); } } }; INSTANTIATE_TYPED_TEST_SUITE_P(CustomName, TypeParametrizedTestWithNames, TwoTypes, TypeParametrizedTestNames); template <typename T> class TypedTestP1 : public Test {}; TYPED_TEST_SUITE_P(TypedTestP1); using IntAfterTypedTestSuiteP = int; TYPED_TEST_P(TypedTestP1, A) {} TYPED_TEST_P(TypedTestP1, B) {} using IntBeforeRegisterTypedTestSuiteP = int; REGISTER_TYPED_TEST_SUITE_P(TypedTestP1, A, B); template <typename T> class TypedTestP2 : public Test {}; TYPED_TEST_SUITE_P(TypedTestP2); TYPED_TEST_P(TypedTestP2, A) {} REGISTER_TYPED_TEST_SUITE_P(TypedTestP2, A); IntAfterTypedTestSuiteP after = 0; IntBeforeRegisterTypedTestSuiteP before = 0; INSTANTIATE_TYPED_TEST_SUITE_P(Int, TypedTestP1, int); INSTANTIATE_TYPED_TEST_SUITE_P(Int, TypedTestP2, Types<int>); INSTANTIATE_TYPED_TEST_SUITE_P(Double, TypedTestP2, Types<double>); typedef Types<std::vector<double>, std::set<char> > MyContainers; INSTANTIATE_TYPED_TEST_SUITE_P(My, ContainerTest, MyContainers); namespace library2 { template <typename T> class NumericTest : public Test {}; TYPED_TEST_SUITE_P(NumericTest); TYPED_TEST_P(NumericTest, DefaultIsZero) { EXPECT_EQ(0, TypeParam()); } TYPED_TEST_P(NumericTest, ZeroIsLessThanOne) { EXPECT_LT(TypeParam(0), TypeParam(1)); } REGISTER_TYPED_TEST_SUITE_P(NumericTest, DefaultIsZero, ZeroIsLessThanOne); typedef Types<int, double> NumericTypes; INSTANTIATE_TYPED_TEST_SUITE_P(My, NumericTest, NumericTypes); static const char* GetTestName() { return testing::UnitTest::GetInstance()->current_test_info()->name(); } template <typename T> class TrimmedTest : public Test {}; TYPED_TEST_SUITE_P(TrimmedTest); TYPED_TEST_P(TrimmedTest, Test1) { EXPECT_STREQ("Test1", GetTestName()); } TYPED_TEST_P(TrimmedTest, Test2) { EXPECT_STREQ("Test2", GetTestName()); } TYPED_TEST_P(TrimmedTest, Test3) { EXPECT_STREQ("Test3", GetTestName()); } TYPED_TEST_P(TrimmedTest, Test4) { EXPECT_STREQ("Test4", GetTestName()); } TYPED_TEST_P(TrimmedTest, Test5) { EXPECT_STREQ("Test5", GetTestName()); } REGISTER_TYPED_TEST_SUITE_P(TrimmedTest, Test1, Test2, Test3, Test4, Test5); template <typename T1, typename T2> struct MyPair {}; typedef Types<int, double, MyPair<int, int> > TrimTypes; INSTANTIATE_TYPED_TEST_SUITE_P(My, TrimmedTest, TrimTypes); } GTEST_DISABLE_MSC_WARNINGS_POP_()
2,328
#include "gtest/gtest.h" #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <wchar.h> #include <wctype.h> #include <algorithm> #include <chrono> #include <cmath> #include <csignal> #include <cstdint> #include <cstdlib> #include <cstring> #include <initializer_list> #include <iomanip> #include <ios> #include <iostream> #include <iterator> #include <limits> #include <list> #include <map> #include <ostream> #include <set> #include <sstream> #include <unordered_set> #include <utility> #include <vector> #include "gtest/gtest-assertion-result.h" #include "gtest/gtest-spi.h" #include "gtest/internal/custom/gtest.h" #include "gtest/internal/gtest-port.h" #ifdef GTEST_OS_LINUX #include <fcntl.h> #include <limits.h> #include <sched.h> #include <strings.h> #include <sys/mman.h> #include <sys/time.h> #include <unistd.h> #include <string> #elif defined(GTEST_OS_ZOS) #include <sys/time.h> #include <strings.h> #elif defined(GTEST_OS_WINDOWS_MOBILE) #include <windows.h> #undef min #elif defined(GTEST_OS_WINDOWS) #include <windows.h> #undef min #ifdef _MSC_VER #include <crtdbg.h> #endif #include <io.h> #include <sys/stat.h> #include <sys/timeb.h> #include <sys/types.h> #ifdef GTEST_OS_WINDOWS_MINGW #include <sys/time.h> #endif #else #include <sys/time.h> #include <unistd.h> #endif #if GTEST_HAS_EXCEPTIONS #include <stdexcept> #endif #if GTEST_CAN_STREAM_RESULTS_ #include <arpa/inet.h> #include <netdb.h> #include <sys/socket.h> #include <sys/types.h> #endif #include "src/gtest-internal-inl.h" #ifdef GTEST_OS_WINDOWS #define vsnprintf _vsnprintf #endif #ifdef GTEST_OS_MAC #ifndef GTEST_OS_IOS #include <crt_externs.h> #endif #endif #ifdef GTEST_HAS_ABSL #include "absl/container/flat_hash_set.h" #include "absl/debugging/failure_signal_handler.h" #include "absl/debugging/stacktrace.h" #include "absl/debugging/symbolize.h" #include "absl/flags/parse.h" #include "absl/flags/usage.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_replace.h" #include "absl/strings/string_view.h" #include "absl/strings/strip.h" #endif #if defined(__has_builtin) #define GTEST_HAS_BUILTIN(x) __has_builtin(x) #else #define GTEST_HAS_BUILTIN(x) 0 #endif #if defined(GTEST_HAS_ABSL) && !defined(GTEST_NO_ABSL_FLAGS) #define GTEST_HAS_ABSL_FLAGS #endif namespace testing { using internal::CountIf; using internal::ForEach; using internal::GetElementOr; using internal::Shuffle; static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*"; static const char kDeathTestSuiteFilter[] = "*DeathTest:*DeathTest/*"; static const char kUniversalFilter[] = "*"; static const char kDefaultOutputFormat[] = "xml"; static const char kDefaultOutputFile[] = "test_detail"; static const char kTestShardIndex[] = "GTEST_SHARD_INDEX"; static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS"; static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE"; namespace internal { const char kStackTraceMarker[] = "\nStack trace:\n"; bool g_help_flag = false; #if GTEST_HAS_FILE_SYSTEM static FILE* OpenFileForWriting(const std::string& output_file) { FILE* fileout = nullptr; FilePath output_file_path(output_file); FilePath output_dir(output_file_path.RemoveFileName()); if (output_dir.CreateDirectoriesRecursively()) { fileout = posix::FOpen(output_file.c_str(), "w"); } if (fileout == nullptr) { GTEST_LOG_(FATAL) << "Unable to open file \"" << output_file << "\""; } return fileout; } #endif } static const char* GetDefaultFilter() { const char* const testbridge_test_only = internal::posix::GetEnv("TESTBRIDGE_TEST_ONLY"); if (testbridge_test_only != nullptr) { return testbridge_test_only; } return kUniversalFilter; } static bool GetDefaultFailFast() { const char* const testbridge_test_runner_fail_fast = internal::posix::GetEnv("TESTBRIDGE_TEST_RUNNER_FAIL_FAST"); if (testbridge_test_runner_fail_fast != nullptr) { return strcmp(testbridge_test_runner_fail_fast, "1") == 0; } return false; } } GTEST_DEFINE_bool_( fail_fast, testing::internal::BoolFromGTestEnv("fail_fast", testing::GetDefaultFailFast()), "True if and only if a test failure should stop further test execution."); GTEST_DEFINE_bool_( also_run_disabled_tests, testing::internal::BoolFromGTestEnv("also_run_disabled_tests", false), "Run disabled tests too, in addition to the tests normally being run."); GTEST_DEFINE_bool_( break_on_failure, testing::internal::BoolFromGTestEnv("break_on_failure", false), "True if and only if a failed assertion should be a debugger " "break-point."); GTEST_DEFINE_bool_(catch_exceptions, testing::internal::BoolFromGTestEnv("catch_exceptions", true), "True if and only if " GTEST_NAME_ " should catch exceptions and treat them as test failures."); GTEST_DEFINE_string_( color, testing::internal::StringFromGTestEnv("color", "auto"), "Whether to use colors in the output. Valid values: yes, no, " "and auto. 'auto' means to use colors if the output is " "being sent to a terminal and the TERM environment variable " "is set to a terminal type that supports colors."); GTEST_DEFINE_string_( filter, testing::internal::StringFromGTestEnv("filter", testing::GetDefaultFilter()), "A colon-separated list of glob (not regex) patterns " "for filtering the tests to run, optionally followed by a " "'-' and a : separated list of negative patterns (tests to " "exclude). A test is run if it matches one of the positive " "patterns and does not match any of the negative patterns."); GTEST_DEFINE_bool_( install_failure_signal_handler, testing::internal::BoolFromGTestEnv("install_failure_signal_handler", false), "If true and supported on the current platform, " GTEST_NAME_ " should " "install a signal handler that dumps debugging information when fatal " "signals are raised."); GTEST_DEFINE_bool_(list_tests, false, "List all tests without running them."); GTEST_DEFINE_string_( output, testing::internal::StringFromGTestEnv( "output", testing::internal::OutputFlagAlsoCheckEnvVar().c_str()), "A format (defaults to \"xml\" but can be specified to be \"json\"), " "optionally followed by a colon and an output file name or directory. " "A directory is indicated by a trailing pathname separator. " "Examples: \"xml:filename.xml\", \"xml::directoryname/\". " "If a directory is specified, output files will be created " "within that directory, with file-names based on the test " "executable's name and, if necessary, made unique by adding " "digits."); GTEST_DEFINE_bool_( brief, testing::internal::BoolFromGTestEnv("brief", false), "True if only test failures should be displayed in text output."); GTEST_DEFINE_bool_(print_time, testing::internal::BoolFromGTestEnv("print_time", true), "True if and only if " GTEST_NAME_ " should display elapsed time in text output."); GTEST_DEFINE_bool_(print_utf8, testing::internal::BoolFromGTestEnv("print_utf8", true), "True if and only if " GTEST_NAME_ " prints UTF8 characters as text."); GTEST_DEFINE_int32_( random_seed, testing::internal::Int32FromGTestEnv("random_seed", 0), "Random number seed to use when shuffling test orders. Must be in range " "[1, 99999], or 0 to use a seed based on the current time."); GTEST_DEFINE_int32_( repeat, testing::internal::Int32FromGTestEnv("repeat", 1), "How many times to repeat each test. Specify a negative number " "for repeating forever. Useful for shaking out flaky tests."); GTEST_DEFINE_bool_( recreate_environments_when_repeating, testing::internal::BoolFromGTestEnv("recreate_environments_when_repeating", false), "Controls whether global test environments are recreated for each repeat " "of the tests. If set to false the global test environments are only set " "up once, for the first iteration, and only torn down once, for the last. " "Useful for shaking out flaky tests with stable, expensive test " "environments. If --gtest_repeat is set to a negative number, meaning " "there is no last run, the environments will always be recreated to avoid " "leaks."); GTEST_DEFINE_bool_(show_internal_stack_frames, false, "True if and only if " GTEST_NAME_ " should include internal stack frames when " "printing test failure stack traces."); GTEST_DEFINE_bool_(shuffle, testing::internal::BoolFromGTestEnv("shuffle", false), "True if and only if " GTEST_NAME_ " should randomize tests' order on every run."); GTEST_DEFINE_int32_( stack_trace_depth, testing::internal::Int32FromGTestEnv("stack_trace_depth", testing::kMaxStackTraceDepth), "The maximum number of stack frames to print when an " "assertion fails. The valid range is 0 through 100, inclusive."); GTEST_DEFINE_string_( stream_result_to, testing::internal::StringFromGTestEnv("stream_result_to", ""), "This flag specifies the host name and the port number on which to stream " "test results. Example: \"localhost:555\". The flag is effective only on " "Linux and macOS."); GTEST_DEFINE_bool_( throw_on_failure, testing::internal::BoolFromGTestEnv("throw_on_failure", false), "When this flag is specified, a failed assertion will throw an exception " "if exceptions are enabled or exit the program with a non-zero code " "otherwise. For use with an external test framework."); #if GTEST_USE_OWN_FLAGFILE_FLAG_ GTEST_DEFINE_string_( flagfile, testing::internal::StringFromGTestEnv("flagfile", ""), "This flag specifies the flagfile to read command-line flags from."); #endif namespace testing { namespace internal { const uint32_t Random::kMaxRange; uint32_t Random::Generate(uint32_t range) { state_ = static_cast<uint32_t>(1103515245ULL * state_ + 12345U) % kMaxRange; GTEST_CHECK_(range > 0) << "Cannot generate a number in the range [0, 0)."; GTEST_CHECK_(range <= kMaxRange) << "Generation of a number in [0, " << range << ") was requested, " << "but this can only generate numbers in [0, " << kMaxRange << ")."; return state_ % range; } static bool GTestIsInitialized() { return !GetArgvs().empty(); } static int SumOverTestSuiteList(const std::vector<TestSuite*>& case_list, int (TestSuite::*method)() const) { int sum = 0; for (size_t i = 0; i < case_list.size(); i++) { sum += (case_list[i]->*method)(); } return sum; } static bool TestSuitePassed(const TestSuite* test_suite) { return test_suite->should_run() && test_suite->Passed(); } static bool TestSuiteFailed(const TestSuite* test_suite) { return test_suite->should_run() && test_suite->Failed(); } static bool ShouldRunTestSuite(const TestSuite* test_suite) { return test_suite->should_run(); } namespace { bool ShouldEmitStackTraceForResultType(TestPartResult::Type type) { return type != TestPartResult::kSuccess && type != TestPartResult::kSkip; } } AssertHelper::AssertHelper(TestPartResult::Type type, const char* file, int line, const char* message) : data_(new AssertHelperData(type, file, line, message)) {} AssertHelper::~AssertHelper() { delete data_; } void AssertHelper::operator=(const Message& message) const { UnitTest::GetInstance()->AddTestPartResult( data_->type, data_->file, data_->line, AppendUserMessage(data_->message, message), ShouldEmitStackTraceForResultType(data_->type) ? UnitTest::GetInstance()->impl()->CurrentOsStackTraceExceptTop(1) : "" ); } namespace { constexpr bool kErrorOnUninstantiatedParameterizedTest = true; constexpr bool kErrorOnUninstantiatedTypeParameterizedTest = true; class FailureTest : public Test { public: explicit FailureTest(const CodeLocation& loc, std::string error_message, bool as_error) : loc_(loc), error_message_(std::move(error_message)), as_error_(as_error) {} void TestBody() override { if (as_error_) { AssertHelper(TestPartResult::kNonFatalFailure, loc_.file.c_str(), loc_.line, "") = Message() << error_message_; } else { std::cout << error_message_ << std::endl; } } private: const CodeLocation loc_; const std::string error_message_; const bool as_error_; }; } std::set<std::string>* GetIgnoredParameterizedTestSuites() { return UnitTest::GetInstance()->impl()->ignored_parameterized_test_suites(); } MarkAsIgnored::MarkAsIgnored(const char* test_suite) { GetIgnoredParameterizedTestSuites()->insert(test_suite); } void InsertSyntheticTestCase(const std::string& name, CodeLocation location, bool has_test_p) { const auto& ignored = *GetIgnoredParameterizedTestSuites(); if (ignored.find(name) != ignored.end()) return; const char kMissingInstantiation[] = " is defined via TEST_P, but never instantiated. None of the test " "cases " "will run. Either no INSTANTIATE_TEST_SUITE_P is provided or the only " "ones provided expand to nothing." "\n\n" "Ideally, TEST_P definitions should only ever be included as part of " "binaries that intend to use them. (As opposed to, for example, being " "placed in a library that may be linked in to get other utilities.)"; const char kMissingTestCase[] = " is instantiated via INSTANTIATE_TEST_SUITE_P, but no tests are " "defined via TEST_P . No test cases will run." "\n\n" "Ideally, INSTANTIATE_TEST_SUITE_P should only ever be invoked from " "code that always depend on code that provides TEST_P. Failing to do " "so is often an indication of dead code, e.g. the last TEST_P was " "removed but the rest got left behind."; std::string message = "Parameterized test suite " + name + (has_test_p ? kMissingInstantiation : kMissingTestCase) + "\n\n" "To suppress this error for this test suite, insert the following line " "(in a non-header) in the namespace it is defined in:" "\n\n" "GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(" + name + ");"; std::string full_name = "UninstantiatedParameterizedTestSuite<" + name + ">"; RegisterTest( "GoogleTestVerification", full_name.c_str(), nullptr, nullptr, location.file.c_str(), location.line, [message, location] { return new FailureTest(location, message, kErrorOnUninstantiatedParameterizedTest); }); } void RegisterTypeParameterizedTestSuite(const char* test_suite_name, CodeLocation code_location) { GetUnitTestImpl()->type_parameterized_test_registry().RegisterTestSuite( test_suite_name, std::move(code_location)); } void RegisterTypeParameterizedTestSuiteInstantiation(const char* case_name) { GetUnitTestImpl()->type_parameterized_test_registry().RegisterInstantiation( case_name); } void TypeParameterizedTestSuiteRegistry::RegisterTestSuite( const char* test_suite_name, CodeLocation code_location) { suites_.emplace(std::string(test_suite_name), TypeParameterizedTestSuiteInfo(std::move(code_location))); } void TypeParameterizedTestSuiteRegistry::RegisterInstantiation( const char* test_suite_name) { auto it = suites_.find(std::string(test_suite_name)); if (it != suites_.end()) { it->second.instantiated = true; } else { GTEST_LOG_(ERROR) << "Unknown type parameterized test suit '" << test_suite_name << "'"; } } void TypeParameterizedTestSuiteRegistry::CheckForInstantiations() { const auto& ignored = *GetIgnoredParameterizedTestSuites(); for (const auto& testcase : suites_) { if (testcase.second.instantiated) continue; if (ignored.find(testcase.first) != ignored.end()) continue; std::string message = "Type parameterized test suite " + testcase.first + " is defined via REGISTER_TYPED_TEST_SUITE_P, but never instantiated " "via INSTANTIATE_TYPED_TEST_SUITE_P. None of the test cases will run." "\n\n" "Ideally, TYPED_TEST_P definitions should only ever be included as " "part of binaries that intend to use them. (As opposed to, for " "example, being placed in a library that may be linked in to get " "other " "utilities.)" "\n\n" "To suppress this error for this test suite, insert the following " "line " "(in a non-header) in the namespace it is defined in:" "\n\n" "GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(" + testcase.first + ");"; std::string full_name = "UninstantiatedTypeParameterizedTestSuite<" + testcase.first + ">"; RegisterTest( "GoogleTestVerification", full_name.c_str(), nullptr, nullptr, testcase.second.code_location.file.c_str(), testcase.second.code_location.line, [message, testcase] { return new FailureTest(testcase.second.code_location, message, kErrorOnUninstantiatedTypeParameterizedTest); }); } } static ::std::vector<std::string> g_argvs; ::std::vector<std::string> GetArgvs() { #if defined(GTEST_CUSTOM_GET_ARGVS_) const auto& custom = GTEST_CUSTOM_GET_ARGVS_(); return ::std::vector<std::string>(custom.begin(), custom.end()); #else return g_argvs; #endif } #if GTEST_HAS_FILE_SYSTEM FilePath GetCurrentExecutableName() { FilePath result; #if defined(GTEST_OS_WINDOWS) || defined(GTEST_OS_OS2) result.Set(FilePath(GetArgvs()[0]).RemoveExtension("exe")); #else result.Set(FilePath(GetArgvs()[0])); #endif return result.RemoveDirectoryName(); } #endif std::string UnitTestOptions::GetOutputFormat() { std::string s = GTEST_FLAG_GET(output); const char* const gtest_output_flag = s.c_str(); const char* const colon = strchr(gtest_output_flag, ':'); return (colon == nullptr) ? std::string(gtest_output_flag) : std::string(gtest_output_flag, static_cast<size_t>(colon - gtest_output_flag)); } #if GTEST_HAS_FILE_SYSTEM std::string UnitTestOptions::GetAbsolutePathToOutputFile() { std::string s = GTEST_FLAG_GET(output); const char* const gtest_output_flag = s.c_str(); std::string format = GetOutputFormat(); if (format.empty()) format = std::string(kDefaultOutputFormat); const char* const colon = strchr(gtest_output_flag, ':'); if (colon == nullptr) return internal::FilePath::MakeFileName( internal::FilePath( UnitTest::GetInstance()->original_working_dir()), internal::FilePath(kDefaultOutputFile), 0, format.c_str()) .string(); internal::FilePath output_name(colon + 1); if (!output_name.IsAbsolutePath()) output_name = internal::FilePath::ConcatPaths( internal::FilePath(UnitTest::GetInstance()->original_working_dir()), internal::FilePath(colon + 1)); if (!output_name.IsDirectory()) return output_name.string(); internal::FilePath result(internal::FilePath::GenerateUniqueFileName( output_name, internal::GetCurrentExecutableName(), GetOutputFormat().c_str())); return result.string(); } #endif static bool PatternMatchesString(const std::string& name_str, const char* pattern, const char* pattern_end) { const char* name = name_str.c_str(); const char* const name_begin = name; const char* const name_end = name + name_str.size(); const char* pattern_next = pattern; const char* name_next = name; while (pattern < pattern_end || name < name_end) { if (pattern < pattern_end) { switch (*pattern) { default: if (name < name_end && *name == *pattern) { ++pattern; ++name; continue; } break; case '?': if (name < name_end) { ++pattern; ++name; continue; } break; case '*': pattern_next = pattern; name_next = name + 1; ++pattern; continue; } } if (name_begin < name_next && name_next <= name_end) { pattern = pattern_next; name = name_next; continue; } return false; } return true; } namespace { bool IsGlobPattern(const std::string& pattern) { return std::any_of(pattern.begin(), pattern.end(), [](const char c) { return c == '?' || c == '*'; }); } class UnitTestFilter { public: UnitTestFilter() = default; explicit UnitTestFilter(const std::string& filter) { std::vector<std::string> all_patterns; SplitString(filter, ':', &all_patterns); const auto exact_match_patterns_begin = std::partition( all_patterns.begin(), all_patterns.end(), &IsGlobPattern); glob_patterns_.reserve(static_cast<size_t>( std::distance(all_patterns.begin(), exact_match_patterns_begin))); std::move(all_patterns.begin(), exact_match_patterns_begin, std::inserter(glob_patterns_, glob_patterns_.begin())); std::move( exact_match_patterns_begin, all_patterns.end(), std::inserter(exact_match_patterns_, exact_match_patterns_.begin())); } bool MatchesName(const std::string& name) const { return exact_match_patterns_.find(name) != exact_match_patterns_.end() || std::any_of(glob_patterns_.begin(), glob_patterns_.end(), [&name](const std::string& pattern) { return PatternMatchesString( name, pattern.c_str(), pattern.c_str() + pattern.size()); }); } private: std::vector<std::string> glob_patterns_; std::unordered_set<std::string> exact_match_patterns_; }; class PositiveAndNegativeUnitTestFilter { public: explicit PositiveAndNegativeUnitTestFilter(const std::string& filter) { std::vector<std::string> positive_and_negative_filters; SplitString(filter, '-', &positive_and_negative_filters); const auto& positive_filter = positive_and_negative_filters.front(); if (positive_and_negative_filters.size() > 1) { positive_filter_ = UnitTestFilter( positive_filter.empty() ? kUniversalFilter : positive_filter); auto negative_filter_string = positive_and_negative_filters[1]; for (std::size_t i = 2; i < positive_and_negative_filters.size(); i++) negative_filter_string = negative_filter_string + '-' + positive_and_negative_filters[i]; negative_filter_ = UnitTestFilter(negative_filter_string); } else { positive_filter_ = UnitTestFilter(positive_filter); } } bool MatchesTest(const std::string& test_suite_name, const std::string& test_name) const { return MatchesName(test_suite_name + "." + test_name); } bool MatchesName(const std::string& name) const { return positive_filter_.MatchesName(name) && !negative_filter_.MatchesName(name); } private: UnitTestFilter positive_filter_; UnitTestFilter negative_filter_; }; } bool UnitTestOptions::MatchesFilter(const std::string& name_str, const char* filter) { return UnitTestFilter(filter).MatchesName(name_str); } bool UnitTestOptions::FilterMatchesTest(const std::string& test_suite_name, const std::string& test_name) {
#include "gtest/gtest.h" TEST(CommandLineFlagsTest, CanBeAccessedInCodeOnceGTestHIsIncluded) { bool dummy = GTEST_FLAG_GET(also_run_disabled_tests) || GTEST_FLAG_GET(break_on_failure) || GTEST_FLAG_GET(catch_exceptions) || GTEST_FLAG_GET(color) != "unknown" || GTEST_FLAG_GET(fail_fast) || GTEST_FLAG_GET(filter) != "unknown" || GTEST_FLAG_GET(list_tests) || GTEST_FLAG_GET(output) != "unknown" || GTEST_FLAG_GET(brief) || GTEST_FLAG_GET(print_time) || GTEST_FLAG_GET(random_seed) || GTEST_FLAG_GET(repeat) > 0 || GTEST_FLAG_GET(recreate_environments_when_repeating) || GTEST_FLAG_GET(show_internal_stack_frames) || GTEST_FLAG_GET(shuffle) || GTEST_FLAG_GET(stack_trace_depth) > 0 || GTEST_FLAG_GET(stream_result_to) != "unknown" || GTEST_FLAG_GET(throw_on_failure); EXPECT_TRUE(dummy || !dummy); } #include <limits.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <cstdint> #include <map> #include <memory> #include <ostream> #include <set> #include <stdexcept> #include <string> #include <type_traits> #include <unordered_set> #include <utility> #include <vector> #include "gtest/gtest-spi.h" #include "src/gtest-internal-inl.h" struct ConvertibleGlobalType { template < class T, std::enable_if_t< false, std::enable_if_t<std::is_constructible<T>::value, int>> = 0> operator T() const; }; void operator<<(ConvertibleGlobalType&, int); static_assert(sizeof(decltype(std::declval<ConvertibleGlobalType&>() << 1)(*)()) > 0, "error in operator<< overload resolution"); namespace testing { namespace internal { #if GTEST_CAN_STREAM_RESULTS_ class StreamingListenerTest : public Test { public: class FakeSocketWriter : public StreamingListener::AbstractSocketWriter { public: void Send(const std::string& message) override { output_ += message; } std::string output_; }; StreamingListenerTest() : fake_sock_writer_(new FakeSocketWriter), streamer_(fake_sock_writer_), test_info_obj_("FooTest", "Bar", nullptr, nullptr, CodeLocation(__FILE__, __LINE__), nullptr, nullptr) {} protected: std::string* output() { return &(fake_sock_writer_->output_); } FakeSocketWriter* const fake_sock_writer_; StreamingListener streamer_; UnitTest unit_test_; TestInfo test_info_obj_; }; TEST_F(StreamingListenerTest, OnTestProgramEnd) { *output() = ""; streamer_.OnTestProgramEnd(unit_test_); EXPECT_EQ("event=TestProgramEnd&passed=1\n", *output()); } TEST_F(StreamingListenerTest, OnTestIterationEnd) { *output() = ""; streamer_.OnTestIterationEnd(unit_test_, 42); EXPECT_EQ("event=TestIterationEnd&passed=1&elapsed_time=0ms\n", *output()); } TEST_F(StreamingListenerTest, OnTestSuiteStart) { *output() = ""; streamer_.OnTestSuiteStart(TestSuite("FooTest", "Bar", nullptr, nullptr)); EXPECT_EQ("event=TestCaseStart&name=FooTest\n", *output()); } TEST_F(StreamingListenerTest, OnTestSuiteEnd) { *output() = ""; streamer_.OnTestSuiteEnd(TestSuite("FooTest", "Bar", nullptr, nullptr)); EXPECT_EQ("event=TestCaseEnd&passed=1&elapsed_time=0ms\n", *output()); } TEST_F(StreamingListenerTest, OnTestStart) { *output() = ""; streamer_.OnTestStart(test_info_obj_); EXPECT_EQ("event=TestStart&name=Bar\n", *output()); } TEST_F(StreamingListenerTest, OnTestEnd) { *output() = ""; streamer_.OnTestEnd(test_info_obj_); EXPECT_EQ("event=TestEnd&passed=1&elapsed_time=0ms\n", *output()); } TEST_F(StreamingListenerTest, OnTestPartResult) { *output() = ""; streamer_.OnTestPartResult(TestPartResult(TestPartResult::kFatalFailure, "foo.cc", 42, "failed=\n&%")); EXPECT_EQ( "event=TestPartResult&file=foo.cc&line=42&message=failed%3D%0A%26%25\n", *output()); } #endif class TestEventListenersAccessor { public: static TestEventListener* GetRepeater(TestEventListeners* listeners) { return listeners->repeater(); } static void SetDefaultResultPrinter(TestEventListeners* listeners, TestEventListener* listener) { listeners->SetDefaultResultPrinter(listener); } static void SetDefaultXmlGenerator(TestEventListeners* listeners, TestEventListener* listener) { listeners->SetDefaultXmlGenerator(listener); } static bool EventForwardingEnabled(const TestEventListeners& listeners) { return listeners.EventForwardingEnabled(); } static void SuppressEventForwarding(TestEventListeners* listeners) { listeners->SuppressEventForwarding(true); } }; class UnitTestRecordPropertyTestHelper : public Test { protected: UnitTestRecordPropertyTestHelper() {} void UnitTestRecordProperty(const char* key, const std::string& value) { unit_test_.RecordProperty(key, value); } UnitTest unit_test_; }; } } using testing::AssertionFailure; using testing::AssertionResult; using testing::AssertionSuccess; using testing::DoubleLE; using testing::EmptyTestEventListener; using testing::Environment; using testing::FloatLE; using testing::IsNotSubstring; using testing::IsSubstring; using testing::kMaxStackTraceDepth; using testing::Message; using testing::ScopedFakeTestPartResultReporter; using testing::StaticAssertTypeEq; using testing::Test; using testing::TestEventListeners; using testing::TestInfo; using testing::TestPartResult; using testing::TestPartResultArray; using testing::TestProperty; using testing::TestResult; using testing::TimeInMillis; using testing::UnitTest; using testing::internal::AlwaysFalse; using testing::internal::AlwaysTrue; using testing::internal::AppendUserMessage; using testing::internal::ArrayAwareFind; using testing::internal::ArrayEq; using testing::internal::CodePointToUtf8; using testing::internal::CopyArray; using testing::internal::CountIf; using testing::internal::EqFailure; using testing::internal::FloatingPoint; using testing::internal::ForEach; using testing::internal::FormatEpochTimeInMillisAsIso8601; using testing::internal::FormatTimeInMillisAsSeconds; using testing::internal::GetElementOr; using testing::internal::GetNextRandomSeed; using testing::internal::GetRandomSeedFromFlag; using testing::internal::GetTestTypeId; using testing::internal::GetTimeInMillis; using testing::internal::GetTypeId; using testing::internal::GetUnitTestImpl; using testing::internal::GTestFlagSaver; using testing::internal::HasDebugStringAndShortDebugString; using testing::internal::Int32FromEnvOrDie; using testing::internal::IsContainer; using testing::internal::IsContainerTest; using testing::internal::IsNotContainer; using testing::internal::kMaxRandomSeed; using testing::internal::kTestTypeIdInGoogleTest; using testing::internal::NativeArray; using testing::internal::ParseFlag; using testing::internal::RelationToSourceCopy; using testing::internal::RelationToSourceReference; using testing::internal::ShouldRunTestOnShard; using testing::internal::ShouldShard; using testing::internal::ShouldUseColor; using testing::internal::Shuffle; using testing::internal::ShuffleRange; using testing::internal::SkipPrefix; using testing::internal::StreamableToString; using testing::internal::String; using testing::internal::TestEventListenersAccessor; using testing::internal::TestResultAccessor; using testing::internal::WideStringToUtf8; using testing::internal::edit_distance::CalculateOptimalEdits; using testing::internal::edit_distance::CreateUnifiedDiff; using testing::internal::edit_distance::EditType; #if GTEST_HAS_STREAM_REDIRECTION using testing::internal::CaptureStdout; using testing::internal::GetCapturedStdout; #endif #ifdef GTEST_IS_THREADSAFE using testing::internal::ThreadWithParam; #endif class TestingVector : public std::vector<int> {}; ::std::ostream& operator<<(::std::ostream& os, const TestingVector& vector) { os << "{ "; for (size_t i = 0; i < vector.size(); i++) { os << vector[i] << " "; } os << "}"; return os; } namespace { TEST(GetRandomSeedFromFlagTest, HandlesZero) { const int seed = GetRandomSeedFromFlag(0); EXPECT_LE(1, seed); EXPECT_LE(seed, static_cast<int>(kMaxRandomSeed)); } TEST(GetRandomSeedFromFlagTest, PreservesValidSeed) { EXPECT_EQ(1, GetRandomSeedFromFlag(1)); EXPECT_EQ(2, GetRandomSeedFromFlag(2)); EXPECT_EQ(kMaxRandomSeed - 1, GetRandomSeedFromFlag(kMaxRandomSeed - 1)); EXPECT_EQ(static_cast<int>(kMaxRandomSeed), GetRandomSeedFromFlag(kMaxRandomSeed)); } TEST(GetRandomSeedFromFlagTest, NormalizesInvalidSeed) { const int seed1 = GetRandomSeedFromFlag(-1); EXPECT_LE(1, seed1); EXPECT_LE(seed1, static_cast<int>(kMaxRandomSeed)); const int seed2 = GetRandomSeedFromFlag(kMaxRandomSeed + 1); EXPECT_LE(1, seed2); EXPECT_LE(seed2, static_cast<int>(kMaxRandomSeed)); } TEST(GetNextRandomSeedTest, WorksForValidInput) { EXPECT_EQ(2, GetNextRandomSeed(1)); EXPECT_EQ(3, GetNextRandomSeed(2)); EXPECT_EQ(static_cast<int>(kMaxRandomSeed), GetNextRandomSeed(kMaxRandomSeed - 1)); EXPECT_EQ(1, GetNextRandomSeed(kMaxRandomSeed)); } static void ClearCurrentTestPartResults() { TestResultAccessor::ClearTestPartResults( GetUnitTestImpl()->current_test_result()); } TEST(GetTypeIdTest, ReturnsSameValueForSameType) { EXPECT_EQ(GetTypeId<int>(), GetTypeId<int>()); EXPECT_EQ(GetTypeId<Test>(), GetTypeId<Test>()); } class SubClassOfTest : public Test {}; class AnotherSubClassOfTest : public Test {}; TEST(GetTypeIdTest, ReturnsDifferentValuesForDifferentTypes) { EXPECT_NE(GetTypeId<int>(), GetTypeId<const int>()); EXPECT_NE(GetTypeId<int>(), GetTypeId<char>()); EXPECT_NE(GetTypeId<int>(), GetTestTypeId()); EXPECT_NE(GetTypeId<SubClassOfTest>(), GetTestTypeId()); EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTestTypeId()); EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTypeId<SubClassOfTest>()); } TEST(GetTestTypeIdTest, ReturnsTheSameValueInsideOrOutsideOfGoogleTest) { EXPECT_EQ(kTestTypeIdInGoogleTest, GetTestTypeId()); } using ::testing::internal::CanonicalizeForStdLibVersioning; TEST(CanonicalizeForStdLibVersioning, LeavesUnversionedNamesUnchanged) { EXPECT_EQ("std::bind", CanonicalizeForStdLibVersioning("std::bind")); EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::_")); EXPECT_EQ("std::__foo", CanonicalizeForStdLibVersioning("std::__foo")); EXPECT_EQ("gtl::__1::x", CanonicalizeForStdLibVersioning("gtl::__1::x")); EXPECT_EQ("__1::x", CanonicalizeForStdLibVersioning("__1::x")); EXPECT_EQ("::__1::x", CanonicalizeForStdLibVersioning("::__1::x")); } TEST(CanonicalizeForStdLibVersioning, ElidesDoubleUnderNames) { EXPECT_EQ("std::bind", CanonicalizeForStdLibVersioning("std::__1::bind")); EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::__1::_")); EXPECT_EQ("std::bind", CanonicalizeForStdLibVersioning("std::__g::bind")); EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::__g::_")); EXPECT_EQ("std::bind", CanonicalizeForStdLibVersioning("std::__google::bind")); EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::__google::_")); } TEST(FormatTimeInMillisAsSecondsTest, FormatsZero) { EXPECT_EQ("0.", FormatTimeInMillisAsSeconds(0)); } TEST(FormatTimeInMillisAsSecondsTest, FormatsPositiveNumber) { EXPECT_EQ("0.003", FormatTimeInMillisAsSeconds(3)); EXPECT_EQ("0.01", FormatTimeInMillisAsSeconds(10)); EXPECT_EQ("0.2", FormatTimeInMillisAsSeconds(200)); EXPECT_EQ("1.2", FormatTimeInMillisAsSeconds(1200)); EXPECT_EQ("3.", FormatTimeInMillisAsSeconds(3000)); EXPECT_EQ("10.", FormatTimeInMillisAsSeconds(10000)); EXPECT_EQ("100.", FormatTimeInMillisAsSeconds(100000)); EXPECT_EQ("123.456", FormatTimeInMillisAsSeconds(123456)); EXPECT_EQ("1234567.89", FormatTimeInMillisAsSeconds(1234567890)); } TEST(FormatTimeInMillisAsSecondsTest, FormatsNegativeNumber) { EXPECT_EQ("-0.003", FormatTimeInMillisAsSeconds(-3)); EXPECT_EQ("-0.01", FormatTimeInMillisAsSeconds(-10)); EXPECT_EQ("-0.2", FormatTimeInMillisAsSeconds(-200)); EXPECT_EQ("-1.2", FormatTimeInMillisAsSeconds(-1200)); EXPECT_EQ("-3.", FormatTimeInMillisAsSeconds(-3000)); EXPECT_EQ("-10.", FormatTimeInMillisAsSeconds(-10000)); EXPECT_EQ("-100.", FormatTimeInMillisAsSeconds(-100000)); EXPECT_EQ("-123.456", FormatTimeInMillisAsSeconds(-123456)); EXPECT_EQ("-1234567.89", FormatTimeInMillisAsSeconds(-1234567890)); } #if !defined(__EMSCRIPTEN__) class FormatEpochTimeInMillisAsIso8601Test : public Test { public: static const TimeInMillis kMillisPerSec = 1000; private: void SetUp() override { saved_tz_.reset(); GTEST_DISABLE_MSC_DEPRECATED_PUSH_() if (const char* tz = getenv("TZ")) { saved_tz_ = std::make_unique<std::string>(tz); } GTEST_DISABLE_MSC_DEPRECATED_POP_() SetTimeZone("UTC+00"); } void TearDown() override { SetTimeZone(saved_tz_ != nullptr ? saved_tz_->c_str() : nullptr); saved_tz_.reset(); } static void SetTimeZone(const char* time_zone) { #if defined(_MSC_VER) || defined(GTEST_OS_WINDOWS_MINGW) const std::string env_var = std::string("TZ=") + (time_zone ? time_zone : ""); _putenv(env_var.c_str()); GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996 ) tzset(); GTEST_DISABLE_MSC_WARNINGS_POP_() #else #if defined(GTEST_OS_LINUX_ANDROID) && __ANDROID_API__ < 21 setenv("TZ", "UTC", 1); tzset(); #endif if (time_zone) { setenv(("TZ"), time_zone, 1); } else { unsetenv("TZ"); } tzset(); #endif } std::unique_ptr<std::string> saved_tz_; }; const TimeInMillis FormatEpochTimeInMillisAsIso8601Test::kMillisPerSec; TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsTwoDigitSegments) { EXPECT_EQ("2011-10-31T18:52:42.000", FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec)); } TEST_F(FormatEpochTimeInMillisAsIso8601Test, IncludesMillisecondsAfterDot) { EXPECT_EQ("2011-10-31T18:52:42.234", FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec + 234)); } TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsLeadingZeroes) { EXPECT_EQ("2011-09-03T05:07:02.000", FormatEpochTimeInMillisAsIso8601(1315026422 * kMillisPerSec)); } TEST_F(FormatEpochTimeInMillisAsIso8601Test, Prints24HourTime) { EXPECT_EQ("2011-09-28T17:08:22.000", FormatEpochTimeInMillisAsIso8601(1317229702 * kMillisPerSec)); } TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsEpochStart) { EXPECT_EQ("1970-01-01T00:00:00.000", FormatEpochTimeInMillisAsIso8601(0)); } #endif #ifdef __BORLANDC__ #pragma option push -w-ccc -w-rch #endif TEST(NullLiteralTest, LHSAllowsNullLiterals) { EXPECT_EQ(0, static_cast<void*>(nullptr)); ASSERT_EQ(0, static_cast<void*>(nullptr)); EXPECT_EQ(NULL, static_cast<void*>(nullptr)); ASSERT_EQ(NULL, static_cast<void*>(nullptr)); EXPECT_EQ(nullptr, static_cast<void*>(nullptr)); ASSERT_EQ(nullptr, static_cast<void*>(nullptr)); const int* const p = nullptr; EXPECT_EQ(0, p); ASSERT_EQ(0, p); EXPECT_EQ(NULL, p); ASSERT_EQ(NULL, p); EXPECT_EQ(nullptr, p); ASSERT_EQ(nullptr, p); } struct ConvertToAll { template <typename T> operator T() const { return T(); } }; struct ConvertToPointer { template <class T> operator T*() const { return nullptr; } }; struct ConvertToAllButNoPointers { template <typename T, typename std::enable_if<!std::is_pointer<T>::value, int>::type = 0> operator T() const { return T(); } }; struct MyType {}; inline bool operator==(MyType const&, MyType const&) { return true; } TEST(NullLiteralTest, ImplicitConversion) { EXPECT_EQ(ConvertToPointer{}, static_cast<void*>(nullptr)); #if !defined(__GNUC__) || defined(__clang__) EXPECT_EQ(ConvertToAll{}, static_cast<void*>(nullptr)); #endif EXPECT_EQ(ConvertToAll{}, MyType{}); EXPECT_EQ(ConvertToAllButNoPointers{}, MyType{}); } #ifdef __clang__ #pragma clang diagnostic push #if __has_warning("-Wzero-as-null-pointer-constant") #pragma clang diagnostic error "-Wzero-as-null-pointer-constant" #endif #endif TEST(NullLiteralTest, NoConversionNoWarning) { EXPECT_EQ(0, 0); ASSERT_EQ(0, 0); } #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __BORLANDC__ #pragma option pop #endif TEST(CodePointToUtf8Test, CanEncodeNul) { EXPECT_EQ("", CodePointToUtf8(L'\0')); } TEST(CodePointToUtf8Test, CanEncodeAscii) { EXPECT_EQ("a", CodePointToUtf8(L'a')); EXPECT_EQ("Z", CodePointToUtf8(L'Z')); EXPECT_EQ("&", CodePointToUtf8(L'&')); EXPECT_EQ("\x7F", CodePointToUtf8(L'\x7F')); } TEST(CodePointToUtf8Test, CanEncode8To11Bits) { EXPECT_EQ("\xC3\x93", CodePointToUtf8(L'\xD3')); EXPECT_EQ("\xD5\xB6", CodePointToUtf8(static_cast<wchar_t>(0x576))); } TEST(CodePointToUtf8Test, CanEncode12To16Bits) { EXPECT_EQ("\xE0\xA3\x93", CodePointToUtf8(static_cast<wchar_t>(0x8D3))); EXPECT_EQ("\xEC\x9D\x8D", CodePointToUtf8(static_cast<wchar_t>(0xC74D))); } #if !GTEST_WIDE_STRING_USES_UTF16_ TEST(CodePointToUtf8Test, CanEncode17To21Bits) { EXPECT_EQ("\xF0\x90\xA3\x93", CodePointToUtf8(L'\x108D3')); EXPECT_EQ("\xF0\x90\x90\x80", CodePointToUtf8(L'\x10400')); EXPECT_EQ("\xF4\x88\x98\xB4", CodePointToUtf8(L'\x108634')); } TEST(CodePointToUtf8Test, CanEncodeInvalidCodePoint) { EXPECT_EQ("(Invalid Unicode 0x1234ABCD)", CodePointToUtf8(L'\x1234ABCD')); } #endif TEST(WideStringToUtf8Test, CanEncodeNul) { EXPECT_STREQ("", WideStringToUtf8(L"", 0).c_str()); EXPECT_STREQ("", WideStringToUtf8(L"", -1).c_str()); } TEST(WideStringToUtf8Test, CanEncodeAscii) { EXPECT_STREQ("a", WideStringToUtf8(L"a", 1).c_str()); EXPECT_STREQ("ab", WideStringToUtf8(L"ab", 2).c_str()); EXPECT_STREQ("a", WideStringToUtf8(L"a", -1).c_str()); EXPECT_STREQ("ab", WideStringToUtf8(L"ab", -1).c_str()); } TEST(WideStringToUtf8Test, CanEncode8To11Bits) { EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", 1).c_str()); EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", -1).c_str()); const wchar_t s[] = {0x576, '\0'}; EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(s, 1).c_str()); EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(s, -1).c_str()); } TEST(WideStringToUtf8Test, CanEncode12To16Bits) { const wchar_t s1[] = {0x8D3, '\0'}; EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(s1, 1).c_str()); EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(s1, -1).c_str()); const wchar_t s2[] = {0xC74D, '\0'}; EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(s2, 1).c_str()); EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(s2, -1).c_str()); } TEST(WideStringToUtf8Test, StopsOnNulCharacter) { EXPECT_STREQ("ABC", WideStringToUtf8(L"ABC\0XYZ", 100).c_str()); } TEST(WideStringToUtf8Test, StopsWhenLengthLimitReached) { EXPECT_STREQ("ABC", WideStringToUtf8(L"ABCDEF", 3).c_str()); } #if !GTEST_WIDE_STRING_USES_UTF16_ TEST(WideStringToUtf8Test, CanEncode17To21Bits) { EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", 1).c_str()); EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", -1).c_str()); EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", 1).c_str()); EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", -1).c_str()); } TEST(WideStringToUtf8Test, CanEncodeInvalidCodePoint) { EXPECT_STREQ("(Invalid Unicode 0xABCDFF)", WideStringToUtf8(L"\xABCDFF", -1).c_str()); } #else TEST(WideStringToUtf8Test, CanEncodeValidUtf16SUrrogatePairs) { const wchar_t s[] = {0xD801, 0xDC00, '\0'}; EXPECT_STREQ("\xF0\x90\x90\x80", WideStringToUtf8(s, -1).c_str()); } TEST(WideStringToUtf8Test, CanEncodeInvalidUtf16SurrogatePair) { const wchar_t s1[] = {0xD800, '\0'}; EXPECT_STREQ("\xED\xA0\x80", WideStringToUtf8(s1, -1).c_str()); const wchar_t s2[] = {0xD800, 'M', '\0'}; EXPECT_STREQ("\xED\xA0\x80M", WideStringToUtf8(s2, -1).c_str()); const wchar_t s3[] = {0xDC00, 'P', 'Q', 'R', '\0'}; EXPECT_STREQ("\xED\xB0\x80PQR", WideStringToUtf8(s3, -1).c_str()); } #endif #if !GTEST_WIDE_STRING_USES_UTF16_ TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) { const wchar_t s[] = {0x108634, 0xC74D, '\n', 0x576, 0x8D3, 0x108634, '\0'}; EXPECT_STREQ( "\xF4\x88\x98\xB4" "\xEC\x9D\x8D" "\n" "\xD5\xB6" "\xE0\xA3\x93" "\xF4\x88\x98\xB4", WideStringToUtf8(s, -1).c_str()); } #else TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) { const wchar_t s[] = {0xC74D, '\n', 0x576, 0x8D3, '\0'}; EXPECT_STREQ( "\xEC\x9D\x8D" "\n" "\xD5\xB6" "\xE0\xA3\x93", WideStringToUtf8(s, -1).c_str()); } #endif TEST(RandomDeathTest, GeneratesCrashesOnInvalidRange) { testing::internal::Random random(42); EXPECT_DEATH_IF_SUPPORTED(random.Generate(0), "Cannot generate a number in the range \\[0, 0\\)"); EXPECT_DEATH_IF_SUPPORTED( random.Generate(testing::internal::Random::kMaxRange + 1), "Generation of a number in \\[0, 2147483649\\) was requested, " "but this can only generate numbers in \\[0, 2147483648\\)"); } TEST(RandomTest, GeneratesNumbersWithinRange) { constexpr uint32_t kRange = 10000; testing::internal::Random random(12345); for (int i = 0; i < 10; i++) { EXPECT_LT(random.Generate(kRange), kRange) << " for iteration " << i; } testing::internal::Random random2(testing::internal::Random::kMaxRange); for (int i = 0; i < 10; i++) { EXPECT_LT(random2.Generate(kRange), kRange) << " for iteration " << i; } } TEST(RandomTest, RepeatsWhenReseeded) { constexpr int kSeed = 123; constexpr int kArraySize = 10; constexpr uint32_t kRange = 10000; uint32_t values[kArraySize]; testing::internal::Random random(kSeed); for (int i = 0; i < kArraySize; i++) { values[i] = random.Generate(kRange); } random.Reseed(kSeed); for (int i = 0; i < kArraySize; i++) { EXPECT_EQ(values[i], random.Generate(kRange)) << " for iteration " << i; } } static bool IsPositive(int n) { return n > 0; } TEST(ContainerUtilityTest, CountIf) { std::vector<int> v; EXPECT_EQ(0, CountIf(v, IsPositive)); v.push_back(-1); v.push_back(0); EXPECT_EQ(0, CountIf(v, IsPositive)); v.push_back(2); v.push_back(-10); v.push_back(10); EXPECT_EQ(2, CountIf(v, IsPositive)); } static int g_sum = 0; static void Accumulate(int n) { g_sum += n; } TEST(ContainerUtilityTest, ForEach) { std::vector<int> v; g_sum = 0; ForEach(v, Accumulate); EXPECT_EQ(0, g_sum); g_sum = 0; v.push_back(1); ForEach(v, Accumulate); EXPECT_EQ(1, g_sum); g_sum = 0; v.push_back(20); v.push_back(300); ForEach(v, Accumulate); EXPECT_EQ(321, g_sum); } TEST(ContainerUtilityTest, GetElementOr) { std::vector<char> a; EXPECT_EQ('x', GetElementOr(a, 0, 'x')); a.push_back('a'); a.push_back('b'); EXPECT_EQ('a', GetElementOr(a, 0, 'x')); EXPECT_EQ('b', GetElementOr(a, 1, 'x')); EXPECT_EQ('x', GetElementOr(a, -2, 'x')); EXPECT_EQ('x', GetElementOr(a, 2, 'x')); } TEST(ContainerUtilityDeathTest, ShuffleRange) { std::vector<int> a; a.push_back(0); a.push_back(1); a.push_back(2); testing::internal::Random random(1); EXPECT_DEATH_IF_SUPPORTED( ShuffleRange(&random, -1, 1, &a), "Invalid shuffle range start -1: must be in range \\[0, 3\\]"); EXPECT_DEATH_IF_SUPPORTED( ShuffleRange(&random, 4, 4, &a), "Invalid shuffle range start 4: must be in range \\[0, 3\\]"); EXPECT_DEATH_IF_SUPPORTED( ShuffleRange(&random, 3, 2, &a), "Invalid shuffle range finish 2: must be in range \\[3, 3\\]"); EXPECT_DEATH_IF_SUPPORTED( ShuffleRange(&random, 3, 4, &a), "Invalid shuffle range finish 4: must be in range \\[3, 3\\]"); } class VectorShuffleTest : public Test { protected: static const size_t kVectorSize = 20; VectorShuffleTest() : random_(1) { for (int i = 0; i < static_cast<int>(kVectorSize); i++) { vector_.push_back(i); } } static bool VectorIsCorrupt(const TestingVector& vector) { if (kVectorSize != vector.size()) { return true; } bool found_in_vector[kVectorSize] = {false}; for (size_t i = 0; i < vector.size(); i++) { const int e = vector[i]; if (e < 0 || e >= static_cast<int>(kVectorSize) || found_in_vector[e]) { return true; } found_in_vector[e] = true; } return false; } static bool VectorIsNo
2,329
#include "gmock/gmock-cardinalities.h" #include <limits.h> #include <ostream> #include <sstream> #include <string> #include "gmock/internal/gmock-internal-utils.h" #include "gtest/gtest.h" namespace testing { namespace { class BetweenCardinalityImpl : public CardinalityInterface { public: BetweenCardinalityImpl(int min, int max) : min_(min >= 0 ? min : 0), max_(max >= min_ ? max : min_) { std::stringstream ss; if (min < 0) { ss << "The invocation lower bound must be >= 0, " << "but is actually " << min << "."; internal::Expect(false, __FILE__, __LINE__, ss.str()); } else if (max < 0) { ss << "The invocation upper bound must be >= 0, " << "but is actually " << max << "."; internal::Expect(false, __FILE__, __LINE__, ss.str()); } else if (min > max) { ss << "The invocation upper bound (" << max << ") must be >= the invocation lower bound (" << min << ")."; internal::Expect(false, __FILE__, __LINE__, ss.str()); } } int ConservativeLowerBound() const override { return min_; } int ConservativeUpperBound() const override { return max_; } bool IsSatisfiedByCallCount(int call_count) const override { return min_ <= call_count && call_count <= max_; } bool IsSaturatedByCallCount(int call_count) const override { return call_count >= max_; } void DescribeTo(::std::ostream* os) const override; private: const int min_; const int max_; BetweenCardinalityImpl(const BetweenCardinalityImpl&) = delete; BetweenCardinalityImpl& operator=(const BetweenCardinalityImpl&) = delete; }; inline std::string FormatTimes(int n) { if (n == 1) { return "once"; } else if (n == 2) { return "twice"; } else { std::stringstream ss; ss << n << " times"; return ss.str(); } } void BetweenCardinalityImpl::DescribeTo(::std::ostream* os) const { if (min_ == 0) { if (max_ == 0) { *os << "never called"; } else if (max_ == INT_MAX) { *os << "called any number of times"; } else { *os << "called at most " << FormatTimes(max_); } } else if (min_ == max_) { *os << "called " << FormatTimes(min_); } else if (max_ == INT_MAX) { *os << "called at least " << FormatTimes(min_); } else { *os << "called between " << min_ << " and " << max_ << " times"; } } } void Cardinality::DescribeActualCallCountTo(int actual_call_count, ::std::ostream* os) { if (actual_call_count > 0) { *os << "called " << FormatTimes(actual_call_count); } else { *os << "never called"; } } GTEST_API_ Cardinality AtLeast(int n) { return Between(n, INT_MAX); } GTEST_API_ Cardinality AtMost(int n) { return Between(0, n); } GTEST_API_ Cardinality AnyNumber() { return AtLeast(0); } GTEST_API_ Cardinality Between(int min, int max) { return Cardinality(new BetweenCardinalityImpl(min, max)); } GTEST_API_ Cardinality Exactly(int n) { return Between(n, n); } }
#include <ostream> #include "gmock/gmock.h" #include "gtest/gtest-spi.h" #include "gtest/gtest.h" namespace { using std::stringstream; using testing::AnyNumber; using testing::AtLeast; using testing::AtMost; using testing::Between; using testing::Cardinality; using testing::CardinalityInterface; using testing::Exactly; using testing::IsSubstring; using testing::MakeCardinality; class MockFoo { public: MockFoo() = default; MOCK_METHOD0(Bar, int()); private: MockFoo(const MockFoo&) = delete; MockFoo& operator=(const MockFoo&) = delete; }; TEST(CardinalityTest, IsDefaultConstructable) { Cardinality c; } TEST(CardinalityTest, IsCopyable) { Cardinality c = Exactly(1); EXPECT_FALSE(c.IsSatisfiedByCallCount(0)); EXPECT_TRUE(c.IsSatisfiedByCallCount(1)); EXPECT_TRUE(c.IsSaturatedByCallCount(1)); c = Exactly(2); EXPECT_FALSE(c.IsSatisfiedByCallCount(1)); EXPECT_TRUE(c.IsSatisfiedByCallCount(2)); EXPECT_TRUE(c.IsSaturatedByCallCount(2)); } TEST(CardinalityTest, IsOverSaturatedByCallCountWorks) { const Cardinality c = AtMost(5); EXPECT_FALSE(c.IsOverSaturatedByCallCount(4)); EXPECT_FALSE(c.IsOverSaturatedByCallCount(5)); EXPECT_TRUE(c.IsOverSaturatedByCallCount(6)); } TEST(CardinalityTest, CanDescribeActualCallCount) { stringstream ss0; Cardinality::DescribeActualCallCountTo(0, &ss0); EXPECT_EQ("never called", ss0.str()); stringstream ss1; Cardinality::DescribeActualCallCountTo(1, &ss1); EXPECT_EQ("called once", ss1.str()); stringstream ss2; Cardinality::DescribeActualCallCountTo(2, &ss2); EXPECT_EQ("called twice", ss2.str()); stringstream ss3; Cardinality::DescribeActualCallCountTo(3, &ss3); EXPECT_EQ("called 3 times", ss3.str()); } TEST(AnyNumber, Works) { const Cardinality c = AnyNumber(); EXPECT_TRUE(c.IsSatisfiedByCallCount(0)); EXPECT_FALSE(c.IsSaturatedByCallCount(0)); EXPECT_TRUE(c.IsSatisfiedByCallCount(1)); EXPECT_FALSE(c.IsSaturatedByCallCount(1)); EXPECT_TRUE(c.IsSatisfiedByCallCount(9)); EXPECT_FALSE(c.IsSaturatedByCallCount(9)); stringstream ss; c.DescribeTo(&ss); EXPECT_PRED_FORMAT2(IsSubstring, "called any number of times", ss.str()); } TEST(AnyNumberTest, HasCorrectBounds) { const Cardinality c = AnyNumber(); EXPECT_EQ(0, c.ConservativeLowerBound()); EXPECT_EQ(INT_MAX, c.ConservativeUpperBound()); } TEST(AtLeastTest, OnNegativeNumber) { EXPECT_NONFATAL_FAILURE( { AtLeast(-1); }, "The invocation lower bound must be >= 0"); } TEST(AtLeastTest, OnZero) { const Cardinality c = AtLeast(0); EXPECT_TRUE(c.IsSatisfiedByCallCount(0)); EXPECT_FALSE(c.IsSaturatedByCallCount(0)); EXPECT_TRUE(c.IsSatisfiedByCallCount(1)); EXPECT_FALSE(c.IsSaturatedByCallCount(1)); stringstream ss; c.DescribeTo(&ss); EXPECT_PRED_FORMAT2(IsSubstring, "any number of times", ss.str()); } TEST(AtLeastTest, OnPositiveNumber) { const Cardinality c = AtLeast(2); EXPECT_FALSE(c.IsSatisfiedByCallCount(0)); EXPECT_FALSE(c.IsSaturatedByCallCount(0)); EXPECT_FALSE(c.IsSatisfiedByCallCount(1)); EXPECT_FALSE(c.IsSaturatedByCallCount(1)); EXPECT_TRUE(c.IsSatisfiedByCallCount(2)); EXPECT_FALSE(c.IsSaturatedByCallCount(2)); stringstream ss1; AtLeast(1).DescribeTo(&ss1); EXPECT_PRED_FORMAT2(IsSubstring, "at least once", ss1.str()); stringstream ss2; c.DescribeTo(&ss2); EXPECT_PRED_FORMAT2(IsSubstring, "at least twice", ss2.str()); stringstream ss3; AtLeast(3).DescribeTo(&ss3); EXPECT_PRED_FORMAT2(IsSubstring, "at least 3 times", ss3.str()); } TEST(AtLeastTest, HasCorrectBounds) { const Cardinality c = AtLeast(2); EXPECT_EQ(2, c.ConservativeLowerBound()); EXPECT_EQ(INT_MAX, c.ConservativeUpperBound()); } TEST(AtMostTest, OnNegativeNumber) { EXPECT_NONFATAL_FAILURE( { AtMost(-1); }, "The invocation upper bound must be >= 0"); } TEST(AtMostTest, OnZero) { const Cardinality c = AtMost(0); EXPECT_TRUE(c.IsSatisfiedByCallCount(0)); EXPECT_TRUE(c.IsSaturatedByCallCount(0)); EXPECT_FALSE(c.IsSatisfiedByCallCount(1)); EXPECT_TRUE(c.IsSaturatedByCallCount(1)); stringstream ss; c.DescribeTo(&ss); EXPECT_PRED_FORMAT2(IsSubstring, "never called", ss.str()); } TEST(AtMostTest, OnPositiveNumber) { const Cardinality c = AtMost(2); EXPECT_TRUE(c.IsSatisfiedByCallCount(0)); EXPECT_FALSE(c.IsSaturatedByCallCount(0)); EXPECT_TRUE(c.IsSatisfiedByCallCount(1)); EXPECT_FALSE(c.IsSaturatedByCallCount(1)); EXPECT_TRUE(c.IsSatisfiedByCallCount(2)); EXPECT_TRUE(c.IsSaturatedByCallCount(2)); stringstream ss1; AtMost(1).DescribeTo(&ss1); EXPECT_PRED_FORMAT2(IsSubstring, "called at most once", ss1.str()); stringstream ss2; c.DescribeTo(&ss2); EXPECT_PRED_FORMAT2(IsSubstring, "called at most twice", ss2.str()); stringstream ss3; AtMost(3).DescribeTo(&ss3); EXPECT_PRED_FORMAT2(IsSubstring, "called at most 3 times", ss3.str()); } TEST(AtMostTest, HasCorrectBounds) { const Cardinality c = AtMost(2); EXPECT_EQ(0, c.ConservativeLowerBound()); EXPECT_EQ(2, c.ConservativeUpperBound()); } TEST(BetweenTest, OnNegativeStart) { EXPECT_NONFATAL_FAILURE( { Between(-1, 2); }, "The invocation lower bound must be >= 0, but is actually -1"); } TEST(BetweenTest, OnNegativeEnd) { EXPECT_NONFATAL_FAILURE( { Between(1, -2); }, "The invocation upper bound must be >= 0, but is actually -2"); } TEST(BetweenTest, OnStartBiggerThanEnd) { EXPECT_NONFATAL_FAILURE( { Between(2, 1); }, "The invocation upper bound (1) must be >= " "the invocation lower bound (2)"); } TEST(BetweenTest, OnZeroStartAndZeroEnd) { const Cardinality c = Between(0, 0); EXPECT_TRUE(c.IsSatisfiedByCallCount(0)); EXPECT_TRUE(c.IsSaturatedByCallCount(0)); EXPECT_FALSE(c.IsSatisfiedByCallCount(1)); EXPECT_TRUE(c.IsSaturatedByCallCount(1)); stringstream ss; c.DescribeTo(&ss); EXPECT_PRED_FORMAT2(IsSubstring, "never called", ss.str()); } TEST(BetweenTest, OnZeroStartAndNonZeroEnd) { const Cardinality c = Between(0, 2); EXPECT_TRUE(c.IsSatisfiedByCallCount(0)); EXPECT_FALSE(c.IsSaturatedByCallCount(0)); EXPECT_TRUE(c.IsSatisfiedByCallCount(2)); EXPECT_TRUE(c.IsSaturatedByCallCount(2)); EXPECT_FALSE(c.IsSatisfiedByCallCount(4)); EXPECT_TRUE(c.IsSaturatedByCallCount(4)); stringstream ss; c.DescribeTo(&ss); EXPECT_PRED_FORMAT2(IsSubstring, "called at most twice", ss.str()); } TEST(BetweenTest, OnSameStartAndEnd) { const Cardinality c = Between(3, 3); EXPECT_FALSE(c.IsSatisfiedByCallCount(2)); EXPECT_FALSE(c.IsSaturatedByCallCount(2)); EXPECT_TRUE(c.IsSatisfiedByCallCount(3)); EXPECT_TRUE(c.IsSaturatedByCallCount(3)); EXPECT_FALSE(c.IsSatisfiedByCallCount(4)); EXPECT_TRUE(c.IsSaturatedByCallCount(4)); stringstream ss; c.DescribeTo(&ss); EXPECT_PRED_FORMAT2(IsSubstring, "called 3 times", ss.str()); } TEST(BetweenTest, OnDifferentStartAndEnd) { const Cardinality c = Between(3, 5); EXPECT_FALSE(c.IsSatisfiedByCallCount(2)); EXPECT_FALSE(c.IsSaturatedByCallCount(2)); EXPECT_TRUE(c.IsSatisfiedByCallCount(3)); EXPECT_FALSE(c.IsSaturatedByCallCount(3)); EXPECT_TRUE(c.IsSatisfiedByCallCount(5)); EXPECT_TRUE(c.IsSaturatedByCallCount(5)); EXPECT_FALSE(c.IsSatisfiedByCallCount(6)); EXPECT_TRUE(c.IsSaturatedByCallCount(6)); stringstream ss; c.DescribeTo(&ss); EXPECT_PRED_FORMAT2(IsSubstring, "called between 3 and 5 times", ss.str()); } TEST(BetweenTest, HasCorrectBounds) { const Cardinality c = Between(3, 5); EXPECT_EQ(3, c.ConservativeLowerBound()); EXPECT_EQ(5, c.ConservativeUpperBound()); } TEST(ExactlyTest, OnNegativeNumber) { EXPECT_NONFATAL_FAILURE( { Exactly(-1); }, "The invocation lower bound must be >= 0"); } TEST(ExactlyTest, OnZero) { const Cardinality c = Exactly(0); EXPECT_TRUE(c.IsSatisfiedByCallCount(0)); EXPECT_TRUE(c.IsSaturatedByCallCount(0)); EXPECT_FALSE(c.IsSatisfiedByCallCount(1)); EXPECT_TRUE(c.IsSaturatedByCallCount(1)); stringstream ss; c.DescribeTo(&ss); EXPECT_PRED_FORMAT2(IsSubstring, "never called", ss.str()); } TEST(ExactlyTest, OnPositiveNumber) { const Cardinality c = Exactly(2); EXPECT_FALSE(c.IsSatisfiedByCallCount(0)); EXPECT_FALSE(c.IsSaturatedByCallCount(0)); EXPECT_TRUE(c.IsSatisfiedByCallCount(2)); EXPECT_TRUE(c.IsSaturatedByCallCount(2)); stringstream ss1; Exactly(1).DescribeTo(&ss1); EXPECT_PRED_FORMAT2(IsSubstring, "called once", ss1.str()); stringstream ss2; c.DescribeTo(&ss2); EXPECT_PRED_FORMAT2(IsSubstring, "called twice", ss2.str()); stringstream ss3; Exactly(3).DescribeTo(&ss3); EXPECT_PRED_FORMAT2(IsSubstring, "called 3 times", ss3.str()); } TEST(ExactlyTest, HasCorrectBounds) { const Cardinality c = Exactly(3); EXPECT_EQ(3, c.ConservativeLowerBound()); EXPECT_EQ(3, c.ConservativeUpperBound()); } class EvenCardinality : public CardinalityInterface { public: bool IsSatisfiedByCallCount(int call_count) const override { return (call_count % 2 == 0); } bool IsSaturatedByCallCount(int ) const override { return false; } void DescribeTo(::std::ostream* ss) const override { *ss << "called even number of times"; } }; TEST(MakeCardinalityTest, ConstructsCardinalityFromInterface) { const Cardinality c = MakeCardinality(new EvenCardinality); EXPECT_TRUE(c.IsSatisfiedByCallCount(2)); EXPECT_FALSE(c.IsSatisfiedByCallCount(3)); EXPECT_FALSE(c.IsSaturatedByCallCount(10000)); stringstream ss; c.DescribeTo(&ss); EXPECT_EQ("called even number of times", ss.str()); } }
2,330
#include "gmock/internal/gmock-internal-utils.h" #include <ctype.h> #include <array> #include <cctype> #include <cstdint> #include <cstring> #include <iostream> #include <ostream> #include <string> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gmock/internal/gmock-port.h" #include "gtest/gtest.h" namespace testing { namespace internal { GTEST_API_ std::string JoinAsKeyValueTuple( const std::vector<const char*>& names, const Strings& values) { GTEST_CHECK_(names.size() == values.size()); if (values.empty()) { return ""; } const auto build_one = [&](const size_t i) { return std::string(names[i]) + ": " + values[i]; }; std::string result = "(" + build_one(0); for (size_t i = 1; i < values.size(); i++) { result += ", "; result += build_one(i); } result += ")"; return result; } GTEST_API_ std::string ConvertIdentifierNameToWords(const char* id_name) { std::string result; char prev_char = '\0'; for (const char* p = id_name; *p != '\0'; prev_char = *(p++)) { const bool starts_new_word = IsUpper(*p) || (!IsAlpha(prev_char) && IsLower(*p)) || (!IsDigit(prev_char) && IsDigit(*p)); if (IsAlNum(*p)) { if (starts_new_word && !result.empty()) result += ' '; result += ToLower(*p); } } return result; } class GoogleTestFailureReporter : public FailureReporterInterface { public: void ReportFailure(FailureType type, const char* file, int line, const std::string& message) override { AssertHelper(type == kFatal ? TestPartResult::kFatalFailure : TestPartResult::kNonFatalFailure, file, line, message.c_str()) = Message(); if (type == kFatal) { posix::Abort(); } } }; GTEST_API_ FailureReporterInterface* GetFailureReporter() { static FailureReporterInterface* const failure_reporter = new GoogleTestFailureReporter(); return failure_reporter; } static GTEST_DEFINE_STATIC_MUTEX_(g_log_mutex); GTEST_API_ bool LogIsVisible(LogSeverity severity) { if (GMOCK_FLAG_GET(verbose) == kInfoVerbosity) { return true; } else if (GMOCK_FLAG_GET(verbose) == kErrorVerbosity) { return false; } else { return severity == kWarning; } } GTEST_API_ void Log(LogSeverity severity, const std::string& message, int stack_frames_to_skip) { if (!LogIsVisible(severity)) return; MutexLock l(&g_log_mutex); if (severity == kWarning) { std::cout << "\nGMOCK WARNING:"; } if (message.empty() || message[0] != '\n') { std::cout << "\n"; } std::cout << message; if (stack_frames_to_skip >= 0) { #ifdef NDEBUG const int actual_to_skip = 0; #else const int actual_to_skip = stack_frames_to_skip + 1; #endif if (!message.empty() && *message.rbegin() != '\n') { std::cout << "\n"; } std::cout << "Stack trace:\n" << ::testing::internal::GetCurrentOsStackTraceExceptTop( actual_to_skip); } std::cout << ::std::flush; } GTEST_API_ WithoutMatchers GetWithoutMatchers() { return WithoutMatchers(); } GTEST_API_ void IllegalDoDefault(const char* file, int line) { internal::Assert( false, file, line, "You are using DoDefault() inside a composite action like " "DoAll() or WithArgs(). This is not supported for technical " "reasons. Please instead spell out the default action, or " "assign the default action to an Action variable and use " "the variable in various places."); } constexpr char UndoWebSafeEncoding(char c) { return c == '-' ? '+' : c == '_' ? '/' : c; } constexpr char UnBase64Impl(char c, const char* const base64, char carry) { return *base64 == 0 ? static_cast<char>(65) : *base64 == c ? carry : UnBase64Impl(c, base64 + 1, static_cast<char>(carry + 1)); } template <size_t... I> constexpr std::array<char, 256> UnBase64Impl(std::index_sequence<I...>, const char* const base64) { return { {UnBase64Impl(UndoWebSafeEncoding(static_cast<char>(I)), base64, 0)...}}; } constexpr std::array<char, 256> UnBase64(const char* const base64) { return UnBase64Impl(std::make_index_sequence<256>{}, base64); } static constexpr char kBase64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; static constexpr std::array<char, 256> kUnBase64 = UnBase64(kBase64); bool Base64Unescape(const std::string& encoded, std::string* decoded) { decoded->clear(); size_t encoded_len = encoded.size(); decoded->reserve(3 * (encoded_len / 4) + (encoded_len % 4)); int bit_pos = 0; char dst = 0; for (int src : encoded) { if (std::isspace(src) || src == '=') { continue; } char src_bin = kUnBase64[static_cast<size_t>(src)]; if (src_bin >= 64) { decoded->clear(); return false; } if (bit_pos == 0) { dst |= static_cast<char>(src_bin << 2); bit_pos = 6; } else { dst |= static_cast<char>(src_bin >> (bit_pos - 2)); decoded->push_back(dst); dst = static_cast<char>(src_bin << (10 - bit_pos)); bit_pos = (bit_pos + 6) % 8; } } return true; } } }
#include "gmock/internal/gmock-internal-utils.h" #include <stdlib.h> #include <cstdint> #include <map> #include <memory> #include <sstream> #include <string> #include <tuple> #include <vector> #include "gmock/gmock.h" #include "gmock/internal/gmock-port.h" #include "gtest/gtest-spi.h" #include "gtest/gtest.h" #define GTEST_IMPLEMENTATION_ 1 #include "src/gtest-internal-inl.h" #undef GTEST_IMPLEMENTATION_ #ifdef GTEST_OS_CYGWIN #include <sys/types.h> #endif namespace proto2 { class Message; } namespace testing { namespace internal { namespace { TEST(JoinAsKeyValueTupleTest, JoinsEmptyTuple) { EXPECT_EQ("", JoinAsKeyValueTuple({}, Strings())); } TEST(JoinAsKeyValueTupleTest, JoinsOneTuple) { EXPECT_EQ("(a: 1)", JoinAsKeyValueTuple({"a"}, {"1"})); } TEST(JoinAsKeyValueTupleTest, JoinsTwoTuple) { EXPECT_EQ("(a: 1, b: 2)", JoinAsKeyValueTuple({"a", "b"}, {"1", "2"})); } TEST(JoinAsKeyValueTupleTest, JoinsTenTuple) { EXPECT_EQ( "(a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10)", JoinAsKeyValueTuple({"a", "b", "c", "d", "e", "f", "g", "h", "i", "j"}, {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"})); } TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameContainsNoWord) { EXPECT_EQ("", ConvertIdentifierNameToWords("")); EXPECT_EQ("", ConvertIdentifierNameToWords("_")); EXPECT_EQ("", ConvertIdentifierNameToWords("__")); } TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameContainsDigits) { EXPECT_EQ("1", ConvertIdentifierNameToWords("_1")); EXPECT_EQ("2", ConvertIdentifierNameToWords("2_")); EXPECT_EQ("34", ConvertIdentifierNameToWords("_34_")); EXPECT_EQ("34 56", ConvertIdentifierNameToWords("_34_56")); } TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameContainsCamelCaseWords) { EXPECT_EQ("a big word", ConvertIdentifierNameToWords("ABigWord")); EXPECT_EQ("foo bar", ConvertIdentifierNameToWords("FooBar")); EXPECT_EQ("foo", ConvertIdentifierNameToWords("Foo_")); EXPECT_EQ("foo bar", ConvertIdentifierNameToWords("_Foo_Bar_")); EXPECT_EQ("foo and bar", ConvertIdentifierNameToWords("_Foo__And_Bar")); } TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameContains_SeparatedWords) { EXPECT_EQ("foo bar", ConvertIdentifierNameToWords("foo_bar")); EXPECT_EQ("foo", ConvertIdentifierNameToWords("_foo_")); EXPECT_EQ("foo bar", ConvertIdentifierNameToWords("_foo_bar_")); EXPECT_EQ("foo and bar", ConvertIdentifierNameToWords("_foo__and_bar")); } TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameIsMixture) { EXPECT_EQ("foo bar 123", ConvertIdentifierNameToWords("Foo_bar123")); EXPECT_EQ("chapter 11 section 1", ConvertIdentifierNameToWords("_Chapter11Section_1_")); } TEST(GetRawPointerTest, WorksForSmartPointers) { const char* const raw_p1 = new const char('a'); const std::unique_ptr<const char> p1(raw_p1); EXPECT_EQ(raw_p1, GetRawPointer(p1)); double* const raw_p2 = new double(2.5); const std::shared_ptr<double> p2(raw_p2); EXPECT_EQ(raw_p2, GetRawPointer(p2)); } TEST(GetRawPointerTest, WorksForRawPointers) { int* p = nullptr; EXPECT_TRUE(nullptr == GetRawPointer(p)); int n = 1; EXPECT_EQ(&n, GetRawPointer(&n)); } TEST(GetRawPointerTest, WorksForStdReferenceWrapper) { int n = 1; EXPECT_EQ(&n, GetRawPointer(std::ref(n))); EXPECT_EQ(&n, GetRawPointer(std::cref(n))); } class Base {}; class Derived : public Base {}; TEST(KindOfTest, Bool) { EXPECT_EQ(kBool, GMOCK_KIND_OF_(bool)); } TEST(KindOfTest, Integer) { EXPECT_EQ(kInteger, GMOCK_KIND_OF_(char)); EXPECT_EQ(kInteger, GMOCK_KIND_OF_(signed char)); EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned char)); EXPECT_EQ(kInteger, GMOCK_KIND_OF_(short)); EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned short)); EXPECT_EQ(kInteger, GMOCK_KIND_OF_(int)); EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned int)); EXPECT_EQ(kInteger, GMOCK_KIND_OF_(long)); EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned long)); EXPECT_EQ(kInteger, GMOCK_KIND_OF_(long long)); EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned long long)); EXPECT_EQ(kInteger, GMOCK_KIND_OF_(wchar_t)); EXPECT_EQ(kInteger, GMOCK_KIND_OF_(size_t)); #if defined(GTEST_OS_LINUX) || defined(GTEST_OS_MAC) || defined(GTEST_OS_CYGWIN) EXPECT_EQ(kInteger, GMOCK_KIND_OF_(ssize_t)); #endif } TEST(KindOfTest, FloatingPoint) { EXPECT_EQ(kFloatingPoint, GMOCK_KIND_OF_(float)); EXPECT_EQ(kFloatingPoint, GMOCK_KIND_OF_(double)); EXPECT_EQ(kFloatingPoint, GMOCK_KIND_OF_(long double)); } TEST(KindOfTest, Other) { EXPECT_EQ(kOther, GMOCK_KIND_OF_(void*)); EXPECT_EQ(kOther, GMOCK_KIND_OF_(char**)); EXPECT_EQ(kOther, GMOCK_KIND_OF_(Base)); } TEST(LosslessArithmeticConvertibleTest, BoolToBool) { EXPECT_TRUE((LosslessArithmeticConvertible<bool, bool>::value)); } TEST(LosslessArithmeticConvertibleTest, BoolToInteger) { EXPECT_TRUE((LosslessArithmeticConvertible<bool, char>::value)); EXPECT_TRUE((LosslessArithmeticConvertible<bool, int>::value)); EXPECT_TRUE( (LosslessArithmeticConvertible<bool, unsigned long>::value)); } TEST(LosslessArithmeticConvertibleTest, BoolToFloatingPoint) { EXPECT_TRUE((LosslessArithmeticConvertible<bool, float>::value)); EXPECT_TRUE((LosslessArithmeticConvertible<bool, double>::value)); } TEST(LosslessArithmeticConvertibleTest, IntegerToBool) { EXPECT_FALSE((LosslessArithmeticConvertible<unsigned char, bool>::value)); EXPECT_FALSE((LosslessArithmeticConvertible<int, bool>::value)); } TEST(LosslessArithmeticConvertibleTest, IntegerToInteger) { EXPECT_TRUE((LosslessArithmeticConvertible<unsigned char, int>::value)); EXPECT_TRUE((LosslessArithmeticConvertible<unsigned short, uint64_t>::value)); EXPECT_FALSE( (LosslessArithmeticConvertible<short, uint64_t>::value)); EXPECT_FALSE((LosslessArithmeticConvertible<signed char, unsigned int>::value)); EXPECT_TRUE( (LosslessArithmeticConvertible<unsigned char, unsigned char>::value)); EXPECT_TRUE((LosslessArithmeticConvertible<int, int>::value)); EXPECT_TRUE((LosslessArithmeticConvertible<wchar_t, wchar_t>::value)); EXPECT_TRUE((LosslessArithmeticConvertible<unsigned long, unsigned long>::value)); EXPECT_FALSE( (LosslessArithmeticConvertible<unsigned char, signed char>::value)); EXPECT_FALSE((LosslessArithmeticConvertible<int, unsigned int>::value)); EXPECT_FALSE((LosslessArithmeticConvertible<uint64_t, int64_t>::value)); EXPECT_FALSE((LosslessArithmeticConvertible<long, char>::value)); EXPECT_FALSE((LosslessArithmeticConvertible<int, signed char>::value)); EXPECT_FALSE((LosslessArithmeticConvertible<int64_t, unsigned int>::value)); } TEST(LosslessArithmeticConvertibleTest, IntegerToFloatingPoint) { EXPECT_FALSE((LosslessArithmeticConvertible<char, float>::value)); EXPECT_FALSE((LosslessArithmeticConvertible<int, double>::value)); EXPECT_FALSE( (LosslessArithmeticConvertible<short, long double>::value)); } TEST(LosslessArithmeticConvertibleTest, FloatingPointToBool) { EXPECT_FALSE((LosslessArithmeticConvertible<float, bool>::value)); EXPECT_FALSE((LosslessArithmeticConvertible<double, bool>::value)); } TEST(LosslessArithmeticConvertibleTest, FloatingPointToInteger) { EXPECT_FALSE((LosslessArithmeticConvertible<float, long>::value)); EXPECT_FALSE((LosslessArithmeticConvertible<double, int64_t>::value)); EXPECT_FALSE((LosslessArithmeticConvertible<long double, int>::value)); } TEST(LosslessArithmeticConvertibleTest, FloatingPointToFloatingPoint) { EXPECT_TRUE((LosslessArithmeticConvertible<float, double>::value)); EXPECT_TRUE((LosslessArithmeticConvertible<float, long double>::value)); EXPECT_TRUE((LosslessArithmeticConvertible<double, long double>::value)); EXPECT_TRUE((LosslessArithmeticConvertible<float, float>::value)); EXPECT_TRUE((LosslessArithmeticConvertible<double, double>::value)); EXPECT_FALSE((LosslessArithmeticConvertible<double, float>::value)); GTEST_INTENTIONAL_CONST_COND_PUSH_() if (sizeof(double) == sizeof(long double)) { GTEST_INTENTIONAL_CONST_COND_POP_() EXPECT_TRUE((LosslessArithmeticConvertible<long double, double>::value)); } else { EXPECT_FALSE((LosslessArithmeticConvertible<long double, double>::value)); } } TEST(TupleMatchesTest, WorksForSize0) { std::tuple<> matchers; std::tuple<> values; EXPECT_TRUE(TupleMatches(matchers, values)); } TEST(TupleMatchesTest, WorksForSize1) { std::tuple<Matcher<int>> matchers(Eq(1)); std::tuple<int> values1(1), values2(2); EXPECT_TRUE(TupleMatches(matchers, values1)); EXPECT_FALSE(TupleMatches(matchers, values2)); } TEST(TupleMatchesTest, WorksForSize2) { std::tuple<Matcher<int>, Matcher<char>> matchers(Eq(1), Eq('a')); std::tuple<int, char> values1(1, 'a'), values2(1, 'b'), values3(2, 'a'), values4(2, 'b'); EXPECT_TRUE(TupleMatches(matchers, values1)); EXPECT_FALSE(TupleMatches(matchers, values2)); EXPECT_FALSE(TupleMatches(matchers, values3)); EXPECT_FALSE(TupleMatches(matchers, values4)); } TEST(TupleMatchesTest, WorksForSize5) { std::tuple<Matcher<int>, Matcher<char>, Matcher<bool>, Matcher<long>, Matcher<std::string>> matchers(Eq(1), Eq('a'), Eq(true), Eq(2L), Eq("hi")); std::tuple<int, char, bool, long, std::string> values1(1, 'a', true, 2L, "hi"), values2(1, 'a', true, 2L, "hello"), values3(2, 'a', true, 2L, "hi"); EXPECT_TRUE(TupleMatches(matchers, values1)); EXPECT_FALSE(TupleMatches(matchers, values2)); EXPECT_FALSE(TupleMatches(matchers, values3)); } TEST(AssertTest, SucceedsOnTrue) { Assert(true, __FILE__, __LINE__, "This should succeed."); Assert(true, __FILE__, __LINE__); } TEST(AssertTest, FailsFatallyOnFalse) { EXPECT_DEATH_IF_SUPPORTED( { Assert(false, __FILE__, __LINE__, "This should fail."); }, ""); EXPECT_DEATH_IF_SUPPORTED({ Assert(false, __FILE__, __LINE__); }, ""); } TEST(ExpectTest, SucceedsOnTrue) { Expect(true, __FILE__, __LINE__, "This should succeed."); Expect(true, __FILE__, __LINE__); } TEST(ExpectTest, FailsNonfatallyOnFalse) { EXPECT_NONFATAL_FAILURE( { Expect(false, __FILE__, __LINE__, "This should fail."); }, "This should fail"); EXPECT_NONFATAL_FAILURE( { Expect(false, __FILE__, __LINE__); }, "Expectation failed"); } class LogIsVisibleTest : public ::testing::Test { protected: void SetUp() override { original_verbose_ = GMOCK_FLAG_GET(verbose); } void TearDown() override { GMOCK_FLAG_SET(verbose, original_verbose_); } std::string original_verbose_; }; TEST_F(LogIsVisibleTest, AlwaysReturnsTrueIfVerbosityIsInfo) { GMOCK_FLAG_SET(verbose, kInfoVerbosity); EXPECT_TRUE(LogIsVisible(kInfo)); EXPECT_TRUE(LogIsVisible(kWarning)); } TEST_F(LogIsVisibleTest, AlwaysReturnsFalseIfVerbosityIsError) { GMOCK_FLAG_SET(verbose, kErrorVerbosity); EXPECT_FALSE(LogIsVisible(kInfo)); EXPECT_FALSE(LogIsVisible(kWarning)); } TEST_F(LogIsVisibleTest, WorksWhenVerbosityIsWarning) { GMOCK_FLAG_SET(verbose, kWarningVerbosity); EXPECT_FALSE(LogIsVisible(kInfo)); EXPECT_TRUE(LogIsVisible(kWarning)); } #if GTEST_HAS_STREAM_REDIRECTION void TestLogWithSeverity(const std::string& verbosity, LogSeverity severity, bool should_print) { const std::string old_flag = GMOCK_FLAG_GET(verbose); GMOCK_FLAG_SET(verbose, verbosity); CaptureStdout(); Log(severity, "Test log.\n", 0); if (should_print) { EXPECT_THAT( GetCapturedStdout().c_str(), ContainsRegex(severity == kWarning ? "^\nGMOCK WARNING:\nTest log\\.\nStack trace:\n" : "^\nTest log\\.\nStack trace:\n")); } else { EXPECT_STREQ("", GetCapturedStdout().c_str()); } GMOCK_FLAG_SET(verbose, old_flag); } TEST(LogTest, NoStackTraceWhenStackFramesToSkipIsNegative) { const std::string saved_flag = GMOCK_FLAG_GET(verbose); GMOCK_FLAG_SET(verbose, kInfoVerbosity); CaptureStdout(); Log(kInfo, "Test log.\n", -1); EXPECT_STREQ("\nTest log.\n", GetCapturedStdout().c_str()); GMOCK_FLAG_SET(verbose, saved_flag); } struct MockStackTraceGetter : testing::internal::OsStackTraceGetterInterface { std::string CurrentStackTrace(int max_depth, int skip_count) override { return (testing::Message() << max_depth << "::" << skip_count << "\n") .GetString(); } void UponLeavingGTest() override {} }; TEST(LogTest, NoSkippingStackFrameInOptMode) { MockStackTraceGetter* mock_os_stack_trace_getter = new MockStackTraceGetter; GetUnitTestImpl()->set_os_stack_trace_getter(mock_os_stack_trace_getter); CaptureStdout(); Log(kWarning, "Test log.\n", 100); const std::string log = GetCapturedStdout(); std::string expected_trace = (testing::Message() << GTEST_FLAG_GET(stack_trace_depth) << "::") .GetString(); std::string expected_message = "\nGMOCK WARNING:\n" "Test log.\n" "Stack trace:\n" + expected_trace; EXPECT_THAT(log, HasSubstr(expected_message)); int skip_count = atoi(log.substr(expected_message.size()).c_str()); #if defined(NDEBUG) const int expected_skip_count = 0; #else const int expected_skip_count = 100; #endif EXPECT_THAT(skip_count, AllOf(Ge(expected_skip_count), Le(expected_skip_count + 10))); GetUnitTestImpl()->set_os_stack_trace_getter(nullptr); } TEST(LogTest, AllLogsArePrintedWhenVerbosityIsInfo) { TestLogWithSeverity(kInfoVerbosity, kInfo, true); TestLogWithSeverity(kInfoVerbosity, kWarning, true); } TEST(LogTest, OnlyWarningsArePrintedWhenVerbosityIsWarning) { TestLogWithSeverity(kWarningVerbosity, kInfo, false); TestLogWithSeverity(kWarningVerbosity, kWarning, true); } TEST(LogTest, NoLogsArePrintedWhenVerbosityIsError) { TestLogWithSeverity(kErrorVerbosity, kInfo, false); TestLogWithSeverity(kErrorVerbosity, kWarning, false); } TEST(LogTest, OnlyWarningsArePrintedWhenVerbosityIsInvalid) { TestLogWithSeverity("invalid", kInfo, false); TestLogWithSeverity("invalid", kWarning, true); } std::string GrabOutput(void (*logger)(), const char* verbosity) { const std::string saved_flag = GMOCK_FLAG_GET(verbose); GMOCK_FLAG_SET(verbose, verbosity); CaptureStdout(); logger(); GMOCK_FLAG_SET(verbose, saved_flag); return GetCapturedStdout(); } class DummyMock { public: MOCK_METHOD0(TestMethod, void()); MOCK_METHOD1(TestMethodArg, void(int dummy)); }; void ExpectCallLogger() { DummyMock mock; EXPECT_CALL(mock, TestMethod()); mock.TestMethod(); } TEST(ExpectCallTest, LogsWhenVerbosityIsInfo) { EXPECT_THAT(std::string(GrabOutput(ExpectCallLogger, kInfoVerbosity)), HasSubstr("EXPECT_CALL(mock, TestMethod())")); } TEST(ExpectCallTest, DoesNotLogWhenVerbosityIsWarning) { EXPECT_STREQ("", GrabOutput(ExpectCallLogger, kWarningVerbosity).c_str()); } TEST(ExpectCallTest, DoesNotLogWhenVerbosityIsError) { EXPECT_STREQ("", GrabOutput(ExpectCallLogger, kErrorVerbosity).c_str()); } void OnCallLogger() { DummyMock mock; ON_CALL(mock, TestMethod()); } TEST(OnCallTest, LogsWhenVerbosityIsInfo) { EXPECT_THAT(std::string(GrabOutput(OnCallLogger, kInfoVerbosity)), HasSubstr("ON_CALL(mock, TestMethod())")); } TEST(OnCallTest, DoesNotLogWhenVerbosityIsWarning) { EXPECT_STREQ("", GrabOutput(OnCallLogger, kWarningVerbosity).c_str()); } TEST(OnCallTest, DoesNotLogWhenVerbosityIsError) { EXPECT_STREQ("", GrabOutput(OnCallLogger, kErrorVerbosity).c_str()); } void OnCallAnyArgumentLogger() { DummyMock mock; ON_CALL(mock, TestMethodArg(_)); } TEST(OnCallTest, LogsAnythingArgument) { EXPECT_THAT(std::string(GrabOutput(OnCallAnyArgumentLogger, kInfoVerbosity)), HasSubstr("ON_CALL(mock, TestMethodArg(_)")); } #endif TEST(StlContainerViewTest, WorksForStlContainer) { StaticAssertTypeEq<std::vector<int>, StlContainerView<std::vector<int>>::type>(); StaticAssertTypeEq<const std::vector<double>&, StlContainerView<std::vector<double>>::const_reference>(); typedef std::vector<char> Chars; Chars v1; const Chars& v2(StlContainerView<Chars>::ConstReference(v1)); EXPECT_EQ(&v1, &v2); v1.push_back('a'); Chars v3 = StlContainerView<Chars>::Copy(v1); EXPECT_THAT(v3, Eq(v3)); } TEST(StlContainerViewTest, WorksForStaticNativeArray) { StaticAssertTypeEq<NativeArray<int>, StlContainerView<int[3]>::type>(); StaticAssertTypeEq<NativeArray<double>, StlContainerView<const double[4]>::type>(); StaticAssertTypeEq<NativeArray<char[3]>, StlContainerView<const char[2][3]>::type>(); StaticAssertTypeEq<const NativeArray<int>, StlContainerView<int[2]>::const_reference>(); int a1[3] = {0, 1, 2}; NativeArray<int> a2 = StlContainerView<int[3]>::ConstReference(a1); EXPECT_EQ(3U, a2.size()); EXPECT_EQ(a1, a2.begin()); const NativeArray<int> a3 = StlContainerView<int[3]>::Copy(a1); ASSERT_EQ(3U, a3.size()); EXPECT_EQ(0, a3.begin()[0]); EXPECT_EQ(1, a3.begin()[1]); EXPECT_EQ(2, a3.begin()[2]); a1[0] = 3; EXPECT_EQ(0, a3.begin()[0]); } TEST(StlContainerViewTest, WorksForDynamicNativeArray) { StaticAssertTypeEq<NativeArray<int>, StlContainerView<std::tuple<const int*, size_t>>::type>(); StaticAssertTypeEq< NativeArray<double>, StlContainerView<std::tuple<std::shared_ptr<double>, int>>::type>(); StaticAssertTypeEq< const NativeArray<int>, StlContainerView<std::tuple<const int*, int>>::const_reference>(); int a1[3] = {0, 1, 2}; const int* const p1 = a1; NativeArray<int> a2 = StlContainerView<std::tuple<const int*, int>>::ConstReference( std::make_tuple(p1, 3)); EXPECT_EQ(3U, a2.size()); EXPECT_EQ(a1, a2.begin()); const NativeArray<int> a3 = StlContainerView<std::tuple<int*, size_t>>::Copy( std::make_tuple(static_cast<int*>(a1), 3)); ASSERT_EQ(3U, a3.size()); EXPECT_EQ(0, a3.begin()[0]); EXPECT_EQ(1, a3.begin()[1]); EXPECT_EQ(2, a3.begin()[2]); a1[0] = 3; EXPECT_EQ(0, a3.begin()[0]); } TEST(FunctionTest, Nullary) { typedef Function<int()> F; EXPECT_EQ(0u, F::ArgumentCount); EXPECT_TRUE((std::is_same<int, F::Result>::value)); EXPECT_TRUE((std::is_same<std::tuple<>, F::ArgumentTuple>::value)); EXPECT_TRUE((std::is_same<std::tuple<>, F::ArgumentMatcherTuple>::value)); EXPECT_TRUE((std::is_same<void(), F::MakeResultVoid>::value)); EXPECT_TRUE((std::is_same<IgnoredValue(), F::MakeResultIgnoredValue>::value)); } TEST(FunctionTest, Unary) { typedef Function<int(bool)> F; EXPECT_EQ(1u, F::ArgumentCount); EXPECT_TRUE((std::is_same<int, F::Result>::value)); EXPECT_TRUE((std::is_same<bool, F::Arg<0>::type>::value)); EXPECT_TRUE((std::is_same<std::tuple<bool>, F::ArgumentTuple>::value)); EXPECT_TRUE(( std::is_same<std::tuple<Matcher<bool>>, F::ArgumentMatcherTuple>::value)); EXPECT_TRUE((std::is_same<void(bool), F::MakeResultVoid>::value)); EXPECT_TRUE((std::is_same<IgnoredValue(bool), F::MakeResultIgnoredValue>::value)); } TEST(FunctionTest, Binary) { typedef Function<int(bool, const long&)> F; EXPECT_EQ(2u, F::ArgumentCount); EXPECT_TRUE((std::is_same<int, F::Result>::value)); EXPECT_TRUE((std::is_same<bool, F::Arg<0>::type>::value)); EXPECT_TRUE((std::is_same<const long&, F::Arg<1>::type>::value)); EXPECT_TRUE((std::is_same<std::tuple<bool, const long&>, F::ArgumentTuple>::value)); EXPECT_TRUE( (std::is_same<std::tuple<Matcher<bool>, Matcher<const long&>>, F::ArgumentMatcherTuple>::value)); EXPECT_TRUE((std::is_same<void(bool, const long&), F::MakeResultVoid>::value)); EXPECT_TRUE((std::is_same<IgnoredValue(bool, const long&), F::MakeResultIgnoredValue>::value)); } TEST(FunctionTest, LongArgumentList) { typedef Function<char(bool, int, char*, int&, const long&)> F; EXPECT_EQ(5u, F::ArgumentCount); EXPECT_TRUE((std::is_same<char, F::Result>::value)); EXPECT_TRUE((std::is_same<bool, F::Arg<0>::type>::value)); EXPECT_TRUE((std::is_same<int, F::Arg<1>::type>::value)); EXPECT_TRUE((std::is_same<char*, F::Arg<2>::type>::value)); EXPECT_TRUE((std::is_same<int&, F::Arg<3>::type>::value)); EXPECT_TRUE((std::is_same<const long&, F::Arg<4>::type>::value)); EXPECT_TRUE( (std::is_same<std::tuple<bool, int, char*, int&, const long&>, F::ArgumentTuple>::value)); EXPECT_TRUE( (std::is_same< std::tuple<Matcher<bool>, Matcher<int>, Matcher<char*>, Matcher<int&>, Matcher<const long&>>, F::ArgumentMatcherTuple>::value)); EXPECT_TRUE( (std::is_same<void(bool, int, char*, int&, const long&), F::MakeResultVoid>::value)); EXPECT_TRUE(( std::is_same<IgnoredValue(bool, int, char*, int&, const long&), F::MakeResultIgnoredValue>::value)); } TEST(Base64Unescape, InvalidString) { std::string unescaped; EXPECT_FALSE(Base64Unescape("(invalid)", &unescaped)); } TEST(Base64Unescape, ShortString) { std::string unescaped; EXPECT_TRUE(Base64Unescape("SGVsbG8gd29ybGQh", &unescaped)); EXPECT_EQ("Hello world!", unescaped); } TEST(Base64Unescape, ShortStringWithPadding) { std::string unescaped; EXPECT_TRUE(Base64Unescape("SGVsbG8gd29ybGQ=", &unescaped)); EXPECT_EQ("Hello world", unescaped); } TEST(Base64Unescape, ShortStringWithoutPadding) { std::string unescaped; EXPECT_TRUE(Base64Unescape("SGVsbG8gd29ybGQ", &unescaped)); EXPECT_EQ("Hello world", unescaped); } TEST(Base64Unescape, LongStringWithWhiteSpaces) { std::string escaped = R"(TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlz IHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2Yg dGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGlu dWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRo ZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4=)"; std::string expected = "Man is distinguished, not only by his reason, but by this singular " "passion from other animals, which is a lust of the mind, that by a " "perseverance of delight in the continued and indefatigable generation " "of knowledge, exceeds the short vehemence of any carnal pleasure."; std::string unescaped; EXPECT_TRUE(Base64Unescape(escaped, &unescaped)); EXPECT_EQ(expected, unescaped); } } } }
2,331
#include "gmock/gmock.h" #include <string> #include "gmock/internal/gmock-port.h" GMOCK_DEFINE_bool_(catch_leaked_mocks, true, "true if and only if Google Mock should report leaked " "mock objects as failures."); GMOCK_DEFINE_string_(verbose, testing::internal::kWarningVerbosity, "Controls how verbose Google Mock's output is." " Valid values:\n" " info - prints all messages.\n" " warning - prints warnings and errors.\n" " error - prints errors only."); GMOCK_DEFINE_int32_(default_mock_behavior, 1, "Controls the default behavior of mocks." " Valid values:\n" " 0 - by default, mocks act as NiceMocks.\n" " 1 - by default, mocks act as NaggyMocks.\n" " 2 - by default, mocks act as StrictMocks."); namespace testing { namespace internal { static const char* ParseGoogleMockFlagValue(const char* str, const char* flag_name, bool def_optional) { if (str == nullptr || flag_name == nullptr) return nullptr; const std::string flag_name_str = std::string("--gmock_") + flag_name; const size_t flag_name_len = flag_name_str.length(); if (strncmp(str, flag_name_str.c_str(), flag_name_len) != 0) return nullptr; const char* flag_end = str + flag_name_len; if (def_optional && (flag_end[0] == '\0')) { return flag_end; } if (flag_end[0] != '=') return nullptr; return flag_end + 1; } static bool ParseGoogleMockFlag(const char* str, const char* flag_name, bool* value) { const char* const value_str = ParseGoogleMockFlagValue(str, flag_name, true); if (value_str == nullptr) return false; *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F'); return true; } template <typename String> static bool ParseGoogleMockFlag(const char* str, const char* flag_name, String* value) { const char* const value_str = ParseGoogleMockFlagValue(str, flag_name, false); if (value_str == nullptr) return false; *value = value_str; return true; } static bool ParseGoogleMockFlag(const char* str, const char* flag_name, int32_t* value) { const char* const value_str = ParseGoogleMockFlagValue(str, flag_name, true); if (value_str == nullptr) return false; return ParseInt32(Message() << "The value of flag --" << flag_name, value_str, value); } template <typename CharType> void InitGoogleMockImpl(int* argc, CharType** argv) { InitGoogleTest(argc, argv); if (*argc <= 0) return; for (int i = 1; i != *argc; i++) { const std::string arg_string = StreamableToString(argv[i]); const char* const arg = arg_string.c_str(); bool found_gmock_flag = false; #define GMOCK_INTERNAL_PARSE_FLAG(flag_name) \ if (!found_gmock_flag) { \ auto value = GMOCK_FLAG_GET(flag_name); \ if (ParseGoogleMockFlag(arg, #flag_name, &value)) { \ GMOCK_FLAG_SET(flag_name, value); \ found_gmock_flag = true; \ } \ } GMOCK_INTERNAL_PARSE_FLAG(catch_leaked_mocks) GMOCK_INTERNAL_PARSE_FLAG(verbose) GMOCK_INTERNAL_PARSE_FLAG(default_mock_behavior) if (found_gmock_flag) { for (int j = i; j != *argc; j++) { argv[j] = argv[j + 1]; } (*argc)--; i--; } } } } GTEST_API_ void InitGoogleMock(int* argc, char** argv) { internal::InitGoogleMockImpl(argc, argv); } GTEST_API_ void InitGoogleMock(int* argc, wchar_t** argv) { internal::InitGoogleMockImpl(argc, argv); } GTEST_API_ void InitGoogleMock() { int argc = 1; const auto arg0 = "dummy"; char* argv0 = const_cast<char*>(arg0); char** argv = &argv0; internal::InitGoogleMockImpl(&argc, argv); } }
#include "gmock/gmock.h" #include <string> #include "gtest/gtest.h" #include "gtest/internal/custom/gtest.h" #if !defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) using testing::InitGoogleMock; template <typename Char, int M, int N> void TestInitGoogleMock(const Char* (&argv)[M], const Char* (&new_argv)[N], const ::std::string& expected_gmock_verbose) { const ::std::string old_verbose = GMOCK_FLAG_GET(verbose); int argc = M - 1; InitGoogleMock(&argc, const_cast<Char**>(argv)); ASSERT_EQ(N - 1, argc) << "The new argv has wrong number of elements."; for (int i = 0; i < N; i++) { EXPECT_STREQ(new_argv[i], argv[i]); } EXPECT_EQ(expected_gmock_verbose, GMOCK_FLAG_GET(verbose)); GMOCK_FLAG_SET(verbose, old_verbose); } TEST(InitGoogleMockTest, ParsesInvalidCommandLine) { const char* argv[] = {nullptr}; const char* new_argv[] = {nullptr}; TestInitGoogleMock(argv, new_argv, GMOCK_FLAG_GET(verbose)); } TEST(InitGoogleMockTest, ParsesEmptyCommandLine) { const char* argv[] = {"foo.exe", nullptr}; const char* new_argv[] = {"foo.exe", nullptr}; TestInitGoogleMock(argv, new_argv, GMOCK_FLAG_GET(verbose)); } TEST(InitGoogleMockTest, ParsesSingleFlag) { const char* argv[] = {"foo.exe", "--gmock_verbose=info", nullptr}; const char* new_argv[] = {"foo.exe", nullptr}; TestInitGoogleMock(argv, new_argv, "info"); } TEST(InitGoogleMockTest, ParsesMultipleFlags) { int old_default_behavior = GMOCK_FLAG_GET(default_mock_behavior); const wchar_t* argv[] = {L"foo.exe", L"--gmock_verbose=info", L"--gmock_default_mock_behavior=2", nullptr}; const wchar_t* new_argv[] = {L"foo.exe", nullptr}; TestInitGoogleMock(argv, new_argv, "info"); EXPECT_EQ(2, GMOCK_FLAG_GET(default_mock_behavior)); EXPECT_NE(2, old_default_behavior); GMOCK_FLAG_SET(default_mock_behavior, old_default_behavior); } TEST(InitGoogleMockTest, ParsesUnrecognizedFlag) { const char* argv[] = {"foo.exe", "--non_gmock_flag=blah", nullptr}; const char* new_argv[] = {"foo.exe", "--non_gmock_flag=blah", nullptr}; TestInitGoogleMock(argv, new_argv, GMOCK_FLAG_GET(verbose)); } TEST(InitGoogleMockTest, ParsesGoogleMockFlagAndUnrecognizedFlag) { const char* argv[] = {"foo.exe", "--non_gmock_flag=blah", "--gmock_verbose=error", nullptr}; const char* new_argv[] = {"foo.exe", "--non_gmock_flag=blah", nullptr}; TestInitGoogleMock(argv, new_argv, "error"); } TEST(WideInitGoogleMockTest, ParsesInvalidCommandLine) { const wchar_t* argv[] = {nullptr}; const wchar_t* new_argv[] = {nullptr}; TestInitGoogleMock(argv, new_argv, GMOCK_FLAG_GET(verbose)); } TEST(WideInitGoogleMockTest, ParsesEmptyCommandLine) { const wchar_t* argv[] = {L"foo.exe", nullptr}; const wchar_t* new_argv[] = {L"foo.exe", nullptr}; TestInitGoogleMock(argv, new_argv, GMOCK_FLAG_GET(verbose)); } TEST(WideInitGoogleMockTest, ParsesSingleFlag) { const wchar_t* argv[] = {L"foo.exe", L"--gmock_verbose=info", nullptr}; const wchar_t* new_argv[] = {L"foo.exe", nullptr}; TestInitGoogleMock(argv, new_argv, "info"); } TEST(WideInitGoogleMockTest, ParsesMultipleFlags) { int old_default_behavior = GMOCK_FLAG_GET(default_mock_behavior); const wchar_t* argv[] = {L"foo.exe", L"--gmock_verbose=info", L"--gmock_default_mock_behavior=2", nullptr}; const wchar_t* new_argv[] = {L"foo.exe", nullptr}; TestInitGoogleMock(argv, new_argv, "info"); EXPECT_EQ(2, GMOCK_FLAG_GET(default_mock_behavior)); EXPECT_NE(2, old_default_behavior); GMOCK_FLAG_SET(default_mock_behavior, old_default_behavior); } TEST(WideInitGoogleMockTest, ParsesUnrecognizedFlag) { const wchar_t* argv[] = {L"foo.exe", L"--non_gmock_flag=blah", nullptr}; const wchar_t* new_argv[] = {L"foo.exe", L"--non_gmock_flag=blah", nullptr}; TestInitGoogleMock(argv, new_argv, GMOCK_FLAG_GET(verbose)); } TEST(WideInitGoogleMockTest, ParsesGoogleMockFlagAndUnrecognizedFlag) { const wchar_t* argv[] = {L"foo.exe", L"--non_gmock_flag=blah", L"--gmock_verbose=error", nullptr}; const wchar_t* new_argv[] = {L"foo.exe", L"--non_gmock_flag=blah", nullptr}; TestInitGoogleMock(argv, new_argv, "error"); } #endif TEST(FlagTest, IsAccessibleInCode) { bool dummy = GMOCK_FLAG_GET(catch_leaked_mocks) && GMOCK_FLAG_GET(verbose).empty(); (void)dummy; }
2,332
#include "gmock/gmock-spec-builders.h" #include <stdlib.h> #include <iostream> #include <map> #include <memory> #include <set> #include <sstream> #include <string> #include <unordered_map> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "gtest/internal/gtest-port.h" #if defined(GTEST_OS_CYGWIN) || defined(GTEST_OS_LINUX) || defined(GTEST_OS_MAC) #include <unistd.h> #endif #ifdef GTEST_OS_QURT #include <qurt_event.h> #endif #if defined(_MSC_VER) && (_MSC_VER == 1900) GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800) #endif namespace testing { namespace internal { GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_gmock_mutex); GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity, const char* file, int line, const std::string& message) { ::std::ostringstream s; s << internal::FormatFileLocation(file, line) << " " << message << ::std::endl; Log(severity, s.str(), 0); } ExpectationBase::ExpectationBase(const char* a_file, int a_line, const std::string& a_source_text) : file_(a_file), line_(a_line), source_text_(a_source_text), cardinality_specified_(false), cardinality_(Exactly(1)), call_count_(0), retired_(false), extra_matcher_specified_(false), repeated_action_specified_(false), retires_on_saturation_(false), last_clause_(kNone), action_count_checked_(false) {} ExpectationBase::~ExpectationBase() = default; void ExpectationBase::SpecifyCardinality(const Cardinality& a_cardinality) { cardinality_specified_ = true; cardinality_ = a_cardinality; } void ExpectationBase::RetireAllPreRequisites() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { if (is_retired()) { return; } ::std::vector<ExpectationBase*> expectations(1, this); while (!expectations.empty()) { ExpectationBase* exp = expectations.back(); expectations.pop_back(); for (ExpectationSet::const_iterator it = exp->immediate_prerequisites_.begin(); it != exp->immediate_prerequisites_.end(); ++it) { ExpectationBase* next = it->expectation_base().get(); if (!next->is_retired()) { next->Retire(); expectations.push_back(next); } } } } bool ExpectationBase::AllPrerequisitesAreSatisfied() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); ::std::vector<const ExpectationBase*> expectations(1, this); while (!expectations.empty()) { const ExpectationBase* exp = expectations.back(); expectations.pop_back(); for (ExpectationSet::const_iterator it = exp->immediate_prerequisites_.begin(); it != exp->immediate_prerequisites_.end(); ++it) { const ExpectationBase* next = it->expectation_base().get(); if (!next->IsSatisfied()) return false; expectations.push_back(next); } } return true; } void ExpectationBase::FindUnsatisfiedPrerequisites(ExpectationSet* result) const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); ::std::vector<const ExpectationBase*> expectations(1, this); while (!expectations.empty()) { const ExpectationBase* exp = expectations.back(); expectations.pop_back(); for (ExpectationSet::const_iterator it = exp->immediate_prerequisites_.begin(); it != exp->immediate_prerequisites_.end(); ++it) { const ExpectationBase* next = it->expectation_base().get(); if (next->IsSatisfied()) { if (next->call_count_ == 0) { expectations.push_back(next); } } else { *result += *it; } } } } void ExpectationBase::DescribeCallCountTo(::std::ostream* os) const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); *os << " Expected: to be "; cardinality().DescribeTo(os); *os << "\n Actual: "; Cardinality::DescribeActualCallCountTo(call_count(), os); *os << " - " << (IsOverSaturated() ? "over-saturated" : IsSaturated() ? "saturated" : IsSatisfied() ? "satisfied" : "unsatisfied") << " and " << (is_retired() ? "retired" : "active"); } void ExpectationBase::CheckActionCountIfNotDone() const GTEST_LOCK_EXCLUDED_(mutex_) { bool should_check = false; { MutexLock l(&mutex_); if (!action_count_checked_) { action_count_checked_ = true; should_check = true; } } if (should_check) { if (!cardinality_specified_) { return; } const int action_count = static_cast<int>(untyped_actions_.size()); const int upper_bound = cardinality().ConservativeUpperBound(); const int lower_bound = cardinality().ConservativeLowerBound(); bool too_many; if (action_count > upper_bound || (action_count == upper_bound && repeated_action_specified_)) { too_many = true; } else if (0 < action_count && action_count < lower_bound && !repeated_action_specified_) { too_many = false; } else { return; } ::std::stringstream ss; DescribeLocationTo(&ss); ss << "Too " << (too_many ? "many" : "few") << " actions specified in " << source_text() << "...\n" << "Expected to be "; cardinality().DescribeTo(&ss); ss << ", but has " << (too_many ? "" : "only ") << action_count << " WillOnce()" << (action_count == 1 ? "" : "s"); if (repeated_action_specified_) { ss << " and a WillRepeatedly()"; } ss << "."; Log(kWarning, ss.str(), -1); } } void ExpectationBase::UntypedTimes(const Cardinality& a_cardinality) { if (last_clause_ == kTimes) { ExpectSpecProperty(false, ".Times() cannot appear " "more than once in an EXPECT_CALL()."); } else { ExpectSpecProperty( last_clause_ < kTimes, ".Times() may only appear *before* .InSequence(), .WillOnce(), " ".WillRepeatedly(), or .RetiresOnSaturation(), not after."); } last_clause_ = kTimes; SpecifyCardinality(a_cardinality); } GTEST_API_ ThreadLocal<Sequence*> g_gmock_implicit_sequence; void ReportUninterestingCall(CallReaction reaction, const std::string& msg) { const int stack_frames_to_skip = GMOCK_FLAG_GET(verbose) == kInfoVerbosity ? 3 : -1; switch (reaction) { case kAllow: Log(kInfo, msg, stack_frames_to_skip); break; case kWarn: Log(kWarning, msg + "\nNOTE: You can safely ignore the above warning unless this " "call should not happen. Do not suppress it by blindly adding " "an EXPECT_CALL() if you don't mean to enforce the call. " "See " "https: "gmock_cook_book.md#" "knowing-when-to-expect-useoncall for details.\n", stack_frames_to_skip); break; default: Expect(false, nullptr, -1, msg); } } UntypedFunctionMockerBase::UntypedFunctionMockerBase() : mock_obj_(nullptr), name_("") {} UntypedFunctionMockerBase::~UntypedFunctionMockerBase() = default; void UntypedFunctionMockerBase::RegisterOwner(const void* mock_obj) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { { MutexLock l(&g_gmock_mutex); mock_obj_ = mock_obj; } Mock::Register(mock_obj, this); } void UntypedFunctionMockerBase::SetOwnerAndName(const void* mock_obj, const char* name) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { MutexLock l(&g_gmock_mutex); mock_obj_ = mock_obj; name_ = name; } const void* UntypedFunctionMockerBase::MockObject() const GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { const void* mock_obj; { MutexLock l(&g_gmock_mutex); Assert(mock_obj_ != nullptr, __FILE__, __LINE__, "MockObject() must not be called before RegisterOwner() or " "SetOwnerAndName() has been called."); mock_obj = mock_obj_; } return mock_obj; } const char* UntypedFunctionMockerBase::Name() const GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { const char* name; { MutexLock l(&g_gmock_mutex); Assert(name_ != nullptr, __FILE__, __LINE__, "Name() must not be called before SetOwnerAndName() has " "been called."); name = name_; } return name; } Expectation UntypedFunctionMockerBase::GetHandleOf(ExpectationBase* exp) { for (UntypedExpectations::const_iterator it = untyped_expectations_.begin(); it != untyped_expectations_.end(); ++it) { if (it->get() == exp) { return Expectation(*it); } } Assert(false, __FILE__, __LINE__, "Cannot find expectation."); return Expectation(); } bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); bool expectations_met = true; for (UntypedExpectations::const_iterator it = untyped_expectations_.begin(); it != untyped_expectations_.end(); ++it) { ExpectationBase* const untyped_expectation = it->get(); if (untyped_expectation->IsOverSaturated()) { expectations_met = false; } else if (!untyped_expectation->IsSatisfied()) { expectations_met = false; ::std::stringstream ss; const ::std::string& expectation_name = untyped_expectation->GetDescription(); ss << "Actual function "; if (!expectation_name.empty()) { ss << "\"" << expectation_name << "\" "; } ss << "call count doesn't match " << untyped_expectation->source_text() << "...\n"; untyped_expectation->MaybeDescribeExtraMatcherTo(&ss); untyped_expectation->DescribeCallCountTo(&ss); Expect(false, untyped_expectation->file(), untyped_expectation->line(), ss.str()); } } UntypedExpectations expectations_to_delete; untyped_expectations_.swap(expectations_to_delete); g_gmock_mutex.Unlock(); expectations_to_delete.clear(); g_gmock_mutex.Lock(); return expectations_met; } static CallReaction intToCallReaction(int mock_behavior) { if (mock_behavior >= kAllow && mock_behavior <= kFail) { return static_cast<internal::CallReaction>(mock_behavior); } return kWarn; } } namespace { typedef std::set<internal::UntypedFunctionMockerBase*> FunctionMockers; struct MockObjectState { MockObjectState() : first_used_file(nullptr), first_used_line(-1), leakable(false) {} const char* first_used_file; int first_used_line; ::std::string first_used_test_suite; ::std::string first_used_test; bool leakable; FunctionMockers function_mockers; }; class MockObjectRegistry { public: typedef std::map<const void*, MockObjectState> StateMap; ~MockObjectRegistry() { if (!GMOCK_FLAG_GET(catch_leaked_mocks)) return; internal::MutexLock l(&internal::g_gmock_mutex); int leaked_count = 0; for (StateMap::const_iterator it = states_.begin(); it != states_.end(); ++it) { if (it->second.leakable) continue; std::cout << "\n"; const MockObjectState& state = it->second; std::cout << internal::FormatFileLocation(state.first_used_file, state.first_used_line); std::cout << " ERROR: this mock object"; if (!state.first_used_test.empty()) { std::cout << " (used in test " << state.first_used_test_suite << "." << state.first_used_test << ")"; } std::cout << " should be deleted but never is. Its address is @" << it->first << "."; leaked_count++; } if (leaked_count > 0) { std::cout << "\nERROR: " << leaked_count << " leaked mock " << (leaked_count == 1 ? "object" : "objects") << " found at program exit. Expectations on a mock object are " "verified when the object is destructed. Leaking a mock " "means that its expectations aren't verified, which is " "usually a test bug. If you really intend to leak a mock, " "you can suppress this error using " "testing::Mock::AllowLeak(mock_object), or you may use a " "fake or stub instead of a mock.\n"; std::cout.flush(); ::std::cerr.flush(); #ifdef GTEST_OS_QURT qurt_exception_raise_fatal(); #else _Exit(1); #endif } } StateMap& states() { return states_; } private: StateMap states_; }; MockObjectRegistry g_mock_object_registry; std::unordered_map<uintptr_t, internal::CallReaction>& UninterestingCallReactionMap() { static auto* map = new std::unordered_map<uintptr_t, internal::CallReaction>; return *map; } void SetReactionOnUninterestingCalls(uintptr_t mock_obj, internal::CallReaction reaction) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { internal::MutexLock l(&internal::g_gmock_mutex); UninterestingCallReactionMap()[mock_obj] = reaction; } } void Mock::AllowUninterestingCalls(uintptr_t mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { SetReactionOnUninterestingCalls(mock_obj, internal::kAllow); } void Mock::WarnUninterestingCalls(uintptr_t mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { SetReactionOnUninterestingCalls(mock_obj, internal::kWarn); } void Mock::FailUninterestingCalls(uintptr_t mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { SetReactionOnUninterestingCalls(mock_obj, internal::kFail); } void Mock::UnregisterCallReaction(uintptr_t mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { internal::MutexLock l(&internal::g_gmock_mutex); UninterestingCallReactionMap().erase(static_cast<uintptr_t>(mock_obj)); } internal::CallReaction Mock::GetReactionOnUninterestingCalls( const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { internal::MutexLock l(&internal::g_gmock_mutex); return (UninterestingCallReactionMap().count( reinterpret_cast<uintptr_t>(mock_obj)) == 0) ? internal::intToCallReaction( GMOCK_FLAG_GET(default_mock_behavior)) : UninterestingCallReactionMap()[reinterpret_cast<uintptr_t>( mock_obj)]; } void Mock::AllowLeak(const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { internal::MutexLock l(&internal::g_gmock_mutex); g_mock_object_registry.states()[mock_obj].leakable = true; } bool Mock::VerifyAndClearExpectations(void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { internal::MutexLock l(&internal::g_gmock_mutex); return VerifyAndClearExpectationsLocked(mock_obj); } bool Mock::VerifyAndClear(void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { internal::MutexLock l(&internal::g_gmock_mutex); ClearDefaultActionsLocked(mock_obj); return VerifyAndClearExpectationsLocked(mock_obj); } bool Mock::VerifyAndClearExpectationsLocked(void* mock_obj) GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) { internal::g_gmock_mutex.AssertHeld(); if (g_mock_object_registry.states().count(mock_obj) == 0) { return true; } bool expectations_met = true; FunctionMockers& mockers = g_mock_object_registry.states()[mock_obj].function_mockers; for (FunctionMockers::const_iterator it = mockers.begin(); it != mockers.end(); ++it) { if (!(*it)->VerifyAndClearExpectationsLocked()) { expectations_met = false; } } return expectations_met; } bool Mock::IsNaggy(void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { return Mock::GetReactionOnUninterestingCalls(mock_obj) == internal::kWarn; } bool Mock::IsNice(void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { return Mock::GetReactionOnUninterestingCalls(mock_obj) == internal::kAllow; } bool Mock::IsStrict(void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { return Mock::GetReactionOnUninterestingCalls(mock_obj) == internal::kFail; } void Mock::Register(const void* mock_obj, internal::UntypedFunctionMockerBase* mocker) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { internal::MutexLock l(&internal::g_gmock_mutex); g_mock_object_registry.states()[mock_obj].function_mockers.insert(mocker); } void Mock::RegisterUseByOnCallOrExpectCall(const void* mock_obj, const char* file, int line) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { internal::MutexLock l(&internal::g_gmock_mutex); MockObjectState& state = g_mock_object_registry.states()[mock_obj]; if (state.first_used_file == nullptr) { state.first_used_file = file; state.first_used_line = line; const TestInfo* const test_info = UnitTest::GetInstance()->current_test_info(); if (test_info != nullptr) { state.first_used_test_suite = test_info->test_suite_name(); state.first_used_test = test_info->name(); } } } void Mock::UnregisterLocked(internal::UntypedFunctionMockerBase* mocker) GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) { internal::g_gmock_mutex.AssertHeld(); for (MockObjectRegistry::StateMap::iterator it = g_mock_object_registry.states().begin(); it != g_mock_object_registry.states().end(); ++it) { FunctionMockers& mockers = it->second.function_mockers; if (mockers.erase(mocker) > 0) { if (mockers.empty()) { g_mock_object_registry.states().erase(it); } return; } } } void Mock::ClearDefaultActionsLocked(void* mock_obj) GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) { internal::g_gmock_mutex.AssertHeld(); if (g_mock_object_registry.states().count(mock_obj) == 0) { return; } FunctionMockers& mockers = g_mock_object_registry.states()[mock_obj].function_mockers; for (FunctionMockers::const_iterator it = mockers.begin(); it != mockers.end(); ++it) { (*it)->ClearDefaultActionsLocked(); } } Expectation::Expectation() = default; Expectation::Expectation( const std::shared_ptr<internal::ExpectationBase>& an_expectation_base) : expectation_base_(an_expectation_base) {} Expectation::~Expectation() = default; void Sequence::AddExpectation(const Expectation& expectation) const { if (*last_expectation_ != expectation) { if (last_expectation_->expectation_base() != nullptr) { expectation.expectation_base()->immediate_prerequisites_ += *last_expectation_; } *last_expectation_ = expectation; } } InSequence::InSequence() { if (internal::g_gmock_implicit_sequence.get() == nullptr) { internal::g_gmock_implicit_sequence.set(new Sequence); sequence_created_ = true; } else { sequence_created_ = false; } } InSequence::~InSequence() { if (sequence_created_) { delete internal::g_gmock_implicit_sequence.get(); internal::g_gmock_implicit_sequence.set(nullptr); } } } #if defined(_MSC_VER) && (_MSC_VER == 1900) GTEST_DISABLE_MSC_WARNINGS_POP_() #endif
#include "gmock/gmock-spec-builders.h" #include <memory> #include <ostream> #include <sstream> #include <string> #include <type_traits> #include "gmock/gmock.h" #include "gmock/internal/gmock-port.h" #include "gtest/gtest-spi.h" #include "gtest/gtest.h" #include "gtest/internal/gtest-port.h" namespace testing { namespace { using ::testing::internal::FormatFileLocation; using ::testing::internal::kAllow; using ::testing::internal::kErrorVerbosity; using ::testing::internal::kFail; using ::testing::internal::kInfoVerbosity; using ::testing::internal::kWarn; using ::testing::internal::kWarningVerbosity; #if GTEST_HAS_STREAM_REDIRECTION using ::testing::internal::CaptureStdout; using ::testing::internal::GetCapturedStdout; #endif class Incomplete; class MockIncomplete { public: MOCK_METHOD1(ByRefFunc, void(const Incomplete& x)); }; void PrintTo(const Incomplete& x, ::std::ostream* os); TEST(MockMethodTest, CanInstantiateWithIncompleteArgType) { MockIncomplete incomplete; EXPECT_CALL(incomplete, ByRefFunc(_)).Times(AnyNumber()); } void PrintTo(const Incomplete& , ::std::ostream* os) { *os << "incomplete"; } class Result {}; class NonDefaultConstructible { public: explicit NonDefaultConstructible(int ) {} }; class MockA { public: MockA() = default; MOCK_METHOD1(DoA, void(int n)); MOCK_METHOD1(ReturnResult, Result(int n)); MOCK_METHOD0(ReturnNonDefaultConstructible, NonDefaultConstructible()); MOCK_METHOD2(Binary, bool(int x, int y)); MOCK_METHOD2(ReturnInt, int(int x, int y)); private: MockA(const MockA&) = delete; MockA& operator=(const MockA&) = delete; }; class MockB { public: MockB() = default; MOCK_CONST_METHOD0(DoB, int()); MOCK_METHOD1(DoB, int(int n)); private: MockB(const MockB&) = delete; MockB& operator=(const MockB&) = delete; }; class ReferenceHoldingMock { public: ReferenceHoldingMock() = default; MOCK_METHOD1(AcceptReference, void(std::shared_ptr<MockA>*)); private: ReferenceHoldingMock(const ReferenceHoldingMock&) = delete; ReferenceHoldingMock& operator=(const ReferenceHoldingMock&) = delete; }; #define Method MethodW class CC { public: virtual ~CC() = default; virtual int Method() = 0; }; class MockCC : public CC { public: MockCC() = default; MOCK_METHOD0(Method, int()); private: MockCC(const MockCC&) = delete; MockCC& operator=(const MockCC&) = delete; }; TEST(OnCallSyntaxTest, CompilesWithMethodNameExpandedFromMacro) { MockCC cc; ON_CALL(cc, Method()); } TEST(OnCallSyntaxTest, WorksWithMethodNameExpandedFromMacro) { MockCC cc; ON_CALL(cc, Method()).WillByDefault(Return(42)); EXPECT_EQ(42, cc.Method()); } TEST(ExpectCallSyntaxTest, CompilesWithMethodNameExpandedFromMacro) { MockCC cc; EXPECT_CALL(cc, Method()); cc.Method(); } TEST(ExpectCallSyntaxTest, WorksWithMethodNameExpandedFromMacro) { MockCC cc; EXPECT_CALL(cc, Method()).WillOnce(Return(42)); EXPECT_EQ(42, cc.Method()); } #undef Method TEST(OnCallSyntaxTest, EvaluatesFirstArgumentOnce) { MockA a; MockA* pa = &a; ON_CALL(*pa++, DoA(_)); EXPECT_EQ(&a + 1, pa); } TEST(OnCallSyntaxTest, EvaluatesSecondArgumentOnce) { MockA a; int n = 0; ON_CALL(a, DoA(n++)); EXPECT_EQ(1, n); } TEST(OnCallSyntaxTest, WithIsOptional) { MockA a; ON_CALL(a, DoA(5)).WillByDefault(Return()); ON_CALL(a, DoA(_)).With(_).WillByDefault(Return()); } TEST(OnCallSyntaxTest, WithCanAppearAtMostOnce) { MockA a; EXPECT_NONFATAL_FAILURE( { ON_CALL(a, ReturnResult(_)) .With(_) .With(_) .WillByDefault(Return(Result())); }, ".With() cannot appear more than once in an ON_CALL()"); } TEST(OnCallSyntaxTest, WillByDefaultIsMandatory) { MockA a; EXPECT_DEATH_IF_SUPPORTED( { ON_CALL(a, DoA(5)); a.DoA(5); }, ""); } TEST(OnCallSyntaxTest, WillByDefaultCanAppearAtMostOnce) { MockA a; EXPECT_NONFATAL_FAILURE( { ON_CALL(a, DoA(5)).WillByDefault(Return()).WillByDefault(Return()); }, ".WillByDefault() must appear exactly once in an ON_CALL()"); } TEST(ExpectCallSyntaxTest, EvaluatesFirstArgumentOnce) { MockA a; MockA* pa = &a; EXPECT_CALL(*pa++, DoA(_)); a.DoA(0); EXPECT_EQ(&a + 1, pa); } TEST(ExpectCallSyntaxTest, EvaluatesSecondArgumentOnce) { MockA a; int n = 0; EXPECT_CALL(a, DoA(n++)); a.DoA(0); EXPECT_EQ(1, n); } TEST(ExpectCallSyntaxTest, WithIsOptional) { MockA a; EXPECT_CALL(a, DoA(5)).Times(0); EXPECT_CALL(a, DoA(6)).With(_).Times(0); } TEST(ExpectCallSyntaxTest, WithCanAppearAtMostOnce) { MockA a; EXPECT_NONFATAL_FAILURE( { EXPECT_CALL(a, DoA(6)).With(_).With(_); }, ".With() cannot appear more than once in an EXPECT_CALL()"); a.DoA(6); } TEST(ExpectCallSyntaxTest, WithMustBeFirstClause) { MockA a; EXPECT_NONFATAL_FAILURE( { EXPECT_CALL(a, DoA(1)).Times(1).With(_); }, ".With() must be the first clause in an EXPECT_CALL()"); a.DoA(1); EXPECT_NONFATAL_FAILURE( { EXPECT_CALL(a, DoA(2)).WillOnce(Return()).With(_); }, ".With() must be the first clause in an EXPECT_CALL()"); a.DoA(2); } TEST(ExpectCallSyntaxTest, TimesCanBeInferred) { MockA a; EXPECT_CALL(a, DoA(1)).WillOnce(Return()); EXPECT_CALL(a, DoA(2)).WillOnce(Return()).WillRepeatedly(Return()); a.DoA(1); a.DoA(2); a.DoA(2); } TEST(ExpectCallSyntaxTest, TimesCanAppearAtMostOnce) { MockA a; EXPECT_NONFATAL_FAILURE( { EXPECT_CALL(a, DoA(1)).Times(1).Times(2); }, ".Times() cannot appear more than once in an EXPECT_CALL()"); a.DoA(1); a.DoA(1); } TEST(ExpectCallSyntaxTest, TimesMustBeBeforeInSequence) { MockA a; Sequence s; EXPECT_NONFATAL_FAILURE( { EXPECT_CALL(a, DoA(1)).InSequence(s).Times(1); }, ".Times() may only appear *before* "); a.DoA(1); } TEST(ExpectCallSyntaxTest, InSequenceIsOptional) { MockA a; Sequence s; EXPECT_CALL(a, DoA(1)); EXPECT_CALL(a, DoA(2)).InSequence(s); a.DoA(1); a.DoA(2); } TEST(ExpectCallSyntaxTest, InSequenceCanAppearMultipleTimes) { MockA a; Sequence s1, s2; EXPECT_CALL(a, DoA(1)).InSequence(s1, s2).InSequence(s1); a.DoA(1); } TEST(ExpectCallSyntaxTest, InSequenceMustBeBeforeAfter) { MockA a; Sequence s; Expectation e = EXPECT_CALL(a, DoA(1)).Times(AnyNumber()); EXPECT_NONFATAL_FAILURE( { EXPECT_CALL(a, DoA(2)).After(e).InSequence(s); }, ".InSequence() cannot appear after "); a.DoA(2); } TEST(ExpectCallSyntaxTest, InSequenceMustBeBeforeWillOnce) { MockA a; Sequence s; EXPECT_NONFATAL_FAILURE( { EXPECT_CALL(a, DoA(1)).WillOnce(Return()).InSequence(s); }, ".InSequence() cannot appear after "); a.DoA(1); } TEST(ExpectCallSyntaxTest, AfterMustBeBeforeWillOnce) { MockA a; Expectation e = EXPECT_CALL(a, DoA(1)); EXPECT_NONFATAL_FAILURE( { EXPECT_CALL(a, DoA(2)).WillOnce(Return()).After(e); }, ".After() cannot appear after "); a.DoA(1); a.DoA(2); } TEST(ExpectCallSyntaxTest, WillIsOptional) { MockA a; EXPECT_CALL(a, DoA(1)); EXPECT_CALL(a, DoA(2)).WillOnce(Return()); a.DoA(1); a.DoA(2); } TEST(ExpectCallSyntaxTest, WillCanAppearMultipleTimes) { MockA a; EXPECT_CALL(a, DoA(1)) .Times(AnyNumber()) .WillOnce(Return()) .WillOnce(Return()) .WillOnce(Return()); } TEST(ExpectCallSyntaxTest, WillMustBeBeforeWillRepeatedly) { MockA a; EXPECT_NONFATAL_FAILURE( { EXPECT_CALL(a, DoA(1)).WillRepeatedly(Return()).WillOnce(Return()); }, ".WillOnce() cannot appear after "); a.DoA(1); } TEST(ExpectCallSyntaxTest, WillRepeatedlyIsOptional) { MockA a; EXPECT_CALL(a, DoA(1)).WillOnce(Return()); EXPECT_CALL(a, DoA(2)).WillOnce(Return()).WillRepeatedly(Return()); a.DoA(1); a.DoA(2); a.DoA(2); } TEST(ExpectCallSyntaxTest, WillRepeatedlyCannotAppearMultipleTimes) { MockA a; EXPECT_NONFATAL_FAILURE( { EXPECT_CALL(a, DoA(1)).WillRepeatedly(Return()).WillRepeatedly( Return()); }, ".WillRepeatedly() cannot appear more than once in an " "EXPECT_CALL()"); } TEST(ExpectCallSyntaxTest, WillRepeatedlyMustBeBeforeRetiresOnSaturation) { MockA a; EXPECT_NONFATAL_FAILURE( { EXPECT_CALL(a, DoA(1)).RetiresOnSaturation().WillRepeatedly(Return()); }, ".WillRepeatedly() cannot appear after "); } TEST(ExpectCallSyntaxTest, RetiresOnSaturationIsOptional) { MockA a; EXPECT_CALL(a, DoA(1)); EXPECT_CALL(a, DoA(1)).RetiresOnSaturation(); a.DoA(1); a.DoA(1); } TEST(ExpectCallSyntaxTest, RetiresOnSaturationCannotAppearMultipleTimes) { MockA a; EXPECT_NONFATAL_FAILURE( { EXPECT_CALL(a, DoA(1)).RetiresOnSaturation().RetiresOnSaturation(); }, ".RetiresOnSaturation() cannot appear more than once"); a.DoA(1); } TEST(ExpectCallSyntaxTest, DefaultCardinalityIsOnce) { { MockA a; EXPECT_CALL(a, DoA(1)); a.DoA(1); } EXPECT_NONFATAL_FAILURE( { MockA a; EXPECT_CALL(a, DoA(1)); }, "to be called once"); EXPECT_NONFATAL_FAILURE( { MockA a; EXPECT_CALL(a, DoA(1)); a.DoA(1); a.DoA(1); }, "to be called once"); } #if GTEST_HAS_STREAM_REDIRECTION TEST(ExpectCallSyntaxTest, DoesNotWarnOnAdequateActionCount) { CaptureStdout(); { MockB b; EXPECT_CALL(b, DoB()).Times(0); EXPECT_CALL(b, DoB(1)).Times(AtMost(1)); EXPECT_CALL(b, DoB(2)).Times(1).WillRepeatedly(Return(1)); EXPECT_CALL(b, DoB(3)) .Times(Between(1, 2)) .WillOnce(Return(1)) .WillOnce(Return(2)); EXPECT_CALL(b, DoB(4)).Times(AtMost(3)).WillOnce(Return(1)).WillRepeatedly( Return(2)); b.DoB(2); b.DoB(3); } EXPECT_STREQ("", GetCapturedStdout().c_str()); } TEST(ExpectCallSyntaxTest, WarnsOnTooManyActions) { CaptureStdout(); { MockB b; EXPECT_CALL(b, DoB()).Times(0).WillOnce(Return(1)); EXPECT_CALL(b, DoB()).Times(AtMost(1)).WillOnce(Return(1)).WillOnce( Return(2)); EXPECT_CALL(b, DoB(1)) .Times(1) .WillOnce(Return(1)) .WillOnce(Return(2)) .RetiresOnSaturation(); EXPECT_CALL(b, DoB()).Times(0).WillRepeatedly(Return(1)); EXPECT_CALL(b, DoB(2)).Times(1).WillOnce(Return(1)).WillRepeatedly( Return(2)); b.DoB(1); b.DoB(2); } const std::string output = GetCapturedStdout(); EXPECT_PRED_FORMAT2(IsSubstring, "Too many actions specified in EXPECT_CALL(b, DoB())...\n" "Expected to be never called, but has 1 WillOnce().", output); EXPECT_PRED_FORMAT2(IsSubstring, "Too many actions specified in EXPECT_CALL(b, DoB())...\n" "Expected to be called at most once, " "but has 2 WillOnce()s.", output); EXPECT_PRED_FORMAT2( IsSubstring, "Too many actions specified in EXPECT_CALL(b, DoB(1))...\n" "Expected to be called once, but has 2 WillOnce()s.", output); EXPECT_PRED_FORMAT2(IsSubstring, "Too many actions specified in EXPECT_CALL(b, DoB())...\n" "Expected to be never called, but has 0 WillOnce()s " "and a WillRepeatedly().", output); EXPECT_PRED_FORMAT2( IsSubstring, "Too many actions specified in EXPECT_CALL(b, DoB(2))...\n" "Expected to be called once, but has 1 WillOnce() " "and a WillRepeatedly().", output); } TEST(ExpectCallSyntaxTest, WarnsOnTooFewActions) { MockB b; EXPECT_CALL(b, DoB()).Times(Between(2, 3)).WillOnce(Return(1)); CaptureStdout(); b.DoB(); const std::string output = GetCapturedStdout(); EXPECT_PRED_FORMAT2(IsSubstring, "Too few actions specified in EXPECT_CALL(b, DoB())...\n" "Expected to be called between 2 and 3 times, " "but has only 1 WillOnce().", output); b.DoB(); } TEST(ExpectCallSyntaxTest, WarningIsErrorWithFlag) { int original_behavior = GMOCK_FLAG_GET(default_mock_behavior); GMOCK_FLAG_SET(default_mock_behavior, kAllow); CaptureStdout(); { MockA a; a.DoA(0); } std::string output = GetCapturedStdout(); EXPECT_TRUE(output.empty()) << output; GMOCK_FLAG_SET(default_mock_behavior, kWarn); CaptureStdout(); { MockA a; a.DoA(0); } std::string warning_output = GetCapturedStdout(); EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", warning_output); EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call", warning_output); GMOCK_FLAG_SET(default_mock_behavior, kFail); EXPECT_NONFATAL_FAILURE( { MockA a; a.DoA(0); }, "Uninteresting mock function call"); GMOCK_FLAG_SET(default_mock_behavior, -1); CaptureStdout(); { MockA a; a.DoA(0); } warning_output = GetCapturedStdout(); EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", warning_output); EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call", warning_output); GMOCK_FLAG_SET(default_mock_behavior, 3); CaptureStdout(); { MockA a; a.DoA(0); } warning_output = GetCapturedStdout(); EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", warning_output); EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call", warning_output); GMOCK_FLAG_SET(default_mock_behavior, original_behavior); } #endif TEST(OnCallTest, TakesBuiltInDefaultActionWhenNoOnCall) { MockB b; EXPECT_CALL(b, DoB()); EXPECT_EQ(0, b.DoB()); } TEST(OnCallTest, TakesBuiltInDefaultActionWhenNoOnCallMatches) { MockB b; ON_CALL(b, DoB(1)).WillByDefault(Return(1)); EXPECT_CALL(b, DoB(_)); EXPECT_EQ(0, b.DoB(2)); } TEST(OnCallTest, PicksLastMatchingOnCall) { MockB b; ON_CALL(b, DoB(_)).WillByDefault(Return(3)); ON_CALL(b, DoB(2)).WillByDefault(Return(2)); ON_CALL(b, DoB(1)).WillByDefault(Return(1)); EXPECT_CALL(b, DoB(_)); EXPECT_EQ(2, b.DoB(2)); } TEST(ExpectCallTest, AllowsAnyCallWhenNoSpec) { MockB b; EXPECT_CALL(b, DoB()); b.DoB(); b.DoB(1); b.DoB(2); } TEST(ExpectCallTest, PicksLastMatchingExpectCall) { MockB b; EXPECT_CALL(b, DoB(_)).WillRepeatedly(Return(2)); EXPECT_CALL(b, DoB(1)).WillRepeatedly(Return(1)); EXPECT_EQ(1, b.DoB(1)); } TEST(ExpectCallTest, CatchesTooFewCalls) { EXPECT_NONFATAL_FAILURE( { MockB b; EXPECT_CALL(b, DoB(5)).Description("DoB Method").Times(AtLeast(2)); b.DoB(5); }, "Actual function \"DoB Method\" call count " "doesn't match EXPECT_CALL(b, DoB(5))...\n" " Expected: to be called at least twice\n" " Actual: called once - unsatisfied and active"); } TEST(ExpectCallTest, InfersCardinalityWhenThereIsNoWillRepeatedly) { { MockB b; EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillOnce(Return(2)); EXPECT_EQ(1, b.DoB()); EXPECT_EQ(2, b.DoB()); } EXPECT_NONFATAL_FAILURE( { MockB b; EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillOnce(Return(2)); EXPECT_EQ(1, b.DoB()); }, "to be called twice"); { MockB b; EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillOnce(Return(2)); EXPECT_EQ(1, b.DoB()); EXPECT_EQ(2, b.DoB()); EXPECT_NONFATAL_FAILURE(b.DoB(), "to be called twice"); } } TEST(ExpectCallTest, InfersCardinality1WhenThereIsWillRepeatedly) { { MockB b; EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillRepeatedly(Return(2)); EXPECT_EQ(1, b.DoB()); } { MockB b; EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillRepeatedly(Return(2)); EXPECT_EQ(1, b.DoB()); EXPECT_EQ(2, b.DoB()); EXPECT_EQ(2, b.DoB()); } EXPECT_NONFATAL_FAILURE( { MockB b; EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillRepeatedly(Return(2)); }, "to be called at least once"); } #if defined(GTEST_INTERNAL_CPLUSPLUS_LANG) && \ GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L TEST(ExpectCallTest, NonMoveableType) { struct NonMoveableStruct { explicit NonMoveableStruct(int x_in) : x(x_in) {} NonMoveableStruct(NonMoveableStruct&&) = delete; int x; }; static_assert(!std::is_move_constructible_v<NonMoveableStruct>); static_assert(!std::is_copy_constructible_v<NonMoveableStruct>); static_assert(!std::is_move_assignable_v<NonMoveableStruct>); static_assert(!std::is_copy_assignable_v<NonMoveableStruct>); const auto return_17 = [] { return NonMoveableStruct(17); }; static_cast<void>(OnceAction<NonMoveableStruct()>{return_17}); static_cast<void>(Action<NonMoveableStruct()>{return_17}); static_cast<void>(OnceAction<NonMoveableStruct(int)>{return_17}); static_cast<void>(Action<NonMoveableStruct(int)>{return_17}); MockFunction<NonMoveableStruct()> mock; EXPECT_CALL(mock, Call) .WillOnce(return_17) .WillRepeatedly(return_17); EXPECT_EQ(17, mock.AsStdFunction()().x); EXPECT_EQ(17, mock.AsStdFunction()().x); EXPECT_EQ(17, mock.AsStdFunction()().x); } #endif TEST(ExpectCallTest, NthMatchTakesNthAction) { MockB b; EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillOnce(Return(2)).WillOnce( Return(3)); EXPECT_EQ(1, b.DoB()); EXPECT_EQ(2, b.DoB()); EXPECT_EQ(3, b.DoB()); } TEST(ExpectCallTest, TakesRepeatedActionWhenWillListIsExhausted) { MockB b; EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillRepeatedly(Return(2)); EXPECT_EQ(1, b.DoB()); EXPECT_EQ(2, b.DoB()); EXPECT_EQ(2, b.DoB()); } #if GTEST_HAS_STREAM_REDIRECTION TEST(ExpectCallTest, TakesDefaultActionWhenWillListIsExhausted) { MockB b; EXPECT_CALL(b, DoB(_)).Times(1); EXPECT_CALL(b, DoB()) .Times(AnyNumber()) .WillOnce(Return(1)) .WillOnce(Return(2)); CaptureStdout(); EXPECT_EQ(0, b.DoB(1)); EXPECT_EQ(1, b.DoB()); EXPECT_EQ(2, b.DoB()); const std::string output1 = GetCapturedStdout(); EXPECT_STREQ("", output1.c_str()); CaptureStdout(); EXPECT_EQ(0, b.DoB()); EXPECT_EQ(0, b.DoB()); const std::string output2 = GetCapturedStdout(); EXPECT_THAT(output2.c_str(), HasSubstr("Actions ran out in EXPECT_CALL(b, DoB())...\n" "Called 3 times, but only 2 WillOnce()s are specified" " - returning default value.")); EXPECT_THAT(output2.c_str(), HasSubstr("Actions ran out in EXPECT_CALL(b, DoB())...\n" "Called 4 times, but only 2 WillOnce()s are specified" " - returning default value.")); } TEST(FunctionMockerMessageTest, ReportsExpectCallLocationForExhaustedActions) { MockB b; std::string expect_call_location = FormatFileLocation(__FILE__, __LINE__ + 1); EXPECT_CALL(b, DoB()).Times(AnyNumber()).WillOnce(Return(1)); EXPECT_EQ(1, b.DoB()); CaptureStdout(); EXPECT_EQ(0, b.DoB()); const std::string output = GetCapturedStdout(); EXPECT_PRED_FORMAT2(IsSubstring, expect_call_location, output); } TEST(FunctionMockerMessageTest, ReportsDefaultActionLocationOfUninterestingCallsForNaggyMock) { std::string on_call_location; CaptureStdout(); { NaggyMock<MockB> b; on_call_location = FormatFileLocation(__FILE__, __LINE__ + 1); ON_CALL(b, DoB(_)).WillByDefault(Return(0)); b.DoB(0); } EXPECT_PRED_FORMAT2(IsSubstring, on_call_location, GetCapturedStdout()); } #endif TEST(UninterestingCallTest, DoesDefaultAction) { MockA a; ON_CALL(a, Binary(_, _)).WillByDefault(Return(true)); EXPECT_TRUE(a.Binary(1, 2)); MockB b; EXPECT_EQ(0, b.DoB()); } TEST(UnexpectedCallTest, DoesDefaultAction) { MockA a; ON_CALL(a, Binary(_, _)).WillByDefault(Return(true)); EXPECT_CALL(a, Binary(0, 0)); a.Binary(0, 0); bool result = false; EXPECT_NONFATAL_FAILURE(result = a.Binary(1, 2), "Unexpected mock function call"); EXPECT_TRUE(result); MockB b; EXPECT_CALL(b, DoB(0)).Times(0); int n = -1; EXPECT_NONFATAL_FAILURE(n = b.DoB(1), "Unexpected mock function call"); EXPECT_EQ(0, n); } TEST(UnexpectedCallTest, GeneratesFailureForVoidFunction) { MockA a1; EXPECT_CALL(a1, DoA(1)); a1.DoA(1); EXPECT_NONFATAL_FAILURE( a1.DoA(9), "Unexpected mock function call - returning directly.\n" " Function call: DoA(9)\n" "Google Mock tried the following 1 expectation, but it didn't match:"); EXPECT_NONFATAL_FAILURE( a1.DoA(9), " Expected arg #0: is equal to 1\n" " Actual: 9\n" " Expected: to be called once\n" " Actual: called once - saturated and active"); MockA a2; EXPECT_CALL(a2, DoA(1)); EXPECT_CALL(a2, DoA(3)); a2.DoA(1); EXPECT_NONFATAL_FAILURE( a2.DoA(2), "Unexpected mock function call - returning directly.\n" " Function call: DoA(2)\n" "Google Mock tried the following 2 expectations, but none matched:"); EXPECT_NONFATAL_FAILURE( a2.DoA(2), "tried expectation #0: EXPECT_CALL(a2, DoA(1))...\n" " Expected arg #0: is equal to 1\n" " Actual: 2\n" " Expected: to be called once\n" " Actual: called once - saturated and active"); EXPECT_NONFATAL_FAILURE( a2.DoA(2), "tried expectation #1: EXPECT_CALL(a2, DoA(3))...\n" " Expected arg #0: is equal to 3\n" " Actual: 2\n" " Expected: to be called once\n" " Actual: never called - unsatisfied and active"); a2.DoA(3); } TEST(UnexpectedCallTest, GeneartesFailureForNonVoidFunction) { MockB b1; EXPECT_CALL(b1, DoB(1)); b1.DoB(1); EXPECT_NONFATAL_FAILURE( b1.DoB(2), "Unexpected mock function call - returning default value.\n" " Function call: DoB(2)\n" " Returns: 0\n" "Google Mock tried the following 1 expectation, but it didn't match:"); EXPECT_NONFATAL_FAILURE( b1.DoB(2), " Expected arg #0: is equal to 1\n" " Actual: 2\n" " Expected: to be called once\n" " Actual: called once - saturated and active"); } TEST(UnexpectedCallTest, RetiredExpectation) { MockB b; EXPECT_CALL(b, DoB(1)).RetiresOnSaturation(); b.DoB(1); EXPECT_NONFATAL_FAILURE(b.DoB(1), " Expected: the expectation is active\n" " Actual: it is retired"); } TEST(UnexpectedCallTest, UnmatchedArguments) { MockB b; EXPECT_CALL(b, DoB(1)); EXPECT_NONFATAL_FAILURE(b.DoB(2), " Expected arg #0: is equal to 1\n" " Actual: 2\n"); b.DoB(1); } TEST(UnexpectedCallTest, UnsatisfiedPrerequisites) { Sequence s1, s2; MockB b; EXPECT_CALL(b, DoB(1)).InSequence(s1); EXPECT_CALL(b, DoB(2)).Times(AnyNumber()).InSequence(s1); EXPECT_CALL(b, DoB(3)).InSequence(s2); EXPECT_CALL(b, DoB(4)).InSequence(s1, s2); ::testing::TestPartResultArray failures; { ::testing::ScopedFakeTestPartResultReporter reporter(&failures); b.DoB(4); } ASSERT_EQ(1, failures.size()); const ::testing::TestPartResult& r = failures.GetTestPartResult(0); EXPECT_EQ(::testing::TestPartResult::kNonFatalFailure, r.type()); #ifdef GTEST_USES_POSIX_RE EXPECT_THAT(r.message(), ContainsRegex( "the following immediate pre-requisites are not satisfied:\n" "(.|\n)*: pre-requisite #0\n" "(.|\n)*: pre-requisite #1")); #else EXPECT_THAT(r.message(), ContainsRegex( "the following immediate pre-requisites are not satisfied:")); EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #0")); EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #1")); #endif b.DoB(1); b.DoB(3); b.DoB(4); } TEST(UndefinedReturnValueTest, ReturnValueIsMandatoryWhenNotDefaultConstructible) { MockA a; #if GTEST_HAS_EXCEPTIONS EXPECT_ANY_THROW(a.ReturnNonDefaultConstructible()); #else EXPECT_DEATH_IF_SUPPORTED(a.ReturnNonDefaultConstructible(), ""); #endif } TEST(ExcessiveCallTest, DoesDefaultAction) { MockA a; ON_CALL(a, Binary(_, _)).WillByDefault(Return(true)); EXPECT_CALL(a, Binary(0, 0)); a.Binary(0, 0); bool result = false; EXPECT_NONFATAL_FAILURE(result = a.Binary(0, 0), "Mock f
2,333
#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_PROD_H_ #define GOOGLETEST_INCLUDE_GTEST_GTEST_PROD_H_ #define FRIEND_TEST(test_case_name, test_name) \ friend class test_case_name##_##test_name##_Test #endif
#include "production.h" #include "gtest/gtest.h" TEST(PrivateCodeTest, CanAccessPrivateMembers) { PrivateCode a; EXPECT_EQ(0, a.x_); a.set_x(1); EXPECT_EQ(1, a.x_); } typedef testing::Test PrivateCodeFixtureTest; TEST_F(PrivateCodeFixtureTest, CanAccessPrivateMembers) { PrivateCode a; EXPECT_EQ(0, a.x_); a.set_x(2); EXPECT_EQ(2, a.x_); }
2,334
#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_ #define GOOGLETEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_ #include "gtest/gtest-assertion-result.h" #include "gtest/internal/gtest-internal.h" #include "gtest/internal/gtest-port.h" namespace testing { #define GTEST_ASSERT_(expression, on_failure) \ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ if (const ::testing::AssertionResult gtest_ar = (expression)) \ ; \ else \ on_failure(gtest_ar.failure_message()) template <typename Pred, typename T1> AssertionResult AssertPred1Helper(const char* pred_text, const char* e1, Pred pred, const T1& v1) { if (pred(v1)) return AssertionSuccess(); return AssertionFailure() << pred_text << "(" << e1 << ") evaluates to false, where" << "\n" << e1 << " evaluates to " << ::testing::PrintToString(v1); } #define GTEST_PRED_FORMAT1_(pred_format, v1, on_failure) \ GTEST_ASSERT_(pred_format(#v1, v1), on_failure) #define GTEST_PRED1_(pred, v1, on_failure) \ GTEST_ASSERT_(::testing::AssertPred1Helper(#pred, #v1, pred, v1), on_failure) #define EXPECT_PRED_FORMAT1(pred_format, v1) \ GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_NONFATAL_FAILURE_) #define EXPECT_PRED1(pred, v1) GTEST_PRED1_(pred, v1, GTEST_NONFATAL_FAILURE_) #define ASSERT_PRED_FORMAT1(pred_format, v1) \ GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_FATAL_FAILURE_) #define ASSERT_PRED1(pred, v1) GTEST_PRED1_(pred, v1, GTEST_FATAL_FAILURE_) template <typename Pred, typename T1, typename T2> AssertionResult AssertPred2Helper(const char* pred_text, const char* e1, const char* e2, Pred pred, const T1& v1, const T2& v2) { if (pred(v1, v2)) return AssertionSuccess(); return AssertionFailure() << pred_text << "(" << e1 << ", " << e2 << ") evaluates to false, where" << "\n" << e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n" << e2 << " evaluates to " << ::testing::PrintToString(v2); } #define GTEST_PRED_FORMAT2_(pred_format, v1, v2, on_failure) \ GTEST_ASSERT_(pred_format(#v1, #v2, v1, v2), on_failure) #define GTEST_PRED2_(pred, v1, v2, on_failure) \ GTEST_ASSERT_(::testing::AssertPred2Helper(#pred, #v1, #v2, pred, v1, v2), \ on_failure) #define EXPECT_PRED_FORMAT2(pred_format, v1, v2) \ GTEST_PRED_FORMAT2_(pred_format, v1, v2, GTEST_NONFATAL_FAILURE_) #define EXPECT_PRED2(pred, v1, v2) \ GTEST_PRED2_(pred, v1, v2, GTEST_NONFATAL_FAILURE_) #define ASSERT_PRED_FORMAT2(pred_format, v1, v2) \ GTEST_PRED_FORMAT2_(pred_format, v1, v2, GTEST_FATAL_FAILURE_) #define ASSERT_PRED2(pred, v1, v2) \ GTEST_PRED2_(pred, v1, v2, GTEST_FATAL_FAILURE_) template <typename Pred, typename T1, typename T2, typename T3> AssertionResult AssertPred3Helper(const char* pred_text, const char* e1, const char* e2, const char* e3, Pred pred, const T1& v1, const T2& v2, const T3& v3) { if (pred(v1, v2, v3)) return AssertionSuccess(); return AssertionFailure() << pred_text << "(" << e1 << ", " << e2 << ", " << e3 << ") evaluates to false, where" << "\n" << e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n" << e2 << " evaluates to " << ::testing::PrintToString(v2) << "\n" << e3 << " evaluates to " << ::testing::PrintToString(v3); } #define GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, on_failure) \ GTEST_ASSERT_(pred_format(#v1, #v2, #v3, v1, v2, v3), on_failure) #define GTEST_PRED3_(pred, v1, v2, v3, on_failure) \ GTEST_ASSERT_( \ ::testing::AssertPred3Helper(#pred, #v1, #v2, #v3, pred, v1, v2, v3), \ on_failure) #define EXPECT_PRED_FORMAT3(pred_format, v1, v2, v3) \ GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, GTEST_NONFATAL_FAILURE_) #define EXPECT_PRED3(pred, v1, v2, v3) \ GTEST_PRED3_(pred, v1, v2, v3, GTEST_NONFATAL_FAILURE_) #define ASSERT_PRED_FORMAT3(pred_format, v1, v2, v3) \ GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, GTEST_FATAL_FAILURE_) #define ASSERT_PRED3(pred, v1, v2, v3) \ GTEST_PRED3_(pred, v1, v2, v3, GTEST_FATAL_FAILURE_) template <typename Pred, typename T1, typename T2, typename T3, typename T4> AssertionResult AssertPred4Helper(const char* pred_text, const char* e1, const char* e2, const char* e3, const char* e4, Pred pred, const T1& v1, const T2& v2, const T3& v3, const T4& v4) { if (pred(v1, v2, v3, v4)) return AssertionSuccess(); return AssertionFailure() << pred_text << "(" << e1 << ", " << e2 << ", " << e3 << ", " << e4 << ") evaluates to false, where" << "\n" << e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n" << e2 << " evaluates to " << ::testing::PrintToString(v2) << "\n" << e3 << " evaluates to " << ::testing::PrintToString(v3) << "\n" << e4 << " evaluates to " << ::testing::PrintToString(v4); } #define GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, on_failure) \ GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, v1, v2, v3, v4), on_failure) #define GTEST_PRED4_(pred, v1, v2, v3, v4, on_failure) \ GTEST_ASSERT_(::testing::AssertPred4Helper(#pred, #v1, #v2, #v3, #v4, pred, \ v1, v2, v3, v4), \ on_failure) #define EXPECT_PRED_FORMAT4(pred_format, v1, v2, v3, v4) \ GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, GTEST_NONFATAL_FAILURE_) #define EXPECT_PRED4(pred, v1, v2, v3, v4) \ GTEST_PRED4_(pred, v1, v2, v3, v4, GTEST_NONFATAL_FAILURE_) #define ASSERT_PRED_FORMAT4(pred_format, v1, v2, v3, v4) \ GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, GTEST_FATAL_FAILURE_) #define ASSERT_PRED4(pred, v1, v2, v3, v4) \ GTEST_PRED4_(pred, v1, v2, v3, v4, GTEST_FATAL_FAILURE_) template <typename Pred, typename T1, typename T2, typename T3, typename T4, typename T5> AssertionResult AssertPred5Helper(const char* pred_text, const char* e1, const char* e2, const char* e3, const char* e4, const char* e5, Pred pred, const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5) { if (pred(v1, v2, v3, v4, v5)) return AssertionSuccess(); return AssertionFailure() << pred_text << "(" << e1 << ", " << e2 << ", " << e3 << ", " << e4 << ", " << e5 << ") evaluates to false, where" << "\n" << e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n" << e2 << " evaluates to " << ::testing::PrintToString(v2) << "\n" << e3 << " evaluates to " << ::testing::PrintToString(v3) << "\n" << e4 << " evaluates to " << ::testing::PrintToString(v4) << "\n" << e5 << " evaluates to " << ::testing::PrintToString(v5); } #define GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, on_failure) \ GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, #v5, v1, v2, v3, v4, v5), \ on_failure) #define GTEST_PRED5_(pred, v1, v2, v3, v4, v5, on_failure) \ GTEST_ASSERT_(::testing::AssertPred5Helper(#pred, #v1, #v2, #v3, #v4, #v5, \ pred, v1, v2, v3, v4, v5), \ on_failure) #define EXPECT_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5) \ GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, GTEST_NONFATAL_FAILURE_) #define EXPECT_PRED5(pred, v1, v2, v3, v4, v5) \ GTEST_PRED5_(pred, v1, v2, v3, v4, v5, GTEST_NONFATAL_FAILURE_) #define ASSERT_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5) \ GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, GTEST_FATAL_FAILURE_) #define ASSERT_PRED5(pred, v1, v2, v3, v4, v5) \ GTEST_PRED5_(pred, v1, v2, v3, v4, v5, GTEST_FATAL_FAILURE_) } #endif
#include <iostream> #include <ostream> #include "gtest/gtest-spi.h" #include "gtest/gtest.h" struct Bool { explicit Bool(int val) : value(val != 0) {} bool operator>(int n) const { return value > Bool(n).value; } Bool operator+(const Bool& rhs) const { return Bool(value + rhs.value); } bool operator==(const Bool& rhs) const { return value == rhs.value; } bool value; }; std::ostream& operator<<(std::ostream& os, const Bool& x) { return os << (x.value ? "true" : "false"); } template <typename T1> bool PredFunction1(T1 v1) { return v1 > 0; } bool PredFunction1Int(int v1) { return v1 > 0; } bool PredFunction1Bool(Bool v1) { return v1 > 0; } struct PredFunctor1 { template <typename T1> bool operator()(const T1& v1) { return v1 > 0; } }; template <typename T1> testing::AssertionResult PredFormatFunction1(const char* e1, const T1& v1) { if (PredFunction1(v1)) return testing::AssertionSuccess(); return testing::AssertionFailure() << e1 << " is expected to be positive, but evaluates to " << v1 << "."; } struct PredFormatFunctor1 { template <typename T1> testing::AssertionResult operator()(const char* e1, const T1& v1) const { return PredFormatFunction1(e1, v1); } }; class Predicate1Test : public testing::Test { protected: void SetUp() override { expected_to_finish_ = true; finished_ = false; n1_ = 0; } void TearDown() override { EXPECT_EQ(1, n1_) << "The predicate assertion didn't evaluate argument 2 " "exactly once."; if (expected_to_finish_ && !finished_) { FAIL() << "The predicate assertion unexpectedly aborted the test."; } else if (!expected_to_finish_ && finished_) { FAIL() << "The failed predicate assertion didn't abort the test " "as expected."; } } static bool expected_to_finish_; static bool finished_; static int n1_; }; bool Predicate1Test::expected_to_finish_; bool Predicate1Test::finished_; int Predicate1Test::n1_; typedef Predicate1Test EXPECT_PRED_FORMAT1Test; typedef Predicate1Test ASSERT_PRED_FORMAT1Test; typedef Predicate1Test EXPECT_PRED1Test; typedef Predicate1Test ASSERT_PRED1Test; TEST_F(EXPECT_PRED1Test, FunctionOnBuiltInTypeSuccess) { EXPECT_PRED1(PredFunction1Int, ++n1_); finished_ = true; } TEST_F(EXPECT_PRED1Test, FunctionOnUserTypeSuccess) { EXPECT_PRED1(PredFunction1Bool, Bool(++n1_)); finished_ = true; } TEST_F(EXPECT_PRED1Test, FunctorOnBuiltInTypeSuccess) { EXPECT_PRED1(PredFunctor1(), ++n1_); finished_ = true; } TEST_F(EXPECT_PRED1Test, FunctorOnUserTypeSuccess) { EXPECT_PRED1(PredFunctor1(), Bool(++n1_)); finished_ = true; } TEST_F(EXPECT_PRED1Test, FunctionOnBuiltInTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED1(PredFunction1Int, n1_++); finished_ = true; }, ""); } TEST_F(EXPECT_PRED1Test, FunctionOnUserTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED1(PredFunction1Bool, Bool(n1_++)); finished_ = true; }, ""); } TEST_F(EXPECT_PRED1Test, FunctorOnBuiltInTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED1(PredFunctor1(), n1_++); finished_ = true; }, ""); } TEST_F(EXPECT_PRED1Test, FunctorOnUserTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED1(PredFunctor1(), Bool(n1_++)); finished_ = true; }, ""); } TEST_F(ASSERT_PRED1Test, FunctionOnBuiltInTypeSuccess) { ASSERT_PRED1(PredFunction1Int, ++n1_); finished_ = true; } TEST_F(ASSERT_PRED1Test, FunctionOnUserTypeSuccess) { ASSERT_PRED1(PredFunction1Bool, Bool(++n1_)); finished_ = true; } TEST_F(ASSERT_PRED1Test, FunctorOnBuiltInTypeSuccess) { ASSERT_PRED1(PredFunctor1(), ++n1_); finished_ = true; } TEST_F(ASSERT_PRED1Test, FunctorOnUserTypeSuccess) { ASSERT_PRED1(PredFunctor1(), Bool(++n1_)); finished_ = true; } TEST_F(ASSERT_PRED1Test, FunctionOnBuiltInTypeFailure) { expected_to_finish_ = false; EXPECT_FATAL_FAILURE( { ASSERT_PRED1(PredFunction1Int, n1_++); finished_ = true; }, ""); } TEST_F(ASSERT_PRED1Test, FunctionOnUserTypeFailure) { expected_to_finish_ = false; EXPECT_FATAL_FAILURE( { ASSERT_PRED1(PredFunction1Bool, Bool(n1_++)); finished_ = true; }, ""); } TEST_F(ASSERT_PRED1Test, FunctorOnBuiltInTypeFailure) { expected_to_finish_ = false; EXPECT_FATAL_FAILURE( { ASSERT_PRED1(PredFunctor1(), n1_++); finished_ = true; }, ""); } TEST_F(ASSERT_PRED1Test, FunctorOnUserTypeFailure) { expected_to_finish_ = false; EXPECT_FATAL_FAILURE( { ASSERT_PRED1(PredFunctor1(), Bool(n1_++)); finished_ = true; }, ""); } TEST_F(EXPECT_PRED_FORMAT1Test, FunctionOnBuiltInTypeSuccess) { EXPECT_PRED_FORMAT1(PredFormatFunction1, ++n1_); finished_ = true; } TEST_F(EXPECT_PRED_FORMAT1Test, FunctionOnUserTypeSuccess) { EXPECT_PRED_FORMAT1(PredFormatFunction1, Bool(++n1_)); finished_ = true; } TEST_F(EXPECT_PRED_FORMAT1Test, FunctorOnBuiltInTypeSuccess) { EXPECT_PRED_FORMAT1(PredFormatFunctor1(), ++n1_); finished_ = true; } TEST_F(EXPECT_PRED_FORMAT1Test, FunctorOnUserTypeSuccess) { EXPECT_PRED_FORMAT1(PredFormatFunctor1(), Bool(++n1_)); finished_ = true; } TEST_F(EXPECT_PRED_FORMAT1Test, FunctionOnBuiltInTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED_FORMAT1(PredFormatFunction1, n1_++); finished_ = true; }, ""); } TEST_F(EXPECT_PRED_FORMAT1Test, FunctionOnUserTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED_FORMAT1(PredFormatFunction1, Bool(n1_++)); finished_ = true; }, ""); } TEST_F(EXPECT_PRED_FORMAT1Test, FunctorOnBuiltInTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED_FORMAT1(PredFormatFunctor1(), n1_++); finished_ = true; }, ""); } TEST_F(EXPECT_PRED_FORMAT1Test, FunctorOnUserTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED_FORMAT1(PredFormatFunctor1(), Bool(n1_++)); finished_ = true; }, ""); } TEST_F(ASSERT_PRED_FORMAT1Test, FunctionOnBuiltInTypeSuccess) { ASSERT_PRED_FORMAT1(PredFormatFunction1, ++n1_); finished_ = true; } TEST_F(ASSERT_PRED_FORMAT1Test, FunctionOnUserTypeSuccess) { ASSERT_PRED_FORMAT1(PredFormatFunction1, Bool(++n1_)); finished_ = true; } TEST_F(ASSERT_PRED_FORMAT1Test, FunctorOnBuiltInTypeSuccess) { ASSERT_PRED_FORMAT1(PredFormatFunctor1(), ++n1_); finished_ = true; } TEST_F(ASSERT_PRED_FORMAT1Test, FunctorOnUserTypeSuccess) { ASSERT_PRED_FORMAT1(PredFormatFunctor1(), Bool(++n1_)); finished_ = true; } TEST_F(ASSERT_PRED_FORMAT1Test, FunctionOnBuiltInTypeFailure) { expected_to_finish_ = false; EXPECT_FATAL_FAILURE( { ASSERT_PRED_FORMAT1(PredFormatFunction1, n1_++); finished_ = true; }, ""); } TEST_F(ASSERT_PRED_FORMAT1Test, FunctionOnUserTypeFailure) { expected_to_finish_ = false; EXPECT_FATAL_FAILURE( { ASSERT_PRED_FORMAT1(PredFormatFunction1, Bool(n1_++)); finished_ = true; }, ""); } TEST_F(ASSERT_PRED_FORMAT1Test, FunctorOnBuiltInTypeFailure) { expected_to_finish_ = false; EXPECT_FATAL_FAILURE( { ASSERT_PRED_FORMAT1(PredFormatFunctor1(), n1_++); finished_ = true; }, ""); } TEST_F(ASSERT_PRED_FORMAT1Test, FunctorOnUserTypeFailure) { expected_to_finish_ = false; EXPECT_FATAL_FAILURE( { ASSERT_PRED_FORMAT1(PredFormatFunctor1(), Bool(n1_++)); finished_ = true; }, ""); } template <typename T1, typename T2> bool PredFunction2(T1 v1, T2 v2) { return v1 + v2 > 0; } bool PredFunction2Int(int v1, int v2) { return v1 + v2 > 0; } bool PredFunction2Bool(Bool v1, Bool v2) { return v1 + v2 > 0; } struct PredFunctor2 { template <typename T1, typename T2> bool operator()(const T1& v1, const T2& v2) { return v1 + v2 > 0; } }; template <typename T1, typename T2> testing::AssertionResult PredFormatFunction2(const char* e1, const char* e2, const T1& v1, const T2& v2) { if (PredFunction2(v1, v2)) return testing::AssertionSuccess(); return testing::AssertionFailure() << e1 << " + " << e2 << " is expected to be positive, but evaluates to " << v1 + v2 << "."; } struct PredFormatFunctor2 { template <typename T1, typename T2> testing::AssertionResult operator()(const char* e1, const char* e2, const T1& v1, const T2& v2) const { return PredFormatFunction2(e1, e2, v1, v2); } }; class Predicate2Test : public testing::Test { protected: void SetUp() override { expected_to_finish_ = true; finished_ = false; n1_ = n2_ = 0; } void TearDown() override { EXPECT_EQ(1, n1_) << "The predicate assertion didn't evaluate argument 2 " "exactly once."; EXPECT_EQ(1, n2_) << "The predicate assertion didn't evaluate argument 3 " "exactly once."; if (expected_to_finish_ && !finished_) { FAIL() << "The predicate assertion unexpectedly aborted the test."; } else if (!expected_to_finish_ && finished_) { FAIL() << "The failed predicate assertion didn't abort the test " "as expected."; } } static bool expected_to_finish_; static bool finished_; static int n1_; static int n2_; }; bool Predicate2Test::expected_to_finish_; bool Predicate2Test::finished_; int Predicate2Test::n1_; int Predicate2Test::n2_; typedef Predicate2Test EXPECT_PRED_FORMAT2Test; typedef Predicate2Test ASSERT_PRED_FORMAT2Test; typedef Predicate2Test EXPECT_PRED2Test; typedef Predicate2Test ASSERT_PRED2Test; TEST_F(EXPECT_PRED2Test, FunctionOnBuiltInTypeSuccess) { EXPECT_PRED2(PredFunction2Int, ++n1_, ++n2_); finished_ = true; } TEST_F(EXPECT_PRED2Test, FunctionOnUserTypeSuccess) { EXPECT_PRED2(PredFunction2Bool, Bool(++n1_), Bool(++n2_)); finished_ = true; } TEST_F(EXPECT_PRED2Test, FunctorOnBuiltInTypeSuccess) { EXPECT_PRED2(PredFunctor2(), ++n1_, ++n2_); finished_ = true; } TEST_F(EXPECT_PRED2Test, FunctorOnUserTypeSuccess) { EXPECT_PRED2(PredFunctor2(), Bool(++n1_), Bool(++n2_)); finished_ = true; } TEST_F(EXPECT_PRED2Test, FunctionOnBuiltInTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED2(PredFunction2Int, n1_++, n2_++); finished_ = true; }, ""); } TEST_F(EXPECT_PRED2Test, FunctionOnUserTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED2(PredFunction2Bool, Bool(n1_++), Bool(n2_++)); finished_ = true; }, ""); } TEST_F(EXPECT_PRED2Test, FunctorOnBuiltInTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED2(PredFunctor2(), n1_++, n2_++); finished_ = true; }, ""); } TEST_F(EXPECT_PRED2Test, FunctorOnUserTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED2(PredFunctor2(), Bool(n1_++), Bool(n2_++)); finished_ = true; }, ""); } TEST_F(ASSERT_PRED2Test, FunctionOnBuiltInTypeSuccess) { ASSERT_PRED2(PredFunction2Int, ++n1_, ++n2_); finished_ = true; } TEST_F(ASSERT_PRED2Test, FunctionOnUserTypeSuccess) { ASSERT_PRED2(PredFunction2Bool, Bool(++n1_), Bool(++n2_)); finished_ = true; } TEST_F(ASSERT_PRED2Test, FunctorOnBuiltInTypeSuccess) { ASSERT_PRED2(PredFunctor2(), ++n1_, ++n2_); finished_ = true; } TEST_F(ASSERT_PRED2Test, FunctorOnUserTypeSuccess) { ASSERT_PRED2(PredFunctor2(), Bool(++n1_), Bool(++n2_)); finished_ = true; } TEST_F(ASSERT_PRED2Test, FunctionOnBuiltInTypeFailure) { expected_to_finish_ = false; EXPECT_FATAL_FAILURE( { ASSERT_PRED2(PredFunction2Int, n1_++, n2_++); finished_ = true; }, ""); } TEST_F(ASSERT_PRED2Test, FunctionOnUserTypeFailure) { expected_to_finish_ = false; EXPECT_FATAL_FAILURE( { ASSERT_PRED2(PredFunction2Bool, Bool(n1_++), Bool(n2_++)); finished_ = true; }, ""); } TEST_F(ASSERT_PRED2Test, FunctorOnBuiltInTypeFailure) { expected_to_finish_ = false; EXPECT_FATAL_FAILURE( { ASSERT_PRED2(PredFunctor2(), n1_++, n2_++); finished_ = true; }, ""); } TEST_F(ASSERT_PRED2Test, FunctorOnUserTypeFailure) { expected_to_finish_ = false; EXPECT_FATAL_FAILURE( { ASSERT_PRED2(PredFunctor2(), Bool(n1_++), Bool(n2_++)); finished_ = true; }, ""); } TEST_F(EXPECT_PRED_FORMAT2Test, FunctionOnBuiltInTypeSuccess) { EXPECT_PRED_FORMAT2(PredFormatFunction2, ++n1_, ++n2_); finished_ = true; } TEST_F(EXPECT_PRED_FORMAT2Test, FunctionOnUserTypeSuccess) { EXPECT_PRED_FORMAT2(PredFormatFunction2, Bool(++n1_), Bool(++n2_)); finished_ = true; } TEST_F(EXPECT_PRED_FORMAT2Test, FunctorOnBuiltInTypeSuccess) { EXPECT_PRED_FORMAT2(PredFormatFunctor2(), ++n1_, ++n2_); finished_ = true; } TEST_F(EXPECT_PRED_FORMAT2Test, FunctorOnUserTypeSuccess) { EXPECT_PRED_FORMAT2(PredFormatFunctor2(), Bool(++n1_), Bool(++n2_)); finished_ = true; } TEST_F(EXPECT_PRED_FORMAT2Test, FunctionOnBuiltInTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED_FORMAT2(PredFormatFunction2, n1_++, n2_++); finished_ = true; }, ""); } TEST_F(EXPECT_PRED_FORMAT2Test, FunctionOnUserTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED_FORMAT2(PredFormatFunction2, Bool(n1_++), Bool(n2_++)); finished_ = true; }, ""); } TEST_F(EXPECT_PRED_FORMAT2Test, FunctorOnBuiltInTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED_FORMAT2(PredFormatFunctor2(), n1_++, n2_++); finished_ = true; }, ""); } TEST_F(EXPECT_PRED_FORMAT2Test, FunctorOnUserTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED_FORMAT2(PredFormatFunctor2(), Bool(n1_++), Bool(n2_++)); finished_ = true; }, ""); } TEST_F(ASSERT_PRED_FORMAT2Test, FunctionOnBuiltInTypeSuccess) { ASSERT_PRED_FORMAT2(PredFormatFunction2, ++n1_, ++n2_); finished_ = true; } TEST_F(ASSERT_PRED_FORMAT2Test, FunctionOnUserTypeSuccess) { ASSERT_PRED_FORMAT2(PredFormatFunction2, Bool(++n1_), Bool(++n2_)); finished_ = true; } TEST_F(ASSERT_PRED_FORMAT2Test, FunctorOnBuiltInTypeSuccess) { ASSERT_PRED_FORMAT2(PredFormatFunctor2(), ++n1_, ++n2_); finished_ = true; } TEST_F(ASSERT_PRED_FORMAT2Test, FunctorOnUserTypeSuccess) { ASSERT_PRED_FORMAT2(PredFormatFunctor2(), Bool(++n1_), Bool(++n2_)); finished_ = true; } TEST_F(ASSERT_PRED_FORMAT2Test, FunctionOnBuiltInTypeFailure) { expected_to_finish_ = false; EXPECT_FATAL_FAILURE( { ASSERT_PRED_FORMAT2(PredFormatFunction2, n1_++, n2_++); finished_ = true; }, ""); } TEST_F(ASSERT_PRED_FORMAT2Test, FunctionOnUserTypeFailure) { expected_to_finish_ = false; EXPECT_FATAL_FAILURE( { ASSERT_PRED_FORMAT2(PredFormatFunction2, Bool(n1_++), Bool(n2_++)); finished_ = true; }, ""); } TEST_F(ASSERT_PRED_FORMAT2Test, FunctorOnBuiltInTypeFailure) { expected_to_finish_ = false; EXPECT_FATAL_FAILURE( { ASSERT_PRED_FORMAT2(PredFormatFunctor2(), n1_++, n2_++); finished_ = true; }, ""); } TEST_F(ASSERT_PRED_FORMAT2Test, FunctorOnUserTypeFailure) { expected_to_finish_ = false; EXPECT_FATAL_FAILURE( { ASSERT_PRED_FORMAT2(PredFormatFunctor2(), Bool(n1_++), Bool(n2_++)); finished_ = true; }, ""); } template <typename T1, typename T2, typename T3> bool PredFunction3(T1 v1, T2 v2, T3 v3) { return v1 + v2 + v3 > 0; } bool PredFunction3Int(int v1, int v2, int v3) { return v1 + v2 + v3 > 0; } bool PredFunction3Bool(Bool v1, Bool v2, Bool v3) { return v1 + v2 + v3 > 0; } struct PredFunctor3 { template <typename T1, typename T2, typename T3> bool operator()(const T1& v1, const T2& v2, const T3& v3) { return v1 + v2 + v3 > 0; } }; template <typename T1, typename T2, typename T3> testing::AssertionResult PredFormatFunction3(const char* e1, const char* e2, const char* e3, const T1& v1, const T2& v2, const T3& v3) { if (PredFunction3(v1, v2, v3)) return testing::AssertionSuccess(); return testing::AssertionFailure() << e1 << " + " << e2 << " + " << e3 << " is expected to be positive, but evaluates to " << v1 + v2 + v3 << "."; } struct PredFormatFunctor3 { template <typename T1, typename T2, typename T3> testing::AssertionResult operator()(const char* e1, const char* e2, const char* e3, const T1& v1, const T2& v2, const T3& v3) const { return PredFormatFunction3(e1, e2, e3, v1, v2, v3); } }; class Predicate3Test : public testing::Test { protected: void SetUp() override { expected_to_finish_ = true; finished_ = false; n1_ = n2_ = n3_ = 0; } void TearDown() override { EXPECT_EQ(1, n1_) << "The predicate assertion didn't evaluate argument 2 " "exactly once."; EXPECT_EQ(1, n2_) << "The predicate assertion didn't evaluate argument 3 " "exactly once."; EXPECT_EQ(1, n3_) << "The predicate assertion didn't evaluate argument 4 " "exactly once."; if (expected_to_finish_ && !finished_) { FAIL() << "The predicate assertion unexpectedly aborted the test."; } else if (!expected_to_finish_ && finished_) { FAIL() << "The failed predicate assertion didn't abort the test " "as expected."; } } static bool expected_to_finish_; static bool finished_; static int n1_; static int n2_; static int n3_; }; bool Predicate3Test::expected_to_finish_; bool Predicate3Test::finished_; int Predicate3Test::n1_; int Predicate3Test::n2_; int Predicate3Test::n3_; typedef Predicate3Test EXPECT_PRED_FORMAT3Test; typedef Predicate3Test ASSERT_PRED_FORMAT3Test; typedef Predicate3Test EXPECT_PRED3Test; typedef Predicate3Test ASSERT_PRED3Test; TEST_F(EXPECT_PRED3Test, FunctionOnBuiltInTypeSuccess) { EXPECT_PRED3(PredFunction3Int, ++n1_, ++n2_, ++n3_); finished_ = true; } TEST_F(EXPECT_PRED3Test, FunctionOnUserTypeSuccess) { EXPECT_PRED3(PredFunction3Bool, Bool(++n1_), Bool(++n2_), Bool(++n3_)); finished_ = true; } TEST_F(EXPECT_PRED3Test, FunctorOnBuiltInTypeSuccess) { EXPECT_PRED3(PredFunctor3(), ++n1_, ++n2_, ++n3_); finished_ = true; } TEST_F(EXPECT_PRED3Test, FunctorOnUserTypeSuccess) { EXPECT_PRED3(PredFunctor3(), Bool(++n1_), Bool(++n2_), Bool(++n3_)); finished_ = true; } TEST_F(EXPECT_PRED3Test, FunctionOnBuiltInTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED3(PredFunction3Int, n1_++, n2_++, n3_++); finished_ = true; }, ""); } TEST_F(EXPECT_PRED3Test, FunctionOnUserTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED3(PredFunction3Bool, Bool(n1_++), Bool(n2_++), Bool(n3_++)); finished_ = true; }, ""); } TEST_F(EXPECT_PRED3Test, FunctorOnBuiltInTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED3(PredFunctor3(), n1_++, n2_++, n3_++); finished_ = true; }, ""); } TEST_F(EXPECT_PRED3Test, FunctorOnUserTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED3(PredFunctor3(), Bool(n1_++), Bool(n2_++), Bool(n3_++)); finished_ = true; }, ""); } TEST_F(ASSERT_PRED3Test, FunctionOnBuiltInTypeSuccess) { ASSERT_PRED3(PredFunction3Int, ++n1_, ++n2_, ++n3_); finished_ = true; }
2,335
#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_ #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_ #ifndef _WIN32_WCE #include <errno.h> #endif #include <algorithm> #include <exception> #include <functional> #include <memory> #include <string> #include <tuple> #include <type_traits> #include <utility> #include "gmock/internal/gmock-internal-utils.h" #include "gmock/internal/gmock-port.h" #include "gmock/internal/gmock-pp.h" GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100) namespace testing { namespace internal { template <typename T, bool kDefaultConstructible> struct BuiltInDefaultValueGetter { static T Get() { return T(); } }; template <typename T> struct BuiltInDefaultValueGetter<T, false> { static T Get() { Assert(false, __FILE__, __LINE__, "Default action undefined for the function return type."); #if defined(__GNUC__) || defined(__clang__) __builtin_unreachable(); #elif defined(_MSC_VER) __assume(0); #else return Invalid<T>(); #endif } }; template <typename T> class BuiltInDefaultValue { public: static bool Exists() { return ::std::is_default_constructible<T>::value; } static T Get() { return BuiltInDefaultValueGetter< T, ::std::is_default_constructible<T>::value>::Get(); } }; template <typename T> class BuiltInDefaultValue<const T> { public: static bool Exists() { return BuiltInDefaultValue<T>::Exists(); } static T Get() { return BuiltInDefaultValue<T>::Get(); } }; template <typename T> class BuiltInDefaultValue<T*> { public: static bool Exists() { return true; } static T* Get() { return nullptr; } }; #define GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(type, value) \ template <> \ class BuiltInDefaultValue<type> { \ public: \ static bool Exists() { return true; } \ static type Get() { return value; } \ } GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(void, ); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::std::string, ""); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(bool, false); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned char, '\0'); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed char, '\0'); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(char, '\0'); #if GMOCK_WCHAR_T_IS_NATIVE_ GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(wchar_t, 0U); #endif GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned short, 0U); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed short, 0); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned int, 0U); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed int, 0); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long, 0UL); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long, 0L); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long long, 0); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long long, 0); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(float, 0); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(double, 0); #undef GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_ template <typename P> struct negation : std::integral_constant<bool, bool(!P::value)> {}; template <typename...> struct conjunction : std::true_type {}; template <typename P1> struct conjunction<P1> : P1 {}; template <typename P1, typename... Ps> struct conjunction<P1, Ps...> : std::conditional<bool(P1::value), conjunction<Ps...>, P1>::type {}; template <typename...> struct disjunction : std::false_type {}; template <typename P1> struct disjunction<P1> : P1 {}; template <typename P1, typename... Ps> struct disjunction<P1, Ps...> : std::conditional<!bool(P1::value), disjunction<Ps...>, P1>::type {}; template <typename...> using void_t = void; template <typename From, typename To> struct is_implicitly_convertible { private: template <typename T> static void Accept(T); template <typename T> static T Make(); template <typename T, typename = decltype(Accept<To>(Make<T>()))> static std::true_type TestImplicitConversion(int); template <typename T> static std::false_type TestImplicitConversion(...); public: using type = decltype(TestImplicitConversion<From>(0)); static constexpr bool value = type::value; }; template <typename F, typename... Args> using call_result_t = decltype(std::declval<F>()(std::declval<Args>()...)); template <typename Void, typename R, typename F, typename... Args> struct is_callable_r_impl : std::false_type {}; template <typename R, typename F, typename... Args> struct is_callable_r_impl<void_t<call_result_t<F, Args...>>, R, F, Args...> : std::conditional< std::is_void<R>::value, std::true_type, is_implicitly_convertible<call_result_t<F, Args...>, R>>::type {}; template <typename R, typename F, typename... Args> using is_callable_r = is_callable_r_impl<void, R, F, Args...>; template <typename T> typename std::add_const<T>::type& as_const(T& t) { return t; } } template <typename F> class OnceAction; template <typename Result, typename... Args> class OnceAction<Result(Args...)> final { private: template <typename Callable> using IsDirectlyCompatible = internal::conjunction< std::is_constructible<typename std::decay<Callable>::type, Callable>, internal::is_callable_r<Result, typename std::decay<Callable>::type, Args...>>; template <typename Callable> using IsCompatibleAfterIgnoringArguments = internal::conjunction< std::is_constructible<typename std::decay<Callable>::type, Callable>, internal::is_callable_r<Result, typename std::decay<Callable>::type>>; public: template <typename Callable, typename std::enable_if< internal::conjunction< internal::negation<std::is_same< OnceAction, typename std::decay<Callable>::type>>, IsDirectlyCompatible<Callable>> ::value, int>::type = 0> OnceAction(Callable&& callable) : function_(StdFunctionAdaptor<typename std::decay<Callable>::type>( {}, std::forward<Callable>(callable))) {} template <typename Callable, typename std::enable_if< internal::conjunction< internal::negation<std::is_same< OnceAction, typename std::decay<Callable>::type>>, internal::negation<IsDirectlyCompatible<Callable>>, IsCompatibleAfterIgnoringArguments<Callable>>::value, int>::type = 0> OnceAction(Callable&& callable) : OnceAction(IgnoreIncomingArguments<typename std::decay<Callable>::type>{ std::forward<Callable>(callable)}) {} OnceAction(const OnceAction&) = delete; OnceAction& operator=(const OnceAction&) = delete; OnceAction(OnceAction&&) = default; Result Call(Args... args) && { return function_(std::forward<Args>(args)...); } private: template <typename Callable> class StdFunctionAdaptor final { public: struct CallableTag final {}; template <typename F> explicit StdFunctionAdaptor(CallableTag, F&& callable) : callable_(std::make_shared<Callable>(std::forward<F>(callable))) {} template <typename... ArgRefs> internal::call_result_t<Callable, ArgRefs...> operator()( ArgRefs&&... args) const { return std::move(*callable_)(std::forward<ArgRefs>(args)...); } private: std::shared_ptr<Callable> callable_; }; template <typename Callable> struct IgnoreIncomingArguments { internal::call_result_t<Callable> operator()(Args&&...) { return std::move(callable)(); } Callable callable; }; std::function<Result(Args...)> function_; }; template <typename T> class DefaultValue { public: static void Set(T x) { delete producer_; producer_ = new FixedValueProducer(x); } typedef T (*FactoryFunction)(); static void SetFactory(FactoryFunction factory) { delete producer_; producer_ = new FactoryValueProducer(factory); } static void Clear() { delete producer_; producer_ = nullptr; } static bool IsSet() { return producer_ != nullptr; } static bool Exists() { return IsSet() || internal::BuiltInDefaultValue<T>::Exists(); } static T Get() { return producer_ == nullptr ? internal::BuiltInDefaultValue<T>::Get() : producer_->Produce(); } private: class ValueProducer { public: virtual ~ValueProducer() = default; virtual T Produce() = 0; }; class FixedValueProducer : public ValueProducer { public: explicit FixedValueProducer(T value) : value_(value) {} T Produce() override { return value_; } private: const T value_; FixedValueProducer(const FixedValueProducer&) = delete; FixedValueProducer& operator=(const FixedValueProducer&) = delete; }; class FactoryValueProducer : public ValueProducer { public: explicit FactoryValueProducer(FactoryFunction factory) : factory_(factory) {} T Produce() override { return factory_(); } private: const FactoryFunction factory_; FactoryValueProducer(const FactoryValueProducer&) = delete; FactoryValueProducer& operator=(const FactoryValueProducer&) = delete; }; static ValueProducer* producer_; }; template <typename T> class DefaultValue<T&> { public: static void Set(T& x) { address_ = &x; } static void Clear() { address_ = nullptr; } static bool IsSet() { return address_ != nullptr; } static bool Exists() { return IsSet() || internal::BuiltInDefaultValue<T&>::Exists(); } static T& Get() { return address_ == nullptr ? internal::BuiltInDefaultValue<T&>::Get() : *address_; } private: static T* address_; }; template <> class DefaultValue<void> { public: static bool Exists() { return true; } static void Get() {} }; template <typename T> typename DefaultValue<T>::ValueProducer* DefaultValue<T>::producer_ = nullptr; template <typename T> T* DefaultValue<T&>::address_ = nullptr; template <typename F> class ActionInterface { public: typedef typename internal::Function<F>::Result Result; typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; ActionInterface() = default; virtual ~ActionInterface() = default; virtual Result Perform(const ArgumentTuple& args) = 0; private: ActionInterface(const ActionInterface&) = delete; ActionInterface& operator=(const ActionInterface&) = delete; }; template <typename F> class Action; template <typename R, typename... Args> class Action<R(Args...)> { private: using F = R(Args...); struct ActionAdapter { ::std::shared_ptr<ActionInterface<F>> impl_; template <typename... InArgs> typename internal::Function<F>::Result operator()(InArgs&&... args) { return impl_->Perform( ::std::forward_as_tuple(::std::forward<InArgs>(args)...)); } }; template <typename G> using IsCompatibleFunctor = std::is_constructible<std::function<F>, G>; public: typedef typename internal::Function<F>::Result Result; typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; Action() = default; template < typename G, typename = typename std::enable_if<internal::disjunction< IsCompatibleFunctor<G>, std::is_constructible<std::function<Result()>, G>>::value>::type> Action(G&& fun) { Init(::std::forward<G>(fun), IsCompatibleFunctor<G>()); } explicit Action(ActionInterface<F>* impl) : fun_(ActionAdapter{::std::shared_ptr<ActionInterface<F>>(impl)}) {} template <typename Func> Action(const Action<Func>& action) : fun_(action.fun_) {} bool IsDoDefault() const { return fun_ == nullptr; } Result Perform(ArgumentTuple args) const { if (IsDoDefault()) { internal::IllegalDoDefault(__FILE__, __LINE__); } return internal::Apply(fun_, ::std::move(args)); } operator OnceAction<F>() const { struct OA { Action<F> action; R operator()(Args... args) && { return action.Perform( std::forward_as_tuple(std::forward<Args>(args)...)); } }; return OA{*this}; } private: template <typename G> friend class Action; template <typename G> void Init(G&& g, ::std::true_type) { fun_ = ::std::forward<G>(g); } template <typename G> void Init(G&& g, ::std::false_type) { fun_ = IgnoreArgs<typename ::std::decay<G>::type>{::std::forward<G>(g)}; } template <typename FunctionImpl> struct IgnoreArgs { template <typename... InArgs> Result operator()(const InArgs&...) const { return function_impl(); } FunctionImpl function_impl; }; ::std::function<F> fun_; }; template <typename Impl>
#include "gmock/gmock-actions.h" #include <algorithm> #include <functional> #include <iterator> #include <memory> #include <sstream> #include <string> #include <tuple> #include <type_traits> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gmock/internal/gmock-port.h" #include "gtest/gtest-spi.h" #include "gtest/gtest.h" #include "gtest/internal/gtest-port.h" GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100 4503) #if defined(_MSC_VER) && (_MSC_VER == 1900) GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800) #endif namespace testing { namespace { using ::testing::internal::BuiltInDefaultValue; TEST(TypeTraits, Negation) { static_assert(std::is_base_of<std::false_type, internal::negation<std::true_type>>::value, ""); static_assert(std::is_base_of<std::true_type, internal::negation<std::false_type>>::value, ""); static_assert(std::is_base_of< std::true_type, internal::negation<std::integral_constant<int, 0>>>::value, ""); static_assert(std::is_base_of< std::false_type, internal::negation<std::integral_constant<int, 1>>>::value, ""); static_assert(std::is_base_of< std::false_type, internal::negation<std::integral_constant<int, -1>>>::value, ""); } template <int> struct MyFalse : std::integral_constant<int, 0> {}; template <int> struct MyTrue : std::integral_constant<int, -1> {}; TEST(TypeTraits, Conjunction) { static_assert(std::is_base_of<std::true_type, internal::conjunction<>>::value, ""); static_assert( std::is_base_of<MyFalse<0>, internal::conjunction<MyFalse<0>>>::value, ""); static_assert( std::is_base_of<MyTrue<0>, internal::conjunction<MyTrue<0>>>::value, ""); static_assert( std::is_base_of<MyFalse<1>, internal::conjunction<MyTrue<0>, MyFalse<1>, MyTrue<2>>>::value, ""); static_assert( std::is_base_of<MyFalse<1>, internal::conjunction<MyTrue<0>, MyFalse<1>, MyFalse<2>>>::value, ""); struct Empty {}; static_assert( std::is_base_of<MyFalse<1>, internal::conjunction<MyTrue<0>, MyFalse<1>, Empty>>::value, ""); static_assert( std::is_base_of<MyTrue<2>, internal::conjunction<MyTrue<0>, MyTrue<1>, MyTrue<2>>>::value, ""); } TEST(TypeTraits, Disjunction) { static_assert( std::is_base_of<std::false_type, internal::disjunction<>>::value, ""); static_assert( std::is_base_of<MyFalse<0>, internal::disjunction<MyFalse<0>>>::value, ""); static_assert( std::is_base_of<MyTrue<0>, internal::disjunction<MyTrue<0>>>::value, ""); static_assert( std::is_base_of<MyTrue<1>, internal::disjunction<MyFalse<0>, MyTrue<1>, MyFalse<2>>>::value, ""); static_assert( std::is_base_of<MyTrue<1>, internal::disjunction<MyFalse<0>, MyTrue<1>, MyTrue<2>>>::value, ""); struct Empty {}; static_assert( std::is_base_of<MyTrue<1>, internal::disjunction<MyFalse<0>, MyTrue<1>, Empty>>::value, ""); static_assert( std::is_base_of<MyFalse<2>, internal::disjunction<MyFalse<0>, MyFalse<1>, MyFalse<2>>>::value, ""); } TEST(TypeTraits, IsInvocableRV) { struct C { int operator()() const { return 0; } void operator()(int) & {} std::string operator()(int) && { return ""; }; }; static_assert(internal::is_callable_r<int, C>::value, ""); static_assert(internal::is_callable_r<int, C&>::value, ""); static_assert(internal::is_callable_r<int, const C>::value, ""); static_assert(internal::is_callable_r<int, const C&>::value, ""); static_assert(internal::is_callable_r<void, C>::value, ""); static_assert(internal::is_callable_r<const volatile void, C>::value, ""); static_assert(internal::is_callable_r<char, C>::value, ""); static_assert(internal::is_callable_r<void, C&, int>::value, ""); static_assert(!internal::is_callable_r<int, C&, int>::value, ""); static_assert(!internal::is_callable_r<std::string, C&, int>::value, ""); static_assert(!internal::is_callable_r<void, const C&, int>::value, ""); static_assert(internal::is_callable_r<std::string, C, int>::value, ""); static_assert(internal::is_callable_r<void, C, int>::value, ""); static_assert(!internal::is_callable_r<int, C, int>::value, ""); static_assert(!internal::is_callable_r<void, C, std::string>::value, ""); static_assert(!internal::is_callable_r<void, C, int, int>::value, ""); #if defined(GTEST_INTERNAL_CPLUSPLUS_LANG) && \ GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L { struct NonMoveable { NonMoveable() = default; NonMoveable(NonMoveable&&) = delete; }; static_assert(!std::is_move_constructible_v<NonMoveable>); struct Callable { NonMoveable operator()() { return NonMoveable(); } }; static_assert(internal::is_callable_r<NonMoveable, Callable>::value); static_assert(internal::is_callable_r<void, Callable>::value); static_assert( internal::is_callable_r<const volatile void, Callable>::value); static_assert(!internal::is_callable_r<int, Callable>::value); static_assert(!internal::is_callable_r<NonMoveable, Callable, int>::value); } #endif static_assert(!internal::is_callable_r<void, int>::value, ""); static_assert(!internal::is_callable_r<void, void (C::*)()>::value, ""); static_assert(!internal::is_callable_r<void, void (C::*)(), C*>::value, ""); } TEST(BuiltInDefaultValueTest, IsNullForPointerTypes) { EXPECT_TRUE(BuiltInDefaultValue<int*>::Get() == nullptr); EXPECT_TRUE(BuiltInDefaultValue<const char*>::Get() == nullptr); EXPECT_TRUE(BuiltInDefaultValue<void*>::Get() == nullptr); } TEST(BuiltInDefaultValueTest, ExistsForPointerTypes) { EXPECT_TRUE(BuiltInDefaultValue<int*>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<const char*>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<void*>::Exists()); } TEST(BuiltInDefaultValueTest, IsZeroForNumericTypes) { EXPECT_EQ(0U, BuiltInDefaultValue<unsigned char>::Get()); EXPECT_EQ(0, BuiltInDefaultValue<signed char>::Get()); EXPECT_EQ(0, BuiltInDefaultValue<char>::Get()); #if GMOCK_WCHAR_T_IS_NATIVE_ #if !defined(__WCHAR_UNSIGNED__) EXPECT_EQ(0, BuiltInDefaultValue<wchar_t>::Get()); #else EXPECT_EQ(0U, BuiltInDefaultValue<wchar_t>::Get()); #endif #endif EXPECT_EQ(0U, BuiltInDefaultValue<unsigned short>::Get()); EXPECT_EQ(0, BuiltInDefaultValue<signed short>::Get()); EXPECT_EQ(0, BuiltInDefaultValue<short>::Get()); EXPECT_EQ(0U, BuiltInDefaultValue<unsigned int>::Get()); EXPECT_EQ(0, BuiltInDefaultValue<signed int>::Get()); EXPECT_EQ(0, BuiltInDefaultValue<int>::Get()); EXPECT_EQ(0U, BuiltInDefaultValue<unsigned long>::Get()); EXPECT_EQ(0, BuiltInDefaultValue<signed long>::Get()); EXPECT_EQ(0, BuiltInDefaultValue<long>::Get()); EXPECT_EQ(0U, BuiltInDefaultValue<unsigned long long>::Get()); EXPECT_EQ(0, BuiltInDefaultValue<signed long long>::Get()); EXPECT_EQ(0, BuiltInDefaultValue<long long>::Get()); EXPECT_EQ(0, BuiltInDefaultValue<float>::Get()); EXPECT_EQ(0, BuiltInDefaultValue<double>::Get()); } TEST(BuiltInDefaultValueTest, ExistsForNumericTypes) { EXPECT_TRUE(BuiltInDefaultValue<unsigned char>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<signed char>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<char>::Exists()); #if GMOCK_WCHAR_T_IS_NATIVE_ EXPECT_TRUE(BuiltInDefaultValue<wchar_t>::Exists()); #endif EXPECT_TRUE(BuiltInDefaultValue<unsigned short>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<signed short>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<short>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<unsigned int>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<signed int>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<int>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<unsigned long>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<signed long>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<long>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<unsigned long long>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<signed long long>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<long long>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<float>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<double>::Exists()); } TEST(BuiltInDefaultValueTest, IsFalseForBool) { EXPECT_FALSE(BuiltInDefaultValue<bool>::Get()); } TEST(BuiltInDefaultValueTest, BoolExists) { EXPECT_TRUE(BuiltInDefaultValue<bool>::Exists()); } TEST(BuiltInDefaultValueTest, IsEmptyStringForString) { EXPECT_EQ("", BuiltInDefaultValue<::std::string>::Get()); } TEST(BuiltInDefaultValueTest, ExistsForString) { EXPECT_TRUE(BuiltInDefaultValue<::std::string>::Exists()); } TEST(BuiltInDefaultValueTest, WorksForConstTypes) { EXPECT_EQ("", BuiltInDefaultValue<const std::string>::Get()); EXPECT_EQ(0, BuiltInDefaultValue<const int>::Get()); EXPECT_TRUE(BuiltInDefaultValue<char* const>::Get() == nullptr); EXPECT_FALSE(BuiltInDefaultValue<const bool>::Get()); } class MyDefaultConstructible { public: MyDefaultConstructible() : value_(42) {} int value() const { return value_; } private: int value_; }; class MyNonDefaultConstructible { public: explicit MyNonDefaultConstructible(int a_value) : value_(a_value) {} int value() const { return value_; } private: int value_; }; TEST(BuiltInDefaultValueTest, ExistsForDefaultConstructibleType) { EXPECT_TRUE(BuiltInDefaultValue<MyDefaultConstructible>::Exists()); } TEST(BuiltInDefaultValueTest, IsDefaultConstructedForDefaultConstructibleType) { EXPECT_EQ(42, BuiltInDefaultValue<MyDefaultConstructible>::Get().value()); } TEST(BuiltInDefaultValueTest, DoesNotExistForNonDefaultConstructibleType) { EXPECT_FALSE(BuiltInDefaultValue<MyNonDefaultConstructible>::Exists()); } TEST(BuiltInDefaultValueDeathTest, IsUndefinedForReferences) { EXPECT_DEATH_IF_SUPPORTED({ BuiltInDefaultValue<int&>::Get(); }, ""); EXPECT_DEATH_IF_SUPPORTED({ BuiltInDefaultValue<const char&>::Get(); }, ""); } TEST(BuiltInDefaultValueDeathTest, IsUndefinedForNonDefaultConstructibleType) { EXPECT_DEATH_IF_SUPPORTED( { BuiltInDefaultValue<MyNonDefaultConstructible>::Get(); }, ""); } TEST(DefaultValueTest, IsInitiallyUnset) { EXPECT_FALSE(DefaultValue<int>::IsSet()); EXPECT_FALSE(DefaultValue<MyDefaultConstructible>::IsSet()); EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::IsSet()); } TEST(DefaultValueTest, CanBeSetAndUnset) { EXPECT_TRUE(DefaultValue<int>::Exists()); EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::Exists()); DefaultValue<int>::Set(1); DefaultValue<const MyNonDefaultConstructible>::Set( MyNonDefaultConstructible(42)); EXPECT_EQ(1, DefaultValue<int>::Get()); EXPECT_EQ(42, DefaultValue<const MyNonDefaultConstructible>::Get().value()); EXPECT_TRUE(DefaultValue<int>::Exists()); EXPECT_TRUE(DefaultValue<const MyNonDefaultConstructible>::Exists()); DefaultValue<int>::Clear(); DefaultValue<const MyNonDefaultConstructible>::Clear(); EXPECT_FALSE(DefaultValue<int>::IsSet()); EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::IsSet()); EXPECT_TRUE(DefaultValue<int>::Exists()); EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::Exists()); } TEST(DefaultValueDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) { EXPECT_FALSE(DefaultValue<int>::IsSet()); EXPECT_TRUE(DefaultValue<int>::Exists()); EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible>::IsSet()); EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible>::Exists()); EXPECT_EQ(0, DefaultValue<int>::Get()); EXPECT_DEATH_IF_SUPPORTED({ DefaultValue<MyNonDefaultConstructible>::Get(); }, ""); } TEST(DefaultValueTest, GetWorksForMoveOnlyIfSet) { EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists()); EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Get() == nullptr); DefaultValue<std::unique_ptr<int>>::SetFactory( [] { return std::make_unique<int>(42); }); EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists()); std::unique_ptr<int> i = DefaultValue<std::unique_ptr<int>>::Get(); EXPECT_EQ(42, *i); } TEST(DefaultValueTest, GetWorksForVoid) { return DefaultValue<void>::Get(); } TEST(DefaultValueOfReferenceTest, IsInitiallyUnset) { EXPECT_FALSE(DefaultValue<int&>::IsSet()); EXPECT_FALSE(DefaultValue<MyDefaultConstructible&>::IsSet()); EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet()); } TEST(DefaultValueOfReferenceTest, IsInitiallyNotExisting) { EXPECT_FALSE(DefaultValue<int&>::Exists()); EXPECT_FALSE(DefaultValue<MyDefaultConstructible&>::Exists()); EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::Exists()); } TEST(DefaultValueOfReferenceTest, CanBeSetAndUnset) { int n = 1; DefaultValue<const int&>::Set(n); MyNonDefaultConstructible x(42); DefaultValue<MyNonDefaultConstructible&>::Set(x); EXPECT_TRUE(DefaultValue<const int&>::Exists()); EXPECT_TRUE(DefaultValue<MyNonDefaultConstructible&>::Exists()); EXPECT_EQ(&n, &(DefaultValue<const int&>::Get())); EXPECT_EQ(&x, &(DefaultValue<MyNonDefaultConstructible&>::Get())); DefaultValue<const int&>::Clear(); DefaultValue<MyNonDefaultConstructible&>::Clear(); EXPECT_FALSE(DefaultValue<const int&>::Exists()); EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::Exists()); EXPECT_FALSE(DefaultValue<const int&>::IsSet()); EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet()); } TEST(DefaultValueOfReferenceDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) { EXPECT_FALSE(DefaultValue<int&>::IsSet()); EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet()); EXPECT_DEATH_IF_SUPPORTED({ DefaultValue<int&>::Get(); }, ""); EXPECT_DEATH_IF_SUPPORTED({ DefaultValue<MyNonDefaultConstructible>::Get(); }, ""); } typedef int MyGlobalFunction(bool, int); class MyActionImpl : public ActionInterface<MyGlobalFunction> { public: int Perform(const std::tuple<bool, int>& args) override { return std::get<0>(args) ? std::get<1>(args) : 0; } }; TEST(ActionInterfaceTest, CanBeImplementedByDefiningPerform) { MyActionImpl my_action_impl; (void)my_action_impl; } TEST(ActionInterfaceTest, MakeAction) { Action<MyGlobalFunction> action = MakeAction(new MyActionImpl); EXPECT_EQ(5, action.Perform(std::make_tuple(true, 5))); } TEST(ActionTest, CanBeConstructedFromActionInterface) { Action<MyGlobalFunction> action(new MyActionImpl); } TEST(ActionTest, DelegatesWorkToActionInterface) { const Action<MyGlobalFunction> action(new MyActionImpl); EXPECT_EQ(5, action.Perform(std::make_tuple(true, 5))); EXPECT_EQ(0, action.Perform(std::make_tuple(false, 1))); } TEST(ActionTest, IsCopyable) { Action<MyGlobalFunction> a1(new MyActionImpl); Action<MyGlobalFunction> a2(a1); EXPECT_EQ(5, a1.Perform(std::make_tuple(true, 5))); EXPECT_EQ(0, a1.Perform(std::make_tuple(false, 1))); EXPECT_EQ(5, a2.Perform(std::make_tuple(true, 5))); EXPECT_EQ(0, a2.Perform(std::make_tuple(false, 1))); a2 = a1; EXPECT_EQ(5, a1.Perform(std::make_tuple(true, 5))); EXPECT_EQ(0, a1.Perform(std::make_tuple(false, 1))); EXPECT_EQ(5, a2.Perform(std::make_tuple(true, 5))); EXPECT_EQ(0, a2.Perform(std::make_tuple(false, 1))); } class IsNotZero : public ActionInterface<bool(int)> { public: bool Perform(const std::tuple<int>& arg) override { return std::get<0>(arg) != 0; } }; TEST(ActionTest, CanBeConvertedToOtherActionType) { const Action<bool(int)> a1(new IsNotZero); const Action<int(char)> a2 = Action<int(char)>(a1); EXPECT_EQ(1, a2.Perform(std::make_tuple('a'))); EXPECT_EQ(0, a2.Perform(std::make_tuple('\0'))); } class ReturnSecondArgumentAction { public: template <typename Result, typename ArgumentTuple> Result Perform(const ArgumentTuple& args) { return std::get<1>(args); } }; class ReturnZeroFromNullaryFunctionAction { public: template <typename Result> Result Perform(const std::tuple<>&) const { return 0; } }; PolymorphicAction<ReturnSecondArgumentAction> ReturnSecondArgument() { return MakePolymorphicAction(ReturnSecondArgumentAction()); } PolymorphicAction<ReturnZeroFromNullaryFunctionAction> ReturnZeroFromNullaryFunction() { return MakePolymorphicAction(ReturnZeroFromNullaryFunctionAction()); } TEST(MakePolymorphicActionTest, ConstructsActionFromImpl) { Action<int(bool, int, double)> a1 = ReturnSecondArgument(); EXPECT_EQ(5, a1.Perform(std::make_tuple(false, 5, 2.0))); } TEST(MakePolymorphicActionTest, WorksWhenPerformHasOneTemplateParameter) { Action<int()> a1 = ReturnZeroFromNullaryFunction(); EXPECT_EQ(0, a1.Perform(std::make_tuple())); Action<void*()> a2 = ReturnZeroFromNullaryFunction(); EXPECT_TRUE(a2.Perform(std::make_tuple()) == nullptr); } TEST(ReturnTest, WorksForVoid) { const Action<void(int)> ret = Return(); return ret.Perform(std::make_tuple(1)); } TEST(ReturnTest, ReturnsGivenValue) { Action<int()> ret = Return(1); EXPECT_EQ(1, ret.Perform(std::make_tuple())); ret = Return(-5); EXPECT_EQ(-5, ret.Perform(std::make_tuple())); } TEST(ReturnTest, AcceptsStringLiteral) { Action<const char*()> a1 = Return("Hello"); EXPECT_STREQ("Hello", a1.Perform(std::make_tuple())); Action<std::string()> a2 = Return("world"); EXPECT_EQ("world", a2.Perform(std::make_tuple())); } TEST(ReturnTest, SupportsReferenceLikeReturnType) { struct Result { const std::vector<int>* v; Result(const std::vector<int>& vec) : v(&vec) {} }; MockFunction<Result()> mock; EXPECT_CALL(mock, Call) .WillOnce(Return(std::vector<int>{17, 19, 23})) .WillRepeatedly(Return(std::vector<int>{29, 31, 37})); EXPECT_THAT(mock.AsStdFunction()(), Field(&Result::v, Pointee(ElementsAre(17, 19, 23)))); EXPECT_THAT(mock.AsStdFunction()(), Field(&Result::v, Pointee(ElementsAre(29, 31, 37)))); } TEST(ReturnTest, PrefersConversionOperator) { struct In; struct Out { int x; explicit Out(const int val) : x(val) {} explicit Out(const In&) : x(0) {} }; struct In { operator Out() const { return Out{19}; } }; EXPECT_THAT([]() -> Out { return In(); }(), Field(&Out::x, 19)); MockFunction<Out()> mock; EXPECT_CALL(mock, Call).WillOnce(Return(In())); EXPECT_THAT(mock.AsStdFunction()(), Field(&Out::x, 19)); } TEST(ReturnTest, ConversionRequiresConstLvalueReference) { using R = int; using U = std::reference_wrapper<const int>; static_assert(std::is_convertible<const R&, U>::value, ""); static_assert(!std::is_convertible<R, U>::value, ""); MockFunction<U()> mock; EXPECT_CALL(mock, Call).WillOnce(Return(17)).WillRepeatedly(Return(19)); EXPECT_EQ(17, mock.AsStdFunction()()); EXPECT_EQ(19, mock.AsStdFunction()()); } TEST(ReturnTest, ConversionRequiresMutableLvalueReference) { struct S { S(std::string&) {} }; static_assert(std::is_convertible<std::string&, S>::value, ""); #ifndef _MSC_VER static_assert(!std::is_convertible<std::string&&, S>::value, ""); #endif static_assert(!std::is_convertible<const std::string&, S>::value, ""); using RA = decltype(Return(std::string())); static_assert(!std::is_convertible<RA, Action<S()>>::value, ""); #ifndef _MSC_VER static_assert(!std::is_convertible<RA, OnceAction<S()>>::value, ""); #endif } TEST(ReturnTest, MoveOnlyResultType) { { MockFunction<std::unique_ptr<int>()> mock; EXPECT_CALL(mock, Call) .WillOnce(Return(std::unique_ptr<int>(new int(17)))); EXPECT_THAT(mock.AsStdFunction()(), Pointee(17)); } static_assert(!std::is_convertible<decltype(Return(std::unique_ptr<int>())), Action<std::unique_ptr<int>()>>::value, ""); } struct Base { bool operator==(const Base&) { return true; } }; struct Derived : public Base { bool operator==(const Derived&) { return true; } }; TEST(ReturnTest, IsCovariant) { Base base; Derived derived; Action<Base*()> ret = Return(&base); EXPECT_EQ(&base, ret.Perform(std::make_tuple())); ret = Return(&derived); EXPECT_EQ(&derived, ret.Perform(std::make_tuple())); } class FromType { public: explicit FromType(bool* is_converted) : converted_(is_converted) {} bool* converted() const { return converted_; } private: bool* const converted_; }; class ToType { public: ToType(const FromType& x) { *x.converted() = true; } }; TEST(ReturnTest, ConvertsArgumentWhenConverted) { bool converted = false; FromType x(&converted); Action<ToType()> action(Return(x)); EXPECT_TRUE(converted) << "Return must convert its argument in its own " << "conversion operator."; converted = false; action.Perform(std::tuple<>()); EXPECT_FALSE(converted) << "Action must NOT convert its argument " << "when performed."; } TEST(ReturnNullTest, WorksInPointerReturningFunction) { const Action<int*()> a1 = ReturnNull(); EXPECT_TRUE(a1.Perform(std::make_tuple()) == nullptr); const Action<const char*(bool)> a2 = ReturnNull(); EXPECT_TRUE(a2.Perform(std::make_tuple(true)) == nullptr); }
2,336
#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_FUNCTION_MOCKER_H_ #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_FUNCTION_MOCKER_H_ #include <cstddef> #include <type_traits> #include <utility> #include "gmock/gmock-spec-builders.h" #include "gmock/internal/gmock-internal-utils.h" #include "gmock/internal/gmock-pp.h" namespace testing { namespace internal { template <typename T> using identity_t = T; template <typename Pattern> struct ThisRefAdjuster { template <typename T> using AdjustT = typename std::conditional< std::is_const<typename std::remove_reference<Pattern>::type>::value, typename std::conditional<std::is_lvalue_reference<Pattern>::value, const T&, const T&&>::type, typename std::conditional<std::is_lvalue_reference<Pattern>::value, T&, T&&>::type>::type; template <typename MockType> static AdjustT<MockType> Adjust(const MockType& mock) { return static_cast<AdjustT<MockType>>(const_cast<MockType&>(mock)); } }; constexpr bool PrefixOf(const char* a, const char* b) { return *a == 0 || (*a == *b && internal::PrefixOf(a + 1, b + 1)); } template <size_t N, size_t M> constexpr bool StartsWith(const char (&prefix)[N], const char (&str)[M]) { return N <= M && internal::PrefixOf(prefix, str); } template <size_t N, size_t M> constexpr bool EndsWith(const char (&suffix)[N], const char (&str)[M]) { return N <= M && internal::PrefixOf(suffix, str + M - N); } template <size_t N, size_t M> constexpr bool Equals(const char (&a)[N], const char (&b)[M]) { return N == M && internal::PrefixOf(a, b); } template <size_t N> constexpr bool ValidateSpec(const char (&spec)[N]) { return internal::Equals("const", spec) || internal::Equals("override", spec) || internal::Equals("final", spec) || internal::Equals("noexcept", spec) || (internal::StartsWith("noexcept(", spec) && internal::EndsWith(")", spec)) || internal::Equals("ref(&)", spec) || internal::Equals("ref(&&)", spec) || (internal::StartsWith("Calltype(", spec) && internal::EndsWith(")", spec)); } } using internal::FunctionMocker; } #define MOCK_METHOD(...) \ GMOCK_INTERNAL_WARNING_PUSH() \ GMOCK_INTERNAL_WARNING_CLANG(ignored, "-Wunused-member-function") \ GMOCK_PP_VARIADIC_CALL(GMOCK_INTERNAL_MOCK_METHOD_ARG_, __VA_ARGS__) \ GMOCK_INTERNAL_WARNING_POP() #define GMOCK_INTERNAL_MOCK_METHOD_ARG_1(...) \ GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__) #define GMOCK_INTERNAL_MOCK_METHOD_ARG_2(...) \ GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__) #define GMOCK_INTERNAL_MOCK_METHOD_ARG_3(_Ret, _MethodName, _Args) \ GMOCK_INTERNAL_MOCK_METHOD_ARG_4(_Ret, _MethodName, _Args, ()) #define GMOCK_INTERNAL_MOCK_METHOD_ARG_4(_Ret, _MethodName, _Args, _Spec) \ GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Args); \ GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Spec); \ GMOCK_INTERNAL_ASSERT_VALID_SIGNATURE( \ GMOCK_PP_NARG0 _Args, GMOCK_INTERNAL_SIGNATURE(_Ret, _Args)); \ GMOCK_INTERNAL_ASSERT_VALID_SPEC(_Spec) \ GMOCK_INTERNAL_MOCK_METHOD_IMPL( \ GMOCK_PP_NARG0 _Args, _MethodName, GMOCK_INTERNAL_HAS_CONST(_Spec), \ GMOCK_INTERNAL_HAS_OVERRIDE(_Spec), GMOCK_INTERNAL_HAS_FINAL(_Spec), \ GMOCK_INTERNAL_GET_NOEXCEPT_SPEC(_Spec), \ GMOCK_INTERNAL_GET_CALLTYPE_SPEC(_Spec), \ GMOCK_INTERNAL_GET_REF_SPEC(_Spec), \ (GMOCK_INTERNAL_SIGNATURE(_Ret, _Args))) #define GMOCK_INTERNAL_MOCK_METHOD_ARG_5(...) \ GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__) #define GMOCK_INTERNAL_MOCK_METHOD_ARG_6(...) \ GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__) #define GMOCK_INTERNAL_MOCK_METHOD_ARG_7(...) \ GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__) #define GMOCK_INTERNAL_WRONG_ARITY(...) \ static_assert( \ false, \ "MOCK_METHOD must be called with 3 or 4 arguments. _Ret, " \ "_MethodName, _Args and optionally _Spec. _Args and _Spec must be " \ "enclosed in parentheses. If _Ret is a type with unprotected commas, " \ "it must also be enclosed in parentheses.") #define GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Tuple) \ static_assert( \ GMOCK_PP_IS_ENCLOSED_PARENS(_Tuple), \ GMOCK_PP_STRINGIZE(_Tuple) " should be enclosed in parentheses.") #define GMOCK_INTERNAL_ASSERT_VALID_SIGNATURE(_N, ...) \ static_assert( \ std::is_function<__VA_ARGS__>::value, \ "Signature must be a function type, maybe return type contains " \ "unprotected comma."); \ static_assert( \ ::testing::tuple_size<typename ::testing::internal::Function< \ __VA_ARGS__>::ArgumentTuple>::value == _N, \ "This method does not take " GMOCK_PP_STRINGIZE( \ _N) " arguments. Parenthesize all types with unprotected commas.") #define GMOCK_INTERNAL_ASSERT_VALID_SPEC(_Spec) \ GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_ASSERT_VALID_SPEC_ELEMENT, ~, _Spec) #define GMOCK_INTERNAL_MOCK_METHOD_IMPL(_N, _MethodName, _Constness, \ _Override, _Final, _NoexceptSpec, \ _CallType, _RefSpec, _Signature) \ typename ::testing::internal::Function<GMOCK_PP_REMOVE_PARENS( \ _Signature)>::Result \ GMOCK_INTERNAL_EXPAND(_CallType) \ _MethodName(GMOCK_PP_REPEAT(GMOCK_INTERNAL_PARAMETER, _Signature, _N)) \ GMOCK_PP_IF(_Constness, const, ) \ _RefSpec _NoexceptSpec GMOCK_PP_IF(_Override, override, ) \ GMOCK_PP_IF(_Final, final, ) { \ GMOCK_MOCKER_(_N, _Constness, _MethodName) \ .SetOwnerAndName(this, #_MethodName); \ return GMOCK_MOCKER_(_N, _Constness, _MethodName) \ .Invoke(GMOCK_PP_REPEAT(GMOCK_INTERNAL_FORWARD_ARG, _Signature, _N)); \ } \ ::testing::MockSpec<GMOCK_PP_REMOVE_PARENS(_Signature)> gmock_##_MethodName( \ GMOCK_PP_REPEAT(GMOCK_INTERNAL_MATCHER_PARAMETER, _Signature, _N)) \ GMOCK_PP_IF(_Constness, const, ) _RefSpec { \ GMOCK_MOCKER_(_N, _Constness, _MethodName).RegisterOwner(this); \ return GMOCK_MOCKER_(_N, _Constness, _MethodName) \ .With(GMOCK_PP_REPEAT(GMOCK_INTERNAL_MATCHER_ARGUMENT, , _N)); \ } \ ::testing::MockSpec<GMOCK_PP_REMOVE_PARENS(_Signature)> gmock_##_MethodName( \ const ::testing::internal::WithoutMatchers&, \ GMOCK_PP_IF(_Constness, const, )::testing::internal::Function< \ GMOCK_PP_REMOVE_PARENS(_Signature)>*) const _RefSpec _NoexceptSpec { \ return ::testing::internal::ThisRefAdjuster<GMOCK_PP_IF( \ _Constness, const, ) int _RefSpec>::Adjust(*this) \ .gmock_##_MethodName(GMOCK_PP_REPEAT( \ GMOCK_INTERNAL_A_MATCHER_ARGUMENT, _Signature, _N)); \ } \ mutable ::testing::FunctionMocker<GMOCK_PP_REMOVE_PARENS(_Signature)> \ GMOCK_MOCKER_(_N, _Constness, _MethodName) #define GMOCK_INTERNAL_EXPAND(...) __VA_ARGS__ #define GMOCK_INTERNAL_HAS_CONST(_Tuple) \ GMOCK_PP_HAS_COMMA(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_CONST, ~, _Tuple)) #define GMOCK_INTERNAL_HAS_OVERRIDE(_Tuple) \ GMOCK_PP_HAS_COMMA( \ GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_OVERRIDE, ~, _Tuple)) #define GMOCK_INTERNAL_HAS_FINAL(_Tuple) \ GMOCK_PP_HAS_COMMA(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_FINAL, ~, _Tuple)) #define GMOCK_INTERNAL_GET_NOEXCEPT_SPEC(_Tuple) \ GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_NOEXCEPT_SPEC_IF_NOEXCEPT, ~, _Tuple) #define GMOCK_INTERNAL_NOEXCEPT_SPEC_IF_NOEXCEPT(_i, _, _elem) \ GMOCK_PP_IF( \ GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem)), \ _elem, ) #define GMOCK_INTERNAL_GET_CALLTYPE_SPEC(_Tuple) \ GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_CALLTYPE_SPEC_IF_CALLTYPE, ~, _Tuple) #define GMOCK_INTERNAL_CALLTYPE_SPEC_IF_CALLTYPE(_i, _, _elem) \ GMOCK_PP_IF( \ GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_CALLTYPE(_i, _, _elem)), \ GMOCK_PP_CAT(GMOCK_INTERNAL_UNPACK_, _elem), ) #define GMOCK_INTERNAL_GET_REF_SPEC(_Tuple) \ GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_REF_SPEC_IF_REF, ~, _Tuple) #define GMOCK_INTERNAL_REF_SPEC_IF_REF(_i, _, _elem) \ GMOCK_PP_IF(GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_REF(_i, _, _elem)), \ GMOCK_PP_CAT(GMOCK_INTERNAL_UNPACK_, _elem), ) #ifdef GMOCK_INTERNAL_STRICT_SPEC_ASSERT #define GMOCK_INTERNAL_ASSERT_VALID_SPEC_ELEMENT(_i, _, _elem) \ static_assert( \ ::testing::internal::ValidateSpec(GMOCK_PP_STRINGIZE(_elem)), \ "Token \'" GMOCK_PP_STRINGIZE( \ _elem) "\' cannot be recognized as a valid specification " \ "modifier. Is a ',' missing?"); #else #define GMOCK_INTERNAL_ASSERT_VALID_SPEC_ELEMENT(_i, _, _elem) \ static_assert( \ (GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_CONST(_i, _, _elem)) + \ GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_OVERRIDE(_i, _, _elem)) + \ GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_FINAL(_i, _, _elem)) + \ GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem)) + \ GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_REF(_i, _, _elem)) + \ GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_CALLTYPE(_i, _, _elem))) == 1, \ GMOCK_PP_STRINGIZE( \ _elem) " cannot be recognized as a valid specification modifier."); #endif #define GMOCK_INTERNAL_DETECT_CONST(_i, _, _elem) \ GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_CONST_I_, _elem) #define GMOCK_INTERNAL_DETECT_CONST_I_const , #define GMOCK_INTERNAL_DETECT_OVERRIDE(_i, _, _elem) \ GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_OVERRIDE_I_, _elem) #define GMOCK_INTERNAL_DETECT_OVERRIDE_I_override , #define GMOCK_INTERNAL_DETECT_FINAL(_i, _, _elem) \ GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_FINAL_I_, _elem) #define GMOCK_INTERNAL_DETECT_FINAL_I_final , #define GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem) \ GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_NOEXCEPT_I_, _elem) #define GMOCK_INTERNAL_DETECT_NOEXCEPT_I_noexcept , #define GMOCK_INTERNAL_DETECT_REF(_i, _, _elem) \ GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_REF_I_, _elem) #define GMOCK_INTERNAL_DETECT_REF_I_ref , #define GMOCK_INTERNAL_UNPACK_ref(x) x #define GMOCK_INTERNAL_DETECT_CALLTYPE(_i, _, _elem) \ GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_CALLTYPE_I_, _elem) #define GMOCK_INTERNAL_DETECT_CALLTYPE_I_Calltype , #define GMOCK_INTERNAL_UNPACK_Calltype(...) __VA_ARGS__ #define GMOCK_INTERNAL_SIGNATURE(_Ret, _Args) \ ::testing::internal::identity_t<GMOCK_PP_IF(GMOCK_PP_IS_BEGIN_PARENS(_Ret), \ GMOCK_PP_REMOVE_PARENS, \ GMOCK_PP_IDENTITY)(_Ret)>( \ GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GET_TYPE, _, _Args)) #define GMOCK_INTERNAL_GET_TYPE(_i, _, _elem) \ GMOCK_PP_COMMA_IF(_i) \ GMOCK_PP_IF(GMOCK_PP_IS_BEGIN_PARENS(_elem), GMOCK_PP_REMOVE_PARENS, \ GMOCK_PP_IDENTITY) \ (_elem) #define GMOCK_INTERNAL_PARAMETER(_i, _Signature, _) \ GMOCK_PP_COMMA_IF(_i) \ GMOCK_INTERNAL_ARG_O(_i, GMOCK_PP_REMOVE_PARENS(_Signature)) \ gmock_a##_i #define GMOCK_INTERNAL_FORWARD_ARG(_i, _Signature, _) \ GMOCK_PP_COMMA_IF(_i) \ ::std::forward<GMOCK_INTERNAL_ARG_O( \ _i, GMOCK_PP_REMOVE_PARENS(_Signature))>(gmock_a##_i) #define GMOCK_INTERNAL_MATCHER_PARAMETER(_i, _Signature, _) \ GMOCK_PP_COMMA_IF(_i) \ GMOCK_INTERNAL_MATCHER_O(_i, GMOCK_PP_REMOVE_PARENS(_Signature)) \ gmock_a##_i #define GMOCK_INTERNAL_MATCHER_ARGUMENT(_i, _1, _2) \ GMOCK_PP_COMMA_IF(_i) \ gmock_a##_i #define GMOCK_INTERNAL_A_MATCHER_ARGUMENT(_i, _Signature, _) \ GMOCK_PP_COMMA_IF(_i) \ ::testing::A<GMOCK_INTERNAL_ARG_O(_i, GMOCK_PP_REMOVE_PARENS(_Signature))>() #define GMOCK_INTERNAL_ARG_O(_i, ...) \ typename ::testing::internal::Function<__VA_ARGS__>::template Arg<_i>::type #define GMOCK_INTERNAL_MATCHER_O(_i, ...) \ const ::testing::Matcher<typename ::testing::internal::Function< \ __VA_ARGS__>::template Arg<_i>::type>& #define MOCK_METHOD0(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 0, __VA_ARGS__) #define MOCK_METHOD1(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 1, __VA_ARGS__) #define MOCK_METHOD2(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 2, __VA_ARGS__) #define MOCK_METHOD3(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 3, __VA_ARGS__) #define MOCK_METHOD4(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 4, __VA_ARGS__) #define MOCK_METHOD5(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 5, __VA_ARGS__) #define MOCK_METHOD6(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 6, __VA_ARGS__) #define MOCK_METHOD7(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 7, __VA_ARGS__) #define MOCK_METHOD8(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 8, __VA_ARGS__) #define MOCK_METHOD9(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 9, __VA_ARGS__) #define MOCK_METHOD10(m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(, , m, 10, __VA_ARGS__) #define MOCK_CONST_METHOD0(m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(const, , m, 0, __VA_ARGS__) #define MOCK_CONST_METHOD1(m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(const, , m, 1, __VA_ARGS__) #define MOCK_CONST_METHOD2(m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(const, , m, 2, __VA_ARGS__) #define MOCK_CONST_METHOD3(m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(const, , m, 3, __VA_ARGS__) #define MOCK_CONST_METHOD4(m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(const, , m, 4, __VA_ARGS__) #define MOCK_CONST_METHOD5(m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(const, , m, 5, __VA_ARGS__) #define MOCK_CONST_METHOD6(m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(const, , m, 6, __VA_ARGS__) #define MOCK_CONST_METHOD7(m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(const, , m, 7, __VA_ARGS__) #define MOCK_CONST_METHOD8(m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(const, , m, 8, __VA_ARGS__) #define MOCK_CONST_METHOD9(m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(const, , m, 9, __VA_ARGS__) #define MOCK_CONST_METHOD10(m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(const, , m, 10, __VA_ARGS__) #define MOCK_METHOD0_T(m, ...) MOCK_METHOD0(m, __VA_ARGS__) #define MOCK_METHOD1_T(m, ...) MOCK_METHOD1(m, __VA_ARGS__) #define MOCK_METHOD2_T(m, ...) MOCK_METHOD2(m, __VA_ARGS__) #define MOCK_METHOD3_T(m, ...) MOCK_METHOD3(m, __VA_ARGS__) #define MOCK_METHOD4_T(m, ...) MOCK_METHOD4(m, __VA_ARGS__) #define MOCK_METHOD5_T(m, ...) MOCK_METHOD5(m, __VA_ARGS__) #define MOCK_METHOD6_T(m, ...) MOCK_METHOD6(m, __VA_ARGS__) #define MOCK_METHOD7_T(m, ...) MOCK_METHOD7(m, __VA_ARGS__) #define MOCK_METHOD8_T(m, ...) MOCK_METHOD8(m, __VA_ARGS__) #define MOCK_METHOD9_T(m, ...) MOCK_METHOD9(m, __VA_ARGS__) #define MOCK_METHOD10_T(m, ...) MOCK_METHOD10(m, __VA_ARGS__) #define MOCK_CONST_METHOD0_T(m, ...) MOCK_CONST_METHOD0(m, __VA_ARGS__) #define MOCK_CONST_METHOD1_T(m, ...) MOCK_CONST_METHOD1(m, __VA_ARGS__) #define MOCK_CONST_METHOD2_T(m, ...) MOCK_CONST_METHOD2(m, __VA_ARGS__) #define MOCK_CONST_METHOD3_T(m, ...) MOCK_CONST_METHOD3(m, __VA_ARGS__) #define MOCK_CONST_METHOD4_T(m, ...) MOCK_CONST_METHOD4(m, __VA_ARGS__) #define MOCK_CONST_METHOD5_T(m, ...) MOCK_CONST_METHOD5(m, __VA_ARGS__) #define MOCK_CONST_METHOD6_T(m, ...) MOCK_CONST_METHOD6(m, __VA_ARGS__) #define MOCK_CONST_METHOD7_T(m, ...) MOCK_CONST_METHOD7(m, __VA_ARGS__) #define MOCK_CONST_METHOD8_T(m, ...) MOCK_CONST_METHOD8(m, __VA_ARGS__) #define MOCK_CONST_METHOD9_T(m, ...) MOCK_CONST_METHOD9(m, __VA_ARGS__) #define MOCK_CONST_METHOD10_T(m, ...) MOCK_CONST_METHOD10(m, __VA_ARGS__) #define MOCK_METHOD0_WITH_CALLTYPE(ct, m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 0, __VA_ARGS__) #define MOCK_METHOD1_WITH_CALLTYPE(ct, m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 1, __VA_ARGS__) #define MOCK_METHOD2_WITH_CALLTYPE(ct, m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 2, __VA_ARGS__) #define MOCK_METHOD3_WITH_CALLTYPE(ct, m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 3, __VA_ARGS__) #define MOCK_METHOD4_WITH_CALLTYPE(ct, m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 4, __VA_ARGS__) #define MOCK_METHOD5_WITH_CALLTYPE(ct, m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 5, __VA_ARGS__) #define MOCK_METHOD6_WITH_CALLTYPE(ct, m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 6, __VA_ARGS__) #define MOCK_METHOD7_WITH_CALLTYPE(ct, m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 7, __VA_ARGS__) #define MOCK_METHOD8_WITH_CALLTYPE(ct, m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 8, __VA_ARGS__) #define MOCK_METHOD9_WITH_CALLTYPE(ct, m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 9, __VA_ARGS__) #define MOCK_METHOD10_WITH_CALLTYPE(ct, m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 10, __VA_ARGS__) #define MOCK_CONST_METHOD0_WITH_CALLTYPE(ct, m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 0, __VA_ARGS__) #define MOCK_CONST_METHOD1_WITH_CALLTYPE(ct, m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 1, __VA_ARGS__) #define MOCK_CONST_METHOD2_WITH_CALLTYPE(ct, m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 2, __VA_ARGS__) #define MOCK_CONST_METHOD3_WITH_CALLTYPE(ct, m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 3, __VA_ARGS__) #define MOCK_CONST_METHOD4_WITH_CALLTYPE(ct, m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 4, __VA_ARGS__) #define MOCK_CONST_METHOD5_WITH_CALLTYPE(ct, m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 5, __VA_ARGS__) #define MOCK_CONST_METHOD6_WITH_CALLTYPE(ct, m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 6, __VA_ARGS__) #define MOCK_CONST_METHOD7_WITH_CALLTYPE(ct, m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 7, __VA_ARGS__) #define MOCK_CONST_METHOD8_WITH_CALLTYPE(ct, m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 8, __VA_ARGS__) #define MOCK_CONST_METHOD9_WITH_CALLTYPE(ct, m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 9, __VA_ARGS__) #define MOCK_CONST_METHOD10_WITH_CALLTYPE(ct, m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 10, __VA_ARGS__) #define MOCK_METHOD0_T_WITH_CALLTYPE(ct, m, ...) \ MOCK_METHOD0_WITH_CALLTYPE(ct, m, __VA_ARGS__) #define MOCK_METHOD1_T_WITH_CALLTYPE(ct, m, ...) \ MOCK_METHOD1_WITH_CALLTYPE(ct, m, __VA_ARGS__) #define MOCK_METHOD2_T_WITH_CALLTYPE(ct, m, ...) \ MOCK_METHOD2_WITH_CALLTYPE(ct, m, __VA_ARGS__) #define MOCK_METHOD3_T_WITH_CALLTYPE(ct, m, ...) \ MOCK_METHOD3_WITH_CALLTYPE(ct, m, __VA_ARGS__) #define MOCK_METHOD4_T_WITH_CALLTYPE(ct, m, ...) \ MOCK_METHOD4_WITH_CALLTYPE(ct, m, __VA_ARGS__) #define MOCK_METHOD5_T_WITH_CALLTYPE(ct, m, ...) \ MOCK_METHOD5_WITH_CALLTYPE(ct, m, __VA_ARGS__) #define MOCK_METHOD6_T_WITH_CALLTYPE(ct, m, ...) \ MOCK_METHOD6_WITH_CALLTYPE(ct, m, __VA_ARGS__) #define MOCK_METHOD7_T_WITH_CALLTYPE(ct, m, ...) \ MOCK_METHOD7_WITH_CALLTYPE(ct, m, __VA_ARGS__) #define MOCK_METHOD8_T_WITH_CALLTYPE(ct, m, ...) \ MOCK_METHOD8_WITH_CALLTYPE(ct, m, __VA_ARGS__) #define MOCK_METHOD9_T_WITH_CALLTYPE(ct, m, ...) \ MOCK_METHOD9_WITH_CALLTYPE(ct, m, __VA_ARGS__) #define MOCK_METHOD10_T_WITH_CALLTYPE(ct, m, ...) \ MOCK_METHOD10_WITH_CALLTYPE(ct, m, __VA_ARGS__) #define MOCK_CONST_METHOD0_T_WITH_CALLTYPE(ct, m, ...) \ MOCK_CONST_METHOD0_WITH_CALLTYPE(ct, m, __VA_ARGS__) #define MOCK_CONST_METHOD1_T_WITH_CALLTYPE(ct, m, ...) \ MOCK_CONST_METHOD1_WITH_CALLTYPE(ct, m, __VA_ARGS__) #define MOCK_CONST_METHOD2_T_WITH_CALLTYPE(ct, m, ...) \ MOCK_CONST_METHOD2_WITH_CALLTYPE(ct, m, __VA_ARGS__) #define MOCK_CONST_METHOD3_T_WITH_CALLTYPE(ct, m, ...) \ MOCK_CONST_METHOD3_WITH_CALLTYPE(ct, m, __VA_ARGS__) #define MOCK_CONST_METHOD4_T_WITH_CALLTYPE(ct, m, ...) \ MOCK_CONST_METHOD4_WITH_CALLTYPE(ct, m, __VA_ARGS__) #define MOCK_CONST_METHOD5_T_WITH_CALLTYPE(ct, m, ...) \ MOCK_CONST_METHOD5_WITH_CALLTYPE(ct, m, __VA_ARGS__) #define MOCK_CONST_METHOD6_T_WITH_CALLTYPE(ct, m, ...) \ MOCK_CONST_METHOD6_WITH_CALLTYPE(ct, m, __VA_ARGS__) #define MOCK_CONST_METHOD7_T_WITH_CALLTYPE(ct, m, ...) \ MOCK_CONST_METHOD7_WITH_CALLTYPE(ct, m, __VA_ARGS__) #define MOCK_CONST_METHOD8_T_WITH_CALLTYPE(ct, m, ...) \ MOCK_CONST_METHOD8_WITH_CALLTYPE(ct, m, __VA_ARGS__) #define MOCK_CONST_METHOD9_T_WITH_CALLTYPE(ct, m, ...) \ MOCK_CONST_METHOD9_WITH_CALLTYPE(ct, m, __VA_ARGS__) #define MOCK_CONST_METHOD10_T_WITH_CALLTYPE(ct, m, ...) \ MOCK_CONST_METHOD10_WITH_CALLTYPE(ct, m, __VA_ARGS__) #define GMOCK_INTERNAL_MOCK_METHODN(constness, ct, Method, args_num, ...) \ GMOCK_INTERNAL_ASSERT_VALID_SIGNATURE( \ args_num, ::testing::internal::identity_t<__VA_ARGS__>); \ GMOCK_INTERNAL_MOCK_METHOD_IMPL( \ args_num, Method, GMOCK_PP_NARG0(constness), 0, 0, , ct, , \ (::testing::internal::identity_t<__VA_ARGS__>)) #define GMOCK_MOCKER_(arity, constness, Method) \ GTEST_CONCAT_TOKEN_(gmock##constness##arity##_##Method##_, __LINE__) #endif
#include "gmock/gmock-function-mocker.h" GTEST_DISABLE_MSC_WARNINGS_PUSH_(4503) #ifdef GTEST_OS_WINDOWS #include <objbase.h> #endif #include <functional> #include <map> #include <string> #include <type_traits> #include "gmock/gmock.h" #include "gtest/gtest.h" namespace testing { namespace gmock_function_mocker_test { using testing::_; using testing::A; using testing::An; using testing::AnyNumber; using testing::Const; using testing::DoDefault; using testing::Eq; using testing::Lt; using testing::MockFunction; using testing::Ref; using testing::Return; using testing::ReturnRef; using testing::TypedEq; template <typename T> class TemplatedCopyable { public: TemplatedCopyable() = default; template <typename U> TemplatedCopyable(const U& other) {} }; class FooInterface { public: virtual ~FooInterface() = default; virtual void VoidReturning(int x) = 0; virtual int Nullary() = 0; virtual bool Unary(int x) = 0; virtual long Binary(short x, int y) = 0; virtual int Decimal(bool b, char c, short d, int e, long f, float g, double h, unsigned i, char* j, const std::string& k) = 0; virtual bool TakesNonConstReference(int& n) = 0; virtual std::string TakesConstReference(const int& n) = 0; virtual bool TakesConst(const int x) = 0; virtual int OverloadedOnArgumentNumber() = 0; virtual int OverloadedOnArgumentNumber(int n) = 0; virtual int OverloadedOnArgumentType(int n) = 0; virtual char OverloadedOnArgumentType(char c) = 0; virtual int OverloadedOnConstness() = 0; virtual char OverloadedOnConstness() const = 0; virtual int TypeWithHole(int (*func)()) = 0; virtual int TypeWithComma(const std::map<int, std::string>& a_map) = 0; virtual int TypeWithTemplatedCopyCtor(const TemplatedCopyable<int>&) = 0; virtual int (*ReturnsFunctionPointer1(int))(bool) = 0; using fn_ptr = int (*)(bool); virtual fn_ptr ReturnsFunctionPointer2(int) = 0; virtual int RefQualifiedConstRef() const& = 0; virtual int RefQualifiedConstRefRef() const&& = 0; virtual int RefQualifiedRef() & = 0; virtual int RefQualifiedRefRef() && = 0; virtual int RefQualifiedOverloaded() const& = 0; virtual int RefQualifiedOverloaded() const&& = 0; virtual int RefQualifiedOverloaded() & = 0; virtual int RefQualifiedOverloaded() && = 0; #ifdef GTEST_OS_WINDOWS STDMETHOD_(int, CTNullary)() = 0; STDMETHOD_(bool, CTUnary)(int x) = 0; STDMETHOD_(int, CTDecimal) (bool b, char c, short d, int e, long f, float g, double h, unsigned i, char* j, const std::string& k) = 0; STDMETHOD_(char, CTConst)(int x) const = 0; #endif }; GTEST_DISABLE_MSC_WARNINGS_PUSH_(4373) class MockFoo : public FooInterface { public: MockFoo() = default; MOCK_METHOD(void, VoidReturning, (int n)); MOCK_METHOD(int, Nullary, ()); MOCK_METHOD(bool, Unary, (int)); MOCK_METHOD(long, Binary, (short, int)); MOCK_METHOD(int, Decimal, (bool, char, short, int, long, float, double, unsigned, char*, const std::string& str), (override)); MOCK_METHOD(bool, TakesNonConstReference, (int&)); MOCK_METHOD(std::string, TakesConstReference, (const int&)); MOCK_METHOD(bool, TakesConst, (const int)); MOCK_METHOD((std::map<int, std::string>), ReturnTypeWithComma, (), ()); MOCK_METHOD((std::map<int, std::string>), ReturnTypeWithComma, (int), (const)); MOCK_METHOD(int, OverloadedOnArgumentNumber, ()); MOCK_METHOD(int, OverloadedOnArgumentNumber, (int)); MOCK_METHOD(int, OverloadedOnArgumentType, (int)); MOCK_METHOD(char, OverloadedOnArgumentType, (char)); MOCK_METHOD(int, OverloadedOnConstness, (), (override)); MOCK_METHOD(char, OverloadedOnConstness, (), (override, const)); MOCK_METHOD(int, TypeWithHole, (int (*)()), ()); MOCK_METHOD(int, TypeWithComma, ((const std::map<int, std::string>&))); MOCK_METHOD(int, TypeWithTemplatedCopyCtor, (const TemplatedCopyable<int>&)); MOCK_METHOD(int (*)(bool), ReturnsFunctionPointer1, (int), ()); MOCK_METHOD(fn_ptr, ReturnsFunctionPointer2, (int), ()); #ifdef GTEST_OS_WINDOWS MOCK_METHOD(int, CTNullary, (), (Calltype(STDMETHODCALLTYPE))); MOCK_METHOD(bool, CTUnary, (int), (Calltype(STDMETHODCALLTYPE))); MOCK_METHOD(int, CTDecimal, (bool b, char c, short d, int e, long f, float g, double h, unsigned i, char* j, const std::string& k), (Calltype(STDMETHODCALLTYPE))); MOCK_METHOD(char, CTConst, (int), (const, Calltype(STDMETHODCALLTYPE))); MOCK_METHOD((std::map<int, std::string>), CTReturnTypeWithComma, (), (Calltype(STDMETHODCALLTYPE))); #endif MOCK_METHOD(int, RefQualifiedConstRef, (), (const, ref(&), override)); MOCK_METHOD(int, RefQualifiedConstRefRef, (), (const, ref(&&), override)); MOCK_METHOD(int, RefQualifiedRef, (), (ref(&), override)); MOCK_METHOD(int, RefQualifiedRefRef, (), (ref(&&), override)); MOCK_METHOD(int, RefQualifiedOverloaded, (), (const, ref(&), override)); MOCK_METHOD(int, RefQualifiedOverloaded, (), (const, ref(&&), override)); MOCK_METHOD(int, RefQualifiedOverloaded, (), (ref(&), override)); MOCK_METHOD(int, RefQualifiedOverloaded, (), (ref(&&), override)); private: MockFoo(const MockFoo&) = delete; MockFoo& operator=(const MockFoo&) = delete; }; class LegacyMockFoo : public FooInterface { public: LegacyMockFoo() = default; MOCK_METHOD1(VoidReturning, void(int n)); MOCK_METHOD0(Nullary, int()); MOCK_METHOD1(Unary, bool(int)); MOCK_METHOD2(Binary, long(short, int)); MOCK_METHOD10(Decimal, int(bool, char, short, int, long, float, double, unsigned, char*, const std::string& str)); MOCK_METHOD1(TakesNonConstReference, bool(int&)); MOCK_METHOD1(TakesConstReference, std::string(const int&)); MOCK_METHOD1(TakesConst, bool(const int)); MOCK_METHOD0(ReturnTypeWithComma, std::map<int, std::string>()); MOCK_CONST_METHOD1(ReturnTypeWithComma, std::map<int, std::string>(int)); MOCK_METHOD0(OverloadedOnArgumentNumber, int()); MOCK_METHOD1(OverloadedOnArgumentNumber, int(int)); MOCK_METHOD1(OverloadedOnArgumentType, int(int)); MOCK_METHOD1(OverloadedOnArgumentType, char(char)); MOCK_METHOD0(OverloadedOnConstness, int()); MOCK_CONST_METHOD0(OverloadedOnConstness, char()); MOCK_METHOD1(TypeWithHole, int(int (*)())); MOCK_METHOD1(TypeWithComma, int(const std::map<int, std::string>&)); MOCK_METHOD1(TypeWithTemplatedCopyCtor, int(const TemplatedCopyable<int>&)); MOCK_METHOD1(ReturnsFunctionPointer1, int (*(int))(bool)); MOCK_METHOD1(ReturnsFunctionPointer2, fn_ptr(int)); #ifdef GTEST_OS_WINDOWS MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, CTNullary, int()); MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, CTUnary, bool(int)); MOCK_METHOD10_WITH_CALLTYPE(STDMETHODCALLTYPE, CTDecimal, int(bool b, char c, short d, int e, long f, float g, double h, unsigned i, char* j, const std::string& k)); MOCK_CONST_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, CTConst, char(int)); MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, CTReturnTypeWithComma, std::map<int, std::string>()); #endif int RefQualifiedConstRef() const& override { return 0; } int RefQualifiedConstRefRef() const&& override { return 0; } int RefQualifiedRef() & override { return 0; } int RefQualifiedRefRef() && override { return 0; } int RefQualifiedOverloaded() const& override { return 0; } int RefQualifiedOverloaded() const&& override { return 0; } int RefQualifiedOverloaded() & override { return 0; } int RefQualifiedOverloaded() && override { return 0; } private: LegacyMockFoo(const LegacyMockFoo&) = delete; LegacyMockFoo& operator=(const LegacyMockFoo&) = delete; }; GTEST_DISABLE_MSC_WARNINGS_POP_() template <class T> class FunctionMockerTest : public testing::Test { protected: FunctionMockerTest() : foo_(&mock_foo_) {} FooInterface* const foo_; T mock_foo_; }; using FunctionMockerTestTypes = ::testing::Types<MockFoo, LegacyMockFoo>; TYPED_TEST_SUITE(FunctionMockerTest, FunctionMockerTestTypes); TYPED_TEST(FunctionMockerTest, MocksVoidFunction) { EXPECT_CALL(this->mock_foo_, VoidReturning(Lt(100))); this->foo_->VoidReturning(0); } TYPED_TEST(FunctionMockerTest, MocksNullaryFunction) { EXPECT_CALL(this->mock_foo_, Nullary()) .WillOnce(DoDefault()) .WillOnce(Return(1)); EXPECT_EQ(0, this->foo_->Nullary()); EXPECT_EQ(1, this->foo_->Nullary()); } TYPED_TEST(FunctionMockerTest, MocksUnaryFunction) { EXPECT_CALL(this->mock_foo_, Unary(Eq(2))).Times(2).WillOnce(Return(true)); EXPECT_TRUE(this->foo_->Unary(2)); EXPECT_FALSE(this->foo_->Unary(2)); } TYPED_TEST(FunctionMockerTest, MocksBinaryFunction) { EXPECT_CALL(this->mock_foo_, Binary(2, _)).WillOnce(Return(3)); EXPECT_EQ(3, this->foo_->Binary(2, 1)); } TYPED_TEST(FunctionMockerTest, MocksDecimalFunction) { EXPECT_CALL(this->mock_foo_, Decimal(true, 'a', 0, 0, 1L, A<float>(), Lt(100), 5U, NULL, "hi")) .WillOnce(Return(5)); EXPECT_EQ(5, this->foo_->Decimal(true, 'a', 0, 0, 1, 0, 0, 5, nullptr, "hi")); } TYPED_TEST(FunctionMockerTest, MocksFunctionWithNonConstReferenceArgument) { int a = 0; EXPECT_CALL(this->mock_foo_, TakesNonConstReference(Ref(a))) .WillOnce(Return(true)); EXPECT_TRUE(this->foo_->TakesNonConstReference(a)); } TYPED_TEST(FunctionMockerTest, MocksFunctionWithConstReferenceArgument) { int a = 0; EXPECT_CALL(this->mock_foo_, TakesConstReference(Ref(a))) .WillOnce(Return("Hello")); EXPECT_EQ("Hello", this->foo_->TakesConstReference(a)); } TYPED_TEST(FunctionMockerTest, MocksFunctionWithConstArgument) { EXPECT_CALL(this->mock_foo_, TakesConst(Lt(10))).WillOnce(DoDefault()); EXPECT_FALSE(this->foo_->TakesConst(5)); } TYPED_TEST(FunctionMockerTest, MocksFunctionsOverloadedOnArgumentNumber) { EXPECT_CALL(this->mock_foo_, OverloadedOnArgumentNumber()) .WillOnce(Return(1)); EXPECT_CALL(this->mock_foo_, OverloadedOnArgumentNumber(_)) .WillOnce(Return(2)); EXPECT_EQ(2, this->foo_->OverloadedOnArgumentNumber(1)); EXPECT_EQ(1, this->foo_->OverloadedOnArgumentNumber()); } TYPED_TEST(FunctionMockerTest, MocksFunctionsOverloadedOnArgumentType) { EXPECT_CALL(this->mock_foo_, OverloadedOnArgumentType(An<int>())) .WillOnce(Return(1)); EXPECT_CALL(this->mock_foo_, OverloadedOnArgumentType(TypedEq<char>('a'))) .WillOnce(Return('b')); EXPECT_EQ(1, this->foo_->OverloadedOnArgumentType(0)); EXPECT_EQ('b', this->foo_->OverloadedOnArgumentType('a')); } TYPED_TEST(FunctionMockerTest, MocksFunctionsOverloadedOnConstnessOfThis) { EXPECT_CALL(this->mock_foo_, OverloadedOnConstness()); EXPECT_CALL(Const(this->mock_foo_), OverloadedOnConstness()) .WillOnce(Return('a')); EXPECT_EQ(0, this->foo_->OverloadedOnConstness()); EXPECT_EQ('a', Const(*this->foo_).OverloadedOnConstness()); } TYPED_TEST(FunctionMockerTest, MocksReturnTypeWithComma) { const std::map<int, std::string> a_map; EXPECT_CALL(this->mock_foo_, ReturnTypeWithComma()).WillOnce(Return(a_map)); EXPECT_CALL(this->mock_foo_, ReturnTypeWithComma(42)).WillOnce(Return(a_map)); EXPECT_EQ(a_map, this->mock_foo_.ReturnTypeWithComma()); EXPECT_EQ(a_map, this->mock_foo_.ReturnTypeWithComma(42)); } TYPED_TEST(FunctionMockerTest, MocksTypeWithTemplatedCopyCtor) { EXPECT_CALL(this->mock_foo_, TypeWithTemplatedCopyCtor(_)) .WillOnce(Return(true)); EXPECT_TRUE(this->foo_->TypeWithTemplatedCopyCtor(TemplatedCopyable<int>())); } #ifdef GTEST_OS_WINDOWS TYPED_TEST(FunctionMockerTest, MocksNullaryFunctionWithCallType) { EXPECT_CALL(this->mock_foo_, CTNullary()) .WillOnce(Return(-1)) .WillOnce(Return(0)); EXPECT_EQ(-1, this->foo_->CTNullary()); EXPECT_EQ(0, this->foo_->CTNullary()); } TYPED_TEST(FunctionMockerTest, MocksUnaryFunctionWithCallType) { EXPECT_CALL(this->mock_foo_, CTUnary(Eq(2))) .Times(2) .WillOnce(Return(true)) .WillOnce(Return(false)); EXPECT_TRUE(this->foo_->CTUnary(2)); EXPECT_FALSE(this->foo_->CTUnary(2)); } TYPED_TEST(FunctionMockerTest, MocksDecimalFunctionWithCallType) { EXPECT_CALL(this->mock_foo_, CTDecimal(true, 'a', 0, 0, 1L, A<float>(), Lt(100), 5U, NULL, "hi")) .WillOnce(Return(10)); EXPECT_EQ(10, this->foo_->CTDecimal(true, 'a', 0, 0, 1, 0, 0, 5, NULL, "hi")); } TYPED_TEST(FunctionMockerTest, MocksFunctionsConstFunctionWithCallType) { EXPECT_CALL(Const(this->mock_foo_), CTConst(_)).WillOnce(Return('a')); EXPECT_EQ('a', Const(*this->foo_).CTConst(0)); } TYPED_TEST(FunctionMockerTest, MocksReturnTypeWithCommaAndCallType) { const std::map<int, std::string> a_map; EXPECT_CALL(this->mock_foo_, CTReturnTypeWithComma()).WillOnce(Return(a_map)); EXPECT_EQ(a_map, this->mock_foo_.CTReturnTypeWithComma()); } #endif TEST(FunctionMockerTest, RefQualified) { MockFoo mock_foo; EXPECT_CALL(mock_foo, RefQualifiedConstRef).WillOnce(Return(1)); EXPECT_CALL(std::move(mock_foo), RefQualifiedConstRefRef) .WillOnce(Return(2)); EXPECT_CALL(mock_foo, RefQualifiedRef).WillOnce(Return(3)); EXPECT_CALL(std::move(mock_foo), RefQualifiedRefRef) .WillOnce(Return(4)); EXPECT_CALL(static_cast<const MockFoo&>(mock_foo), RefQualifiedOverloaded()) .WillOnce(Return(5)); EXPECT_CALL(static_cast<const MockFoo&&>(mock_foo), RefQualifiedOverloaded()) .WillOnce(Return(6)); EXPECT_CALL(static_cast<MockFoo&>(mock_foo), RefQualifiedOverloaded()) .WillOnce(Return(7)); EXPECT_CALL(static_cast<MockFoo&&>(mock_foo), RefQualifiedOverloaded()) .WillOnce(Return(8)); EXPECT_EQ(mock_foo.RefQualifiedConstRef(), 1); EXPECT_EQ(std::move(mock_foo).RefQualifiedConstRefRef(), 2); EXPECT_EQ(mock_foo.RefQualifiedRef(), 3); EXPECT_EQ(std::move(mock_foo).RefQualifiedRefRef(), 4); EXPECT_EQ(std::cref(mock_foo).get().RefQualifiedOverloaded(), 5); EXPECT_EQ(std::move(std::cref(mock_foo).get()) .RefQualifiedOverloaded(), 6); EXPECT_EQ(mock_foo.RefQualifiedOverloaded(), 7); EXPECT_EQ(std::move(mock_foo).RefQualifiedOverloaded(), 8); } class MockB { public: MockB() = default; MOCK_METHOD(void, DoB, ()); private: MockB(const MockB&) = delete; MockB& operator=(const MockB&) = delete; }; class LegacyMockB { public: LegacyMockB() = default; MOCK_METHOD0(DoB, void()); private: LegacyMockB(const LegacyMockB&) = delete; LegacyMockB& operator=(const LegacyMockB&) = delete; }; template <typename T> class ExpectCallTest : public ::testing::Test {}; using ExpectCallTestTypes = ::testing::Types<MockB, LegacyMockB>; TYPED_TEST_SUITE(ExpectCallTest, ExpectCallTestTypes); TYPED_TEST(ExpectCallTest, UnmentionedFunctionCanBeCalledAnyNumberOfTimes) { { TypeParam b; } { TypeParam b; b.DoB(); } { TypeParam b; b.DoB(); b.DoB(); } } template <typename T> class StackInterface { public: virtual ~StackInterface() = default; virtual void Push(const T& value) = 0; virtual void Pop() = 0; virtual int GetSize() const = 0; virtual const T& GetTop() const = 0; }; template <typename T> class MockStack : public StackInterface<T> { public: MockStack() = default; MOCK_METHOD(void, Push, (const T& elem), ()); MOCK_METHOD(void, Pop, (), (final)); MOCK_METHOD(int, GetSize, (), (const, override)); MOCK_METHOD(const T&, GetTop, (), (const)); MOCK_METHOD((std::map<int, int>), ReturnTypeWithComma, (), ()); MOCK_METHOD((std::map<int, int>), ReturnTypeWithComma, (int), (const)); private: MockStack(const MockStack&) = delete; MockStack& operator=(const MockStack&) = delete; }; template <typename T> class LegacyMockStack : public StackInterface<T> { public: LegacyMockStack() = default; MOCK_METHOD1_T(Push, void(const T& elem)); MOCK_METHOD0_T(Pop, void()); MOCK_CONST_METHOD0_T(GetSize, int()); MOCK_CONST_METHOD0_T(GetTop, const T&()); MOCK_METHOD0_T(ReturnTypeWithComma, std::map<int, int>()); MOCK_CONST_METHOD1_T(ReturnTypeWithComma, std::map<int, int>(int)); private: LegacyMockStack(const LegacyMockStack&) = delete; LegacyMockStack& operator=(const LegacyMockStack&) = delete; }; template <typename T> class TemplateMockTest : public ::testing::Test {}; using TemplateMockTestTypes = ::testing::Types<MockStack<int>, LegacyMockStack<int>>; TYPED_TEST_SUITE(TemplateMockTest, TemplateMockTestTypes); TYPED_TEST(TemplateMockTest, Works) { TypeParam mock; EXPECT_CALL(mock, GetSize()) .WillOnce(Return(0)) .WillOnce(Return(1)) .WillOnce(Return(0)); EXPECT_CALL(mock, Push(_)); int n = 5; EXPECT_CALL(mock, GetTop()).WillOnce(ReturnRef(n)); EXPECT_CALL(mock, Pop()).Times(AnyNumber()); EXPECT_EQ(0, mock.GetSize()); mock.Push(5); EXPECT_EQ(1, mock.GetSize()); EXPECT_EQ(5, mock.GetTop()); mock.Pop(); EXPECT_EQ(0, mock.GetSize()); } TYPED_TEST(TemplateMockTest, MethodWithCommaInReturnTypeWorks) { TypeParam mock; const std::map<int, int> a_map; EXPECT_CALL(mock, ReturnTypeWithComma()).WillOnce(Return(a_map)); EXPECT_CALL(mock, ReturnTypeWithComma(1)).WillOnce(Return(a_map)); EXPECT_EQ(a_map, mock.ReturnTypeWithComma()); EXPECT_EQ(a_map, mock.ReturnTypeWithComma(1)); } #ifdef GTEST_OS_WINDOWS template <typename T> class StackInterfaceWithCallType { public: virtual ~StackInterfaceWithCallType() {} STDMETHOD_(void, Push)(const T& value) = 0; STDMETHOD_(void, Pop)() = 0; STDMETHOD_(int, GetSize)() const = 0; STDMETHOD_(const T&, GetTop)() const = 0; }; template <typename T> class MockStackWithCallType : public StackInterfaceWithCallType<T> { public: MockStackWithCallType() {} MOCK_METHOD(void, Push, (const T& elem), (Calltype(STDMETHODCALLTYPE), override)); MOCK_METHOD(void, Pop, (), (Calltype(STDMETHODCALLTYPE), override)); MOCK_METHOD(int, GetSize, (), (Calltype(STDMETHODCALLTYPE), override, const)); MOCK_METHOD(const T&, GetTop, (), (Calltype(STDMETHODCALLTYPE), override, const)); private: MockStackWithCallType(const MockStackWithCallType&) = delete; MockStackWithCallType& operator=(const MockStackWithCallType&) = delete; }; template <typename T> class LegacyMockStackWithCallType : public StackInterfaceWithCallType<T> { public: LegacyMockStackWithCallType() {} MOCK_METHOD1_T_WITH_CALLTYPE(STDMETHODCALLTYPE, Push, void(const T& elem)); MOCK_METHOD0_T_WITH_CALLTYPE(STDMETHODCALLTYPE, Pop, void()); MOCK_CONST_METHOD0_T_WITH_CALLTYPE(STDMETHODCALLTYPE, GetSize, int()); MOCK_CONST_METHOD0_T_WITH_CALLTYPE(STDMETHODCALLTYPE, GetTop, const T&()); private: LegacyMockStackWithCallType(const LegacyMockStackWithCallType&) = delete; LegacyMockStackWithCallType& operator=(const LegacyMockStackWithCallType&) = delete; }; template <typename T> class TemplateMockTestWithCallType : public ::testing::Test {}; using TemplateMockTestWithCallTypeTypes = ::testing::Types<MockStackWithCallType<int>, LegacyMockStackWithCallType<int>>; TYPED_TEST_SUITE(TemplateMockTestWithCallType, TemplateMockTestWithCallTypeTypes); TYPED_TEST(TemplateMockTestWithCallType, Works) { TypeParam mock; EXPECT_CALL(mock, GetSize()) .WillOnce(Return(0)) .WillOnce(Return(1)) .WillOnce(Return(0)); EXPECT_CALL(mock, Push(_)); int n = 5; EXPECT_CALL(mock, GetTop()).WillOnce(ReturnRef(n)); EXPECT_CALL(mock, Pop()).Times(AnyNumber()); EXPECT_EQ(0, mock.GetSize()); mock.Push(5); EXPECT_EQ(1, mock.GetSize()); EXPECT_EQ(5, mock.GetTop()); mock.Pop(); EXPECT_EQ(0, mock.GetSize()); } #endif #define MY_MOCK_METHODS1_ \ MOCK_METHOD(void, Overloaded, ()); \ MOCK_METHOD(int, Overloaded, (int), (const)); \ MOCK_METHOD(bool, Overloaded, (bool f, int n)) #define LEGACY_MY_MOCK_METHODS1_ \ MOCK_METHOD0(Overloaded, void()); \ MOCK_CONST_METHOD1(Overloaded, int(int n)); \ MOCK_METHOD2(Overloaded, bool(bool f, int n)) class MockOverloadedOnArgNumber { public: MockOverloadedOnArgNumber() = default; MY_MOCK_METHODS1_; private: MockOverloadedOnArgNumber(const MockOverloadedOnArgNumber&) = delete; MockOverloadedOnArgNumber& operator=(const MockOverloadedOnArgNumber&) = delete; }; class LegacyMockOverloadedOnArgNumber { public: LegacyMockOverloadedOnArgNumber() = default; LEGACY_MY_MOCK_METHODS1_; private: LegacyMockOverloadedOnArgNumber(const LegacyMockOverloadedOnArgNumber&) = delete; LegacyMockOverloadedOnArgNumber& operator=( const LegacyMockOverloadedOnArgNumber&) = delete; }; template <typename T> class OverloadedMockMethodTest : public ::testing::Test {}; using OverloadedMockMethodTestTypes = ::testing::Types<MockOverloadedOnArgNumber, LegacyMockOverloadedOnArgNumber>; TYPED_TEST_SUITE(OverloadedMockMethodTest, OverloadedMockMethodTestTypes); TYPED_TEST(OverloadedMockMethodTest, CanOverloadOnArgNumberInMacroBody) { TypeParam mock; EXPECT_CALL(mock, Overloaded()); EXPECT_CALL(mock, Overloaded(1)).WillOnce(Return(2)); EXPECT_CALL(mock, Overloaded(true, 1)).WillOnce(Return(true)); mock.Overloaded(); EXPECT_EQ(2, mock.Overloaded(1)); EXPECT_TRUE(mock.Overloaded(true, 1)); } #define MY_MOCK_METHODS2_ \ MOCK_CONST_METHOD1(Overloaded, int(int n)); \ MOCK_METHOD1(Overloaded, int(int n)) class MockOverloadedOnConstness { public: MockOverloadedOnConstness() = default; MY_MOCK_METHODS2_; private: MockOverloadedOnConstness(const MockOverloadedOnConstness&) = delete; MockOverloadedOnConstness& operator=(const MockOverloadedOnConstness&) = delete; }; TEST(MockMethodOverloadedMockMethodTest, CanOverloadOnConstnessInMacroBody) { MockOverloadedOnConstness mock; const MockOverloadedOnConstness* const_mock = &mock; EXPECT_CALL(mock, Overloaded(1)).WillOnce(Return(2)); EXPECT_CALL(*const_mock, Overloaded(1)).WillOnce(Return(3)); EXPECT_EQ(2, mock.Overloaded(1)); EXPECT_EQ(3, const_mock->Overloaded(1)); } TEST(MockMethodMockFunctionTest, WorksForVoidNullary) { MockFunction<void()> foo; EXPECT_CALL(foo, Call()); foo.Call(); } TEST(MockMethodMockFunctionTest, WorksForNonVoidNullary) { MockFunction<int()> foo; EXPECT_CALL(foo, Call()).WillOnce(Return(1)).WillOnce(Return(2)); EXPECT_EQ(1, foo.Call()); EXPECT_EQ(2, foo.Call()); } TEST(MockMethodMockFunctionTest, WorksForVoidUnary) { MockFunction<void(int)> foo; EXPECT_CALL(foo, Call(1)); foo.Call(1); } TEST(MockMethodMockFunctionTest, WorksForNonVoidBinary) { MockFunction<int(bool, int)> foo; EXPECT_CALL(foo, Call(false, 42)).WillOnce(Return(1)).WillOnce(Return(2)); EXPECT_CALL(foo, Call(true, Ge(100))).WillOnce(Return(3)); EXPECT_EQ(1, foo.Call(false, 42)); EXPECT_EQ(2, foo.Call(false, 42)); EXPECT_EQ(3, foo.Call(true, 120)); } TEST(MockMethodMockFunctionTest, WorksFor10Arguments) { MockFunction<int(bool a0, char a1, int a2, int a3, int a4, int a5, int a6, char a7, int a8, bool a9)> foo; EXPECT_CALL(foo, Call(_, 'a', _, _, _, _, _, _, _, _)) .WillOnce(Return(1)) .WillOnce(Return(2)); EXPECT_EQ(1, foo.Call(false, 'a', 0, 0, 0, 0, 0, 'b', 0, true)); EXPECT_EQ(2, foo.Call(true, 'a', 0, 0, 0, 0, 0, 'b', 1, false)); } TEST(MockMethodMockFunctionTest, AsStdFunction) { MockFunction<int(int)> foo; auto call = [](const std::function<int(int)>& f, int i) { return f(i); }; EXPECT_CALL(foo, Call(1)).WillOnce(Return(-1)); EXPECT_CALL(foo, Call(2)).WillOnce(Return(-2)); EXPECT_EQ(-1, call(foo.AsStdFunction(), 1)); EXPECT_EQ(-2, call(foo.AsStdFunction(), 2)); } TEST(MockMethodMockFunctionTest, AsStdFunctionReturnsReference) { MockFunction<int&()> foo; int value = 1; EXPECT_CALL(foo, Call()).WillOnce(ReturnRef(value)); int& ref = foo.AsStdFunction()(); EXPECT_EQ(1, ref); value = 2; EXPECT_EQ(2, ref); } TEST(MockMethodMockFunctionTest, AsStdFunctionWithReferenceParameter) { MockFunction<int(int&)> foo; auto call = [](const std::function<int(int&)>& f, int& i) { return f(i); }; int i = 42; EXPECT_CALL(foo, Call(i)).WillOnce(Return(-1)); EXPECT_EQ(-1, call(foo.AsStdFunction(), i)); } namespace { template <typename Expected, typename F> static constexpr bool IsMockFunctionTemplateArgumentDeducedTo( const internal::MockFunction<F>&) { return std::is_same<F, Expected>::value; } } template <typename F> class MockMethodMockFunctionSignatureTest : public Test {}; using MockMethodMockFunctionSignatureTypes = Types<void(), int(), void(int), int(int), int(bool, int), int(bool, char, int, int, int, int, int, char, int, bool)>; TYPED_TEST_SUITE(MockMethodMockFunctionSignatureTest, MockMethodMockFunctionSignatureTypes); TYPED_TEST(MockMethodMockFunctionSignatureTest, IsMockFunctionTemplateArgumentDeducedForRawSignature) { using Argument = TypeParam; MockFunction<Argument> foo; EXPECT_TRUE(IsMockFunctionTemplateArgumentDeducedTo<TypeParam>(foo)); } TYPED_TEST(MockMethodMockFunctionSignatureTest, IsMockFunctionTemplateArgumentDeducedForStdFunction) { using Argument = std::function<TypeParam>; MockFunction<Argument> foo; EXPECT_TRUE(IsMockFunctionTemplateArgumentDeducedTo<TypeParam>(foo)); } TYPED_TEST( MockMethodMockFunctionSignatureTest, IsMockFunctionCallMethodSignatureTheSameForRawSignatureAndStdFunction) { using ForRawSignature = decltype(&MockFunction<TypeParam>::Call); using ForStdFunction = decltype(&MockFunction<std::function<TypeParam>>::Call); EXPECT_TRUE((std::is_same<ForRawSignature, ForStdFunction>::value)); } template <typename F> struct AlternateCallable {}; TYPED_TEST(MockMethodMockFunctionSignatureTest, IsMockFunctionTemplateArgumentDeducedForAlternateCallable) { using Argument = AlternateCallable<TypeParam>; MockFunction<Argument> foo; EXPECT_TRUE(IsMockFunctionTemplateArgumentDeducedTo<TypeParam>(foo)); } TYPED_TEST(MockMethodMockFunctionSignatureTest, IsMockFunctionCallMethodSignatureTheSameForAlternateCallable) { using ForRawSignature = decltype(&MockFunction<TypeParam>::Call); using ForStdFunction = decltype(&MockFunction<std::function<TypeParam>>::Call); EXPECT_TRUE((std::is_same<ForRawSignature, ForStdFunction>::value)); } struct MockMethodSizes0 { MOCK_METHOD(void, func, ()); }; struct MockMethodSizes1 { MOCK_METHOD(void, func, (int)); }; struct MockMethodSizes2 { MOCK_METHOD(void, func, (int, int)); }; struct MockMethodSizes3 { MOCK_METHOD(void, func, (int, int, int)); }; struct MockMethodSizes4 { MOCK_METHOD(void, func, (int, int, int, int)); }; struct LegacyMockMethodSizes0 { MOCK_METHOD0(func, void()); }; struct LegacyMockMethodSizes1 { MOCK_METHOD1(func, void(int)); }; struct LegacyMockMethodSizes2 { MOCK_METHOD2(func, void(int, int)); }; struct LegacyMockMethodSizes3 { MOCK_METHOD3(func, void(int, int, int)); }; struct LegacyMockMethodSizes4 { MOCK_METHOD4(func, void(int, int, int, int)); }; TEST(MockMethodMockFunctionTest, MockMethodSizeOverhead) { EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes1)); EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes2)); EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes3)); EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes4)); EXPECT_EQ(sizeof(LegacyMockMethodSizes0), sizeof(Leg
2,337
#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_NICE_STRICT_H_ #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_NICE_STRICT_H_ #include <cstdint> #include <type_traits> #include "gmock/gmock-spec-builders.h" #include "gmock/internal/gmock-port.h" namespace testing { template <class MockClass> class NiceMock; template <class MockClass> class NaggyMock; template <class MockClass> class StrictMock; namespace internal { template <typename T> std::true_type StrictnessModifierProbe(const NiceMock<T>&); template <typename T> std::true_type StrictnessModifierProbe(const NaggyMock<T>&); template <typename T> std::true_type StrictnessModifierProbe(const StrictMock<T>&); std::false_type StrictnessModifierProbe(...); template <typename T> constexpr bool HasStrictnessModifier() { return decltype(StrictnessModifierProbe(std::declval<const T&>()))::value; } #if defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_MINGW) && \ (defined(_MSC_VER) || defined(__clang__)) #define GTEST_INTERNAL_EMPTY_BASE_CLASS __declspec(empty_bases) #else #define GTEST_INTERNAL_EMPTY_BASE_CLASS #endif template <typename Base> class NiceMockImpl { public: NiceMockImpl() { ::testing::Mock::AllowUninterestingCalls(reinterpret_cast<uintptr_t>(this)); } ~NiceMockImpl() { ::testing::Mock::UnregisterCallReaction(reinterpret_cast<uintptr_t>(this)); } }; template <typename Base> class NaggyMockImpl { public: NaggyMockImpl() { ::testing::Mock::WarnUninterestingCalls(reinterpret_cast<uintptr_t>(this)); } ~NaggyMockImpl() { ::testing::Mock::UnregisterCallReaction(reinterpret_cast<uintptr_t>(this)); } }; template <typename Base> class StrictMockImpl { public: StrictMockImpl() { ::testing::Mock::FailUninterestingCalls(reinterpret_cast<uintptr_t>(this)); } ~StrictMockImpl() { ::testing::Mock::UnregisterCallReaction(reinterpret_cast<uintptr_t>(this)); } }; } template <class MockClass> class GTEST_INTERNAL_EMPTY_BASE_CLASS NiceMock : private internal::NiceMockImpl<MockClass>, public MockClass { public: static_assert(!internal::HasStrictnessModifier<MockClass>(), "Can't apply NiceMock to a class hierarchy that already has a " "strictness modifier. See " "https: "gmock_cook_book.html#NiceStrictNaggy"); NiceMock() : MockClass() { static_assert(sizeof(*this) == sizeof(MockClass), "The impl subclass shouldn't introduce any padding"); } template <typename A> explicit NiceMock(A&& arg) : MockClass(std::forward<A>(arg)) { static_assert(sizeof(*this) == sizeof(MockClass), "The impl subclass shouldn't introduce any padding"); } template <typename TArg1, typename TArg2, typename... An> NiceMock(TArg1&& arg1, TArg2&& arg2, An&&... args) : MockClass(std::forward<TArg1>(arg1), std::forward<TArg2>(arg2), std::forward<An>(args)...) { static_assert(sizeof(*this) == sizeof(MockClass), "The impl subclass shouldn't introduce any padding"); } private: NiceMock(const NiceMock&) = delete; NiceMock& operator=(const NiceMock&) = delete; }; template <class MockClass> class GTEST_INTERNAL_EMPTY_BASE_CLASS NaggyMock : private internal::NaggyMockImpl<MockClass>, public MockClass { static_assert(!internal::HasStrictnessModifier<MockClass>(), "Can't apply NaggyMock to a class hierarchy that already has a " "strictness modifier. See " "https: "gmock_cook_book.html#NiceStrictNaggy"); public: NaggyMock() : MockClass() { static_assert(sizeof(*this) == sizeof(MockClass), "The impl subclass shouldn't introduce any padding"); } template <typename A> explicit NaggyMock(A&& arg) : MockClass(std::forward<A>(arg)) { static_assert(sizeof(*this) == sizeof(MockClass), "The impl subclass shouldn't introduce any padding"); } template <typename TArg1, typename TArg2, typename... An> NaggyMock(TArg1&& arg1, TArg2&& arg2, An&&... args) : MockClass(std::forward<TArg1>(arg1), std::forward<TArg2>(arg2), std::forward<An>(args)...) { static_assert(sizeof(*this) == sizeof(MockClass), "The impl subclass shouldn't introduce any padding"); } private: NaggyMock(const NaggyMock&) = delete; NaggyMock& operator=(const NaggyMock&) = delete; }; template <class MockClass> class GTEST_INTERNAL_EMPTY_BASE_CLASS StrictMock : private internal::StrictMockImpl<MockClass>, public MockClass { public: static_assert( !internal::HasStrictnessModifier<MockClass>(), "Can't apply StrictMock to a class hierarchy that already has a " "strictness modifier. See " "https: "gmock_cook_book.html#NiceStrictNaggy"); StrictMock() : MockClass() { static_assert(sizeof(*this) == sizeof(MockClass), "The impl subclass shouldn't introduce any padding"); } template <typename A> explicit StrictMock(A&& arg) : MockClass(std::forward<A>(arg)) { static_assert(sizeof(*this) == sizeof(MockClass), "The impl subclass shouldn't introduce any padding"); } template <typename TArg1, typename TArg2, typename... An> StrictMock(TArg1&& arg1, TArg2&& arg2, An&&... args) : MockClass(std::forward<TArg1>(arg1), std::forward<TArg2>(arg2), std::forward<An>(args)...) { static_assert(sizeof(*this) == sizeof(MockClass), "The impl subclass shouldn't introduce any padding"); } private: StrictMock(const StrictMock&) = delete; StrictMock& operator=(const StrictMock&) = delete; }; #undef GTEST_INTERNAL_EMPTY_BASE_CLASS } #endif
#include "gmock/gmock-nice-strict.h" #include <string> #include <utility> #include "gmock/gmock.h" #include "gtest/gtest-spi.h" #include "gtest/gtest.h" class Mock { public: Mock() = default; MOCK_METHOD0(DoThis, void()); private: Mock(const Mock&) = delete; Mock& operator=(const Mock&) = delete; }; namespace testing { namespace gmock_nice_strict_test { using testing::HasSubstr; using testing::NaggyMock; using testing::NiceMock; using testing::StrictMock; #if GTEST_HAS_STREAM_REDIRECTION using testing::internal::CaptureStdout; using testing::internal::GetCapturedStdout; #endif class NotDefaultConstructible { public: explicit NotDefaultConstructible(int) {} }; class CallsMockMethodInDestructor { public: ~CallsMockMethodInDestructor() { OnDestroy(); } MOCK_METHOD(void, OnDestroy, ()); }; class Foo { public: virtual ~Foo() = default; virtual void DoThis() = 0; virtual int DoThat(bool flag) = 0; }; class MockFoo : public Foo { public: MockFoo() = default; void Delete() { delete this; } MOCK_METHOD0(DoThis, void()); MOCK_METHOD1(DoThat, int(bool flag)); MOCK_METHOD0(ReturnNonDefaultConstructible, NotDefaultConstructible()); private: MockFoo(const MockFoo&) = delete; MockFoo& operator=(const MockFoo&) = delete; }; class MockBar { public: explicit MockBar(const std::string& s) : str_(s) {} MockBar(char a1, char a2, std::string a3, std::string a4, int a5, int a6, const std::string& a7, const std::string& a8, bool a9, bool a10) { str_ = std::string() + a1 + a2 + a3 + a4 + static_cast<char>(a5) + static_cast<char>(a6) + a7 + a8 + (a9 ? 'T' : 'F') + (a10 ? 'T' : 'F'); } virtual ~MockBar() = default; const std::string& str() const { return str_; } MOCK_METHOD0(This, int()); MOCK_METHOD2(That, std::string(int, bool)); private: std::string str_; MockBar(const MockBar&) = delete; MockBar& operator=(const MockBar&) = delete; }; class MockBaz { public: class MoveOnly { public: MoveOnly() = default; MoveOnly(const MoveOnly&) = delete; MoveOnly& operator=(const MoveOnly&) = delete; MoveOnly(MoveOnly&&) = default; MoveOnly& operator=(MoveOnly&&) = default; }; MockBaz(MoveOnly) {} }; #if GTEST_HAS_STREAM_REDIRECTION TEST(RawMockTest, WarningForUninterestingCall) { const std::string saved_flag = GMOCK_FLAG_GET(verbose); GMOCK_FLAG_SET(verbose, "warning"); MockFoo raw_foo; CaptureStdout(); raw_foo.DoThis(); raw_foo.DoThat(true); EXPECT_THAT(GetCapturedStdout(), HasSubstr("Uninteresting mock function call")); GMOCK_FLAG_SET(verbose, saved_flag); } TEST(RawMockTest, WarningForUninterestingCallAfterDeath) { const std::string saved_flag = GMOCK_FLAG_GET(verbose); GMOCK_FLAG_SET(verbose, "warning"); MockFoo* const raw_foo = new MockFoo; ON_CALL(*raw_foo, DoThis()).WillByDefault(Invoke(raw_foo, &MockFoo::Delete)); CaptureStdout(); raw_foo->DoThis(); EXPECT_THAT(GetCapturedStdout(), HasSubstr("Uninteresting mock function call")); GMOCK_FLAG_SET(verbose, saved_flag); } TEST(RawMockTest, InfoForUninterestingCall) { MockFoo raw_foo; const std::string saved_flag = GMOCK_FLAG_GET(verbose); GMOCK_FLAG_SET(verbose, "info"); CaptureStdout(); raw_foo.DoThis(); EXPECT_THAT(GetCapturedStdout(), HasSubstr("Uninteresting mock function call")); GMOCK_FLAG_SET(verbose, saved_flag); } TEST(RawMockTest, IsNaggy_IsNice_IsStrict) { MockFoo raw_foo; EXPECT_TRUE(Mock::IsNaggy(&raw_foo)); EXPECT_FALSE(Mock::IsNice(&raw_foo)); EXPECT_FALSE(Mock::IsStrict(&raw_foo)); } TEST(NiceMockTest, NoWarningForUninterestingCall) { NiceMock<MockFoo> nice_foo; CaptureStdout(); nice_foo.DoThis(); nice_foo.DoThat(true); EXPECT_EQ("", GetCapturedStdout()); } TEST(NiceMockTest, NoWarningForUninterestingCallAfterDeath) { NiceMock<MockFoo>* const nice_foo = new NiceMock<MockFoo>; ON_CALL(*nice_foo, DoThis()) .WillByDefault(Invoke(nice_foo, &MockFoo::Delete)); CaptureStdout(); nice_foo->DoThis(); EXPECT_EQ("", GetCapturedStdout()); } TEST(NiceMockTest, InfoForUninterestingCall) { NiceMock<MockFoo> nice_foo; const std::string saved_flag = GMOCK_FLAG_GET(verbose); GMOCK_FLAG_SET(verbose, "info"); CaptureStdout(); nice_foo.DoThis(); EXPECT_THAT(GetCapturedStdout(), HasSubstr("Uninteresting mock function call")); GMOCK_FLAG_SET(verbose, saved_flag); } #endif TEST(NiceMockTest, AllowsExpectedCall) { NiceMock<MockFoo> nice_foo; EXPECT_CALL(nice_foo, DoThis()); nice_foo.DoThis(); } TEST(NiceMockTest, ThrowsExceptionForUnknownReturnTypes) { NiceMock<MockFoo> nice_foo; #if GTEST_HAS_EXCEPTIONS try { nice_foo.ReturnNonDefaultConstructible(); FAIL(); } catch (const std::runtime_error& ex) { EXPECT_THAT(ex.what(), HasSubstr("ReturnNonDefaultConstructible")); } #else EXPECT_DEATH_IF_SUPPORTED({ nice_foo.ReturnNonDefaultConstructible(); }, ""); #endif } TEST(NiceMockTest, UnexpectedCallFails) { NiceMock<MockFoo> nice_foo; EXPECT_CALL(nice_foo, DoThis()).Times(0); EXPECT_NONFATAL_FAILURE(nice_foo.DoThis(), "called more times than expected"); } TEST(NiceMockTest, NonDefaultConstructor) { NiceMock<MockBar> nice_bar("hi"); EXPECT_EQ("hi", nice_bar.str()); nice_bar.This(); nice_bar.That(5, true); } TEST(NiceMockTest, NonDefaultConstructor10) { NiceMock<MockBar> nice_bar('a', 'b', "c", "d", 'e', 'f', "g", "h", true, false); EXPECT_EQ("abcdefghTF", nice_bar.str()); nice_bar.This(); nice_bar.That(5, true); } TEST(NiceMockTest, AllowLeak) { NiceMock<MockFoo>* leaked = new NiceMock<MockFoo>; Mock::AllowLeak(leaked); EXPECT_CALL(*leaked, DoThis()); leaked->DoThis(); } TEST(NiceMockTest, MoveOnlyConstructor) { NiceMock<MockBaz> nice_baz(MockBaz::MoveOnly{}); } TEST(NiceMockTest, AcceptsClassNamedMock) { NiceMock< ::Mock> nice; EXPECT_CALL(nice, DoThis()); nice.DoThis(); } TEST(NiceMockTest, IsNiceInDestructor) { { NiceMock<CallsMockMethodInDestructor> nice_on_destroy; } } TEST(NiceMockTest, IsNaggy_IsNice_IsStrict) { NiceMock<MockFoo> nice_foo; EXPECT_FALSE(Mock::IsNaggy(&nice_foo)); EXPECT_TRUE(Mock::IsNice(&nice_foo)); EXPECT_FALSE(Mock::IsStrict(&nice_foo)); } #if GTEST_HAS_STREAM_REDIRECTION TEST(NaggyMockTest, WarningForUninterestingCall) { const std::string saved_flag = GMOCK_FLAG_GET(verbose); GMOCK_FLAG_SET(verbose, "warning"); NaggyMock<MockFoo> naggy_foo; CaptureStdout(); naggy_foo.DoThis(); naggy_foo.DoThat(true); EXPECT_THAT(GetCapturedStdout(), HasSubstr("Uninteresting mock function call")); GMOCK_FLAG_SET(verbose, saved_flag); } TEST(NaggyMockTest, WarningForUninterestingCallAfterDeath) { const std::string saved_flag = GMOCK_FLAG_GET(verbose); GMOCK_FLAG_SET(verbose, "warning"); NaggyMock<MockFoo>* const naggy_foo = new NaggyMock<MockFoo>; ON_CALL(*naggy_foo, DoThis()) .WillByDefault(Invoke(naggy_foo, &MockFoo::Delete)); CaptureStdout(); naggy_foo->DoThis(); EXPECT_THAT(GetCapturedStdout(), HasSubstr("Uninteresting mock function call")); GMOCK_FLAG_SET(verbose, saved_flag); } #endif TEST(NaggyMockTest, AllowsExpectedCall) { NaggyMock<MockFoo> naggy_foo; EXPECT_CALL(naggy_foo, DoThis()); naggy_foo.DoThis(); } TEST(NaggyMockTest, UnexpectedCallFails) { NaggyMock<MockFoo> naggy_foo; EXPECT_CALL(naggy_foo, DoThis()).Times(0); EXPECT_NONFATAL_FAILURE(naggy_foo.DoThis(), "called more times than expected"); } TEST(NaggyMockTest, NonDefaultConstructor) { NaggyMock<MockBar> naggy_bar("hi"); EXPECT_EQ("hi", naggy_bar.str()); naggy_bar.This(); naggy_bar.That(5, true); } TEST(NaggyMockTest, NonDefaultConstructor10) { NaggyMock<MockBar> naggy_bar('0', '1', "2", "3", '4', '5', "6", "7", true, false); EXPECT_EQ("01234567TF", naggy_bar.str()); naggy_bar.This(); naggy_bar.That(5, true); } TEST(NaggyMockTest, AllowLeak) { NaggyMock<MockFoo>* leaked = new NaggyMock<MockFoo>; Mock::AllowLeak(leaked); EXPECT_CALL(*leaked, DoThis()); leaked->DoThis(); } TEST(NaggyMockTest, MoveOnlyConstructor) { NaggyMock<MockBaz> naggy_baz(MockBaz::MoveOnly{}); } TEST(NaggyMockTest, AcceptsClassNamedMock) { NaggyMock< ::Mock> naggy; EXPECT_CALL(naggy, DoThis()); naggy.DoThis(); } TEST(NaggyMockTest, IsNaggyInDestructor) { const std::string saved_flag = GMOCK_FLAG_GET(verbose); GMOCK_FLAG_SET(verbose, "warning"); CaptureStdout(); { NaggyMock<CallsMockMethodInDestructor> naggy_on_destroy; } EXPECT_THAT(GetCapturedStdout(), HasSubstr("Uninteresting mock function call")); GMOCK_FLAG_SET(verbose, saved_flag); } TEST(NaggyMockTest, IsNaggy_IsNice_IsStrict) { NaggyMock<MockFoo> naggy_foo; EXPECT_TRUE(Mock::IsNaggy(&naggy_foo)); EXPECT_FALSE(Mock::IsNice(&naggy_foo)); EXPECT_FALSE(Mock::IsStrict(&naggy_foo)); } TEST(StrictMockTest, AllowsExpectedCall) { StrictMock<MockFoo> strict_foo; EXPECT_CALL(strict_foo, DoThis()); strict_foo.DoThis(); } TEST(StrictMockTest, UnexpectedCallFails) { StrictMock<MockFoo> strict_foo; EXPECT_CALL(strict_foo, DoThis()).Times(0); EXPECT_NONFATAL_FAILURE(strict_foo.DoThis(), "called more times than expected"); } TEST(StrictMockTest, UninterestingCallFails) { StrictMock<MockFoo> strict_foo; EXPECT_NONFATAL_FAILURE(strict_foo.DoThis(), "Uninteresting mock function call"); } TEST(StrictMockTest, UninterestingCallFailsAfterDeath) { StrictMock<MockFoo>* const strict_foo = new StrictMock<MockFoo>; ON_CALL(*strict_foo, DoThis()) .WillByDefault(Invoke(strict_foo, &MockFoo::Delete)); EXPECT_NONFATAL_FAILURE(strict_foo->DoThis(), "Uninteresting mock function call"); } TEST(StrictMockTest, NonDefaultConstructor) { StrictMock<MockBar> strict_bar("hi"); EXPECT_EQ("hi", strict_bar.str()); EXPECT_NONFATAL_FAILURE(strict_bar.That(5, true), "Uninteresting mock function call"); } TEST(StrictMockTest, NonDefaultConstructor10) { StrictMock<MockBar> strict_bar('a', 'b', "c", "d", 'e', 'f', "g", "h", true, false); EXPECT_EQ("abcdefghTF", strict_bar.str()); EXPECT_NONFATAL_FAILURE(strict_bar.That(5, true), "Uninteresting mock function call"); } TEST(StrictMockTest, AllowLeak) { StrictMock<MockFoo>* leaked = new StrictMock<MockFoo>; Mock::AllowLeak(leaked); EXPECT_CALL(*leaked, DoThis()); leaked->DoThis(); } TEST(StrictMockTest, MoveOnlyConstructor) { StrictMock<MockBaz> strict_baz(MockBaz::MoveOnly{}); } TEST(StrictMockTest, AcceptsClassNamedMock) { StrictMock< ::Mock> strict; EXPECT_CALL(strict, DoThis()); strict.DoThis(); } TEST(StrictMockTest, IsStrictInDestructor) { EXPECT_NONFATAL_FAILURE( { StrictMock<CallsMockMethodInDestructor> strict_on_destroy; }, "Uninteresting mock function call"); } TEST(StrictMockTest, IsNaggy_IsNice_IsStrict) { StrictMock<MockFoo> strict_foo; EXPECT_FALSE(Mock::IsNaggy(&strict_foo)); EXPECT_FALSE(Mock::IsNice(&strict_foo)); EXPECT_TRUE(Mock::IsStrict(&strict_foo)); } } }
2,338
#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_ #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_ #include <memory> #include <utility> #include "gmock/gmock-actions.h" #include "gmock/internal/gmock-port.h" #include "gmock/internal/custom/gmock-generated-actions.h" #define GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS(kind0, name0) kind0 name0 #define GMOCK_INTERNAL_DECL_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, name1) \ kind0 name0, kind1 name1 #define GMOCK_INTERNAL_DECL_HAS_3_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ kind2, name2) \ kind0 name0, kind1 name1, kind2 name2 #define GMOCK_INTERNAL_DECL_HAS_4_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ kind2, name2, kind3, name3) \ kind0 name0, kind1 name1, kind2 name2, kind3 name3 #define GMOCK_INTERNAL_DECL_HAS_5_TEMPLATE_PARAMS( \ kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4) \ kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4 #define GMOCK_INTERNAL_DECL_HAS_6_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ kind2, name2, kind3, name3, \ kind4, name4, kind5, name5) \ kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, kind5 name5 #define GMOCK_INTERNAL_DECL_HAS_7_TEMPLATE_PARAMS( \ kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \ kind5, name5, kind6, name6) \ kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, \ kind5 name5, kind6 name6 #define GMOCK_INTERNAL_DECL_HAS_8_TEMPLATE_PARAMS( \ kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \ kind5, name5, kind6, name6, kind7, name7) \ kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, \ kind5 name5, kind6 name6, kind7 name7 #define GMOCK_INTERNAL_DECL_HAS_9_TEMPLATE_PARAMS( \ kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \ kind5, name5, kind6, name6, kind7, name7, kind8, name8) \ kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, \ kind5 name5, kind6 name6, kind7 name7, kind8 name8 #define GMOCK_INTERNAL_DECL_HAS_10_TEMPLATE_PARAMS( \ kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \ kind5, name5, kind6, name6, kind7, name7, kind8, name8, kind9, name9) \ kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, \ kind5 name5, kind6 name6, kind7 name7, kind8 name8, kind9 name9 #define GMOCK_INTERNAL_LIST_HAS_1_TEMPLATE_PARAMS(kind0, name0) name0 #define GMOCK_INTERNAL_LIST_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, name1) \ name0, name1 #define GMOCK_INTERNAL_LIST_HAS_3_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ kind2, name2) \ name0, name1, name2 #define GMOCK_INTERNAL_LIST_HAS_4_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ kind2, name2, kind3, name3) \ name0, name1, name2, name3 #define GMOCK_INTERNAL_LIST_HAS_5_TEMPLATE_PARAMS( \ kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4) \ name0, name1, name2, name3, name4 #define GMOCK_INTERNAL_LIST_HAS_6_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ kind2, name2, kind3, name3, \ kind4, name4, kind5, name5) \ name0, name1, name2, name3, name4, name5 #define GMOCK_INTERNAL_LIST_HAS_7_TEMPLATE_PARAMS( \ kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \ kind5, name5, kind6, name6) \ name0, name1, name2, name3, name4, name5, name6 #define GMOCK_INTERNAL_LIST_HAS_8_TEMPLATE_PARAMS( \ kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \ kind5, name5, kind6, name6, kind7, name7) \ name0, name1, name2, name3, name4, name5, name6, name7 #define GMOCK_INTERNAL_LIST_HAS_9_TEMPLATE_PARAMS( \ kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \ kind5, name5, kind6, name6, kind7, name7, kind8, name8) \ name0, name1, name2, name3, name4, name5, name6, name7, name8 #define GMOCK_INTERNAL_LIST_HAS_10_TEMPLATE_PARAMS( \ kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \ kind5, name5, kind6, name6, kind7, name7, kind8, name8, kind9, name9) \ name0, name1, name2, name3, name4, name5, name6, name7, name8, name9 #define GMOCK_INTERNAL_DECL_TYPE_AND_0_VALUE_PARAMS() #define GMOCK_INTERNAL_DECL_TYPE_AND_1_VALUE_PARAMS(p0) , typename p0##_type #define GMOCK_INTERNAL_DECL_TYPE_AND_2_VALUE_PARAMS(p0, p1) \ , typename p0##_type, typename p1##_type #define GMOCK_INTERNAL_DECL_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) \ , typename p0##_type, typename p1##_type, typename p2##_type #define GMOCK_INTERNAL_DECL_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) \ , typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type #define GMOCK_INTERNAL_DECL_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \ , typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type #define GMOCK_INTERNAL_DECL_TYPE_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) \ , typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type #define GMOCK_INTERNAL_DECL_TYPE_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ p6) \ , typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type, \ typename p6##_type #define GMOCK_INTERNAL_DECL_TYPE_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ p6, p7) \ , typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type, \ typename p6##_type, typename p7##_type #define GMOCK_INTERNAL_DECL_TYPE_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ p6, p7, p8) \ , typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type, \ typename p6##_type, typename p7##_type, typename p8##_type #define GMOCK_INTERNAL_DECL_TYPE_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ p6, p7, p8, p9) \ , typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type, \ typename p6##_type, typename p7##_type, typename p8##_type, \ typename p9##_type #define GMOCK_INTERNAL_INIT_AND_0_VALUE_PARAMS() () #define GMOCK_INTERNAL_INIT_AND_1_VALUE_PARAMS(p0) \ (p0##_type gmock_p0) : p0(::std::move(gmock_p0)) #define GMOCK_INTERNAL_INIT_AND_2_VALUE_PARAMS(p0, p1) \ (p0##_type gmock_p0, p1##_type gmock_p1) \ : p0(::std::move(gmock_p0)), p1(::std::move(gmock_p1)) #define GMOCK_INTERNAL_INIT_AND_3_VALUE_PARAMS(p0, p1, p2) \ (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2) \ : p0(::std::move(gmock_p0)), \ p1(::std::move(gmock_p1)), \ p2(::std::move(gmock_p2)) #define GMOCK_INTERNAL_INIT_AND_4_VALUE_PARAMS(p0, p1, p2, p3) \ (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3##_type gmock_p3) \ : p0(::std::move(gmock_p0)), \ p1(::std::move(gmock_p1)), \ p2(::std::move(gmock_p2)), \ p3(::std::move(gmock_p3)) #define GMOCK_INTERNAL_INIT_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \ (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3##_type gmock_p3, p4##_type gmock_p4) \ : p0(::std::move(gmock_p0)), \ p1(::std::move(gmock_p1)), \ p2(::std::move(gmock_p2)), \ p3(::std::move(gmock_p3)), \ p4(::std::move(gmock_p4)) #define GMOCK_INTERNAL_INIT_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) \ (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5) \ : p0(::std::move(gmock_p0)), \ p1(::std::move(gmock_p1)), \ p2(::std::move(gmock_p2)), \ p3(::std::move(gmock_p3)), \ p4(::std::move(gmock_p4)), \ p5(::std::move(gmock_p5)) #define GMOCK_INTERNAL_INIT_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) \ (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ p6##_type gmock_p6) \ : p0(::std::move(gmock_p0)), \ p1(::std::move(gmock_p1)), \ p2(::std::move(gmock_p2)), \ p3(::std::move(gmock_p3)), \ p4(::std::move(gmock_p4)), \ p5(::std::move(gmock_p5)), \ p6(::std::move(gmock_p6)) #define GMOCK_INTERNAL_INIT_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7) \ (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ p6##_type gmock_p6, p7##_type gmock_p7) \ : p0(::std::move(gmock_p0)), \ p1(::std::move(gmock_p1)), \ p2(::std::move(gmock_p2)), \ p3(::std::move(gmock_p3)), \ p4(::std::move(gmock_p4)), \ p5(::std::move(gmock_p5)), \ p6(::std::move(gmock_p6)), \ p7(::std::move(gmock_p7)) #define GMOCK_INTERNAL_INIT_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, \ p8) \ (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8) \ : p0(::std::move(gmock_p0)), \ p1(::std::move(gmock_p1)), \ p2(::std::move(gmock_p2)), \ p3(::std::move(gmock_p3)), \ p4(::std::move(gmock_p4)), \ p5(::std::move(gmock_p5)), \ p6(::std::move(gmock_p6)), \ p7(::std::move(gmock_p7)), \ p8(::std::move(gmock_p8)) #define GMOCK_INTERNAL_INIT_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ p7, p8, p9) \ (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8, \ p9##_type gmock_p9) \ : p0(::std::move(gmock_p0)), \ p1(::std::move(gmock_p1)), \ p2(::std::move(gmock_p2)), \ p3(::std::move(gmock_p3)), \ p4(::std::move(gmock_p4)), \ p5(::std::move(gmock_p5)), \ p6(::std::move(gmock_p6)), \ p7(::std::move(gmock_p7)), \ p8(::std::move(gmock_p8)), \ p9(::std::move(gmock_p9)) #define GMOCK_INTERNAL_DEFN_COPY_AND_0_VALUE_PARAMS() \ {} #define GMOCK_INTERNAL_DEFN_COPY_AND_1_VALUE_PARAMS(...) = default; #define GMOCK_INTERNAL_DEFN_COPY_AND_2_VALUE_PARAMS(...) = default; #define GMOCK_INTERNAL_DEFN_COPY_AND_3_VALUE_PARAMS(...) = default; #define GMOCK_INTERNAL_DEFN_COPY_AND_4_VALUE_PARAMS(...) = default; #define GMOCK_INTERNAL_DEFN_COPY_AND_5_VALUE_PARAMS(...) = default; #define GMOCK_INTERNAL_DEFN_COPY_AND_6_VALUE_PARAMS(...) = default; #define GMOCK_INTERNAL_DEFN_COPY_AND_7_VALUE_PARAMS(...) = default; #define GMOCK_INTERNAL_DEFN_COPY_AND_8_VALUE_PARAMS(...) = default; #define GMOCK_INTERNAL_DEFN_COPY_AND_9_VALUE_PARAMS(...) = default; #define GMOCK_INTERNAL_DEFN_COPY_AND_10_VALUE_PARAMS(...) = default; #define GMOCK_INTERNAL_DEFN_AND_0_VALUE_PARAMS() #define GMOCK_INTERNAL_DEFN_AND_1_VALUE_PARAMS(p0) p0##_type p0; #define GMOCK_INTERNAL_DEFN_AND_2_VALUE_PARAMS(p0, p1) \ p0##_type p0; \ p1##_type p1; #define GMOCK_INTERNAL_DEFN_AND_3_VALUE_PARAMS(p0, p1, p2) \ p0##_type p0; \ p1##_type p1; \ p2##_type p2; #define GMOCK_INTERNAL_DEFN_AND_4_VALUE_PARAMS(p0, p1, p2, p3) \ p0##_type p0; \ p1##_type p1; \ p2##_type p2; \ p3##_type p3; #define GMOCK_INTERNAL_DEFN_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \ p0##_type p0; \ p1##_type p1; \ p2##_type p2; \ p3##_type p3; \ p4##_type p4; #define GMOCK_INTERNAL_DEFN_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) \ p0##_type p0; \ p1##_type p1; \ p2##_type p2; \ p3##_type p3; \ p4##_type p4; \ p5##_type p5; #define GMOCK_INTERNAL_DEFN_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) \ p0##_type p0; \ p1##_type p1; \ p2##_type p2; \ p3##_type p3; \ p4##_type p4; \ p5##_type p5; \ p6##_type p6; #define GMOCK_INTERNAL_DEFN_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7) \ p0##_type p0; \ p1##_type p1; \ p2##_type p2; \ p3##_type p3; \ p4##_type p4; \ p5##_type p5; \ p6##_type p6; \ p7##_type p7; #define GMOCK_INTERNAL_DEFN_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, \ p8) \ p0##_type p0; \ p1##_type p1; \ p2##_type p2; \ p3##_type p3; \ p4##_type p4; \ p5##_type p5; \ p6##_type p6; \ p7##_type p7; \ p8##_type p8; #define GMOCK_INTERNAL_DEFN_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ p7, p8, p9) \ p0##_type p0; \ p1##_type p1; \ p2##_type p2; \ p3##_type p3; \ p4##_type p4; \ p5##_type p5; \ p6##_type p6; \ p7##_type p7; \ p8##_type p8; \ p9##_type p9; #define GMOCK_INTERNAL_LIST_AND_0_VALUE_PARAMS() #define GMOCK_INTERNAL_LIST_AND_1_VALUE_PARAMS(p0) p0 #define GMOCK_INTERNAL_LIST_AND_2_VALUE_PARAMS(p0, p1) p0, p1 #define GMOCK_INTERNAL_LIST_AND_3_VALUE_PARAMS(p0, p1, p2) p0, p1, p2 #define GMOCK_INTERNAL_LIST_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0, p1, p2, p3 #define GMOCK_INTERNAL_LIST_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \ p0, p1, p2, p3, p4 #define GMOCK_INTERNAL_LIST_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) \ p0, p1, p2, p3, p4, p5 #define GMOCK_INTERNAL_LIST_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) \ p0, p1, p2, p3, p4, p5, p6 #define GMOCK_INTERNAL_LIST_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7) \ p0, p1, p2, p3, p4, p5, p6, p7 #define GMOCK_INTERNAL_LIST_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, \ p8) \ p0, p1, p2, p3, p4, p5, p6, p7, p8 #define GMOCK_INTERNAL_LIST_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ p7, p8, p9) \ p0, p1, p2, p3, p4, p5, p6, p7, p8, p9 #define GMOCK_INTERNAL_LIST_TYPE_AND_0_VALUE_PARAMS() #define GMOCK_INTERNAL_LIST_TYPE_AND_1_VALUE_PARAMS(p0) , p0##_type #define GMOCK_INTERNAL_LIST_TYPE_AND_2_VALUE_PARAMS(p0, p1) \ , p0##_type, p1##_type #define GMOCK_INTERNAL_LIST_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) \ , p0##_type, p1##_type, p2##_type #define GMOCK_INTERNAL_LIST_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) \ , p0##_type, p1##_type, p2##_type, p3##_type #define GMOCK_INTERNAL_LIST_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \ , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type #define GMOCK_INTERNAL_LIST_TYPE_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) \ , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type #define GMOCK_INTERNAL_LIST_TYPE_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ p6) \ , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type, p6##_type #define GMOCK_INTERNAL_LIST_TYPE_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ p6, p7) \ , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type, \ p6##_type, p7##_type #define GMOCK_INTERNAL_LIST_TYPE_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ p6, p7, p8) \ , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type, \ p6##_type, p7##_type, p8##_type #define GMOCK_INTERNAL_LIST_TYPE_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ p6, p7, p8, p9) \ , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type, \ p6##_type, p7##_type, p8##_type, p9##_type #define GMOCK_INTERNAL_DECL_AND_0_VALUE_PARAMS() #define GMOCK_INTERNAL_DECL_AND_1_VALUE_PARAMS(p0) p0##_type p0 #define GMOCK_INTERNAL_DECL_AND_2_VALUE_PARAMS(p0, p1) \ p0##_type p0, p1##_type p1 #define GMOCK_INTERNAL_DECL_AND_3_VALUE_PARAMS(p0, p1, p2) \ p0##_type p0, p1##_type p1, p2##_type p2 #define GMOCK_INTERNAL_DECL_AND_4_VALUE_PARAMS(p0, p1, p2, p3) \ p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3 #define GMOCK_INTERNAL_DECL_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \ p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4 #define GMOCK_INTERNAL_DECL_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) \ p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \ p5##_type p5 #define GMOCK_INTERNAL_DECL_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) \ p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \ p5##_type p5, p6##_type p6 #define GMOCK_INTERNAL_DECL_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7) \ p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \ p5##_type p5, p6##_type p6, p7##_type p7 #define GMOCK_INTERNAL_DECL_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, \ p8) \ p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \ p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8 #define GMOCK_INTERNAL_DECL_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ p7, p8, p9) \ p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \ p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8, p9##_type p9 #define GMOCK_INTERNAL_COUNT_AND_0_VALUE_PARAMS() #define GMOCK_INTERNAL_COUNT_AND_1_VALUE_PARAMS(p0) P #define GMOCK_INTERNAL_COUNT_AND_2_VALUE_PARAMS(p0, p1) P2 #define GMOCK_INTERNAL_COUNT_AND_3_VALUE_PARAMS(p0, p1, p2) P3 #define GMOCK_INTERNAL_COUNT_AND_4_VALUE_PARAMS(p0, p1, p2, p3) P4 #define GMOCK_INTERNAL_COUNT_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) P5 #define GMOCK_INTERNAL_COUNT_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) P6 #define GMOCK_INTERNAL_COUNT_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) P7 #define GMOCK_INTERNAL_COUNT_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ p7) \ P8 #define GMOCK_INTERNAL_COUNT_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ p7, p8) \ P9 #define GMOCK_INTERNAL_COUNT_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ p7, p8, p9) \ P10 #define GMOCK_ACTION_CLASS_(name, value_params) \ GTEST_CONCAT_TOKEN_(name##Action, GMOCK_INTERNAL_COUNT_##value_params) #define ACTION_TEMPLATE(name, template_params, value_params) \ template <GMOCK_INTERNAL_DECL_##template_params \ GMOCK_INTERNAL_DECL_TYPE_##value_params> \ class GMOCK_ACTION_CLASS_(name, value_params) { \ public: \ explicit GMOCK_ACTION_CLASS_(name, value_params)( \ GMOCK_INTERNAL_DECL_##value_params) \ GMOCK_PP_IF(GMOCK_PP_IS_EMPTY(GMOCK_INTERNAL_COUNT_##value_params), \ = default; \ , \ : impl_(std::make_shared<gmock_Impl>( \ GMOCK_INTERNAL_LIST_##value_params)){}) \ GMOCK_ACTION_CLASS_(name, value_params)(const GMOCK_ACTION_CLASS_( \ name, value_params) &) noexcept GMOCK_INTERNAL_DEFN_COPY_ \ ##value_params \ GMOCK_ACTION_CLASS_(name, value_params)(GMOCK_ACTION_CLASS_( \ name, value_params) &&) noexcept GMOCK_INTERNAL_DEFN_COPY_ \ ##value_params template <typename F> \ operator ::testing::Action<F>() const { \ return GMOCK_PP_IF( \ GMOCK_PP_IS_EMPTY(GMOCK_INTERNAL_COUNT_##value_params), \ (::testing::internal::MakeAction<F, gmock_Impl>()), \ (::testing::internal::MakeAction<F>(impl_))); \ } \ \ private: \ class gmock_Impl { \ public: \ explicit gmock_Impl GMOCK_INTERNAL_INIT_##value_params {} \ template <typename function_type, typename return_type, \ typename args_type, GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \ return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \ GMOCK_INTERNAL_DEFN_##v
#include "gmock/gmock-more-actions.h" #include <algorithm> #include <functional> #include <iterator> #include <memory> #include <sstream> #include <string> #include <tuple> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest-spi.h" #include "gtest/gtest.h" GTEST_DISABLE_MSC_WARNINGS_PUSH_(4577) namespace testing { namespace gmock_more_actions_test { using ::std::plus; using ::std::string; using testing::Action; using testing::DeleteArg; using testing::Invoke; using testing::ReturnArg; using testing::ReturnPointee; using testing::SaveArg; using testing::SaveArgPointee; using testing::SetArgReferee; using testing::Unused; using testing::WithArg; using testing::WithoutArgs; inline short Short(short n) { return n; } inline char Char(char ch) { return ch; } int Nullary() { return 1; } bool g_done = false; bool Unary(int x) { return x < 0; } bool ByConstRef(const std::string& s) { return s == "Hi"; } const double g_double = 0; bool ReferencesGlobalDouble(const double& x) { return &x == &g_double; } struct UnaryFunctor { int operator()(bool x) { return x ? 1 : -1; } }; struct UnaryMoveOnlyFunctor : UnaryFunctor { UnaryMoveOnlyFunctor() = default; UnaryMoveOnlyFunctor(const UnaryMoveOnlyFunctor&) = delete; UnaryMoveOnlyFunctor(UnaryMoveOnlyFunctor&&) = default; }; struct OneShotUnaryFunctor { int operator()(bool x) && { return x ? 1 : -1; } }; const char* Binary(const char* input, short n) { return input + n; } int Ternary(int x, char y, short z) { return x + y + z; } int SumOf4(int a, int b, int c, int d) { return a + b + c + d; } int SumOfFirst2(int a, int b, Unused, Unused) { return a + b; } int SumOf5(int a, int b, int c, int d, int e) { return a + b + c + d + e; } struct SumOf5Functor { int operator()(int a, int b, int c, int d, int e) { return a + b + c + d + e; } }; int SumOf6(int a, int b, int c, int d, int e, int f) { return a + b + c + d + e + f; } struct SumOf6Functor { int operator()(int a, int b, int c, int d, int e, int f) { return a + b + c + d + e + f; } }; std::string Concat7(const char* s1, const char* s2, const char* s3, const char* s4, const char* s5, const char* s6, const char* s7) { return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7; } std::string Concat8(const char* s1, const char* s2, const char* s3, const char* s4, const char* s5, const char* s6, const char* s7, const char* s8) { return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8; } std::string Concat9(const char* s1, const char* s2, const char* s3, const char* s4, const char* s5, const char* s6, const char* s7, const char* s8, const char* s9) { return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9; } std::string Concat10(const char* s1, const char* s2, const char* s3, const char* s4, const char* s5, const char* s6, const char* s7, const char* s8, const char* s9, const char* s10) { return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9 + s10; } class Foo { public: Foo() : value_(123) {} int Nullary() const { return value_; } short Unary(long x) { return static_cast<short>(value_ + x); } std::string Binary(const std::string& str, char c) const { return str + c; } int Ternary(int x, bool y, char z) { return value_ + x + y * z; } int SumOf4(int a, int b, int c, int d) const { return a + b + c + d + value_; } int SumOfLast2(Unused, Unused, int a, int b) const { return a + b; } int SumOf5(int a, int b, int c, int d, int e) { return a + b + c + d + e; } int SumOf6(int a, int b, int c, int d, int e, int f) { return a + b + c + d + e + f; } std::string Concat7(const char* s1, const char* s2, const char* s3, const char* s4, const char* s5, const char* s6, const char* s7) { return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7; } std::string Concat8(const char* s1, const char* s2, const char* s3, const char* s4, const char* s5, const char* s6, const char* s7, const char* s8) { return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8; } std::string Concat9(const char* s1, const char* s2, const char* s3, const char* s4, const char* s5, const char* s6, const char* s7, const char* s8, const char* s9) { return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9; } std::string Concat10(const char* s1, const char* s2, const char* s3, const char* s4, const char* s5, const char* s6, const char* s7, const char* s8, const char* s9, const char* s10) { return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9 + s10; } private: int value_; }; TEST(InvokeTest, Nullary) { Action<int()> a = Invoke(Nullary); EXPECT_EQ(1, a.Perform(std::make_tuple())); } TEST(InvokeTest, Unary) { Action<bool(int)> a = Invoke(Unary); EXPECT_FALSE(a.Perform(std::make_tuple(1))); EXPECT_TRUE(a.Perform(std::make_tuple(-1))); } TEST(InvokeTest, Binary) { Action<const char*(const char*, short)> a = Invoke(Binary); const char* p = "Hello"; EXPECT_EQ(p + 2, a.Perform(std::make_tuple(p, Short(2)))); } TEST(InvokeTest, Ternary) { Action<int(int, char, short)> a = Invoke(Ternary); EXPECT_EQ(6, a.Perform(std::make_tuple(1, '\2', Short(3)))); } TEST(InvokeTest, FunctionThatTakes4Arguments) { Action<int(int, int, int, int)> a = Invoke(SumOf4); EXPECT_EQ(1234, a.Perform(std::make_tuple(1000, 200, 30, 4))); } TEST(InvokeTest, FunctionThatTakes5Arguments) { Action<int(int, int, int, int, int)> a = Invoke(SumOf5); EXPECT_EQ(12345, a.Perform(std::make_tuple(10000, 2000, 300, 40, 5))); } TEST(InvokeTest, FunctionThatTakes6Arguments) { Action<int(int, int, int, int, int, int)> a = Invoke(SumOf6); EXPECT_EQ(123456, a.Perform(std::make_tuple(100000, 20000, 3000, 400, 50, 6))); } inline const char* CharPtr(const char* s) { return s; } TEST(InvokeTest, FunctionThatTakes7Arguments) { Action<std::string(const char*, const char*, const char*, const char*, const char*, const char*, const char*)> a = Invoke(Concat7); EXPECT_EQ("1234567", a.Perform(std::make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"), CharPtr("4"), CharPtr("5"), CharPtr("6"), CharPtr("7")))); } TEST(InvokeTest, FunctionThatTakes8Arguments) { Action<std::string(const char*, const char*, const char*, const char*, const char*, const char*, const char*, const char*)> a = Invoke(Concat8); EXPECT_EQ("12345678", a.Perform(std::make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"), CharPtr("4"), CharPtr("5"), CharPtr("6"), CharPtr("7"), CharPtr("8")))); } TEST(InvokeTest, FunctionThatTakes9Arguments) { Action<std::string(const char*, const char*, const char*, const char*, const char*, const char*, const char*, const char*, const char*)> a = Invoke(Concat9); EXPECT_EQ("123456789", a.Perform(std::make_tuple( CharPtr("1"), CharPtr("2"), CharPtr("3"), CharPtr("4"), CharPtr("5"), CharPtr("6"), CharPtr("7"), CharPtr("8"), CharPtr("9")))); } TEST(InvokeTest, FunctionThatTakes10Arguments) { Action<std::string(const char*, const char*, const char*, const char*, const char*, const char*, const char*, const char*, const char*, const char*)> a = Invoke(Concat10); EXPECT_EQ("1234567890", a.Perform(std::make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"), CharPtr("4"), CharPtr("5"), CharPtr("6"), CharPtr("7"), CharPtr("8"), CharPtr("9"), CharPtr("0")))); } TEST(InvokeTest, FunctionWithUnusedParameters) { Action<int(int, int, double, const std::string&)> a1 = Invoke(SumOfFirst2); std::tuple<int, int, double, std::string> dummy = std::make_tuple(10, 2, 5.6, std::string("hi")); EXPECT_EQ(12, a1.Perform(dummy)); Action<int(int, int, bool, int*)> a2 = Invoke(SumOfFirst2); EXPECT_EQ( 23, a2.Perform(std::make_tuple(20, 3, true, static_cast<int*>(nullptr)))); } TEST(InvokeTest, MethodWithUnusedParameters) { Foo foo; Action<int(std::string, bool, int, int)> a1 = Invoke(&foo, &Foo::SumOfLast2); EXPECT_EQ(12, a1.Perform(std::make_tuple(CharPtr("hi"), true, 10, 2))); Action<int(char, double, int, int)> a2 = Invoke(&foo, &Foo::SumOfLast2); EXPECT_EQ(23, a2.Perform(std::make_tuple('a', 2.5, 20, 3))); } TEST(InvokeTest, Functor) { Action<long(long, int)> a = Invoke(plus<long>()); EXPECT_EQ(3L, a.Perform(std::make_tuple(1, 2))); } TEST(InvokeTest, FunctionWithCompatibleType) { Action<long(int, short, char, bool)> a = Invoke(SumOf4); EXPECT_EQ(4321, a.Perform(std::make_tuple(4000, Short(300), Char(20), true))); } TEST(InvokeMethodTest, Nullary) { Foo foo; Action<int()> a = Invoke(&foo, &Foo::Nullary); EXPECT_EQ(123, a.Perform(std::make_tuple())); } TEST(InvokeMethodTest, Unary) { Foo foo; Action<short(long)> a = Invoke(&foo, &Foo::Unary); EXPECT_EQ(4123, a.Perform(std::make_tuple(4000))); } TEST(InvokeMethodTest, Binary) { Foo foo; Action<std::string(const std::string&, char)> a = Invoke(&foo, &Foo::Binary); std::string s("Hell"); std::tuple<std::string, char> dummy = std::make_tuple(s, 'o'); EXPECT_EQ("Hello", a.Perform(dummy)); } TEST(InvokeMethodTest, Ternary) { Foo foo; Action<int(int, bool, char)> a = Invoke(&foo, &Foo::Ternary); EXPECT_EQ(1124, a.Perform(std::make_tuple(1000, true, Char(1)))); } TEST(InvokeMethodTest, MethodThatTakes4Arguments) { Foo foo; Action<int(int, int, int, int)> a = Invoke(&foo, &Foo::SumOf4); EXPECT_EQ(1357, a.Perform(std::make_tuple(1000, 200, 30, 4))); } TEST(InvokeMethodTest, MethodThatTakes5Arguments) { Foo foo; Action<int(int, int, int, int, int)> a = Invoke(&foo, &Foo::SumOf5); EXPECT_EQ(12345, a.Perform(std::make_tuple(10000, 2000, 300, 40, 5))); } TEST(InvokeMethodTest, MethodThatTakes6Arguments) { Foo foo; Action<int(int, int, int, int, int, int)> a = Invoke(&foo, &Foo::SumOf6); EXPECT_EQ(123456, a.Perform(std::make_tuple(100000, 20000, 3000, 400, 50, 6))); } TEST(InvokeMethodTest, MethodThatTakes7Arguments) { Foo foo; Action<std::string(const char*, const char*, const char*, const char*, const char*, const char*, const char*)> a = Invoke(&foo, &Foo::Concat7); EXPECT_EQ("1234567", a.Perform(std::make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"), CharPtr("4"), CharPtr("5"), CharPtr("6"), CharPtr("7")))); } TEST(InvokeMethodTest, MethodThatTakes8Arguments) { Foo foo; Action<std::string(const char*, const char*, const char*, const char*, const char*, const char*, const char*, const char*)> a = Invoke(&foo, &Foo::Concat8); EXPECT_EQ("12345678", a.Perform(std::make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"), CharPtr("4"), CharPtr("5"), CharPtr("6"), CharPtr("7"), CharPtr("8")))); } TEST(InvokeMethodTest, MethodThatTakes9Arguments) { Foo foo; Action<std::string(const char*, const char*, const char*, const char*, const char*, const char*, const char*, const char*, const char*)> a = Invoke(&foo, &Foo::Concat9); EXPECT_EQ("123456789", a.Perform(std::make_tuple( CharPtr("1"), CharPtr("2"), CharPtr("3"), CharPtr("4"), CharPtr("5"), CharPtr("6"), CharPtr("7"), CharPtr("8"), CharPtr("9")))); } TEST(InvokeMethodTest, MethodThatTakes10Arguments) { Foo foo; Action<std::string(const char*, const char*, const char*, const char*, const char*, const char*, const char*, const char*, const char*, const char*)> a = Invoke(&foo, &Foo::Concat10); EXPECT_EQ("1234567890", a.Perform(std::make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"), CharPtr("4"), CharPtr("5"), CharPtr("6"), CharPtr("7"), CharPtr("8"), CharPtr("9"), CharPtr("0")))); } TEST(InvokeMethodTest, MethodWithCompatibleType) { Foo foo; Action<long(int, short, char, bool)> a = Invoke(&foo, &Foo::SumOf4); EXPECT_EQ(4444, a.Perform(std::make_tuple(4000, Short(300), Char(20), true))); } TEST(WithoutArgsTest, NoArg) { Action<int(int n)> a = WithoutArgs(Invoke(Nullary)); EXPECT_EQ(1, a.Perform(std::make_tuple(2))); } TEST(WithArgTest, OneArg) { Action<bool(double x, int n)> b = WithArg<1>(Invoke(Unary)); EXPECT_TRUE(b.Perform(std::make_tuple(1.5, -1))); EXPECT_FALSE(b.Perform(std::make_tuple(1.5, 1))); } TEST(ReturnArgActionTest, WorksForOneArgIntArg0) { const Action<int(int)> a = ReturnArg<0>(); EXPECT_EQ(5, a.Perform(std::make_tuple(5))); } TEST(ReturnArgActionTest, WorksForMultiArgBoolArg0) { const Action<bool(bool, bool, bool)> a = ReturnArg<0>(); EXPECT_TRUE(a.Perform(std::make_tuple(true, false, false))); } TEST(ReturnArgActionTest, WorksForMultiArgStringArg2) { const Action<std::string(int, int, std::string, int)> a = ReturnArg<2>(); EXPECT_EQ("seven", a.Perform(std::make_tuple(5, 6, std::string("seven"), 8))); } TEST(ReturnArgActionTest, WorksForNonConstRefArg0) { const Action<std::string&(std::string&)> a = ReturnArg<0>(); std::string s = "12345"; EXPECT_EQ(&s, &a.Perform(std::forward_as_tuple(s))); } TEST(SaveArgActionTest, WorksForSameType) { int result = 0; const Action<void(int n)> a1 = SaveArg<0>(&result); a1.Perform(std::make_tuple(5)); EXPECT_EQ(5, result); } TEST(SaveArgActionTest, WorksForCompatibleType) { int result = 0; const Action<void(bool, char)> a1 = SaveArg<1>(&result); a1.Perform(std::make_tuple(true, 'a')); EXPECT_EQ('a', result); } TEST(SaveArgPointeeActionTest, WorksForSameType) { int result = 0; const int value = 5; const Action<void(const int*)> a1 = SaveArgPointee<0>(&result); a1.Perform(std::make_tuple(&value)); EXPECT_EQ(5, result); } TEST(SaveArgPointeeActionTest, WorksForCompatibleType) { int result = 0; char value = 'a'; const Action<void(bool, char*)> a1 = SaveArgPointee<1>(&result); a1.Perform(std::make_tuple(true, &value)); EXPECT_EQ('a', result); } TEST(SetArgRefereeActionTest, WorksForSameType) { int value = 0; const Action<void(int&)> a1 = SetArgReferee<0>(1); a1.Perform(std::tuple<int&>(value)); EXPECT_EQ(1, value); } TEST(SetArgRefereeActionTest, WorksForCompatibleType) { int value = 0; const Action<void(int, int&)> a1 = SetArgReferee<1>('a'); a1.Perform(std::tuple<int, int&>(0, value)); EXPECT_EQ('a', value); } TEST(SetArgRefereeActionTest, WorksWithExtraArguments) { int value = 0; const Action<void(bool, int, int&, const char*)> a1 = SetArgReferee<2>('a'); a1.Perform(std::tuple<bool, int, int&, const char*>(true, 0, value, "hi")); EXPECT_EQ('a', value); } class DeletionTester { public: explicit DeletionTester(bool* is_deleted) : is_deleted_(is_deleted) { *is_deleted_ = false; } ~DeletionTester() { *is_deleted_ = true; } private: bool* is_deleted_; }; TEST(DeleteArgActionTest, OneArg) { bool is_deleted = false; DeletionTester* t = new DeletionTester(&is_deleted); const Action<void(DeletionTester*)> a1 = DeleteArg<0>(); EXPECT_FALSE(is_deleted); a1.Perform(std::make_tuple(t)); EXPECT_TRUE(is_deleted); } TEST(DeleteArgActionTest, TenArgs) { bool is_deleted = false; DeletionTester* t = new DeletionTester(&is_deleted); const Action<void(bool, int, int, const char*, bool, int, int, int, int, DeletionTester*)> a1 = DeleteArg<9>(); EXPECT_FALSE(is_deleted); a1.Perform(std::make_tuple(true, 5, 6, CharPtr("hi"), false, 7, 8, 9, 10, t)); EXPECT_TRUE(is_deleted); } #if GTEST_HAS_EXCEPTIONS TEST(ThrowActionTest, ThrowsGivenExceptionInVoidFunction) { const Action<void(int n)> a = Throw('a'); EXPECT_THROW(a.Perform(std::make_tuple(0)), char); } class MyException {}; TEST(ThrowActionTest, ThrowsGivenExceptionInNonVoidFunction) { const Action<double(char ch)> a = Throw(MyException()); EXPECT_THROW(a.Perform(std::make_tuple('0')), MyException); } TEST(ThrowActionTest, ThrowsGivenExceptionInNullaryFunction) { const Action<double()> a = Throw(MyException()); EXPECT_THROW(a.Perform(std::make_tuple()), MyException); } class Object { public: virtual ~Object() {} virtual void Func() {} }; class MockObject : public Object { public: ~MockObject() override {} MOCK_METHOD(void, Func, (), (override)); }; TEST(ThrowActionTest, Times0) { EXPECT_NONFATAL_FAILURE( [] { try { MockObject m; ON_CALL(m, Func()).WillByDefault([] { throw "something"; }); EXPECT_CALL(m, Func()).Times(0); m.Func(); } catch (...) { } }(), ""); } #endif TEST(SetArrayArgumentTest, SetsTheNthArray) { using MyFunction = void(bool, int*, char*); int numbers[] = {1, 2, 3}; Action<MyFunction> a = SetArrayArgument<1>(numbers, numbers + 3); int n[4] = {}; int* pn = n; char ch[4] = {}; char* pch = ch; a.Perform(std::make_tuple(true, pn, pch)); EXPECT_EQ(1, n[0]); EXPECT_EQ(2, n[1]); EXPECT_EQ(3, n[2]); EXPECT_EQ(0, n[3]); EXPECT_EQ('\0', ch[0]); EXPECT_EQ('\0', ch[1]); EXPECT_EQ('\0', ch[2]); EXPECT_EQ('\0', ch[3]); std::string letters = "abc"; a = SetArrayArgument<2>(letters.begin(), letters.end()); std::fill_n(n, 4, 0); std::fill_n(ch, 4, '\0'); a.Perform(std::make_tuple(true, pn, pch)); EXPECT_EQ(0, n[0]); EXPECT_EQ(0, n[1]); EXPECT_EQ(0, n[2]); EXPECT_EQ(0, n[3]); EXPECT_EQ('a', ch[0]); EXPECT_EQ('b', ch[1]); EXPECT_EQ('c', ch[2]); EXPECT_EQ('\0', ch[3]); } TEST(SetArrayArgumentTest, SetsTheNthArrayWithEmptyRange) { using MyFunction = void(bool, int*); int numbers[] = {1, 2, 3}; Action<MyFunction> a = SetArrayArgument<1>(numbers, numbers); int n[4] = {}; int* pn = n; a.Perform(std::make_tuple(true, pn)); EXPECT_EQ(0, n[0]); EXPECT_EQ(0, n[1]); EXPECT_EQ(0, n[2]); EXPECT_EQ(0, n[3]); } TEST(SetArrayArgumentTest, SetsTheNthArrayWithConvertibleType) { using MyFunction = void(bool, int*); char chars[] = {97, 98, 99}; Action<MyFunction> a = SetArrayArgument<1>(chars, chars + 3); int codes[4] = {111, 222, 333, 444}; int* pcodes = codes; a.Perform(std::make_tuple(true, pcodes)); EXPECT_EQ(97, codes[0]); EXPECT_EQ(98, codes[1]); EXPECT_EQ(99, codes[2]); EXPECT_EQ(444, codes[3]); } TEST(SetArrayArgumentTest, SetsTheNthArrayWithIteratorArgument) { using MyFunction = void(bool, std::back_insert_iterator<std::string>); std::string letters = "abc"; Action<MyFunction> a = SetArrayArgument<1>(letters.begin(), letters.end()); std::string s; a.Perform(std::make_tuple(true, std::back_inserter(s))); EXPECT_EQ(letters, s); } TEST(ReturnPointeeTest, Works) { int n = 42; const Action<int()> a = ReturnPointee(&n); EXPECT_EQ(42, a.Perform(std::make_tuple())); n = 43; EXPECT_EQ(43, a.Perform(std::make_tuple())); } TEST(InvokeArgumentTest, Function0) { Action<int(int, int (*)())> a = InvokeArgument<1>(); EXPECT_EQ(1, a.Perform(std::make_tuple(2, &Nullary))); } TEST(InvokeArgumentTest, Functor1) { Action<int(UnaryFunctor)> a = InvokeArgument<0>(true); EXPECT_EQ(1, a.Perform(std::make_tuple(UnaryFunctor()))); } TEST(InvokeArgumentTest, Functor1MoveOnly) { Action<int(UnaryMoveOnlyFunctor)> a = InvokeArgument<0>(true); EXPECT_EQ(1, a.Perform(std::make_tuple(UnaryMoveOnlyFunctor()))); } TEST(InvokeArgumentTest, OneShotFunctor1) { Action<int(OneShotUnaryFunctor)> a = InvokeArgument<0>(true); EXPECT_EQ(1, a.Perform(std::make_tuple(OneShotUnaryFunctor()))); } TEST(InvokeArgumentTest, Function5) { Action<int(int (*)(int, int, int, int, int))> a = InvokeArgument<0>(10000, 2000, 300, 40, 5); EXPECT_EQ(12345, a.Perform(std::make_tuple(&SumOf5))); } TEST(InvokeArgumentTest, Functor5) { Action<int(SumOf5Functor)> a = InvokeArgument<0>(10000, 2000, 300, 40, 5); EXPECT_EQ(12345, a.Perform(std::make_tuple(SumOf5Functor()))); } TEST(InvokeArgumentTest, Function6) { Action<int(int (*)(int, int, int, int, int, int))> a = InvokeArgument<0>(100000, 20000, 3000, 400, 50, 6); EXPECT_EQ(123456, a.Perform(std::make_tuple(&SumOf6))); } TEST(InvokeArgumentTest, Functor6) { Action<int(SumOf6Functor)> a = InvokeArgument<0>(100000, 20000, 3000, 400, 50, 6); EXPECT_EQ(123456, a.Perform(std::make_tuple(SumOf6Functor()))); } TEST(InvokeArgumentTest, Function7) { Action<std::string(std::string(*)(const char*, const char*, const char*, const char*, const char*, const char*, const char*))> a = InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7"); EXPECT_EQ("1234567", a.Perform(std::make_tuple(&Concat7))); } TEST(InvokeArgumentTest, Function8) { Action<std::string(std::string(*)(const char*, const char*, const char*, const char*, const char*, const char*, const char*, const char*))> a = InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7", "8"); EXPECT_EQ("12345678", a.Perform(std::make_tuple(&Concat8))); } TEST(InvokeArgumentTest, Function9) { Action<std::string(std::string(*)(const char*, const char*, const char*, const char*, const char*, const char*, const char*, const char*, const char*))> a = InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7", "8", "9"); EXPECT_EQ("123456789", a.Perform(std::make_tuple(&Concat9))); } TEST(InvokeArgumentTest, Function10) { Action<std::string(std::string(*)( const char*, const char*, const char*, const char*, const char*, const char*, const char*, const char*, const char*, const char*))> a = InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7", "8", "9", "0"); EXPECT_EQ("1234567890", a.Perform(std::make_tuple(&Concat10))); } TEST(InvokeArgumentTest, ByPointerFunction) { Action<const char*(const char* (*)(const char* input, short n))> a = InvokeArgument<0>(static_cast<const char*>("Hi"), Short(1)); EXPECT_STREQ("i", a.Perform(std::make_tuple(&Binary))); } TEST(InvokeArgumentTest, FunctionWithCStringLiteral) { Action<const char*(const char* (*)(const char* input, short n))> a = InvokeArgument<0>("Hi", Short(1)); EXPECT_STREQ("i", a.Perform(std::make_tuple(&Binary))); } TEST(InvokeArgumentTest, ByConstReferenceFunction) { Action<bool(bool (*function)(const std::string& s))> a = InvokeArgument<0>(std::string("Hi")); EXPECT_TRUE(a.Perform(std::make_tuple(&ByConstRef))); } TEST(InvokeArgumentTest, ByExplicitConstReferenceFunction) { Action<bool(bool (*)(const double& x))> a = InvokeArgument<0>(ByRef(g_double)); EXPECT_TRUE(a.Perform(std::make_tuple(&ReferencesGlobalDouble))); double x = 0; a = InvokeArgument<0>(ByRef(x)); EXPECT_FALSE(a.Perform(std::make_tuple(&ReferencesGlobalDouble))); } TEST(InvokeArgumentTest, MoveOnlyType) { struct Marker {}; struct { MOCK_METHOD(bool, MockMethod, (std::unique_ptr<Marker>, std::function<int()>), ()); } mock; ON_CALL(mock, MockMethod(_, _)).WillByDefault(InvokeArgument<1>()); ON_CALL(mock, MockMethod(_, _)) .WillByDefault(WithArg<1>(InvokeArgument<0>())); } TEST(DoAllTest, TwoActions) { int n = 0; Action<int(int*)> a = DoAll(SetArgPointee<0>(1), Return(2)); EXPECT_EQ(2, a.Perform(std::make_tuple(&n))); EXPECT_EQ(1, n); } TEST(DoAllTest, ThreeActions) { int m = 0, n = 0; Action<int(int*, int*)> a = DoAll(SetArgPointee<0>(1), SetArgPointee<1>(2), Return(3)); EXPECT_EQ(3, a.Perform(std::make_tuple(&m, &n))); EXPECT_EQ(1, m); EXPECT_EQ(2, n); } TEST(DoAllTest, FourActions) { int m = 0, n = 0; char ch = '\0'; Action<int(int*, int*, char*)> a = DoAll(SetArgPointee<0>(1), SetArgPointee<1>(2), SetArgPointee<2>('a'), Return(3)); EXPECT_EQ(3, a.Perform(std::make_tuple(&m, &n, &ch))); EXPECT_EQ(1, m); EXPECT_EQ(2, n); EXPECT_EQ('a', ch); } TEST(DoAllTest, FiveActions) { int m = 0, n = 0; char a = '\0', b = '\0'; Action<int(int*, int*, char*, char*)> action = DoAll(SetArgPointee<0>(1), SetArgPointee<1>(2), SetArgPointee<2>('a'), SetArgPointee<3>('b'), Return(3)); EXPECT_EQ(3, action.Perform(std::make_tuple(&m, &n, &a, &b))); EXPECT_EQ(1, m); EXPECT_EQ(2, n); EXPECT_EQ('a', a); EXPECT_EQ('b', b); } TEST(DoAllTest, SixActions) { int m = 0, n = 0; char a = '\0', b = '\0', c = '\0'; Action<int(int*, int*, char*, char*, char*)> action = DoAll(SetArgPointee<0>(1), SetArgPointee<1>(2), SetArgPointee<2>('a'), SetArgPointee<3>('b'), SetArgPointee<4>('c'), Return(3)); EXPECT_EQ(3, action.Perform(std::make_tuple(&m, &n, &a, &b, &c))); EXPECT_EQ(1, m); EXPECT_EQ(2, n); EXPECT_EQ('a', a); EXPECT_EQ('b', b); EXPECT_EQ('c', c); } TEST(DoAllTest, SevenActions) { int m = 0, n = 0; char a = '\0', b = '\0', c = '\0', d = '\0'; Action<int(int*, int*, char*, char*, char*, char*)> action = DoAll(SetArgPointee<0>(1), SetArgPointee<1>(2), SetArgPointee<2>('a'), SetArgPointee<3>('b'), SetArgPointee<4>('c'), SetArgPointee<5>('d'), Return(3)); EXPECT_EQ(3, action.Perform(std::make_tuple(&m, &n, &a, &b, &c, &d))); EXPECT_EQ(1, m); EXPECT_EQ(2, n); EXPECT_EQ('a', a); EXPECT_EQ('b', b); EXPECT_EQ('c', c); EXPECT_EQ('d', d); }
2,339
#ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PP_H_ #define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PP_H_ #define GMOCK_PP_CAT(_1, _2) GMOCK_PP_INTERNAL_CAT(_1, _2) #define GMOCK_PP_STRINGIZE(...) GMOCK_PP_INTERNAL_STRINGIZE(__VA_ARGS__) #define GMOCK_PP_EMPTY(...) #define GMOCK_PP_COMMA(...) , #define GMOCK_PP_IDENTITY(_1) _1 #define GMOCK_PP_NARG(...) \ GMOCK_PP_INTERNAL_16TH( \ (__VA_ARGS__, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)) #define GMOCK_PP_HAS_COMMA(...) \ GMOCK_PP_INTERNAL_16TH( \ (__VA_ARGS__, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0)) #define GMOCK_PP_HEAD(...) GMOCK_PP_INTERNAL_HEAD((__VA_ARGS__, unusedArg)) #define GMOCK_PP_TAIL(...) GMOCK_PP_INTERNAL_TAIL((__VA_ARGS__)) #define GMOCK_PP_VARIADIC_CALL(_Macro, ...) \ GMOCK_PP_IDENTITY( \ GMOCK_PP_CAT(_Macro, GMOCK_PP_NARG(__VA_ARGS__))(__VA_ARGS__)) #define GMOCK_PP_IS_EMPTY(...) \ GMOCK_PP_INTERNAL_IS_EMPTY(GMOCK_PP_HAS_COMMA(__VA_ARGS__), \ GMOCK_PP_HAS_COMMA(GMOCK_PP_COMMA __VA_ARGS__), \ GMOCK_PP_HAS_COMMA(__VA_ARGS__()), \ GMOCK_PP_HAS_COMMA(GMOCK_PP_COMMA __VA_ARGS__())) #define GMOCK_PP_IF(_Cond, _Then, _Else) \ GMOCK_PP_CAT(GMOCK_PP_INTERNAL_IF_, _Cond)(_Then, _Else) #define GMOCK_PP_GENERIC_IF(_Cond, _Then, _Else) \ GMOCK_PP_REMOVE_PARENS(GMOCK_PP_IF(_Cond, _Then, _Else)) #define GMOCK_PP_NARG0(...) \ GMOCK_PP_IF(GMOCK_PP_IS_EMPTY(__VA_ARGS__), 0, GMOCK_PP_NARG(__VA_ARGS__)) #define GMOCK_PP_IS_BEGIN_PARENS(...) \ GMOCK_PP_HEAD(GMOCK_PP_CAT(GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_R_, \ GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_C __VA_ARGS__)) #define GMOCK_PP_IS_ENCLOSED_PARENS(...) \ GMOCK_PP_IF(GMOCK_PP_IS_BEGIN_PARENS(__VA_ARGS__), \ GMOCK_PP_IS_EMPTY(GMOCK_PP_EMPTY __VA_ARGS__), 0) #define GMOCK_PP_REMOVE_PARENS(...) GMOCK_PP_INTERNAL_REMOVE_PARENS __VA_ARGS__ #define GMOCK_PP_FOR_EACH(_Macro, _Data, _Tuple) \ GMOCK_PP_CAT(GMOCK_PP_INTERNAL_FOR_EACH_IMPL_, GMOCK_PP_NARG0 _Tuple) \ (0, _Macro, _Data, _Tuple) #define GMOCK_PP_REPEAT(_Macro, _Data, _N) \ GMOCK_PP_CAT(GMOCK_PP_INTERNAL_FOR_EACH_IMPL_, _N) \ (0, _Macro, _Data, GMOCK_PP_INTENRAL_EMPTY_TUPLE) #define GMOCK_PP_INC(_i) GMOCK_PP_CAT(GMOCK_PP_INTERNAL_INC_, _i) #define GMOCK_PP_COMMA_IF(_i) GMOCK_PP_CAT(GMOCK_PP_INTERNAL_COMMA_IF_, _i) #define GMOCK_PP_INTENRAL_EMPTY_TUPLE (, , , , , , , , , , , , , , , ) #define GMOCK_PP_INTERNAL_CAT(_1, _2) _1##_2 #define GMOCK_PP_INTERNAL_STRINGIZE(...) #__VA_ARGS__ #define GMOCK_PP_INTERNAL_CAT_5(_1, _2, _3, _4, _5) _1##_2##_3##_4##_5 #define GMOCK_PP_INTERNAL_IS_EMPTY(_1, _2, _3, _4) \ GMOCK_PP_HAS_COMMA(GMOCK_PP_INTERNAL_CAT_5(GMOCK_PP_INTERNAL_IS_EMPTY_CASE_, \ _1, _2, _3, _4)) #define GMOCK_PP_INTERNAL_IS_EMPTY_CASE_0001 , #define GMOCK_PP_INTERNAL_IF_1(_Then, _Else) _Then #define GMOCK_PP_INTERNAL_IF_0(_Then, _Else) _Else #define GMOCK_PP_INTERNAL_INTERNAL_16TH(_1, _2, _3, _4, _5, _6, _7, _8, _9, \ _10, _11, _12, _13, _14, _15, _16, \ ...) \ _16 #define GMOCK_PP_INTERNAL_16TH(_Args) \ GMOCK_PP_IDENTITY(GMOCK_PP_INTERNAL_INTERNAL_16TH _Args) #define GMOCK_PP_INTERNAL_INTERNAL_HEAD(_1, ...) _1 #define GMOCK_PP_INTERNAL_HEAD(_Args) \ GMOCK_PP_IDENTITY(GMOCK_PP_INTERNAL_INTERNAL_HEAD _Args) #define GMOCK_PP_INTERNAL_INTERNAL_TAIL(_1, ...) __VA_ARGS__ #define GMOCK_PP_INTERNAL_TAIL(_Args) \ GMOCK_PP_IDENTITY(GMOCK_PP_INTERNAL_INTERNAL_TAIL _Args) #define GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_C(...) 1 _ #define GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_R_1 1, #define GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_R_GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_C \ 0, #define GMOCK_PP_INTERNAL_REMOVE_PARENS(...) __VA_ARGS__ #define GMOCK_PP_INTERNAL_INC_0 1 #define GMOCK_PP_INTERNAL_INC_1 2 #define GMOCK_PP_INTERNAL_INC_2 3 #define GMOCK_PP_INTERNAL_INC_3 4 #define GMOCK_PP_INTERNAL_INC_4 5 #define GMOCK_PP_INTERNAL_INC_5 6 #define GMOCK_PP_INTERNAL_INC_6 7 #define GMOCK_PP_INTERNAL_INC_7 8 #define GMOCK_PP_INTERNAL_INC_8 9 #define GMOCK_PP_INTERNAL_INC_9 10 #define GMOCK_PP_INTERNAL_INC_10 11 #define GMOCK_PP_INTERNAL_INC_11 12 #define GMOCK_PP_INTERNAL_INC_12 13 #define GMOCK_PP_INTERNAL_INC_13 14 #define GMOCK_PP_INTERNAL_INC_14 15 #define GMOCK_PP_INTERNAL_INC_15 16 #define GMOCK_PP_INTERNAL_COMMA_IF_0 #define GMOCK_PP_INTERNAL_COMMA_IF_1 , #define GMOCK_PP_INTERNAL_COMMA_IF_2 , #define GMOCK_PP_INTERNAL_COMMA_IF_3 , #define GMOCK_PP_INTERNAL_COMMA_IF_4 , #define GMOCK_PP_INTERNAL_COMMA_IF_5 , #define GMOCK_PP_INTERNAL_COMMA_IF_6 , #define GMOCK_PP_INTERNAL_COMMA_IF_7 , #define GMOCK_PP_INTERNAL_COMMA_IF_8 , #define GMOCK_PP_INTERNAL_COMMA_IF_9 , #define GMOCK_PP_INTERNAL_COMMA_IF_10 , #define GMOCK_PP_INTERNAL_COMMA_IF_11 , #define GMOCK_PP_INTERNAL_COMMA_IF_12 , #define GMOCK_PP_INTERNAL_COMMA_IF_13 , #define GMOCK_PP_INTERNAL_COMMA_IF_14 , #define GMOCK_PP_INTERNAL_COMMA_IF_15 , #define GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, _element) \ _Macro(_i, _Data, _element) #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_0(_i, _Macro, _Data, _Tuple) #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_1(_i, _Macro, _Data, _Tuple) \ GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_2(_i, _Macro, _Data, _Tuple) \ GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \ GMOCK_PP_INTERNAL_FOR_EACH_IMPL_1(GMOCK_PP_INC(_i), _Macro, _Data, \ (GMOCK_PP_TAIL _Tuple)) #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_3(_i, _Macro, _Data, _Tuple) \ GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \ GMOCK_PP_INTERNAL_FOR_EACH_IMPL_2(GMOCK_PP_INC(_i), _Macro, _Data, \ (GMOCK_PP_TAIL _Tuple)) #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_4(_i, _Macro, _Data, _Tuple) \ GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \ GMOCK_PP_INTERNAL_FOR_EACH_IMPL_3(GMOCK_PP_INC(_i), _Macro, _Data, \ (GMOCK_PP_TAIL _Tuple)) #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_5(_i, _Macro, _Data, _Tuple) \ GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \ GMOCK_PP_INTERNAL_FOR_EACH_IMPL_4(GMOCK_PP_INC(_i), _Macro, _Data, \ (GMOCK_PP_TAIL _Tuple)) #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_6(_i, _Macro, _Data, _Tuple) \ GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \ GMOCK_PP_INTERNAL_FOR_EACH_IMPL_5(GMOCK_PP_INC(_i), _Macro, _Data, \ (GMOCK_PP_TAIL _Tuple)) #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_7(_i, _Macro, _Data, _Tuple) \ GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \ GMOCK_PP_INTERNAL_FOR_EACH_IMPL_6(GMOCK_PP_INC(_i), _Macro, _Data, \ (GMOCK_PP_TAIL _Tuple)) #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_8(_i, _Macro, _Data, _Tuple) \ GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \ GMOCK_PP_INTERNAL_FOR_EACH_IMPL_7(GMOCK_PP_INC(_i), _Macro, _Data, \ (GMOCK_PP_TAIL _Tuple)) #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_9(_i, _Macro, _Data, _Tuple) \ GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \ GMOCK_PP_INTERNAL_FOR_EACH_IMPL_8(GMOCK_PP_INC(_i), _Macro, _Data, \ (GMOCK_PP_TAIL _Tuple)) #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_10(_i, _Macro, _Data, _Tuple) \ GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \ GMOCK_PP_INTERNAL_FOR_EACH_IMPL_9(GMOCK_PP_INC(_i), _Macro, _Data, \ (GMOCK_PP_TAIL _Tuple)) #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_11(_i, _Macro, _Data, _Tuple) \ GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \ GMOCK_PP_INTERNAL_FOR_EACH_IMPL_10(GMOCK_PP_INC(_i), _Macro, _Data, \ (GMOCK_PP_TAIL _Tuple)) #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_12(_i, _Macro, _Data, _Tuple) \ GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \ GMOCK_PP_INTERNAL_FOR_EACH_IMPL_11(GMOCK_PP_INC(_i), _Macro, _Data, \ (GMOCK_PP_TAIL _Tuple)) #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_13(_i, _Macro, _Data, _Tuple) \ GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \ GMOCK_PP_INTERNAL_FOR_EACH_IMPL_12(GMOCK_PP_INC(_i), _Macro, _Data, \ (GMOCK_PP_TAIL _Tuple)) #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_14(_i, _Macro, _Data, _Tuple) \ GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \ GMOCK_PP_INTERNAL_FOR_EACH_IMPL_13(GMOCK_PP_INC(_i), _Macro, _Data, \ (GMOCK_PP_TAIL _Tuple)) #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_15(_i, _Macro, _Data, _Tuple) \ GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \ GMOCK_PP_INTERNAL_FOR_EACH_IMPL_14(GMOCK_PP_INC(_i), _Macro, _Data, \ (GMOCK_PP_TAIL _Tuple)) #endif
#include "gmock/internal/gmock-pp.h" #define GMOCK_TEST_REPLACE_comma_WITH_COMMA_I_comma , #define GMOCK_TEST_REPLACE_comma_WITH_COMMA(x) \ GMOCK_PP_CAT(GMOCK_TEST_REPLACE_comma_WITH_COMMA_I_, x) namespace testing { namespace internal { namespace gmockpp { static_assert(GMOCK_PP_CAT(1, 4) == 14, ""); static_assert(GMOCK_PP_INTERNAL_INTERNAL_16TH(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18) == 16, ""); static_assert(GMOCK_PP_NARG() == 1, ""); static_assert(GMOCK_PP_NARG(x) == 1, ""); static_assert(GMOCK_PP_NARG(x, y) == 2, ""); static_assert(GMOCK_PP_NARG(x, y, z) == 3, ""); static_assert(GMOCK_PP_NARG(x, y, z, w) == 4, ""); static_assert(!GMOCK_PP_HAS_COMMA(), ""); static_assert(GMOCK_PP_HAS_COMMA(b, ), ""); static_assert(!GMOCK_PP_HAS_COMMA((, )), ""); static_assert(GMOCK_PP_HAS_COMMA(GMOCK_TEST_REPLACE_comma_WITH_COMMA(comma)), ""); static_assert( GMOCK_PP_HAS_COMMA(GMOCK_TEST_REPLACE_comma_WITH_COMMA(comma(unrelated))), ""); static_assert(!GMOCK_PP_IS_EMPTY(, ), ""); static_assert(!GMOCK_PP_IS_EMPTY(a), ""); static_assert(!GMOCK_PP_IS_EMPTY(()), ""); static_assert(GMOCK_PP_IF(1, 1, 2) == 1, ""); static_assert(GMOCK_PP_IF(0, 1, 2) == 2, ""); static_assert(GMOCK_PP_NARG0(x) == 1, ""); static_assert(GMOCK_PP_NARG0(x, y) == 2, ""); static_assert(GMOCK_PP_HEAD(1) == 1, ""); static_assert(GMOCK_PP_HEAD(1, 2) == 1, ""); static_assert(GMOCK_PP_HEAD(1, 2, 3) == 1, ""); static_assert(GMOCK_PP_TAIL(1, 2) == 2, ""); static_assert(GMOCK_PP_HEAD(GMOCK_PP_TAIL(1, 2, 3)) == 2, ""); static_assert(!GMOCK_PP_IS_BEGIN_PARENS(sss), ""); static_assert(!GMOCK_PP_IS_BEGIN_PARENS(sss()), ""); static_assert(!GMOCK_PP_IS_BEGIN_PARENS(sss() sss), ""); static_assert(GMOCK_PP_IS_BEGIN_PARENS((sss)), ""); static_assert(GMOCK_PP_IS_BEGIN_PARENS((sss)ss), ""); static_assert(!GMOCK_PP_IS_ENCLOSED_PARENS(sss), ""); static_assert(!GMOCK_PP_IS_ENCLOSED_PARENS(sss()), ""); static_assert(!GMOCK_PP_IS_ENCLOSED_PARENS(sss() sss), ""); static_assert(!GMOCK_PP_IS_ENCLOSED_PARENS((sss)ss), ""); static_assert(GMOCK_PP_REMOVE_PARENS((1 + 1)) * 2 == 3, ""); static_assert(GMOCK_PP_INC(4) == 5, ""); template <class... Args> struct Test { static constexpr int kArgs = sizeof...(Args); }; #define GMOCK_PP_INTERNAL_TYPE_TEST(_i, _Data, _element) \ GMOCK_PP_COMMA_IF(_i) _element static_assert(Test<GMOCK_PP_FOR_EACH(GMOCK_PP_INTERNAL_TYPE_TEST, ~, (int, float, double, char))>::kArgs == 4, ""); #define GMOCK_PP_INTERNAL_VAR_TEST_1(_x) 1 #define GMOCK_PP_INTERNAL_VAR_TEST_2(_x, _y) 2 #define GMOCK_PP_INTERNAL_VAR_TEST_3(_x, _y, _z) 3 #define GMOCK_PP_INTERNAL_VAR_TEST(...) \ GMOCK_PP_VARIADIC_CALL(GMOCK_PP_INTERNAL_VAR_TEST_, __VA_ARGS__) static_assert(GMOCK_PP_INTERNAL_VAR_TEST(x, y) == 2, ""); static_assert(GMOCK_PP_INTERNAL_VAR_TEST(silly) == 1, ""); static_assert(GMOCK_PP_INTERNAL_VAR_TEST(x, y, z) == 3, ""); #define GMOCK_PP_INTERNAL_IS_EMPTY_TEST_1 static_assert(GMOCK_PP_IS_EMPTY(GMOCK_PP_INTERNAL_IS_EMPTY_TEST_1), ""); static_assert(GMOCK_PP_IS_EMPTY(), ""); static_assert(GMOCK_PP_IS_ENCLOSED_PARENS((sss)), ""); static_assert(GMOCK_PP_IS_EMPTY(GMOCK_PP_TAIL(1)), ""); static_assert(GMOCK_PP_NARG0() == 0, ""); } } }
2,340
#ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_ #define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_ #endif
#include "gmock/internal/gmock-port.h" #include "gtest/gtest.h" TEST(DummyTest, Dummy) {}
2,341
#ifndef AROLLA_EXAMPLES_CUSTOM_QTYPE_COMPLEX_H_ #define AROLLA_EXAMPLES_CUSTOM_QTYPE_COMPLEX_H_ #include "arolla/qtype/simple_qtype.h" #include "arolla/util/fingerprint.h" #include "arolla/util/repr.h" namespace my_namespace { struct MyComplex { double re; double im; }; } namespace arolla { AROLLA_DECLARE_FINGERPRINT_HASHER_TRAITS(my_namespace::MyComplex); AROLLA_DECLARE_REPR(my_namespace::MyComplex); AROLLA_DECLARE_SIMPLE_QTYPE(MY_COMPLEX, my_namespace::MyComplex); } #endif #include "arolla/examples/custom_qtype/complex.h" #include "absl/strings/str_format.h" #include "arolla/qtype/simple_qtype.h" #include "arolla/util/fingerprint.h" #include "arolla/util/repr.h" namespace arolla { void FingerprintHasherTraits<my_namespace::MyComplex>::operator()( FingerprintHasher* hasher, const my_namespace::MyComplex& value) const { hasher->Combine(value.im, value.re); } ReprToken ReprTraits<my_namespace::MyComplex>::operator()( const my_namespace::MyComplex& value) const { return ReprToken{absl::StrFormat("%v + %vi", value.re, value.im)}; } AROLLA_DEFINE_SIMPLE_QTYPE(MY_COMPLEX, my_namespace::MyComplex); }
#include "arolla/examples/custom_qtype/complex.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/util/fingerprint.h" #include "arolla/util/init_arolla.h" #include "arolla/util/repr.h" namespace my_namespace { namespace { using ::testing::Eq; using ::testing::Ne; class ComplexTest : public ::testing::Test { void SetUp() override { ASSERT_OK(arolla::InitArolla()); } }; TEST_F(ComplexTest, GetQType) { EXPECT_THAT(arolla::GetQType<MyComplex>()->name(), Eq("MY_COMPLEX")); } TEST_F(ComplexTest, Fingerprint) { MyComplex c{.re = 5.7, .im = 0.7}; auto c_fingerprint = arolla::FingerprintHasher("").Combine(c).Finish(); EXPECT_THAT(arolla::FingerprintHasher("").Combine(c).Finish(), Eq(c_fingerprint)); EXPECT_THAT(arolla::FingerprintHasher("") .Combine(MyComplex{.re = 0.7, .im = 5.7}) .Finish(), Ne(c_fingerprint)); } TEST_F(ComplexTest, Repr) { EXPECT_THAT(arolla::Repr(MyComplex{}), Eq("0 + 0i")); EXPECT_THAT(arolla::Repr(MyComplex{.re = 5.7, .im = 0.7}), Eq("5.7 + 0.7i")); } } }
2,342
#ifndef AROLLA_NAMING_TABLE_H_ #define AROLLA_NAMING_TABLE_H_ #include <cstddef> #include <optional> #include <ostream> #include <string> #include <utility> #include <vector> #include "absl/hash/hash.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "arolla/util/types.h" namespace arolla::naming { constexpr absl::string_view kSizeColumnName = "@size"; constexpr absl::string_view kExtensionFieldPrefix = "Ext::"; constexpr absl::string_view kIndexMarker = "[:]"; inline std::string FieldAccess(absl::string_view field_name) { return std::string(field_name); } inline std::string MapAccess(absl::string_view field_name, absl::string_view key) { return absl::StrCat(field_name, "[\"", key, "\"]"); } inline std::string ArrayAccess(absl::string_view field_name, size_t idx) { return absl::StrCat(field_name, "[", idx, "]"); } inline std::string ProtoExtensionAccess(absl::string_view ext_name) { return absl::StrCat(kExtensionFieldPrefix, ext_name); } class PathSegment { public: PathSegment(absl::string_view field_name, bool is_index) : field_name_(field_name), is_index_(is_index) {} const std::string& FieldName() const { return field_name_; } bool IsIndex() const { return is_index_; } template <typename H> friend H AbslHashValue(H h, const PathSegment& s) { return H::combine(std::move(h), s.field_name_, s.is_index_); } signed_size_t PythonHash() const { return absl::Hash<PathSegment>()(*this); } std::string DebugString() const; private: std::string field_name_; bool is_index_; }; inline bool operator==(const PathSegment& a, const PathSegment& b) { return std::pair(a.FieldName(), a.IsIndex()) == std::pair(b.FieldName(), b.IsIndex()); } inline bool operator!=(const PathSegment& a, const PathSegment& b) { return std::pair(a.FieldName(), a.IsIndex()) != std::pair(b.FieldName(), b.IsIndex()); } inline bool operator<(const PathSegment& a, const PathSegment& b) { return std::pair(a.FieldName(), a.IsIndex()) < std::pair(b.FieldName(), b.IsIndex()); } class ColumnPath; class TablePath { public: TablePath() = default; explicit TablePath(std::vector<PathSegment> path_segments) : path_segments_(std::move(path_segments)) {} explicit TablePath(absl::string_view name, bool is_index = false) : TablePath({PathSegment(name, is_index)}) {} TablePath Child(PathSegment path_segment) const& { std::vector<PathSegment> segments{path_segments_}; segments.push_back(std::move(path_segment)); return TablePath{std::move(segments)}; } TablePath Child(PathSegment path_segment) && { path_segments_.push_back(std::move(path_segment)); return TablePath{std::move(path_segments_)}; } TablePath Child(absl::string_view name, bool is_index = false) const& { return this->Child(PathSegment(name, is_index)); } TablePath Child(absl::string_view name, bool is_index = false) && { return std::move(*this).Child(PathSegment(name, is_index)); } TablePath Child(const TablePath& suffix) const { TablePath ret = *this; for (const PathSegment& path_segment : suffix.path_segments_) { ret = std::move(ret).Child(path_segment); } return ret; } ColumnPath Column(PathSegment path_segment) const; ColumnPath Column(absl::string_view name, bool is_index = false) const; ColumnPath Column(const ColumnPath& column) const; ColumnPath Size(absl::string_view name) const; ColumnPath Size(const TablePath& child) const; TablePath MapKeys() const { return Child("@key", false); } TablePath MapValues() const { return Child("@value", false); } const std::vector<PathSegment>& PathSegments() const { return path_segments_; } std::string FullName() const; std::optional<TablePath> ParentIndexPath() const; absl::StatusOr<TablePath> RemovePrefix(const TablePath& prefix) const; template <typename H> friend H AbslHashValue(H h, const TablePath& t) { return H::combine(std::move(h), t.path_segments_); } signed_size_t PythonHash() const { return absl::Hash<TablePath>()(*this); } std::string DebugString() const; private: std::vector<PathSegment> path_segments_; }; class ColumnPath { public: ColumnPath() = default; explicit ColumnPath(std::vector<PathSegment> path_segments) : path_segments_(std::move(path_segments)) {} explicit ColumnPath(absl::string_view name, bool is_index = false) : ColumnPath({PathSegment(name, is_index)}) {} const std::vector<PathSegment>& PathSegments() const { return path_segments_; } std::string FullName() const; TablePath ParentIndexPath() const; absl::StatusOr<ColumnPath> RemovePrefix(const TablePath& prefix) const; std::string DebugString() const; template <typename H> friend H AbslHashValue(H h, const ColumnPath& c) { return H::combine(std::move(h), c.FullName()); } signed_size_t PythonHash() const { return absl::Hash<ColumnPath>()(*this); } friend std::ostream& operator<<(std::ostream& stream, const ColumnPath& path) { stream << path.DebugString(); return stream; } private: std::vector<PathSegment> path_segments_; }; inline bool operator==(const TablePath& a, const TablePath& b) { return a.PathSegments() == b.PathSegments(); } inline bool operator!=(const TablePath& a, const TablePath& b) { return a.PathSegments() != b.PathSegments(); } inline bool operator<(const TablePath& a, const TablePath& b) { return a.PathSegments() < b.PathSegments(); } inline bool operator==(const ColumnPath& a, const ColumnPath& b) { return a.PathSegments() == b.PathSegments(); } inline bool operator!=(const ColumnPath& a, const ColumnPath& b) { return a.PathSegments() != b.PathSegments(); } inline bool operator<(const ColumnPath& a, const ColumnPath& b) { return a.PathSegments() < b.PathSegments(); } } #endif #include "arolla/naming/table.h" #include <cstddef> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/util/status_macros_backport.h" namespace arolla::naming { namespace { std::string FormatSegments(const std::vector<PathSegment>& segments, bool show_index_markers) { std::string ret; for (const PathSegment& segment : segments) { ret += '/'; ret += segment.FieldName(); if (show_index_markers && segment.IsIndex()) { ret += std::string(kIndexMarker); } } return ret; } } std::string PathSegment::DebugString() const { return absl::StrFormat("PathSegment(\"%s\", is_index=%s)", field_name_, is_index_ ? "True" : "False"); } ColumnPath TablePath::Column(PathSegment segment) const { std::vector<PathSegment> segments{path_segments_}; segments.emplace_back(std::move(segment)); return ColumnPath(std::move(segments)); } ColumnPath TablePath::Column(absl::string_view name, bool is_index) const { return Column(PathSegment(name, is_index)); } ColumnPath TablePath::Column(const ColumnPath& column) const { std::vector<PathSegment> segments; segments.reserve(path_segments_.size() + column.PathSegments().size()); for (const PathSegment& path_segment : path_segments_) { segments.push_back(path_segment); } for (const PathSegment& path_segment : column.PathSegments()) { segments.push_back(path_segment); } return ColumnPath(std::move(segments)); } ColumnPath TablePath::Size(absl::string_view name) const { return name.empty() ? Column(kSizeColumnName) : Child(name).Column(kSizeColumnName); } ColumnPath TablePath::Size(const TablePath& child) const { return Child(child).Column(kSizeColumnName); } std::string TablePath::FullName() const { return FormatSegments(path_segments_, false); } std::string ColumnPath::FullName() const { return FormatSegments(path_segments_, false); } std::string TablePath::DebugString() const { return absl::StrFormat("TablePath(\"%s\")", FormatSegments(path_segments_, true)); } std::string ColumnPath::DebugString() const { return absl::StrFormat("ColumnPath(\"%s\")", FormatSegments(path_segments_, true)); } std::optional<TablePath> TablePath::ParentIndexPath() const { std::vector<PathSegment> segments{path_segments_}; if (segments.empty()) { return std::nullopt; } if (segments.back().IsIndex()) { segments.pop_back(); } while (!segments.empty() && !segments.back().IsIndex()) { segments.pop_back(); } return TablePath(std::move(segments)); } TablePath ColumnPath::ParentIndexPath() const { std::vector<PathSegment> segments = {path_segments_}; while (!segments.empty() && !segments.back().IsIndex()) { segments.pop_back(); } return TablePath(std::move(segments)); } namespace { absl::StatusOr<std::vector<PathSegment>> RemovePrefixSegments( const std::vector<PathSegment>& path_segments, const TablePath& prefix) { absl::Span<const PathSegment> segs = absl::MakeSpan(path_segments); const size_t prefix_len = prefix.PathSegments().size(); if (segs.subspan(0, prefix_len) != absl::MakeSpan(prefix.PathSegments())) { return absl::InvalidArgumentError( absl::StrFormat("%s must be a prefix of %s", prefix.DebugString(), FormatSegments(path_segments, true))); } absl::Span<const PathSegment> suffix = segs.subspan(prefix_len); return std::vector<PathSegment>(suffix.begin(), suffix.end()); } } absl::StatusOr<TablePath> TablePath::RemovePrefix( const TablePath& prefix) const { ASSIGN_OR_RETURN(std::vector<PathSegment> suffix, RemovePrefixSegments(PathSegments(), prefix)); return TablePath(std::move(suffix)); } absl::StatusOr<ColumnPath> ColumnPath::RemovePrefix( const TablePath& prefix) const { ASSIGN_OR_RETURN(std::vector<PathSegment> suffix, RemovePrefixSegments(PathSegments(), prefix)); return ColumnPath(std::move(suffix)); } }
#include "arolla/naming/table.h" #include <optional> #include <sstream> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "arolla/util/testing/status_matchers_backport.h" using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; namespace arolla::naming { namespace { TEST(Field, simple) { EXPECT_EQ(FieldAccess("aaa"), "aaa"); EXPECT_EQ(MapAccess("dict", "zz"), "dict[\"zz\"]"); EXPECT_EQ(ArrayAccess("lst", 3), "lst[3]"); EXPECT_EQ(ProtoExtensionAccess("package.bar"), "Ext::package.bar"); } TEST(PathSegment, simple) { PathSegment seg("foo", true); EXPECT_EQ(seg.FieldName(), "foo"); EXPECT_TRUE(seg.IsIndex()); EXPECT_EQ(seg, PathSegment("foo", true)); EXPECT_NE(seg, PathSegment("bar", true)); EXPECT_NE(seg.PythonHash(), PathSegment("bar", true).PythonHash()); EXPECT_EQ(seg.DebugString(), "PathSegment(\"foo\", is_index=True)"); } TEST(TablePath, simple) { TablePath scalar; EXPECT_EQ(scalar.FullName(), ""); TablePath query("query"); EXPECT_EQ(query.FullName(), "/query"); TablePath experiment = scalar.Child("exp"); EXPECT_EQ(experiment.FullName(), "/exp"); TablePath doc = query.Child("docs"); EXPECT_EQ(doc.FullName(), "/query/docs"); TablePath token = doc.Child("details").Child("token"); EXPECT_EQ(token.FullName(), "/query/docs/details/token"); TablePath term = query.Child("query_details").Child("terms"); EXPECT_EQ(term.FullName(), "/query/query_details/terms"); EXPECT_EQ(term.Child(doc).FullName(), "/query/query_details/terms/query/docs"); EXPECT_EQ(term.Child(scalar).FullName(), "/query/query_details/terms"); EXPECT_EQ(scalar.Child(scalar).FullName(), ""); } TEST(ColumnPath, simple) { EXPECT_EQ(ColumnPath("exp_id").FullName(), "/exp_id"); TablePath query("query"); EXPECT_EQ(query.Column("query_id").FullName(), "/query/query_id"); EXPECT_EQ(query.Child("docs").Child("doc_id").Column("id").FullName(), "/query/docs/doc_id/id"); EXPECT_EQ(query.Column(TablePath("query_details").Column("abc")).FullName(), "/query/query_details/abc"); EXPECT_EQ(query.Child("docs").Size("doc_id").FullName(), "/query/docs/doc_id/@size"); EXPECT_EQ( query.Child("docs").Size(TablePath("title").Child("terms")).FullName(), "/query/docs/title/terms/@size"); EXPECT_EQ(TablePath().Size("").FullName(), "/@size"); EXPECT_EQ(TablePath().Size(TablePath()).FullName(), "/@size"); EXPECT_EQ(query.Child("docs").Child("doc_id").MapKeys().FullName(), "/query/docs/doc_id/@key"); EXPECT_EQ(query.Child("docs").Child("doc_id").MapValues().FullName(), "/query/docs/doc_id/@value"); } TEST(TablePath, comparison) { EXPECT_EQ(TablePath("foo").Child("bar"), TablePath("foo").Child("bar")); EXPECT_NE(TablePath("foo").Child("bar"), TablePath("foo").Child("baz")); EXPECT_NE(TablePath("foo").Child("bar", false), TablePath("foo").Child("bar", true)); EXPECT_LT(TablePath("foo").Child("bar", false), TablePath("foo").Child("bar", true)); } TEST(ColumnPath, comparison) { EXPECT_EQ(TablePath("foo").Column("bar"), TablePath("foo").Column(PathSegment{"bar", false})); EXPECT_NE(TablePath("foo").Column("bar"), ColumnPath()); EXPECT_NE(TablePath("foo").Column("bar"), ColumnPath("foo/bar")); EXPECT_NE(TablePath("foo").Column("bar"), TablePath("foo").Column("baz")); EXPECT_NE(TablePath("foo").Column(PathSegment{"bar", true}), TablePath("foo").Column(PathSegment{"bar", false})); } TEST(TablePath, ParentIndexPath) { EXPECT_EQ(TablePath().ParentIndexPath(), std::nullopt); EXPECT_EQ(TablePath("foo").ParentIndexPath(), TablePath()); EXPECT_EQ(TablePath("foo").Child("bar").ParentIndexPath(), TablePath()); TablePath queries("queries", true); EXPECT_EQ(queries.ParentIndexPath(), TablePath()); EXPECT_EQ(queries.Child("docs", true).ParentIndexPath(), queries); EXPECT_EQ(queries.Child("first_doc", false).ParentIndexPath(), queries); } TEST(ColumnPath, ParentIndexPath) { EXPECT_EQ(ColumnPath("foo").ParentIndexPath(), TablePath()); EXPECT_EQ(TablePath("foo").Column("bar").ParentIndexPath(), TablePath()); TablePath queries("queries", true); EXPECT_EQ(queries.Column("query_text").ParentIndexPath(), queries); EXPECT_EQ(queries.Child("t").Column("c").ParentIndexPath(), queries); ColumnPath repeated_int_field = queries.Column("numbers", true); EXPECT_EQ(repeated_int_field.ParentIndexPath().PathSegments(), (std::vector<PathSegment>{{"queries", true}, {"numbers", true}})); } TEST(TablePath, RemovePrefix) { TablePath table_path = TablePath().Child("foo", true).Child("bar").Child("baz"); EXPECT_THAT(table_path.RemovePrefix(TablePath().Child("foo", true)), IsOkAndHolds(TablePath().Child("bar").Child("baz"))); EXPECT_THAT(table_path.RemovePrefix(TablePath()), IsOkAndHolds(table_path)); EXPECT_THAT(table_path.RemovePrefix(table_path), IsOkAndHolds(TablePath())); } TEST(ColumnPath, RemovePrefix) { ColumnPath column_path = TablePath().Child("foo", true).Child("bar").Column("baz"); EXPECT_THAT(column_path.RemovePrefix(TablePath().Child("foo", true)), IsOkAndHolds(TablePath().Child("bar").Column("baz"))); EXPECT_THAT(column_path.RemovePrefix(TablePath()), IsOkAndHolds(column_path)); EXPECT_THAT(column_path.RemovePrefix(TablePath().Child("fo", true)), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT(column_path.RemovePrefix( TablePath().Child("a").Child("b").Child("c").Child("d")), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT(column_path.RemovePrefix(TablePath().Child("foo", false)), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST(TablePath, DebugString) { EXPECT_EQ(TablePath("foo").Child("bar", true).Child("baz").DebugString(), "TablePath(\"/foo/bar[:]/baz\")"); } TEST(ColumnPath, DebugString) { EXPECT_EQ(TablePath("foo").Child("bar", true).Column("baz").DebugString(), "ColumnPath(\"/foo/bar[:]/baz\")"); std::stringstream ss; ss << TablePath("foo").Child("bar", true).Column("baz"); EXPECT_EQ(ss.str(), "ColumnPath(\"/foo/bar[:]/baz\")"); } TEST(PathSegment, PythonHash) { EXPECT_EQ(PathSegment("foo", true).PythonHash(), PathSegment("foo", true).PythonHash()); EXPECT_NE(PathSegment("foo", true).PythonHash(), PathSegment("foo", false).PythonHash()); EXPECT_NE(PathSegment("foo", true).PythonHash(), PathSegment("bar", true).PythonHash()); EXPECT_NE(PathSegment("foo", true).PythonHash(), TablePath("foo", true).PythonHash()); EXPECT_NE(PathSegment("foo", true).PythonHash(), ColumnPath("foo", true).PythonHash()); EXPECT_NE(TablePath("foo", true).PythonHash(), ColumnPath("foo", true).PythonHash()); } } }
2,343
#ifndef AROLLA_NAMING_PROTOPATH_ID_H_ #define AROLLA_NAMING_PROTOPATH_ID_H_ #include <string> #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "arolla/naming/table.h" namespace arolla::naming { std::string TablePathToProtopathId(const TablePath& table_path); std::string ColumnPathToProtopathId(const ColumnPath& column_path); absl::StatusOr<TablePath> TablePathFromProtopathId( absl::string_view protopath_id); absl::StatusOr<ColumnPath> ColumnPathFromProtopathId( absl::string_view protopath_id); } #endif #include "arolla/naming/protopath_id.h" #include <cstddef> #include <string> #include <utility> #include <vector> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include "absl/strings/strip.h" #include "arolla/naming/table.h" #include "arolla/util/status_macros_backport.h" namespace arolla::naming { namespace { std::string FormatAsProtopathId(const std::vector<PathSegment>& segments) { return absl::StrJoin(segments, "", [](std::string* ret, const PathSegment& segment) { absl::StrAppend(ret, "/", segment.FieldName(), segment.IsIndex() ? kIndexMarker : ""); }); } PathSegment ParsePathSegment(absl::string_view segment_name) { bool is_index = absl::ConsumeSuffix(&segment_name, kIndexMarker); return PathSegment(segment_name, is_index); } absl::StatusOr<std::vector<PathSegment>> ParseProtopathId( absl::string_view protopath_id) { std::vector<PathSegment> parsed; if (protopath_id.empty()) { return parsed; } if (protopath_id[0] != '/') { return absl::InvalidArgumentError( absl::StrFormat("ProtopathId (%s) formatted incorrectly. " "Must start with a slash (/).", protopath_id)); } protopath_id.remove_prefix(1); while (!protopath_id.empty()) { const size_t segment_len = protopath_id.find_first_of('/'); const absl::string_view segment = protopath_id.substr(0, segment_len); parsed.push_back(ParsePathSegment(segment)); if (segment_len == std::string::npos) { break; } protopath_id.remove_prefix(segment_len + 1); } return parsed; } } std::string TablePathToProtopathId(const TablePath& table_path) { return FormatAsProtopathId(table_path.PathSegments()); } std::string ColumnPathToProtopathId(const ColumnPath& column_path) { return FormatAsProtopathId(column_path.PathSegments()); } absl::StatusOr<TablePath> TablePathFromProtopathId( absl::string_view protopath_id) { ASSIGN_OR_RETURN(auto segments, ParseProtopathId(protopath_id)); return TablePath(std::move(segments)); } absl::StatusOr<ColumnPath> ColumnPathFromProtopathId( absl::string_view protopath_id) { ASSIGN_OR_RETURN(auto segments, ParseProtopathId(protopath_id)); return ColumnPath(std::move(segments)); } }
#include "arolla/naming/protopath_id.h" #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "arolla/naming/table.h" #include "arolla/util/status_macros_backport.h" namespace arolla::naming { namespace { TEST(Formatter, Format) { TablePath root; EXPECT_EQ(TablePathToProtopathId(root), ""); EXPECT_EQ(TablePathToProtopathId(root.Child("foo", true).Child("bar", false)), "/foo[:]/bar"); EXPECT_EQ( ColumnPathToProtopathId( root.Child("foo", true).Child("bar", false).Column("baz", true)), "/foo[:]/bar/baz[:]"); } TEST(Formatter, FormatSizeColumn) { TablePath root; EXPECT_EQ(ColumnPathToProtopathId( root.Child("foo", true).Child("bar", false).Size("baz")), "/foo[:]/bar/baz/@size"); } TEST(Parser, ParseRootTablePath) { ASSERT_OK_AND_ASSIGN(TablePath root_path, TablePathFromProtopathId("/")); EXPECT_EQ(root_path.FullName(), ""); ASSERT_OK_AND_ASSIGN(root_path, TablePathFromProtopathId("")); EXPECT_EQ(root_path.FullName(), ""); } TEST(Parser, ParseInvalidTablePath) { EXPECT_FALSE(TablePathFromProtopathId("invalid/path").ok()); } TEST(Parser, ParseNestedTablePath) { ASSERT_OK_AND_ASSIGN(TablePath nested_path, TablePathFromProtopathId("/query/doc")); EXPECT_EQ(nested_path.FullName(), "/query/doc"); ASSERT_OK_AND_ASSIGN(nested_path, TablePathFromProtopathId("/query/doc/")); EXPECT_EQ(nested_path.FullName(), "/query/doc"); ASSERT_OK_AND_ASSIGN(nested_path, TablePathFromProtopathId("/query")); EXPECT_EQ(nested_path.FullName(), "/query"); ASSERT_OK_AND_ASSIGN(nested_path, TablePathFromProtopathId("/query/")); EXPECT_EQ(nested_path.FullName(), "/query"); } TEST(Parser, ParseNestedColumnPath) { ASSERT_OK_AND_ASSIGN(ColumnPath nested_path, ColumnPathFromProtopathId("/query[:]/query_text")); EXPECT_EQ(nested_path.PathSegments(), (std::vector<PathSegment>{{"query", true}, {"query_text", false}})); ASSERT_OK_AND_ASSIGN(nested_path, ColumnPathFromProtopathId("/query/query_text")); EXPECT_EQ( nested_path.PathSegments(), (std::vector<PathSegment>{{"query", false}, {"query_text", false}})); ASSERT_OK_AND_ASSIGN(nested_path, ColumnPathFromProtopathId("/query_count")); EXPECT_EQ(nested_path.PathSegments(), (std::vector<PathSegment>{{"query_count", false}})); } TEST(Parser, ParseTablePathWithIndexMarker) { ASSERT_OK_AND_ASSIGN(TablePath path, TablePathFromProtopathId("/query/doc[:]/url")); EXPECT_EQ(path.PathSegments(), (std::vector<PathSegment>{ {"query", false}, {"doc", true}, {"url", false}})); } } }
2,344
#ifndef AROLLA_NAMING_POLICY_H_ #define AROLLA_NAMING_POLICY_H_ #include <string> #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "arolla/naming/table.h" namespace arolla::naming { class PolicyImpl; class Policy { public: explicit Policy(const PolicyImpl& policy_impl) : policy_impl_(&policy_impl) {} const std::string& Name() const; std::string Format(const ColumnPath& path) const; std::string Format(const TablePath& path) const; private: const PolicyImpl* policy_impl_; }; Policy DefaultPolicy(); constexpr absl::string_view kDefaultPolicyName = "default"; Policy DoubleUnderscorePolicy(); constexpr absl::string_view kDoubleUnderscorePolicyName = "double_underscore"; Policy SingleUnderscorePolicy(); constexpr absl::string_view kSingleUnderscorePolicyName = "single_underscore"; Policy LeafOnlyPolicy(); constexpr absl::string_view kLeafOnlyPolicyName = "leaf_only"; Policy ProtopathIdPolicy(); constexpr absl::string_view kProtopathIdPolicyName = "protopath_id"; Policy GoogleSQLPolicy(); constexpr absl::string_view kGoogleSQLPolicyName = "googlesql"; absl::StatusOr<Policy> GetPolicy(absl::string_view policy_name); } #endif #include "arolla/naming/policy.h" #include <string> #include <vector> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/ascii.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/strings/str_join.h" #include "absl/strings/str_replace.h" #include "absl/strings/string_view.h" #include "absl/strings/strip.h" #include "arolla/naming/protopath_id.h" #include "arolla/naming/table.h" #include "arolla/util/indestructible.h" namespace arolla::naming { class PolicyImpl { public: explicit PolicyImpl(absl::string_view policy_name) : policy_name_(policy_name) {} virtual ~PolicyImpl() = default; virtual std::string Format(const ColumnPath& path) const = 0; virtual std::string Format(const TablePath& path) const = 0; const std::string& Name() const { return policy_name_; } private: std::string policy_name_; }; const std::string& Policy::Name() const { return policy_impl_->Name(); } std::string Policy::Format(const ColumnPath& path) const { return policy_impl_->Format(path); } std::string Policy::Format(const TablePath& path) const { return policy_impl_->Format(path); } namespace { class DefaultPolicyImpl : public PolicyImpl { public: DefaultPolicyImpl() : PolicyImpl(kDefaultPolicyName) {} std::string Format(const TablePath& table_path) const override { return std::string(table_path.FullName()); } std::string Format(const ColumnPath& column_path) const override { return std::string(column_path.FullName()); } }; class DoubleUnderscorePolicyImpl : public PolicyImpl { public: DoubleUnderscorePolicyImpl() : PolicyImpl(kDoubleUnderscorePolicyName) {} std::string Format(const TablePath& table_path) const override { return Format(table_path.PathSegments()); } std::string Format(const ColumnPath& column_path) const override { return Format(column_path.PathSegments()); } private: static std::string MangleExtensionFieldName(absl::string_view field_name) { if (absl::ConsumePrefix(&field_name, kExtensionFieldPrefix)) { return absl::StrReplaceAll(absl::AsciiStrToLower(field_name), {{".", "_"}}); } else { return std::string(field_name); } } std::string Format(const std::vector<PathSegment>& segments) const { return absl::StrJoin( segments, "__", [](std::string* ret, const PathSegment& segment) { std::string field_name = absl::StrReplaceAll(segment.FieldName(), {{"/", "__"}}); absl::StrAppend(ret, MangleExtensionFieldName(field_name)); }); } }; class SingleUnderscorePolicyImpl : public PolicyImpl { public: SingleUnderscorePolicyImpl() : PolicyImpl(kSingleUnderscorePolicyName) {} std::string Format(const TablePath& table_path) const override { return Reformat(table_path.FullName()); } std::string Format(const ColumnPath& column_path) const override { return Reformat(column_path.FullName()); } private: std::string Reformat(absl::string_view name) const { if (name.empty()) return ""; return absl::StrReplaceAll(name.substr(1), {{"/", "_"}}); } }; class LeafOnlyPolicyImpl : public PolicyImpl { public: LeafOnlyPolicyImpl() : PolicyImpl(kLeafOnlyPolicyName) {} std::string Format(const TablePath& table_path) const override { return Reformat(table_path.FullName()); } std::string Format(const ColumnPath& column_path) const override { return Reformat(column_path.FullName()); } private: std::string Reformat(absl::string_view name) const { return std::string(absl::EndsWith(name, "@size") ? name : name.substr(name.find_last_of('/') + 1)); } }; class ProtopathIdPolicyImpl : public PolicyImpl { public: ProtopathIdPolicyImpl() : PolicyImpl(kProtopathIdPolicyName) {} std::string Format(const TablePath& table_path) const override { return TablePathToProtopathId(table_path); } std::string Format(const ColumnPath& column_path) const override { return ColumnPathToProtopathId(column_path); } }; class GoogleSQLPolicyImpl : public PolicyImpl { public: GoogleSQLPolicyImpl() : PolicyImpl(kGoogleSQLPolicyName) {} std::string Format(const TablePath& table_path) const override { return Format(table_path.PathSegments()); } std::string Format(const ColumnPath& column_path) const override { return Format(column_path.PathSegments()); } private: std::string Format(const std::vector<PathSegment>& segments) const { return absl::StrJoin( segments, ".", [](std::string* ret, const PathSegment& segment) { absl::string_view field_name = segment.FieldName(); if (absl::ConsumePrefix(&field_name, kExtensionFieldPrefix)) { absl::StrAppend(ret, "(", field_name, ")"); } else { absl::StrAppend(ret, field_name); } }); } }; } Policy DefaultPolicy() { static const Indestructible<DefaultPolicyImpl> impl; return Policy{*impl}; } Policy DoubleUnderscorePolicy() { static const Indestructible<DoubleUnderscorePolicyImpl> impl; return Policy{*impl}; } Policy SingleUnderscorePolicy() { static const Indestructible<SingleUnderscorePolicyImpl> impl; return Policy{*impl}; } Policy LeafOnlyPolicy() { static const Indestructible<LeafOnlyPolicyImpl> impl; return Policy{*impl}; } Policy ProtopathIdPolicy() { static const Indestructible<ProtopathIdPolicyImpl> impl; return Policy{*impl}; } Policy GoogleSQLPolicy() { static const Indestructible<GoogleSQLPolicyImpl> impl; return Policy{*impl}; } absl::StatusOr<Policy> GetPolicy(absl::string_view policy_name) { if (policy_name == kDefaultPolicyName) { return DefaultPolicy(); } if (policy_name == kDoubleUnderscorePolicyName) { return DoubleUnderscorePolicy(); } if (policy_name == kSingleUnderscorePolicyName) { return SingleUnderscorePolicy(); } if (policy_name == kLeafOnlyPolicyName) { return LeafOnlyPolicy(); } if (policy_name == kProtopathIdPolicyName) { return ProtopathIdPolicy(); } if (policy_name == kGoogleSQLPolicyName) { return GoogleSQLPolicy(); } return absl::InvalidArgumentError( absl::StrFormat("undefined naming policy: %s", policy_name)); } }
#include "arolla/naming/policy.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "arolla/naming/table.h" #include "arolla/util/testing/status_matchers_backport.h" using ::arolla::testing::StatusIs; namespace arolla::naming { namespace { TEST(Policy, name) { EXPECT_EQ(DefaultPolicy().Name(), "default"); EXPECT_EQ(DoubleUnderscorePolicy().Name(), "double_underscore"); } TEST(Policy, format) { TablePath root; EXPECT_EQ(DefaultPolicy().Format(root), ""); EXPECT_EQ(DoubleUnderscorePolicy().Format(root), ""); EXPECT_EQ(SingleUnderscorePolicy().Format(root), ""); EXPECT_EQ(LeafOnlyPolicy().Format(root), ""); EXPECT_EQ(ProtopathIdPolicy().Format(root), ""); EXPECT_EQ(GoogleSQLPolicy().Format(root), ""); TablePath query("query"); EXPECT_EQ(DefaultPolicy().Format(query), "/query"); EXPECT_EQ(DoubleUnderscorePolicy().Format(query), "query"); EXPECT_EQ(SingleUnderscorePolicy().Format(query), "query"); EXPECT_EQ(LeafOnlyPolicy().Format(query), "query"); EXPECT_EQ(ProtopathIdPolicy().Format(query), "/query"); EXPECT_EQ(GoogleSQLPolicy().Format(query), "query"); TablePath doc = query.Child("docs", true); EXPECT_EQ(DefaultPolicy().Format(doc), "/query/docs"); EXPECT_EQ(DoubleUnderscorePolicy().Format(doc), "query__docs"); EXPECT_EQ(SingleUnderscorePolicy().Format(doc), "query_docs"); EXPECT_EQ(LeafOnlyPolicy().Format(doc), "docs"); EXPECT_EQ(ProtopathIdPolicy().Format(doc), "/query/docs[:]"); EXPECT_EQ(GoogleSQLPolicy().Format(doc), "query.docs"); ColumnPath quality = doc.Column("quality"); EXPECT_EQ(DefaultPolicy().Format(quality), "/query/docs/quality"); EXPECT_EQ(DoubleUnderscorePolicy().Format(quality), "query__docs__quality"); EXPECT_EQ(SingleUnderscorePolicy().Format(quality), "query_docs_quality"); EXPECT_EQ(LeafOnlyPolicy().Format(quality), "quality"); EXPECT_EQ(ProtopathIdPolicy().Format(quality), "/query/docs[:]/quality"); EXPECT_EQ(GoogleSQLPolicy().Format(quality), "query.docs.quality"); ColumnPath terms_size = doc.Size("terms"); EXPECT_EQ(DefaultPolicy().Format(terms_size), "/query/docs/terms/@size"); EXPECT_EQ(DoubleUnderscorePolicy().Format(terms_size), "query__docs__terms__@size"); EXPECT_EQ(SingleUnderscorePolicy().Format(terms_size), "query_docs_terms_@size"); EXPECT_EQ(LeafOnlyPolicy().Format(terms_size), "/query/docs/terms/@size"); EXPECT_EQ(ProtopathIdPolicy().Format(terms_size), "/query/docs[:]/terms/@size"); EXPECT_EQ(GoogleSQLPolicy().Format(terms_size), "query.docs.terms.@size"); TablePath ext = doc.Child(ProtoExtensionAccess("foo_pkg.Bar.baz_ext")); EXPECT_EQ(DefaultPolicy().Format(ext), "/query/docs/Ext::foo_pkg.Bar.baz_ext"); EXPECT_EQ(DoubleUnderscorePolicy().Format(ext), "query__docs__foo_pkg_bar_baz_ext"); EXPECT_EQ(SingleUnderscorePolicy().Format(ext), "query_docs_Ext::foo_pkg.Bar.baz_ext"); EXPECT_EQ(LeafOnlyPolicy().Format(ext), "Ext::foo_pkg.Bar.baz_ext"); EXPECT_EQ(ProtopathIdPolicy().Format(ext), "/query/docs[:]/Ext::foo_pkg.Bar.baz_ext"); EXPECT_EQ(GoogleSQLPolicy().Format(ext), "query.docs.(foo_pkg.Bar.baz_ext)"); } TEST(Policy, get_policy) { EXPECT_EQ(GetPolicy("default").value().Name(), "default"); EXPECT_EQ(GetPolicy("double_underscore").value().Name(), "double_underscore"); EXPECT_EQ(GetPolicy("single_underscore").value().Name(), "single_underscore"); EXPECT_EQ(GetPolicy("leaf_only").value().Name(), "leaf_only"); EXPECT_THAT(GetPolicy("unknown-policy-XYZ"), StatusIs(absl::StatusCode::kInvalidArgument, "undefined naming policy: unknown-policy-XYZ")); } } }
2,345
#ifndef AROLLA_QTYPE_SHAPE_QTYPE_H_ #define AROLLA_QTYPE_SHAPE_QTYPE_H_ #include <string> #include <utility> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/simple_qtype.h" #include "arolla/util/api.h" #include "arolla/util/fingerprint.h" #include "arolla/util/meta.h" #include "arolla/util/repr.h" namespace arolla { class AROLLA_API ShapeQType : public SimpleQType { public: virtual absl::StatusOr<QTypePtr> WithValueQType( QTypePtr value_qtype) const = 0; virtual QTypePtr presence_qtype() const = 0; protected: template <typename T> ShapeQType(meta::type<T> type, std::string type_name) : SimpleQType(type, std::move(type_name)) {} }; inline bool IsShapeQType(const QType* qtype) { return dynamic_cast<const ShapeQType*>(qtype) != nullptr; } inline absl::StatusOr<const ShapeQType*> ToShapeQType(QTypePtr qtype) { const ShapeQType* shape_qtype = dynamic_cast<const ShapeQType*>(qtype); if (!shape_qtype) { return absl::InvalidArgumentError( absl::StrFormat("expected a shape, got %s", qtype->name())); } return shape_qtype; } struct AROLLA_API ScalarShape {}; inline bool operator==(ScalarShape, ScalarShape) { return true; } inline bool operator!=(ScalarShape, ScalarShape) { return false; } struct AROLLA_API OptionalScalarShape {}; inline bool operator==(OptionalScalarShape, OptionalScalarShape) { return true; } inline bool operator!=(OptionalScalarShape, OptionalScalarShape) { return false; } AROLLA_DECLARE_QTYPE(ScalarShape); AROLLA_DECLARE_REPR(ScalarShape); AROLLA_DECLARE_FINGERPRINT_HASHER_TRAITS(ScalarShape); AROLLA_DECLARE_QTYPE(OptionalScalarShape); AROLLA_DECLARE_REPR(OptionalScalarShape); AROLLA_DECLARE_FINGERPRINT_HASHER_TRAITS(OptionalScalarShape); } #endif #include "arolla/qtype/shape_qtype.h" #include <string> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/util/fingerprint.h" #include "arolla/util/indestructible.h" #include "arolla/util/meta.h" #include "arolla/util/repr.h" #include "arolla/util/unit.h" #include "arolla/util/status_macros_backport.h" namespace arolla { namespace { absl::Status EnsureIsBaseType(QTypePtr qtype) { return IsScalarQType(qtype) || IsOptionalQType(qtype) ? absl::OkStatus() : absl::InvalidArgumentError(absl::StrFormat( "Shape::WithValueQType supports only scalar and " "optional values, got %s", qtype->name())); } class ScalarShapeQType final : public ShapeQType { public: ScalarShapeQType() : ShapeQType(meta::type<ScalarShape>(), "SCALAR_SHAPE") {} absl::StatusOr<QTypePtr> WithValueQType(QTypePtr value_qtype) const final { RETURN_IF_ERROR(EnsureIsBaseType(value_qtype)); return value_qtype; } QTypePtr presence_qtype() const final { return GetQType<Unit>(); } }; class OptionalScalarShapeQType final : public ShapeQType { public: OptionalScalarShapeQType() : ShapeQType(meta::type<OptionalScalarShape>(), "OPTIONAL_SCALAR_SHAPE") { } absl::StatusOr<QTypePtr> WithValueQType(QTypePtr value_qtype) const final { RETURN_IF_ERROR(EnsureIsBaseType(value_qtype)); return ToOptionalQType(value_qtype); } QTypePtr presence_qtype() const final { return GetOptionalQType<Unit>(); } }; } QTypePtr QTypeTraits<ScalarShape>::type() { static const Indestructible<ScalarShapeQType> shape_qtype; return shape_qtype.get(); } QTypePtr QTypeTraits<OptionalScalarShape>::type() { static const Indestructible<OptionalScalarShapeQType> shape_qtype; return shape_qtype.get(); } ReprToken ReprTraits<ScalarShape>::operator()( const ScalarShape& ) const { return ReprToken{"scalar_shape"}; } void FingerprintHasherTraits<ScalarShape>::operator()( FingerprintHasher* hasher, const ScalarShape& ) const { hasher->Combine(absl::string_view("scalar_shape")); } ReprToken ReprTraits<OptionalScalarShape>::operator()( const OptionalScalarShape& ) const { return ReprToken{"optional_scalar_shape"}; } void FingerprintHasherTraits<OptionalScalarShape>::operator()( FingerprintHasher* hasher, const OptionalScalarShape& ) const { hasher->Combine(absl::string_view("optional_scalar_shape")); } }
#include "arolla/qtype/shape_qtype.h" #include <cstdint> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/bytes.h" #include "arolla/util/repr.h" #include "arolla/util/testing/repr_token_eq.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla { namespace { using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::ReprTokenEq; using ::testing::Eq; using ::testing::NotNull; TEST(ShapeQType, ScalarShape) { auto scalar_shape = dynamic_cast<const ShapeQType*>(GetQType<ScalarShape>()); ASSERT_THAT(scalar_shape, NotNull()); EXPECT_THAT(scalar_shape->WithValueQType(GetQType<int64_t>()), IsOkAndHolds(Eq(GetQType<int64_t>()))); EXPECT_THAT(scalar_shape->WithValueQType(GetQType<Bytes>()), IsOkAndHolds(Eq(GetQType<Bytes>()))); EXPECT_THAT(scalar_shape->WithValueQType(GetOptionalQType<int64_t>()), IsOkAndHolds(Eq(GetOptionalQType<int64_t>()))); } TEST(ShapeQType, OptionalScalarShape) { auto optional_shape = dynamic_cast<const ShapeQType*>(GetQType<OptionalScalarShape>()); ASSERT_THAT(optional_shape, NotNull()); EXPECT_THAT(optional_shape->WithValueQType(GetQType<int64_t>()), IsOkAndHolds(Eq(GetOptionalQType<int64_t>()))); EXPECT_THAT(optional_shape->WithValueQType(GetQType<Bytes>()), IsOkAndHolds(Eq(GetOptionalQType<Bytes>()))); EXPECT_THAT(optional_shape->WithValueQType(GetOptionalQType<int64_t>()), IsOkAndHolds(Eq(GetOptionalQType<int64_t>()))); } TEST(ShapeQType, ScalarShapeRepr) { EXPECT_THAT(GenReprToken(ScalarShape{}), ReprTokenEq("scalar_shape")); } TEST(ShapeQType, OptionalScalarShapeRepr) { EXPECT_THAT(GenReprToken(OptionalScalarShape{}), ReprTokenEq("optional_scalar_shape")); } TEST(ShapeQType, TypedValuScalarShapeRepr) { EXPECT_THAT(TypedValue::FromValue(ScalarShape{}).GenReprToken(), ReprTokenEq("scalar_shape")); } TEST(ShapeQType, TypedValueOptionalScalarShapeRepr) { EXPECT_THAT(TypedValue::FromValue(OptionalScalarShape{}).GenReprToken(), ReprTokenEq("optional_scalar_shape")); } TEST(ShapeQType, ScalarShapeFingerprint) { EXPECT_THAT(TypedValue::FromValue(ScalarShape{}).GetFingerprint(), Eq(TypedValue::FromValue(ScalarShape{}).GetFingerprint())); } TEST(ShapeQType, OptionalScalarShapeFingerprint) { EXPECT_THAT( TypedValue::FromValue(OptionalScalarShape{}).GetFingerprint(), Eq(TypedValue::FromValue(OptionalScalarShape{}).GetFingerprint())); } TEST(ShapeQType, IsShapeQType) { EXPECT_TRUE(IsShapeQType(GetQType<OptionalScalarShape>())); EXPECT_FALSE(IsShapeQType(GetQType<int32_t>())); } } }
2,346
#ifndef AROLLA_QTYPE_SLICE_QTYPE_H_ #define AROLLA_QTYPE_SLICE_QTYPE_H_ #include "absl/strings/string_view.h" #include "arolla/qtype/qtype.h" namespace arolla { bool IsSliceQType(const QType* qtype); QTypePtr MakeSliceQType(QTypePtr start, QTypePtr stop, QTypePtr step); absl::string_view GetSliceQTypeSpecializationKey(); } #endif #include "arolla/qtype/slice_qtype.h" #include <memory> #include <string> #include <tuple> #include <utility> #include "absl/base/thread_annotations.h" #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/synchronization/mutex.h" #include "arolla/qtype/derived_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/tuple_qtype.h" #include "arolla/util/fast_dynamic_downcast_final.h" #include "arolla/util/indestructible.h" #include "arolla/util/repr.h" namespace arolla { namespace { std::string SliceQTypeName(QTypePtr start, QTypePtr stop, QTypePtr step) { return absl::StrCat("slice<", JoinTypeNames({start, stop, step}), ">"); } class SliceQType final : public BasicDerivedQType { public: SliceQType(QTypePtr start, QTypePtr stop, QTypePtr step) : BasicDerivedQType(ConstructorArgs{ .name = SliceQTypeName(start, stop, step), .base_qtype = MakeTupleQType({start, stop, step}), .qtype_specialization_key = std::string(GetSliceQTypeSpecializationKey()), }) {} ReprToken UnsafeReprToken(const void* source) const override { return ReprToken{ absl::StrCat("slice", GetBaseQType()->UnsafeReprToken(source).str)}; } }; class SliceQTypeRegistry { public: static SliceQTypeRegistry* instance() { static Indestructible<SliceQTypeRegistry> result; return result.get(); } QTypePtr GetQType(QTypePtr start, QTypePtr stop, QTypePtr step) ABSL_LOCKS_EXCLUDED(lock_) { { absl::ReaderMutexLock guard(&lock_); if (const auto it = registry_.find({start, stop, step}); it != registry_.end()) { return it->second.get(); } } auto slice_qtype = std::make_unique<SliceQType>(start, stop, step); absl::MutexLock guard(&lock_); return registry_.try_emplace({start, stop, step}, std::move(slice_qtype)) .first->second.get(); } private: using RegistryKey = std::tuple<QTypePtr, QTypePtr, QTypePtr>; absl::Mutex lock_; absl::flat_hash_map<RegistryKey, std::unique_ptr<SliceQType>> registry_ ABSL_GUARDED_BY(lock_); }; } bool IsSliceQType(const QType* qtype) { return fast_dynamic_downcast_final<const SliceQType*>(qtype) != nullptr; } QTypePtr MakeSliceQType(QTypePtr start, QTypePtr stop, QTypePtr step) { return SliceQTypeRegistry::instance()->GetQType(start, stop, step); } absl::string_view GetSliceQTypeSpecializationKey() { return "::arolla::SliceQType"; } }
#include "arolla/qtype/slice_qtype.h" #include <cstdint> #include "gtest/gtest.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/derived_qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/tuple_qtype.h" #include "arolla/util/bytes.h" namespace arolla::testing { namespace { TEST(SliceQType, MakeSliceQType) { auto start = GetQType<int32_t>(); auto stop = GetQType<double>(); auto step = GetQType<Bytes>(); auto qtype = MakeSliceQType(start, stop, step); EXPECT_EQ(qtype->name(), "slice<INT32,FLOAT64,BYTES>"); auto derived_qtype_interface = dynamic_cast<const DerivedQTypeInterface*>(qtype); ASSERT_NE(derived_qtype_interface, nullptr); auto tuple_qtype = MakeTupleQType({start, stop, step}); EXPECT_EQ(derived_qtype_interface->GetBaseQType(), tuple_qtype); { auto qtype2 = MakeSliceQType(start, stop, step); EXPECT_EQ(qtype, qtype2); } { auto qtype2 = MakeSliceQType(start, stop, start); EXPECT_EQ(qtype2->name(), "slice<INT32,FLOAT64,INT32>"); EXPECT_NE(qtype, qtype2); } } TEST(SliceQType, IsSliceQType) { auto start = GetQType<int32_t>(); auto stop = GetQType<double>(); auto step = GetQType<Bytes>(); auto tuple_qtype = MakeTupleQType({start, stop, step}); EXPECT_FALSE(IsSliceQType(tuple_qtype)); auto qtype = MakeSliceQType(start, stop, step); EXPECT_TRUE(IsSliceQType(qtype)); } } }
2,347
#ifndef AROLLA_QTYPE_TUPLE_QTYPE_H_ #define AROLLA_QTYPE_TUPLE_QTYPE_H_ #include <initializer_list> #include <string> #include <type_traits> #include "absl/status/statusor.h" #include "absl/types/span.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_ref.h" #include "arolla/qtype/typed_value.h" namespace arolla { bool IsTupleQType(const QType* qtype); QTypePtr MakeTupleQType(absl::Span<const QTypePtr> field_qtypes); TypedValue MakeTuple(absl::Span<const TypedRef> fields); TypedValue MakeTuple(absl::Span<const TypedValue> fields); template <typename... Ts> TypedValue MakeTupleFromFields(const Ts&... fields) { auto typed_fields = std::initializer_list<TypedRef>{[](const auto& field) { using FieldType = std::decay_t<decltype(field)>; if constexpr (std::is_same_v<FieldType, TypedRef>) { return field; } else if constexpr (std::is_same_v<FieldType, TypedValue>) { return field.AsRef(); } else { return TypedRef::FromValue(field); } }(fields)...}; return MakeTuple(absl::Span<const TypedRef>(typed_fields)); } bool IsNamedTupleQType(const QType* qtype); absl::StatusOr<QTypePtr> MakeNamedTupleQType( absl::Span<const std::string> field_names, QTypePtr tuple_qtype); } #endif #include "arolla/qtype/tuple_qtype.h" #include <algorithm> #include <cstddef> #include <cstdint> #include <memory> #include <optional> #include <sstream> #include <string> #include <utility> #include <vector> #include "absl/base/thread_annotations.h" #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "absl/log/check.h" #include "absl/log/log.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "absl/synchronization/mutex.h" #include "absl/types/span.h" #include "arolla/memory/frame.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/derived_qtype.h" #include "arolla/qtype/named_field_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_ref.h" #include "arolla/qtype/typed_slot.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/fast_dynamic_downcast_final.h" #include "arolla/util/fingerprint.h" #include "arolla/util/indestructible.h" #include "arolla/util/repr.h" #include "arolla/util/string.h" #include "arolla/util/unit.h" namespace arolla { namespace { class Tuple {}; class TupleQType final : public QType { public: static std::unique_ptr<TupleQType> Make( absl::Span<const QTypePtr> field_qtypes) { FrameLayout::Builder layout_builder; std::vector<TypedSlot> fields; fields.reserve(field_qtypes.size()); for (auto field_qtype : field_qtypes) { fields.push_back(AddSlot(field_qtype, &layout_builder)); } bool needTupleTag = true; for (const auto& field : fields) { if (field.byte_offset() == 0 && field.GetType()->type_layout().HasField(0, typeid(Tuple))) { needTupleTag = false; break; } } if (needTupleTag) { auto status = layout_builder.RegisterUnsafeSlot(0, 0, typeid(Tuple)); if (!status.ok()) { LOG(FATAL) << status; } } return std::make_unique<TupleQType>( field_qtypes, std::move(layout_builder).Build(), std::move(fields)); } TupleQType(absl::Span<const QTypePtr> field_qtypes, FrameLayout&& layout, std::vector<TypedSlot>&& fields) : QType(ConstructorArgs{ .name = absl::StrCat("tuple<", JoinTypeNames(field_qtypes), ">"), .type_info = typeid(Tuple), .type_layout = std::move(layout), .type_fields = std::move(fields), .qtype_specialization_key = "::arolla::TupleQType", }), field_qtypes_(field_qtypes.begin(), field_qtypes.end()) {} absl::Span<const QTypePtr> field_qtypes() const { return field_qtypes_; } void UnsafeCopy(const void* source, void* destination) const override { ConstFramePtr source_frame(source, &type_layout()); FramePtr destination_frame(destination, &type_layout()); for (const auto& field : type_fields()) { field.CopyTo(source_frame, field, destination_frame); } } void UnsafeCombineToFingerprintHasher( const void* source, FingerprintHasher* hasher) const override { hasher->Combine(type_fields().size()); for (const auto& field : type_fields()) { field.GetType()->UnsafeCombineToFingerprintHasher( static_cast<const char*>(source) + field.byte_offset(), hasher); } } ReprToken UnsafeReprToken(const void* source) const override { ConstFramePtr frame_ptr(source, &type_layout()); std::ostringstream result; result << "("; bool first = true; for (const auto& field : type_fields()) { result << NonFirstComma(first) << TypedRef::FromSlot(field, frame_ptr).Repr(); } result << ")"; return ReprToken{std::move(result).str()}; } private: std::vector<QTypePtr> field_qtypes_; }; class TupleQTypeRegistry { public: static TupleQTypeRegistry* instance() { static Indestructible<TupleQTypeRegistry> result; return result.get(); } QTypePtr GetQType(absl::Span<const QTypePtr> field_qtypes) ABSL_LOCKS_EXCLUDED(lock_) { { absl::ReaderMutexLock guard(&lock_); if (const auto it = registry_.find(field_qtypes); it != registry_.end()) { return it->second.get(); } } auto tuple_qtype = TupleQType::Make(field_qtypes); absl::MutexLock guard(&lock_); return registry_ .try_emplace(tuple_qtype->field_qtypes(), std::move(tuple_qtype)) .first->second.get(); } private: absl::Mutex lock_; absl::flat_hash_map<absl::Span<const QTypePtr>, std::unique_ptr<TupleQType>> registry_ ABSL_GUARDED_BY(lock_); }; template <typename TypedRef > TypedValue MakeTupleImpl(absl::Span<const TypedRef> fields) { std::vector<QTypePtr> field_types; field_types.reserve(fields.size()); for (const auto& field : fields) { field_types.push_back(field.GetType()); } auto status_or_result = TypedValue::FromFields(MakeTupleQType(field_types), fields); DCHECK_OK(status_or_result.status()); return status_or_result.value_or(TypedValue::FromValue(Unit{})); } std::string NamedTupleQTypeName(absl::Span<const std::string> field_names, QTypePtr tuple_qtype) { constexpr size_t kMaxFieldNames = 5; std::ostringstream o; o << "namedtuple<"; size_t fields_to_report = std::min(field_names.size(), kMaxFieldNames); for (size_t i = 0; i != fields_to_report; ++i) { if (i != 0) { o << ","; } o << field_names[i] << "=" << tuple_qtype->type_fields()[i].GetType()->name(); } if (fields_to_report < field_names.size()) { o << ", [" << field_names.size() - fields_to_report << " fields]"; } o << ">"; return o.str(); } class NamedTupleQType final : public BasicDerivedQType, public NamedFieldQTypeInterface { public: NamedTupleQType(absl::Span<const std::string> field_names, QTypePtr tuple_qtype) : BasicDerivedQType(ConstructorArgs{ .name = NamedTupleQTypeName(field_names, tuple_qtype), .base_qtype = tuple_qtype, .qtype_specialization_key = "::arolla::NamedTupleQType", }), field_names_(field_names.begin(), field_names.end()) { name2index_.reserve(field_names.size()); int64_t id = 0; for (const std::string& name : field_names_) { name2index_.emplace(name, id++); } } absl::Span<const std::string> GetFieldNames() const final { return field_names_; } std::optional<int64_t> GetFieldIndexByName( absl::string_view field_name) const final { if (auto it = name2index_.find(field_name); it != name2index_.end()) { return it->second; } return std::nullopt; } private: absl::flat_hash_map<absl::string_view, int64_t> name2index_; std::vector<std::string> field_names_; }; class NamedTupleQTypeRegistry { public: static NamedTupleQTypeRegistry* instance() { static Indestructible<NamedTupleQTypeRegistry> result; return result.get(); } QTypePtr GetQType(absl::Span<const std::string> field_names, QTypePtr tuple_qtype) ABSL_LOCKS_EXCLUDED(lock_) { { absl::ReaderMutexLock guard(&lock_); if (const auto it = registry_.find({field_names, tuple_qtype}); it != registry_.end()) { return it->second.get(); } } auto named_tuple_qtype = std::make_unique<NamedTupleQType>(field_names, tuple_qtype); absl::MutexLock guard(&lock_); return registry_ .try_emplace({named_tuple_qtype->GetFieldNames(), tuple_qtype}, std::move(named_tuple_qtype)) .first->second.get(); } private: using RegistryKey = std::pair<absl::Span<const std::string>, QTypePtr>; absl::Mutex lock_; absl::flat_hash_map<RegistryKey, std::unique_ptr<NamedTupleQType>> registry_ ABSL_GUARDED_BY(lock_); }; } bool IsTupleQType(const QType* qtype) { return fast_dynamic_downcast_final<const TupleQType*>(qtype) != nullptr; } QTypePtr MakeTupleQType(absl::Span<const QTypePtr> field_qtypes) { return TupleQTypeRegistry::instance()->GetQType(field_qtypes); } TypedValue MakeTuple(absl::Span<const TypedRef> fields) { return MakeTupleImpl(fields); } TypedValue MakeTuple(absl::Span<const TypedValue> fields) { return MakeTupleImpl(fields); } bool IsNamedTupleQType(const QType* qtype) { return fast_dynamic_downcast_final<const NamedTupleQType*>(qtype) != nullptr; } absl::StatusOr<QTypePtr> MakeNamedTupleQType( absl::Span<const std::string> field_names, QTypePtr tuple_qtype) { if (!IsTupleQType(tuple_qtype)) { return absl::FailedPreconditionError(absl::StrFormat( "incorrect NamedTupleQType: expected tuple, found %s", tuple_qtype != nullptr ? tuple_qtype->name() : std::string("nullptr"))); } if (field_names.size() != tuple_qtype->type_fields().size()) { return absl::FailedPreconditionError(absl::StrFormat( "incorrect NamedTupleQType #field_names != #fields: %d vs %d", field_names.size(), tuple_qtype->type_fields().size())); } absl::flat_hash_set<absl::string_view> name_set; for (const std::string& name : field_names) { if (!name_set.insert(name).second) { return absl::FailedPreconditionError(absl::StrFormat( "incorrect NamedTupleQType: field name %s is duplicated", name)); } } return NamedTupleQTypeRegistry::instance()->GetQType(field_names, tuple_qtype); } }
#include "arolla/qtype/tuple_qtype.h" #include <cstddef> #include <cstdint> #include <optional> #include <string> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/types/span.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/derived_qtype.h" #include "arolla/qtype/named_field_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_ref.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/bytes.h" #include "arolla/util/testing/repr_token_eq.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/status_macros_backport.h" namespace arolla::testing { namespace { using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::ReprTokenEq; using ::arolla::testing::StatusIs; using ::testing::ElementsAre; using ::testing::ElementsAreArray; using ::testing::HasSubstr; using ::testing::IsEmpty; using ::testing::Eq; using ::testing::MatchesRegex; TEST(TupleQType, Empty) { auto qtype = MakeTupleQType({}); EXPECT_TRUE(IsTupleQType(qtype)); EXPECT_EQ(qtype->name(), "tuple<>"); EXPECT_EQ(qtype->type_layout().AllocSize(), 0); EXPECT_EQ(qtype->type_layout().AllocAlignment().value, 1); auto value = MakeTupleFromFields(); EXPECT_EQ(value.GetType(), qtype); EXPECT_EQ(value.GetFieldCount(), 0); EXPECT_THAT(value.GenReprToken(), ReprTokenEq("()")); } TEST(TupleQType, EmptyRegression) { auto qtype_0 = MakeTupleQType({}); auto qtype_1 = MakeTupleQType({qtype_0, qtype_0}); EXPECT_TRUE(IsTupleQType(qtype_1)); EXPECT_EQ(qtype_1->name(), "tuple<tuple<>,tuple<>>"); EXPECT_EQ(qtype_1->type_layout().AllocSize(), 0); EXPECT_EQ(qtype_1->type_layout().AllocAlignment().value, 1); auto value_0 = MakeTupleFromFields(); auto value_1 = MakeTupleFromFields(value_0, value_0); EXPECT_EQ(value_1.GetType(), qtype_1); auto copy_1 = TypedValue(value_1.AsRef()); EXPECT_EQ(value_1.GetFingerprint(), copy_1.GetFingerprint()); EXPECT_THAT(value_1.GenReprToken(), ReprTokenEq("((), ())")); } TEST(TupleQType, Trivial) { auto qtype = MakeTupleQType( {GetQType<int32_t>(), GetQType<double>(), GetQType<Bytes>()}); EXPECT_TRUE(IsTupleQType(qtype)); EXPECT_EQ(qtype->name(), "tuple<INT32,FLOAT64,BYTES>"); auto value = MakeTupleFromFields(int32_t{34}, double{17}, Bytes("Hello")); EXPECT_EQ(value.GetType(), qtype); EXPECT_EQ(value.GetFieldCount(), 3); EXPECT_THAT(value.GetField(0).As<int32_t>(), IsOkAndHolds(int32_t{34})); EXPECT_THAT(value.GetField(1).As<double>(), IsOkAndHolds(double{17.})); ASSERT_OK_AND_ASSIGN(Bytes bytes, value.GetField(2).As<Bytes>()); EXPECT_THAT(bytes, Eq(Bytes("Hello"))); EXPECT_THAT(value.GenReprToken(), ReprTokenEq("(34, float64{17}, b'Hello')")); } TEST(TupleQType, CopyTo) { auto qtype = MakeTupleQType( {GetQType<int32_t>(), GetQType<double>(), GetQType<Bytes>()}); EXPECT_TRUE(IsTupleQType(qtype)); EXPECT_EQ(qtype->name(), "tuple<INT32,FLOAT64,BYTES>"); auto value = MakeTupleFromFields(int32_t{34}, double{17}, Bytes("Hello")); EXPECT_THAT(value.GetField(0).As<int32_t>(), IsOkAndHolds(int32_t{34})); EXPECT_THAT(value.GetField(1).As<double>(), IsOkAndHolds(double{17.})); auto copy = TypedValue(value.AsRef()); EXPECT_EQ(value.GetFingerprint(), copy.GetFingerprint()); EXPECT_THAT(copy.GenReprToken(), ReprTokenEq("(34, float64{17}, b'Hello')")); } TEST(TupleQType, QValueFromFields) { auto qtype = MakeTupleQType({GetQType<int>(), GetQType<float>()}); { ASSERT_OK_AND_ASSIGN(auto qvalue, TypedValue::FromFields( qtype, {TypedRef::FromValue(2), TypedRef::FromValue(3.14f)})); EXPECT_THAT(qvalue.GetField(0).As<int>(), IsOkAndHolds(2)); EXPECT_THAT(qvalue.GetField(1).As<float>(), IsOkAndHolds(3.14f)); } { ASSERT_OK_AND_ASSIGN( auto qvalue, TypedValue::FromFields( qtype, {TypedValue::FromValue(2), TypedValue::FromValue(3.14f)})); EXPECT_THAT(qvalue.GetField(0).As<int>(), IsOkAndHolds(2)); EXPECT_THAT(qvalue.GetField(1).As<float>(), IsOkAndHolds(3.14f)); } { EXPECT_THAT(TypedValue::FromFields(qtype, {TypedValue::FromValue(2)}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("expected 2 values, got 1; " "compound_qtype=tuple<INT32,FLOAT32>"))); } { EXPECT_THAT(TypedValue::FromFields(qtype, {TypedValue::FromValue(2), TypedValue::FromValue(3)}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("expected fields[1]: FLOAT32, got INT32; " "compound_qtype=tuple<INT32,FLOAT32>"))); } } TEST(NamedTupleQType, Empty) { auto tuple_qtype = MakeTupleQType({}); ASSERT_OK_AND_ASSIGN(auto qtype, MakeNamedTupleQType({}, tuple_qtype)); EXPECT_TRUE(IsNamedTupleQType(qtype)); EXPECT_THAT(GetFieldNames(qtype), IsEmpty()); } TEST(NamedTupleQType, Trivial) { auto tuple_qtype = MakeTupleQType( {GetQType<int32_t>(), GetQType<double>(), GetQType<Bytes>()}); ASSERT_OK_AND_ASSIGN(auto qtype, MakeNamedTupleQType({"a", "b", "c"}, tuple_qtype)); EXPECT_TRUE(IsNamedTupleQType(qtype)); EXPECT_EQ(qtype->name(), "namedtuple<a=INT32,b=FLOAT64,c=BYTES>"); EXPECT_EQ(GetFieldIndexByName(nullptr, "a"), std::nullopt); EXPECT_EQ(GetFieldIndexByName(qtype, "a"), 0); EXPECT_EQ(GetFieldIndexByName(qtype, "b"), 1); EXPECT_EQ(GetFieldIndexByName(qtype, "c"), 2); EXPECT_EQ(GetFieldIndexByName(qtype, "d"), std::nullopt); EXPECT_THAT(GetFieldNames(qtype), ElementsAre("a", "b", "c")); EXPECT_EQ(GetFieldQTypeByName(nullptr, "a"), nullptr); EXPECT_EQ(GetFieldQTypeByName(qtype, "a"), GetQType<int32_t>()); EXPECT_EQ(GetFieldQTypeByName(qtype, "b"), GetQType<double>()); EXPECT_EQ(GetFieldQTypeByName(qtype, "c"), GetQType<Bytes>()); EXPECT_EQ(GetFieldQTypeByName(qtype, "d"), nullptr); auto derived_qtype_interface = dynamic_cast<const DerivedQTypeInterface*>(qtype); ASSERT_NE(derived_qtype_interface, nullptr); EXPECT_EQ(derived_qtype_interface->GetBaseQType(), tuple_qtype); { ASSERT_OK_AND_ASSIGN(auto qtype2, MakeNamedTupleQType({"a", "b", "c"}, tuple_qtype)); EXPECT_EQ(qtype, qtype2); EXPECT_THAT(GetFieldNames(qtype2), ElementsAre("a", "b", "c")); } { ASSERT_OK_AND_ASSIGN(auto qtype2, MakeNamedTupleQType({"c", "b", "a"}, tuple_qtype)); EXPECT_EQ(qtype2->name(), "namedtuple<c=INT32,b=FLOAT64,a=BYTES>"); EXPECT_EQ(GetFieldIndexByName(qtype2, "c"), 0); EXPECT_NE(qtype, qtype2); EXPECT_THAT(GetFieldNames(qtype2), ElementsAre("c", "b", "a")); } { auto tuple_qtype2 = MakeTupleQType( {GetQType<int32_t>(), GetQType<double>(), GetQType<int32_t>()}); ASSERT_OK_AND_ASSIGN(auto qtype2, MakeNamedTupleQType({"a", "b", "c"}, tuple_qtype2)); EXPECT_EQ(qtype2->name(), "namedtuple<a=INT32,b=FLOAT64,c=INT32>"); EXPECT_NE(qtype, qtype2); EXPECT_THAT(GetFieldNames(qtype2), ElementsAre("a", "b", "c")); } } TEST(NamedTupleQType, QValueFromFields) { auto tuple_qtype = MakeTupleQType({GetQType<int>(), GetQType<float>()}); ASSERT_OK_AND_ASSIGN(auto qtype, MakeNamedTupleQType({"a", "b"}, tuple_qtype)); { ASSERT_OK_AND_ASSIGN(auto qvalue, TypedValue::FromFields( qtype, {TypedRef::FromValue(2), TypedRef::FromValue(3.14f)})); EXPECT_TRUE(IsNamedTupleQType(qvalue.GetType())); EXPECT_EQ(qvalue.GetType(), qtype); EXPECT_THAT(qvalue.GetField(0).As<int>(), IsOkAndHolds(2)); EXPECT_THAT(qvalue.GetField(1).As<float>(), IsOkAndHolds(3.14f)); } { ASSERT_OK_AND_ASSIGN( auto qvalue, TypedValue::FromFields( qtype, {TypedValue::FromValue(2), TypedValue::FromValue(3.14f)})); EXPECT_TRUE(IsNamedTupleQType(qvalue.GetType())); EXPECT_EQ(qvalue.GetType(), qtype); EXPECT_THAT(qvalue.GetField(0).As<int>(), IsOkAndHolds(2)); EXPECT_THAT(qvalue.GetField(1).As<float>(), IsOkAndHolds(3.14f)); } { EXPECT_THAT( TypedValue::FromFields(qtype, {TypedValue::FromValue(2)}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("expected 2 values, got 1; " "compound_qtype=namedtuple<a=INT32,b=FLOAT32>"))); } { EXPECT_THAT( TypedValue::FromFields(qtype, {TypedValue::FromValue(2), TypedValue::FromValue(3)}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("expected fields[1]: FLOAT32, got INT32; " "compound_qtype=namedtuple<a=INT32,b=FLOAT32>"))); } } TEST(NamedTupleQType, BigTuple) { constexpr size_t kFieldCount = 100; QTypePtr field_qtype = GetQType<int32_t>(); auto tuple_qtype = MakeTupleQType(std::vector<QTypePtr>{kFieldCount, field_qtype}); std::vector<std::string> names; for (size_t i = 0; i != kFieldCount; ++i) { names.push_back(std::to_string(i)); } ASSERT_OK_AND_ASSIGN(auto qtype, MakeNamedTupleQType(names, tuple_qtype)); EXPECT_TRUE(IsNamedTupleQType(qtype)); EXPECT_THAT(GetFieldNames(qtype), ElementsAreArray(names)); EXPECT_EQ(qtype->name(), "namedtuple<0=INT32,1=INT32,2=INT32,3=INT32,4=INT32, [95 fields]>"); } TEST(NamedTupleQType, Errors) { EXPECT_THAT( MakeNamedTupleQType({"a", "b"}, nullptr).status(), StatusIs(absl::StatusCode::kFailedPrecondition, MatchesRegex(".*NamedTupleQType.*tuple.*found.*nullptr.*"))); EXPECT_THAT( MakeNamedTupleQType({"a", "b"}, GetQType<int32_t>()).status(), StatusIs(absl::StatusCode::kFailedPrecondition, MatchesRegex(".*NamedTupleQType.*tuple.*found.*INT32.*"))); auto tuple_qtype = MakeTupleQType( {GetQType<int32_t>(), GetQType<double>(), GetQType<Bytes>()}); EXPECT_THAT(MakeNamedTupleQType({"a", "b"}, tuple_qtype).status(), StatusIs(absl::StatusCode::kFailedPrecondition, MatchesRegex(".*NamedTupleQType.*2 vs 3.*"))); EXPECT_THAT(MakeNamedTupleQType({"a", "b", "a"}, tuple_qtype).status(), StatusIs(absl::StatusCode::kFailedPrecondition, MatchesRegex(".*NamedTupleQType.*a.*duplicate.*"))); EXPECT_THAT(GetFieldNames(nullptr), IsEmpty()); EXPECT_THAT(GetFieldNames(GetQType<int32_t>()), IsEmpty()); } absl::StatusOr<TypedValue> CreateNamedTuple( absl::Span<const std::string> field_names, TypedValue tuple) { ASSIGN_OR_RETURN(auto namedtuple_qtype, MakeNamedTupleQType(field_names, tuple.GetType())); return UnsafeDowncastDerivedQValue(namedtuple_qtype, tuple); } TEST(NamedTupleQType, GetFieldByNameAs) { TypedValue tuple = MakeTupleFromFields(2.0f, 3); ASSERT_OK_AND_ASSIGN(TypedValue named_tuple, CreateNamedTuple({"a", "b"}, tuple)); EXPECT_THAT(GetFieldByNameAs<float>(named_tuple.AsRef(), "a"), IsOkAndHolds(2.0f)); EXPECT_THAT(GetFieldByNameAs<float>(named_tuple.AsRef(), "c").status(), StatusIs(absl::StatusCode::kInvalidArgument, MatchesRegex(".*no field named \"c\".*"))); EXPECT_THAT( GetFieldByNameAs<Bytes>(named_tuple.AsRef(), "a").status(), StatusIs( absl::StatusCode::kFailedPrecondition, HasSubstr("type mismatch: expected C++ type `float` (FLOAT32), got " "`arolla::Bytes`; while accessing field \"a\""))); } } }
2,348
#ifndef AROLLA_QTYPE_TYPED_VALUE_H_ #define AROLLA_QTYPE_TYPED_VALUE_H_ #include <cstdint> #include <functional> #include <new> #include <string> #include <type_traits> #include <utility> #include "absl/base/attributes.h" #include "absl/base/call_once.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/memory/frame.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_ref.h" #include "arolla/qtype/typed_slot.h" #include "arolla/util/fingerprint.h" #include "arolla/util/refcount.h" #include "arolla/util/repr.h" namespace arolla { class TypedValue { public: template <typename T> static TypedValue FromValue(T&& value); template <typename T> static TypedValue FromValue(const T& value); template <typename T> static absl::StatusOr<TypedValue> FromValueWithQType(T&& value, QTypePtr qtype); template <typename T> static absl::StatusOr<TypedValue> FromValueWithQType(const T& value, QTypePtr qtype); static TypedValue UnsafeFromTypeDefaultConstructed(QTypePtr type); static TypedValue FromSlot(TypedSlot slot, ConstFramePtr frame); static absl::StatusOr<TypedValue> FromFields( QTypePtr compound_type, absl::Span<const TypedRef> fields); static absl::StatusOr<TypedValue> FromFields( QTypePtr compound_type, absl::Span<const TypedValue> fields); explicit TypedValue(TypedRef value_ref); ~TypedValue() noexcept; TypedValue(TypedValue&& rhs) noexcept; TypedValue& operator=(TypedValue&& rhs) noexcept; TypedValue(const TypedValue& rhs) noexcept; TypedValue& operator=(const TypedValue& rhs) noexcept; QTypePtr GetType() const; const void* GetRawPointer() const ABSL_ATTRIBUTE_LIFETIME_BOUND; TypedRef AsRef() const ABSL_ATTRIBUTE_LIFETIME_BOUND; const Fingerprint& GetFingerprint() const ABSL_ATTRIBUTE_LIFETIME_BOUND; int64_t GetFieldCount() const; TypedRef GetField(int64_t index) const ABSL_ATTRIBUTE_LIFETIME_BOUND; absl::Status CopyToSlot(TypedSlot slot, FramePtr frame) const; template <typename T> absl::StatusOr<std::reference_wrapper<const T>> As() const ABSL_ATTRIBUTE_LIFETIME_BOUND; template <typename T> const T& UnsafeAs() const ABSL_ATTRIBUTE_LIFETIME_BOUND; std::string Repr() const; ReprToken GenReprToken() const; absl::string_view PyQValueSpecializationKey() const ABSL_ATTRIBUTE_LIFETIME_BOUND; private: struct Impl { Refcount refcount; absl::once_flag fingerprint_once; QTypePtr qtype; void* data; Fingerprint fingerprint; }; TypedValue(Impl* impl) noexcept : impl_(impl) {} static Impl* AllocRawImpl(QTypePtr qtype); static Impl* AllocImpl(QTypePtr qtype, const void* value); Impl* impl_; }; template <typename T> TypedValue TypedValue::FromValue(T&& value) { using V = std::decay_t<T>; static const QTypePtr qtype = GetQType<V>(); if constexpr (std::is_copy_constructible_v<V> || std::is_move_constructible_v<V>) { auto* raw_impl = AllocRawImpl(qtype); new (raw_impl->data) V(std::forward<T>(value)); return TypedValue(raw_impl); } else { return TypedValue(AllocImpl(qtype, &value)); } } template <typename T> TypedValue TypedValue::FromValue(const T& value) { static const QTypePtr qtype = GetQType<T>(); if constexpr (std::is_copy_constructible_v<T>) { auto* raw_impl = AllocRawImpl(qtype); new (raw_impl->data) T(value); return TypedValue(raw_impl); } else { return TypedValue(AllocImpl(qtype, &value)); } } template <typename T> absl::StatusOr<TypedValue> TypedValue::FromValueWithQType(T&& value, QTypePtr qtype) { using V = std::decay_t<T>; if (auto status = VerifyQTypeTypeInfo(qtype, typeid(V)); !status.ok()) { return status; } if constexpr (std::is_copy_constructible_v<V> || std::is_move_constructible_v<V>) { auto* raw_impl = AllocRawImpl(qtype); new (raw_impl->data) V(std::forward<T>(value)); return TypedValue(raw_impl); } else { return TypedValue(AllocImpl(qtype, &value)); } } template <typename T> absl::StatusOr<TypedValue> TypedValue::FromValueWithQType(const T& value, QTypePtr qtype) { if (auto status = VerifyQTypeTypeInfo(qtype, typeid(T)); !status.ok()) { return status; } if constexpr (std::is_copy_constructible_v<T>) { auto* raw_impl = AllocRawImpl(qtype); new (raw_impl->data) T(value); return TypedValue(raw_impl); } else { return TypedValue(AllocImpl(qtype, &value)); } } inline TypedValue TypedValue::FromSlot(TypedSlot slot, ConstFramePtr frame) { return TypedValue(TypedRef::FromSlot(slot, frame)); } inline TypedValue::TypedValue(TypedRef value_ref) : impl_(AllocImpl(value_ref.GetType(), value_ref.GetRawPointer())) {} inline TypedValue::~TypedValue() noexcept { if (impl_ != nullptr && !impl_->refcount.skewed_decrement()) { impl_->qtype->type_layout().DestroyAlloc(impl_->data); impl_->~Impl(); ::operator delete(impl_); } } inline TypedValue::TypedValue(TypedValue&& rhs) noexcept : impl_(rhs.impl_) { rhs.impl_ = nullptr; } inline TypedValue& TypedValue::operator=(TypedValue&& rhs) noexcept { using std::swap; swap(impl_, rhs.impl_); return *this; } inline TypedValue::TypedValue(const TypedValue& rhs) noexcept : impl_(rhs.impl_) { if (impl_ != nullptr) { impl_->refcount.increment(); } } inline TypedValue& TypedValue::operator=(const TypedValue& rhs) noexcept { if (impl_ != rhs.impl_) { *this = TypedValue(rhs); } return *this; } inline QTypePtr TypedValue::GetType() const { return impl_->qtype; } inline const void* TypedValue::GetRawPointer() const { return impl_->data; } inline TypedRef TypedValue::AsRef() const { return TypedRef::UnsafeFromRawPointer(impl_->qtype, impl_->data); } inline int64_t TypedValue::GetFieldCount() const { return impl_->qtype->type_fields().size(); } inline TypedRef TypedValue::GetField(int64_t index) const { return AsRef().GetField(index); } inline absl::Status TypedValue::CopyToSlot(TypedSlot slot, FramePtr frame) const { return AsRef().CopyToSlot(slot, frame); } template <typename T> absl::StatusOr<std::reference_wrapper<const T>> TypedValue::As() const { return AsRef().As<T>(); } template <typename T> const T& TypedValue::UnsafeAs() const { return AsRef().UnsafeAs<T>(); } inline std::string TypedValue::Repr() const { return std::move(AsRef().GenReprToken().str); } inline ReprToken TypedValue::GenReprToken() const { return AsRef().GenReprToken(); } inline absl::string_view TypedValue::PyQValueSpecializationKey() const { return AsRef().PyQValueSpecializationKey(); } } #endif #include "arolla/qtype/typed_value.h" #include <cstddef> #include <memory> #include <new> #include <utility> #include "absl/base/call_once.h" #include "absl/log/check.h" #include "absl/log/log.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/types/span.h" #include "arolla/memory/frame.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_ref.h" #include "arolla/util/fingerprint.h" #include "arolla/util/memory.h" namespace arolla { namespace { template <typename TypedRef > absl::Status CheckPreconditionsForInitCompound( QTypePtr compound_qtype, absl::Span<const TypedRef> field_refs) { const auto& field_slots = compound_qtype->type_fields(); if (field_slots.size() != field_refs.size()) { return absl::InvalidArgumentError(absl::StrFormat( "expected %d values, got %d; compound_qtype=%s", field_slots.size(), field_refs.size(), compound_qtype->name())); } for (size_t i = 0; i < field_refs.size(); ++i) { if (field_refs[i].GetType() != field_slots[i].GetType()) { return absl::InvalidArgumentError(absl::StrFormat( "expected fields[%d]: %s, got %s; compound_qtype=%s", i, field_slots[i].GetType()->name(), field_refs[i].GetType()->name(), compound_qtype->name())); } } return absl::OkStatus(); } template <typename TypedRef > void InitCompound(QTypePtr compound_qtype, absl::Span<const TypedRef> field_refs, void* destination) { compound_qtype->type_layout().InitializeAlignedAlloc(destination); const auto& field_slots = compound_qtype->type_fields(); FramePtr frame(destination, &compound_qtype->type_layout()); for (size_t i = 0; i < field_refs.size(); ++i) { const auto& field_ref = field_refs[i]; field_ref.GetType()->UnsafeCopy( field_ref.GetRawPointer(), frame.GetRawPointer(field_slots[i].byte_offset())); } } } TypedValue::Impl* TypedValue::AllocRawImpl(QTypePtr qtype) { const auto& type_layout = qtype->type_layout(); const size_t alignment = type_layout.AllocAlignment().value; size_t extra_space = type_layout.AllocSize() + alignment; void* buffer = ::operator new(sizeof(Impl) + extra_space); Impl* impl = new (buffer) Impl; impl->qtype = qtype; impl->data = static_cast<char*>(buffer) + sizeof(Impl); void* tmp = std::align(alignment, extra_space, impl->data, extra_space); DCHECK_NE(tmp, nullptr); return impl; } TypedValue::Impl* TypedValue::AllocImpl(QTypePtr qtype, const void* value) { auto* impl = AllocRawImpl(qtype); qtype->type_layout().InitializeAlignedAlloc(impl->data); qtype->UnsafeCopy(value, impl->data); return impl; } TypedValue TypedValue::UnsafeFromTypeDefaultConstructed(QTypePtr qtype) { auto* impl = AllocRawImpl(qtype); qtype->type_layout().InitializeAlignedAlloc(impl->data); return TypedValue(impl); } absl::StatusOr<TypedValue> TypedValue::FromFields( QTypePtr compound_qtype, absl::Span<const TypedRef> fields) { if (auto status = CheckPreconditionsForInitCompound(compound_qtype, fields); !status.ok()) { return status; } auto* impl = AllocRawImpl(compound_qtype); InitCompound(compound_qtype, fields, impl->data); return TypedValue(impl); } absl::StatusOr<TypedValue> TypedValue::FromFields( QTypePtr compound_qtype, absl::Span<const TypedValue> fields) { if (auto status = CheckPreconditionsForInitCompound(compound_qtype, fields); !status.ok()) { return status; } auto* impl = AllocRawImpl(compound_qtype); InitCompound(compound_qtype, fields, impl->data); return TypedValue(impl); } const Fingerprint& TypedValue::GetFingerprint() const { absl::call_once(impl_->fingerprint_once, [impl = impl_] { FingerprintHasher hasher("TypedValue"); hasher.Combine(impl->qtype); impl->qtype->UnsafeCombineToFingerprintHasher(impl->data, &hasher); impl->fingerprint = std::move(hasher).Finish(); }); return impl_->fingerprint; } }
#include "arolla/qtype/typed_value.h" #include <cstdint> #include <utility> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/container/flat_hash_set.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "arolla/memory/frame.h" #include "arolla/memory/memory_allocation.h" #include "arolla/memory/optional_value.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_slot.h" #include "arolla/util/bytes.h" #include "arolla/util/fingerprint.h" #include "arolla/util/testing/status_matchers_backport.h" struct WithoutQTypeTraits {}; namespace arolla { namespace { using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::testing::Eq; using ::testing::HasSubstr; TEST(TypedValueTest, ReprBasic) { EXPECT_EQ(TypedValue::FromValue<bool>(true).Repr(), "true"); EXPECT_EQ(TypedValue::FromValue<int32_t>(5).Repr(), "5"); EXPECT_EQ(TypedValue::FromValue<int64_t>(5).Repr(), "int64{5}"); EXPECT_EQ(TypedValue::FromValue<uint64_t>(5).Repr(), "uint64{5}"); EXPECT_EQ(TypedValue::FromValue<float>(5.0f).Repr(), "5."); EXPECT_EQ(TypedValue::FromValue<double>(5.0).Repr(), "float64{5}"); } TEST(TypedValueTest, FromValue) { auto tval = TypedValue::FromValue<int64_t>(1); EXPECT_THAT(tval.GetType(), Eq(GetQType<int64_t>())); EXPECT_THAT(tval.As<int64_t>(), IsOkAndHolds(int64_t{1})); EXPECT_THAT(tval.As<float>().status(), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST(TypedValueTest, As) { auto int_value = TypedValue::FromValue<double>(1.0); EXPECT_THAT(int_value.As<double>(), IsOkAndHolds(1.0)); EXPECT_THAT(int_value.As<float>().status(), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("type mismatch: expected C++ type `double` " "(FLOAT64), got `float`"))); EXPECT_THAT(int_value.As<WithoutQTypeTraits>().status(), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("type mismatch: expected C++ type `double` " "(FLOAT64), got `WithoutQTypeTraits`"))); } TEST(TypedValueTest, FromValueWithQType) { auto f64 = GetQType<double>(); absl::StatusOr<TypedValue> tmp = TypedValue::FromValueWithQType(1.0, f64); auto tval = std::move(tmp).value(); EXPECT_THAT(tval.GetType(), Eq(f64)); EXPECT_THAT(tval.As<double>(), IsOkAndHolds(1.0)); EXPECT_THAT(tval.As<float>(), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("type mismatch: expected C++ type `double` " "(FLOAT64), got `float`"))); EXPECT_THAT(TypedValue::FromValueWithQType(1.0f, f64).status(), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST(TypedValueTest, UnsafeFromTypeDefaultConstructed) { { auto f64 = GetQType<double>(); auto tval = TypedValue::UnsafeFromTypeDefaultConstructed(f64); EXPECT_THAT(tval.GetType(), Eq(GetQType<double>())); EXPECT_THAT(tval.As<double>(), IsOkAndHolds(double{0.})); EXPECT_THAT(tval.As<float>().status(), StatusIs(absl::StatusCode::kFailedPrecondition)); } { auto bytes = GetQType<Bytes>(); auto tval = TypedValue::UnsafeFromTypeDefaultConstructed(bytes); EXPECT_THAT(tval.GetType(), Eq(GetQType<Bytes>())); ASSERT_OK_AND_ASSIGN(auto val_ref, tval.As<Bytes>()); EXPECT_THAT(val_ref.get(), Eq(Bytes())); EXPECT_THAT(tval.As<float>().status(), StatusIs(absl::StatusCode::kFailedPrecondition)); } { auto of64 = GetQType<OptionalValue<double>>(); auto tval = TypedValue::UnsafeFromTypeDefaultConstructed(of64); EXPECT_THAT(tval.GetType(), Eq(GetQType<OptionalValue<double>>())); ASSERT_OK_AND_ASSIGN(auto val_ref, tval.As<OptionalValue<double>>()); EXPECT_THAT(val_ref.get(), Eq(OptionalValue<double>())); EXPECT_THAT(tval.As<OptionalValue<float>>().status(), StatusIs(absl::StatusCode::kFailedPrecondition)); } } TEST(TypedValueTest, FromSlot) { FrameLayout::Builder builder; QTypePtr f32 = GetQType<float>(); TypedSlot tslot = AddSlot(f32, &builder); auto layout = std::move(builder).Build(); MemoryAllocation alloc(&layout); FramePtr ptr = alloc.frame(); EXPECT_OK(TypedValue::FromValue(7.5f).CopyToSlot(tslot, ptr)); auto tval = TypedValue::FromSlot(tslot, ptr); EXPECT_THAT(tval.GetType(), Eq(f32)); EXPECT_THAT(tval.As<float>(), IsOkAndHolds(7.5f)); } TEST(TypedValueTest, ToSlot) { FrameLayout::Builder builder; QTypePtr f64 = GetQType<double>(); TypedSlot tslot = AddSlot(f64, &builder); auto layout = std::move(builder).Build(); MemoryAllocation alloc(&layout); FramePtr ptr = alloc.frame(); auto tval = TypedValue::FromValue(double{1.0}); EXPECT_OK(tval.CopyToSlot(tslot, ptr)); auto slot = tslot.ToSlot<double>().value(); EXPECT_THAT(ptr.Get(slot), Eq(1.0)); } TEST(TypedValueTest, Copy) { auto tval = TypedValue::FromValue(double{1.0}); auto tval_copy = tval; EXPECT_THAT(tval_copy.As<double>(), IsOkAndHolds(1.0)); } TEST(TypedValueTest, FingerprintUniqueness) { absl::flat_hash_set<Fingerprint> fingerprints; EXPECT_TRUE( fingerprints.insert(TypedValue::FromValue(int32_t{0}).GetFingerprint()) .second); EXPECT_TRUE( fingerprints.insert(TypedValue::FromValue(int64_t{0}).GetFingerprint()) .second); EXPECT_TRUE( fingerprints.insert(TypedValue::FromValue(uint64_t{0}).GetFingerprint()) .second); EXPECT_TRUE( fingerprints.insert(TypedValue::FromValue(double{0}).GetFingerprint()) .second); EXPECT_TRUE( fingerprints.insert(TypedValue::FromValue(float{0}).GetFingerprint()) .second); } TEST(TypedValueTest, FingerprintReproducibility) { EXPECT_EQ(TypedValue::FromValue(int32_t{0}).GetFingerprint(), TypedValue::FromValue(int32_t{0}).GetFingerprint()); EXPECT_EQ(TypedValue::FromValue(int64_t{0}).GetFingerprint(), TypedValue::FromValue(int64_t{0}).GetFingerprint()); EXPECT_EQ(TypedValue::FromValue(uint64_t{0}).GetFingerprint(), TypedValue::FromValue(uint64_t{0}).GetFingerprint()); EXPECT_EQ(TypedValue::FromValue(float{0}).GetFingerprint(), TypedValue::FromValue(float{0}).GetFingerprint()); EXPECT_EQ(TypedValue::FromValue(double{0}).GetFingerprint(), TypedValue::FromValue(double{0}).GetFingerprint()); } TEST(TypedValueTest, UnsafeAs) { auto tval = TypedValue::FromValue<int64_t>(1); ASSERT_THAT(tval.GetType(), Eq(GetQType<int64_t>())); EXPECT_THAT(tval.UnsafeAs<int64_t>(), Eq(int64_t{1})); } TEST(TypedValueTest, CopyConstructor) { TypedValue x = TypedValue::FromValue<int64_t>(1); TypedValue y = x; EXPECT_EQ(x.GetType(), y.GetType()); EXPECT_EQ(x.GetRawPointer(), y.GetRawPointer()); } TEST(TypedValueTest, CopyOperator) { TypedValue x = TypedValue::FromValue<int64_t>(1); TypedValue y = TypedValue::FromValue<int64_t>(2); y = x; EXPECT_EQ(x.GetType(), y.GetType()); EXPECT_EQ(x.GetRawPointer(), y.GetRawPointer()); } TEST(TypedValueTest, MoveConstructor) { TypedValue x = TypedValue::FromValue<int64_t>(1); auto* x_type = x.GetType(); auto* x_raw_ptr = x.GetRawPointer(); TypedValue y = std::move(x); EXPECT_EQ(y.GetType(), x_type); EXPECT_EQ(y.GetRawPointer(), x_raw_ptr); } TEST(TypedValueTest, MoveOperator) { TypedValue x = TypedValue::FromValue<int64_t>(1); TypedValue y = TypedValue::FromValue<int64_t>(2); auto* x_type = x.GetType(); auto* x_raw_ptr = x.GetRawPointer(); y = std::move(x); EXPECT_EQ(y.GetType(), x_type); EXPECT_EQ(y.GetRawPointer(), x_raw_ptr); } TEST(TypedValueTest, CopyFromValue) { const Bytes bytes("data"); TypedValue x = TypedValue::FromValue(bytes); ASSERT_OK_AND_ASSIGN(Bytes x_bytes, x.As<Bytes>()); EXPECT_THAT(x_bytes, Eq(bytes)); } TEST(TypedValueTest, CopyFromValueT) { const Bytes bytes("data"); TypedValue x = TypedValue::FromValue<Bytes>(bytes); ASSERT_OK_AND_ASSIGN(Bytes x_bytes, x.As<Bytes>()); EXPECT_THAT(x_bytes, Eq(bytes)); } TEST(TypedValueTest, MoveFromValueT) { Bytes bytes("a long string literal to ensure memory allocation"); auto* data_raw_ptr = bytes.data(); TypedValue x = TypedValue::FromValue<Bytes>(std::move(bytes)); EXPECT_EQ(x.UnsafeAs<Bytes>().data(), data_raw_ptr); } TEST(TypedValueTest, CopyFromValueWithQType) { const Bytes bytes("data"); ASSERT_OK_AND_ASSIGN( TypedValue x, TypedValue::FromValueWithQType(bytes, GetQType<Bytes>())); ASSERT_OK_AND_ASSIGN(Bytes x_bytes, x.As<Bytes>()); EXPECT_THAT(x_bytes, Eq(bytes)); } TEST(TypedValueTest, MoveFromValueWithQType) { Bytes bytes("a long string literal to ensure memory allocation"); auto* data_raw_ptr = bytes.data(); ASSERT_OK_AND_ASSIGN(TypedValue x, TypedValue::FromValueWithQType( std::move(bytes), GetQType<Bytes>())); EXPECT_EQ(x.UnsafeAs<Bytes>().data(), data_raw_ptr); } } }
2,349
#ifndef AROLLA_QTYPE_WEAK_QTYPE_H_ #define AROLLA_QTYPE_WEAK_QTYPE_H_ #include "arolla/qtype/qtype.h" namespace arolla { QTypePtr GetWeakFloatQType(); QTypePtr GetOptionalWeakFloatQType(); } #endif #include "arolla/qtype/weak_qtype.h" #include <utility> #include <vector> #include "absl/log/check.h" #include "absl/strings/str_cat.h" #include "arolla/memory/optional_value.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/derived_qtype.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/util/fingerprint.h" #include "arolla/util/indestructible.h" #include "arolla/util/repr.h" namespace arolla { namespace { class WeakFloatQType final : public BasicDerivedQType { public: explicit WeakFloatQType() : BasicDerivedQType(ConstructorArgs{ .name = "WEAK_FLOAT", .base_qtype = GetQType<double>(), }) { CHECK_OK(VerifyDerivedQType(this)); } static QTypePtr get() { static const Indestructible<WeakFloatQType> result; return result.get(); } ReprToken UnsafeReprToken(const void* source) const override { return GenReprTokenWeakFloat(*static_cast<const double*>(source)); } }; class OptionalWeakFloatQType final : public QType, public DerivedQTypeInterface { public: OptionalWeakFloatQType() : QType(MakeConstructorArgs()) { CHECK_OK(VerifyDerivedQType(this)); } static QTypePtr get() { static const Indestructible<OptionalWeakFloatQType> result; return result.get(); } QTypePtr GetBaseQType() const final { return GetOptionalQType<double>(); } ReprToken UnsafeReprToken(const void* source) const final { const auto& value = *static_cast<const OptionalValue<double>*>(source); if (value.present) { return ReprToken{ absl::StrCat("optional_", GenReprTokenWeakFloat(value.value).str)}; } return ReprToken{"optional_weak_float{NA}"}; } void UnsafeCopy(const void* source, void* destination) const final { if (source != destination) { *static_cast<OptionalValue<double>*>(destination) = *static_cast<const OptionalValue<double>*>(source); } } void UnsafeCombineToFingerprintHasher(const void* source, FingerprintHasher* hasher) const final { hasher->Combine(*static_cast<const OptionalValue<double>*>(source)); } private: static ConstructorArgs MakeConstructorArgs() { auto base_qtype = GetOptionalQType<double>(); std::vector<TypedSlot> fields = base_qtype->type_fields(); DCHECK_EQ(fields.size(), 2); fields[1] = TypedSlot::UnsafeFromOffset(WeakFloatQType::get(), fields[1].byte_offset()); return ConstructorArgs{ .name = "OPTIONAL_WEAK_FLOAT", .type_info = base_qtype->type_info(), .type_layout = base_qtype->type_layout(), .type_fields = std::move(fields), .value_qtype = WeakFloatQType::get(), }; } }; } QTypePtr GetWeakFloatQType() { return WeakFloatQType::get(); } QTypePtr GetOptionalWeakFloatQType() { return OptionalWeakFloatQType::get(); } namespace { static const int optional_weak_float_registered = (RegisterOptionalQType(GetOptionalWeakFloatQType()), 1); } }
#include "arolla/qtype/weak_qtype.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "arolla/array/qtype/types.h" #include "arolla/memory/optional_value.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/shape_qtype.h" #include "arolla/qtype/standard_type_properties/properties.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/testing/repr_token_eq.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/unit.h" namespace arolla { namespace { using ::arolla::testing::ReprTokenEq; using ::arolla::testing::StatusIs; using ::testing::MatchesRegex; TEST(WeakQTypeTest, Smoke) { auto qtype = GetWeakFloatQType(); EXPECT_EQ(qtype->name(), "WEAK_FLOAT"); auto optional_qtype = GetOptionalWeakFloatQType(); EXPECT_EQ(optional_qtype->name(), "OPTIONAL_WEAK_FLOAT"); } TEST(WeakQTypeTest, Optional) { QTypePtr qtype = GetWeakFloatQType(); QTypePtr optional_qtype = GetOptionalWeakFloatQType(); EXPECT_EQ(optional_qtype->value_qtype(), qtype); EXPECT_TRUE(IsOptionalQType(optional_qtype)); ASSERT_OK_AND_ASSIGN(QTypePtr to_optional_res, ToOptionalQType(qtype)); EXPECT_EQ(to_optional_res, optional_qtype); EXPECT_EQ(DecayOptionalQType(optional_qtype), qtype); ASSERT_OK_AND_ASSIGN(TypedValue v, CreateMissingValue(optional_qtype)); ASSERT_EQ(v.GetType(), optional_qtype); } TEST(WeakQTypeTest, IsScalarQType) { EXPECT_TRUE(IsScalarQType(GetWeakFloatQType())); EXPECT_FALSE(IsScalarQType(GetOptionalWeakFloatQType())); } TEST(WeakQTypeTest, GetScalarQType) { { ASSERT_OK_AND_ASSIGN(QTypePtr scalar_qtype, GetScalarQType(GetWeakFloatQType())); EXPECT_EQ(scalar_qtype, GetWeakFloatQType()); } { ASSERT_OK_AND_ASSIGN(QTypePtr scalar_qtype, GetScalarQType(GetOptionalWeakFloatQType())); EXPECT_EQ(scalar_qtype, GetWeakFloatQType()); } } TEST(WeakQTypeTest, WithScalarQType) { { ASSERT_OK_AND_ASSIGN( QTypePtr res_qtype, WithScalarQType(GetQType<float>(), GetWeakFloatQType())); EXPECT_EQ(res_qtype, GetWeakFloatQType()); } { ASSERT_OK_AND_ASSIGN( QTypePtr res_qtype, WithScalarQType(GetOptionalQType<double>(), GetWeakFloatQType())); EXPECT_EQ(res_qtype, GetOptionalWeakFloatQType()); } EXPECT_THAT(WithScalarQType(GetArrayQType<float>(), GetWeakFloatQType()), StatusIs(absl::StatusCode::kInvalidArgument, MatchesRegex("Array type with elements of type " "WEAK_FLOAT is not registered."))); { ASSERT_OK_AND_ASSIGN( QTypePtr res_qtype, WithScalarQType(GetWeakFloatQType(), GetQType<double>())); EXPECT_EQ(res_qtype, GetQType<double>()); } { ASSERT_OK_AND_ASSIGN( QTypePtr res_qtype, WithScalarQType(GetOptionalWeakFloatQType(), GetQType<float>())); EXPECT_EQ(res_qtype, GetOptionalQType<float>()); } } TEST(WeakQTypeTest, DecayContainerQType) { EXPECT_EQ(DecayContainerQType(GetWeakFloatQType()), GetWeakFloatQType()); EXPECT_EQ(DecayContainerQType(GetOptionalWeakFloatQType()), GetWeakFloatQType()); } TEST(WeakQTypeTest, GetShapeQType) { { ASSERT_OK_AND_ASSIGN(QTypePtr shape_qtype, GetShapeQType(GetWeakFloatQType())); EXPECT_EQ(shape_qtype, GetQType<ScalarShape>()); } { ASSERT_OK_AND_ASSIGN(QTypePtr shape_qtype, GetShapeQType(GetOptionalWeakFloatQType())); EXPECT_EQ(shape_qtype, GetQType<OptionalScalarShape>()); } } TEST(WeakQTypeTest, GetPresenceQType) { { ASSERT_OK_AND_ASSIGN(QTypePtr presence_qtype, GetPresenceQType(GetWeakFloatQType())); EXPECT_EQ(presence_qtype, GetQType<Unit>()); } { ASSERT_OK_AND_ASSIGN(QTypePtr presence_qtype, GetPresenceQType(GetOptionalWeakFloatQType())); EXPECT_EQ(presence_qtype, GetOptionalQType<Unit>()); } } TEST(WeakQTypeTest, OptionalLike) { EXPECT_FALSE(IsOptionalLikeQType(GetWeakFloatQType())); EXPECT_TRUE(IsOptionalLikeQType(GetOptionalWeakFloatQType())); { ASSERT_OK_AND_ASSIGN(QTypePtr optional_like_qtype, ToOptionalLikeQType(GetWeakFloatQType())); EXPECT_EQ(optional_like_qtype, GetOptionalWeakFloatQType()); } { ASSERT_OK_AND_ASSIGN(QTypePtr optional_like_qtype, ToOptionalLikeQType(GetOptionalWeakFloatQType())); EXPECT_EQ(optional_like_qtype, GetOptionalWeakFloatQType()); } } TEST(WeakQTypeTest, WeakFloatFingerprint) { const double value_a = 1.5; const double value_b = 2.5; const auto float64_qvalue_a = TypedValue::FromValue(value_a); ASSERT_OK_AND_ASSIGN( const auto weak_float_qvalue_a1, TypedValue::FromValueWithQType(value_a, GetWeakFloatQType())); ASSERT_OK_AND_ASSIGN( const auto weak_float_qvalue_a2, TypedValue::FromValueWithQType(value_a, GetWeakFloatQType())); ASSERT_OK_AND_ASSIGN( const auto weak_float_qvalue_b, TypedValue::FromValueWithQType(value_b, GetWeakFloatQType())); EXPECT_NE(float64_qvalue_a.GetFingerprint(), weak_float_qvalue_a1.GetFingerprint()); EXPECT_EQ(weak_float_qvalue_a1.GetFingerprint(), weak_float_qvalue_a2.GetFingerprint()); EXPECT_NE(weak_float_qvalue_a1.GetFingerprint(), weak_float_qvalue_b.GetFingerprint()); } TEST(WeakQTypeTest, OptionalWeakFloatFingerprint) { const OptionalValue<double> value_a(1.5); const OptionalValue<double> value_b(2.5); const auto optional_float64_qvalue_a = TypedValue::FromValue(value_a); ASSERT_OK_AND_ASSIGN( const auto optional_weak_float_qvalue_a1, TypedValue::FromValueWithQType(value_a, GetOptionalWeakFloatQType())); ASSERT_OK_AND_ASSIGN( const auto optional_weak_float_qvalue_a2, TypedValue::FromValueWithQType(value_a, GetOptionalWeakFloatQType())); ASSERT_OK_AND_ASSIGN( const auto optional_weak_float_qvalue_b, TypedValue::FromValueWithQType(value_b, GetOptionalWeakFloatQType())); EXPECT_NE(optional_float64_qvalue_a.GetFingerprint(), optional_weak_float_qvalue_a1.GetFingerprint()); EXPECT_EQ(optional_weak_float_qvalue_a1.GetFingerprint(), optional_weak_float_qvalue_a2.GetFingerprint()); EXPECT_NE(optional_weak_float_qvalue_a1.GetFingerprint(), optional_weak_float_qvalue_b.GetFingerprint()); } TEST(WeakQTypeTest, WeakFloatRepr) { ASSERT_OK_AND_ASSIGN(auto qvalue, TypedValue::FromValueWithQType( double{1.5}, GetWeakFloatQType())); EXPECT_THAT(qvalue.GenReprToken(), ReprTokenEq("weak_float{1.5}")); } TEST(WeakQTypeTest, OptionalWeakFloatRepr) { ASSERT_OK_AND_ASSIGN( auto qvalue, TypedValue::FromValueWithQType(OptionalValue<double>(1.5), GetOptionalWeakFloatQType())); EXPECT_THAT(qvalue.GenReprToken(), ReprTokenEq("optional_weak_float{1.5}")); } TEST(WeakQTypeTest, OptionalWeakFloatMissingValueRepr) { ASSERT_OK_AND_ASSIGN( auto qvalue, TypedValue::FromValueWithQType(OptionalValue<double>(), GetOptionalWeakFloatQType())); EXPECT_THAT(qvalue.GenReprToken(), ReprTokenEq("optional_weak_float{NA}")); } } }
2,350
#ifndef AROLLA_QTYPE_ANY_QTYPE_H_ #define AROLLA_QTYPE_ANY_QTYPE_H_ #include <any> #include <cstdint> #include <functional> #include <type_traits> #include <typeinfo> #include "absl/random/distributions.h" #include "absl/random/random.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "arolla/qtype/simple_qtype.h" #include "arolla/util/fingerprint.h" namespace arolla { class Any { public: Any() = default; Any(Any&&) = default; Any(const Any&) = default; Any& operator=(Any&&) = default; Any& operator=(const Any&) = default; template <typename T, typename = std::enable_if_t<!std::is_same_v<Any, std::decay_t<T>>>> explicit Any(T&& v) : value_(std::forward<T>(v)) { absl::BitGen b; fingerprint_val1_ = absl::Uniform<uint64_t>(b); fingerprint_val2_ = absl::Uniform<uint64_t>(b); } template <typename T> absl::StatusOr<std::reference_wrapper<const T>> As() const { const T* v = std::any_cast<T>(&value_); if (v) { return *v; } else { return InvalidCast(typeid(T)); } } void ArollaFingerprint(FingerprintHasher* hasher) const { hasher->Combine(fingerprint_val1_, fingerprint_val2_); } private: std::any value_; uint64_t fingerprint_val1_, fingerprint_val2_; absl::Status InvalidCast(const std::type_info& t) const; }; AROLLA_DECLARE_SIMPLE_QTYPE(ANY, Any); } #endif #include "arolla/qtype/any_qtype.h" #include <typeinfo> #include "absl/status/status.h" #include "absl/strings/str_format.h" #include "arolla/qtype/simple_qtype.h" #include "arolla/util/demangle.h" namespace arolla { absl::Status Any::InvalidCast(const std::type_info& t) const { if (value_.has_value()) { return absl::FailedPreconditionError(absl::StrFormat( "can not cast Any(%s) to %s", TypeName(value_.type()), TypeName(t))); } else { return absl::FailedPreconditionError("can not cast an empty ::arolla::Any"); } } AROLLA_DEFINE_SIMPLE_QTYPE(ANY, Any); }
#include "arolla/qtype/any_qtype.h" #include <string> #include <utility> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla { namespace { using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::testing::HasSubstr; TEST(AnyQType, AnyConstructorRegression) { Any any; Any copy_1 = any; Any copy_2(any); Any copy_3 = std::move(any); Any copy_4(std::move(copy_2)); } TEST(AnyQType, Any) { int v1 = 5; std::string v2 = "string"; TypedValue tv1 = TypedValue::FromValue(Any(v1)); TypedValue tv2 = TypedValue::FromValue(Any(v2)); TypedValue tv3 = TypedValue::FromValue(Any()); ASSERT_OK_AND_ASSIGN(const Any& a1, tv1.As<Any>()); ASSERT_OK_AND_ASSIGN(const Any& a2, tv2.As<Any>()); ASSERT_OK_AND_ASSIGN(const Any& a3, tv3.As<Any>()); EXPECT_THAT(a1.As<int>(), IsOkAndHolds(v1)); EXPECT_THAT(a1.As<double>(), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("can not cast Any"))); ASSERT_OK_AND_ASSIGN(const std::string& v2_res, a2.As<std::string>()); EXPECT_EQ(v2, v2_res); EXPECT_THAT(a2.As<double>(), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("can not cast Any"))); EXPECT_THAT(a3.As<double>(), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("can not cast an empty ::arolla::Any"))); } TEST(AnyQType, Fingerprint) { Any a = Any(1); Any b = Any(1); Any a_copy = a; EXPECT_NE(TypedValue::FromValue(a).GetFingerprint(), TypedValue::FromValue(b).GetFingerprint()); EXPECT_EQ(TypedValue::FromValue(a).GetFingerprint(), TypedValue::FromValue(a_copy).GetFingerprint()); } } }
2,351
#ifndef AROLLA_QTYPE_DERIVED_QTYPE_H_ #define AROLLA_QTYPE_DERIVED_QTYPE_H_ #include <string> #include "absl/status/status.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_ref.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/fingerprint.h" #include "arolla/util/repr.h" namespace arolla { class DerivedQTypeInterface { public: virtual ~DerivedQTypeInterface() = default; virtual QTypePtr GetBaseQType() const = 0; }; class BasicDerivedQType : public QType, public DerivedQTypeInterface { public: ReprToken UnsafeReprToken(const void* source) const override; void UnsafeCombineToFingerprintHasher(const void* source, FingerprintHasher* hasher) const final; void UnsafeCopy(const void* source, void* destination) const final; QTypePtr GetBaseQType() const final { return base_qtype_; } protected: struct ConstructorArgs { std::string name; QTypePtr base_qtype; const QType* value_qtype = nullptr; std::string qtype_specialization_key; }; explicit BasicDerivedQType(ConstructorArgs args); private: QTypePtr base_qtype_; }; absl::Status VerifyDerivedQType(QTypePtr qtype); const QType* DecayDerivedQType(const QType* qtype); TypedRef DecayDerivedQValue(TypedRef qvalue); TypedValue DecayDerivedQValue(const TypedValue& qvalue); TypedRef UnsafeDowncastDerivedQValue(QTypePtr derived_qtype, TypedRef qvalue); TypedValue UnsafeDowncastDerivedQValue(QTypePtr derived_qtype, const TypedValue& qvalue); } #endif #include "arolla/qtype/derived_qtype.h" #include <cstddef> #include <utility> #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_ref.h" #include "arolla/qtype/typed_slot.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/fingerprint.h" #include "arolla/util/repr.h" namespace arolla { BasicDerivedQType::BasicDerivedQType(ConstructorArgs args) : QType(QType::ConstructorArgs{ .name = std::move(args.name), .type_info = args.base_qtype->type_info(), .type_layout = args.base_qtype->type_layout(), .type_fields = args.base_qtype->type_fields(), .value_qtype = args.value_qtype, .qtype_specialization_key = std::move(args.qtype_specialization_key), }), base_qtype_(args.base_qtype) { CHECK_OK(VerifyDerivedQType(this)); } ReprToken BasicDerivedQType::UnsafeReprToken(const void* source) const { return ReprToken{ absl::StrCat(name(), "{", base_qtype_->UnsafeReprToken(source).str, "}")}; } void BasicDerivedQType::UnsafeCopy(const void* source, void* destination) const { base_qtype_->UnsafeCopy(source, destination); } void BasicDerivedQType::UnsafeCombineToFingerprintHasher( const void* source, FingerprintHasher* hasher) const { base_qtype_->UnsafeCombineToFingerprintHasher(source, hasher); } const QType* DecayDerivedQType(const QType* qtype) { if (auto* derived_qtype_interface = dynamic_cast<const DerivedQTypeInterface*>(qtype)) { return derived_qtype_interface->GetBaseQType(); } return qtype; } absl::Status VerifyDerivedQType(QTypePtr qtype) { const auto* derived_qtype_interface = dynamic_cast<const DerivedQTypeInterface*>(qtype); if (derived_qtype_interface == nullptr) { return absl::InvalidArgumentError( absl::StrFormat("%s is not a derived qtype", qtype->name())); } const auto* base_qtype = derived_qtype_interface->GetBaseQType(); if (base_qtype == nullptr) { return absl::FailedPreconditionError(absl::StrFormat( "invalid derived_qtype=%s: base_qtype=nullptr", qtype->name())); } if (dynamic_cast<const DerivedQTypeInterface*>(base_qtype) != nullptr) { return absl::FailedPreconditionError(absl::StrFormat( "base_qtype=%s cannot be a derived qtype", base_qtype->name())); } const bool type_info_ok = (qtype->type_info() == base_qtype->type_info()); if (!type_info_ok) { return absl::FailedPreconditionError(absl::StrFormat( "invalid derived_qtype=%s: base_qtype=%s: incompatible type_info", qtype->name(), base_qtype->name())); } const bool type_layout_ok = (qtype->type_layout().AllocSize() == base_qtype->type_layout().AllocSize() && qtype->type_layout().AllocAlignment().value == base_qtype->type_layout().AllocAlignment().value); if (!type_layout_ok) { return absl::FailedPreconditionError(absl::StrFormat( "invalid derived_qtype=%s: base_qtype=%s: incompatible type_layout", qtype->name(), base_qtype->name())); } bool type_fields_ok = (qtype->type_fields().empty() || qtype->type_fields().size() == base_qtype->type_fields().size()); for (size_t i = 0; type_fields_ok && i < qtype->type_fields().size() && i < base_qtype->type_fields().size(); ++i) { const auto& derived_field = qtype->type_fields()[i]; const auto& base_field = base_qtype->type_fields()[i]; type_fields_ok = type_fields_ok && (derived_field.byte_offset() == base_field.byte_offset() && DecayDerivedQType(derived_field.GetType()) == DecayDerivedQType(base_field.GetType())); } if (!type_layout_ok) { return absl::FailedPreconditionError(absl::StrFormat( "invalid derived_qtype=%s: base_qtype=%s: incompatible type_fields", qtype->name(), base_qtype->name())); } const bool value_qtype_ok = (qtype->value_qtype() == nullptr || base_qtype->value_qtype() == nullptr || DecayDerivedQType(qtype->value_qtype()) == DecayDerivedQType(base_qtype->value_qtype())); if (!value_qtype_ok) { return absl::FailedPreconditionError(absl::StrFormat( "invalid derived_qtype=%s: base_qtype=%s: incompatible value_qtype", qtype->name(), base_qtype->name())); } return absl::OkStatus(); } TypedRef DecayDerivedQValue(TypedRef qvalue) { return TypedRef::UnsafeFromRawPointer(DecayDerivedQType(qvalue.GetType()), qvalue.GetRawPointer()); } TypedValue DecayDerivedQValue(const TypedValue& qvalue) { return TypedValue(DecayDerivedQValue(qvalue.AsRef())); } TypedRef UnsafeDowncastDerivedQValue(QTypePtr derived_qtype, TypedRef qvalue) { DCHECK_NE(derived_qtype, nullptr); auto* base_qtype = DecayDerivedQType(derived_qtype); DCHECK_EQ(qvalue.GetType(), base_qtype); return TypedRef::UnsafeFromRawPointer(derived_qtype, qvalue.GetRawPointer()); } TypedValue UnsafeDowncastDerivedQValue(QTypePtr derived_qtype, const TypedValue& qvalue) { return TypedValue(UnsafeDowncastDerivedQValue(derived_qtype, qvalue.AsRef())); } }
#include "arolla/qtype/derived_qtype.h" #include <utility> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/tuple_qtype.h" #include "arolla/qtype/typed_ref.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/fingerprint.h" #include "arolla/util/indestructible.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/repr_token_eq.h" namespace arolla { namespace { using ::arolla::testing::ReprTokenEq; struct PointQType final : BasicDerivedQType { PointQType() : BasicDerivedQType(ConstructorArgs{ .name = "POINT", .base_qtype = MakeTupleQType({GetQType<double>(), GetQType<double>()}), .value_qtype = GetQType<double>(), .qtype_specialization_key = "::arolla::PointQType", }) {} static QTypePtr get() { static const Indestructible<PointQType> result; return result.get(); } }; class BasicDerivedQTypeTest : public ::testing::Test { void SetUp() override { ASSERT_OK(InitArolla()); } }; TEST_F(BasicDerivedQTypeTest, QTypeProperties) { const auto point_qtype = PointQType::get(); EXPECT_EQ(point_qtype->name(), "POINT"); EXPECT_EQ(point_qtype->value_qtype(), GetQType<double>()); EXPECT_EQ(point_qtype->qtype_specialization_key(), "::arolla::PointQType"); const auto tuple_qtype = MakeTupleQType({GetQType<double>(), GetQType<double>()}); EXPECT_EQ(point_qtype->type_info(), tuple_qtype->type_info()); EXPECT_EQ(point_qtype->type_layout().AllocSize(), tuple_qtype->type_layout().AllocSize()); EXPECT_EQ(point_qtype->type_layout().AllocAlignment().value, tuple_qtype->type_layout().AllocAlignment().value); EXPECT_EQ(point_qtype->type_fields().size(), 2); } TEST_F(BasicDerivedQTypeTest, DefaultRepr) { const auto tuple_qvalue = MakeTupleFromFields(1., 2.); const auto point_qvalue = UnsafeDowncastDerivedQValue(PointQType::get(), tuple_qvalue.AsRef()); EXPECT_THAT(point_qvalue.GenReprToken(), ReprTokenEq("POINT{(float64{1}, float64{2})}")); } TEST_F(BasicDerivedQTypeTest, UnsafeCombineToFingerprintHasher) { const auto tuple_qvalue = MakeTupleFromFields(1., 2.); const auto* tuple_qtype = tuple_qvalue.GetType(); const auto* point_qtype = PointQType::get(); FingerprintHasher hasher1("seed"); FingerprintHasher hasher2("seed"); tuple_qtype->UnsafeCombineToFingerprintHasher(tuple_qvalue.GetRawPointer(), &hasher1); point_qtype->UnsafeCombineToFingerprintHasher(tuple_qvalue.GetRawPointer(), &hasher2); EXPECT_EQ(std::move(hasher1).Finish(), std::move(hasher2).Finish()); } TEST_F(BasicDerivedQTypeTest, DecayDerivedQType) { const auto point_qtype = PointQType::get(); const auto tuple_qtype = MakeTupleQType({GetQType<double>(), GetQType<double>()}); EXPECT_NE(point_qtype, tuple_qtype); EXPECT_EQ(DecayDerivedQType(point_qtype), tuple_qtype); EXPECT_EQ(DecayDerivedQType(tuple_qtype), tuple_qtype); EXPECT_EQ(DecayDerivedQType(nullptr), nullptr); } TEST_F(BasicDerivedQTypeTest, UnsafeDowncastDerivedQRef) { const auto tuple_qvalue = MakeTupleFromFields(1., 2.); const auto point_qvalue = TypedValue( UnsafeDowncastDerivedQValue(PointQType::get(), tuple_qvalue.AsRef())); EXPECT_EQ(point_qvalue.GetType(), PointQType::get()); EXPECT_NE(point_qvalue.GetFingerprint(), tuple_qvalue.GetFingerprint()); } TEST_F(BasicDerivedQTypeTest, UnsafeDowncastDerivedQValue) { const auto tuple_qvalue = MakeTupleFromFields(1., 2.); const auto point_qvalue = UnsafeDowncastDerivedQValue(PointQType::get(), tuple_qvalue); EXPECT_EQ(point_qvalue.GetType(), PointQType::get()); EXPECT_NE(point_qvalue.GetFingerprint(), tuple_qvalue.GetFingerprint()); } TEST_F(BasicDerivedQTypeTest, DecayDerivedQRef) { const auto tuple_qvalue = MakeTupleFromFields(1., 2.); const auto point_qvalue = TypedValue( UnsafeDowncastDerivedQValue(PointQType::get(), tuple_qvalue.AsRef())); EXPECT_NE(point_qvalue.GetFingerprint(), tuple_qvalue.GetFingerprint()); EXPECT_EQ( TypedValue(DecayDerivedQValue(point_qvalue.AsRef())).GetFingerprint(), tuple_qvalue.GetFingerprint()); EXPECT_EQ( TypedValue(DecayDerivedQValue(tuple_qvalue.AsRef())).GetFingerprint(), tuple_qvalue.GetFingerprint()); } TEST_F(BasicDerivedQTypeTest, DecayDerivedQValue) { const auto tuple_qvalue = MakeTupleFromFields(1., 2.); const auto point_qvalue = UnsafeDowncastDerivedQValue(PointQType::get(), tuple_qvalue); EXPECT_NE(point_qvalue.GetFingerprint(), tuple_qvalue.GetFingerprint()); EXPECT_EQ(DecayDerivedQValue(point_qvalue).GetFingerprint(), tuple_qvalue.GetFingerprint()); EXPECT_EQ(TypedValue(DecayDerivedQValue(tuple_qvalue)).GetFingerprint(), tuple_qvalue.GetFingerprint()); } } }
2,352
#ifndef AROLLA_QTYPE_TYPED_SLOT_H_ #define AROLLA_QTYPE_TYPED_SLOT_H_ #include <array> #include <cstddef> #include <cstdint> #include <optional> #include <ostream> #include <string> #include <tuple> #include <typeinfo> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/types/span.h" #include "arolla/memory/frame.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/util/status.h" #include "arolla/util/status_macros_backport.h" namespace arolla { class TypedSlot { public: template <typename T> using Slot = FrameLayout::Slot<T>; TypedSlot(const TypedSlot&) = default; TypedSlot& operator=(const TypedSlot&) = default; static TypedSlot UnsafeFromOffset(QTypePtr type, size_t byte_offset) { return TypedSlot(type, byte_offset); } template <typename T> static TypedSlot FromSlot(Slot<T> slot, QTypePtr type) { DCHECK(type->type_info() == typeid(T)) << "Type mismatch"; return TypedSlot(type, slot.byte_offset()); } template <typename T> static TypedSlot FromSlot(Slot<T> slot) { return TypedSlot(GetQType<T>(), slot.byte_offset()); } template <class T> absl::StatusOr<Slot<T>> ToSlot() const { RETURN_IF_ERROR(VerifyType(typeid(T))); return Slot<T>::UnsafeSlotFromOffset(byte_offset_); } template <class T> Slot<T> UnsafeToSlot() const { DCHECK(GetType()->type_info() == typeid(T)); return Slot<T>::UnsafeSlotFromOffset(byte_offset_); } int64_t SubSlotCount() const { return type_->type_fields().size(); } TypedSlot SubSlot(int64_t index) const { DCHECK_GE(index, 0); DCHECK_LT(index, SubSlotCount()); const auto& field = type_->type_fields()[index]; return TypedSlot(field.GetType(), byte_offset_ + field.byte_offset()); } QTypePtr GetType() const { return type_; } size_t byte_offset() const { return byte_offset_; } void CopyTo(ConstFramePtr source_frame, TypedSlot destination_slot, FramePtr destination_frame) const { DCHECK_EQ(type_, destination_slot.type_) << "Type mismatch"; source_frame.DCheckFieldType(byte_offset_, type_->type_info()); destination_frame.DCheckFieldType(destination_slot.byte_offset_, destination_slot.type_->type_info()); type_->UnsafeCopy( source_frame.GetRawPointer(byte_offset_), destination_frame.GetRawPointer(destination_slot.byte_offset_)); } void Reset(FramePtr frame) const { frame.DCheckFieldType(byte_offset_, type_->type_info()); const auto& layout = type_->type_layout(); void* ptr = frame.GetRawPointer(byte_offset_); layout.DestroyAlloc(ptr); layout.InitializeAlignedAlloc(ptr); } friend bool operator==(const TypedSlot& a, const TypedSlot& b) { return a.type_ == b.type_ && a.byte_offset_ == b.byte_offset_; } friend bool operator!=(const TypedSlot& a, const TypedSlot& b) { return !(a == b); } template <typename H> friend H AbslHashValue(H h, const TypedSlot& a) { return H::combine(std::move(h), a.type_, a.byte_offset_); } friend std::ostream& operator<<(std::ostream& out, const TypedSlot& ts) { return out << "TypedSlot<" << ts.GetType()->name() << ">@" << ts.byte_offset_; } template <typename... Ts> static absl::StatusOr<std::tuple<FrameLayout::Slot<Ts>...>> ToSlots( absl::Span<const TypedSlot> slots) { if (slots.size() != sizeof...(Ts)) { return absl::Status( absl::StatusCode::kInvalidArgument, absl::StrFormat("wrong number of slots: expected %d, got %d", sizeof...(Ts), slots.size())); } return ToSlotsImpl<std::tuple<FrameLayout::Slot<Ts>...>>( slots, std::index_sequence_for<Ts...>{}); } private: TypedSlot(const QType* type, size_t byte_offset) : type_(type), byte_offset_(byte_offset) {} absl::Status VerifyType(const std::type_info& tpe) const; template <typename ResultTuple, std::size_t... is> static absl::StatusOr<ResultTuple> ToSlotsImpl( absl::Span<const TypedSlot> slots, std::index_sequence<is...>) { (void)slots; return LiftStatusUp(slots[is] .ToSlot<typename std::tuple_element_t< is, ResultTuple>::value_type>()...); } QTypePtr type_; size_t byte_offset_; }; template <typename... Slots> std::array<TypedSlot, sizeof...(Slots)> ToTypedSlots(Slots... slots) { return std::array<TypedSlot, sizeof...(Slots)>{TypedSlot::FromSlot(slots)...}; } std::vector<QTypePtr> SlotsToTypes(absl::Span<const TypedSlot> slots); absl::flat_hash_map<std::string, QTypePtr> SlotsToTypes( const absl::flat_hash_map<std::string, TypedSlot>& slots); inline TypedSlot AddSlot(QTypePtr type, FrameLayout::Builder* layout_builder) { return TypedSlot::UnsafeFromOffset( type, layout_builder->AddSubFrame(type->type_layout()).byte_offset()); } std::vector<TypedSlot> AddSlots(absl::Span<const QTypePtr> types, FrameLayout::Builder* layout_builder); std::vector<std::pair<std::string, TypedSlot>> AddNamedSlots( absl::Span<const std::pair<std::string, QTypePtr>> types, FrameLayout::Builder* layout_builder); absl::flat_hash_map<std::string, TypedSlot> AddSlotsMap( const absl::flat_hash_map<std::string, QTypePtr>& types, FrameLayout::Builder* layout_builder); absl::Status RegisterUnsafeSlots(absl::Span<const TypedSlot> slots, FrameLayout::Builder* layout_builder); absl::Status RegisterUnsafeSlotsMap( const absl::flat_hash_map<std::string, TypedSlot>& slots, FrameLayout::Builder* layout_builder); absl::StatusOr<std::vector<std::optional<TypedSlot>>> MaybeFindSlotsAndVerifyTypes( absl::Span<const std::pair<std::string, QTypePtr>> types_in_order, const absl::flat_hash_map<std::string, TypedSlot>& slots); absl::StatusOr<std::vector<TypedSlot>> FindSlotsAndVerifyTypes( absl::Span<const std::pair<std::string, QTypePtr>> types_in_order, const absl::flat_hash_map<std::string, TypedSlot>& slots); absl::Status VerifySlotTypes( const absl::flat_hash_map<std::string, QTypePtr>& types, const absl::flat_hash_map<std::string, TypedSlot>& slots, bool verify_unwanted_slots = true, bool verify_missed_slots = true); } #endif #include "arolla/qtype/typed_slot.h" #include <algorithm> #include <optional> #include <string> #include <typeinfo> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/memory/frame.h" #include "arolla/qtype/qtype.h" #include "arolla/util/demangle.h" #include "arolla/util/status_macros_backport.h" namespace arolla { namespace { std::string TypeMismatchError(absl::string_view name, QTypePtr expected_type, QTypePtr actual_type) { return absl::StrFormat("%s{expected:%s, actual:%s}", name, expected_type->name(), actual_type->name()); } absl::Status SlotTypesError(std::vector<std::string> missed_slots, std::vector<std::string> type_mismatch, std::vector<std::string> unwanted_slots) { if (missed_slots.empty() && type_mismatch.empty() && unwanted_slots.empty()) { return absl::OkStatus(); } std::string msg = "slots/types match errors:"; if (!missed_slots.empty()) { std::sort(missed_slots.begin(), missed_slots.end()); msg += absl::StrFormat("missed slots: %s;", absl::StrJoin(missed_slots, ",")); } if (!type_mismatch.empty()) { std::sort(type_mismatch.begin(), type_mismatch.end()); msg += absl::StrFormat("slot types mismatch: %s;", absl::StrJoin(type_mismatch, ",")); } if (!unwanted_slots.empty()) { std::sort(unwanted_slots.begin(), unwanted_slots.end()); msg += absl::StrFormat("unwanted slots: %s;", absl::StrJoin(unwanted_slots, ",")); } return absl::FailedPreconditionError(msg); } } std::vector<QTypePtr> SlotsToTypes(absl::Span<const TypedSlot> slots) { std::vector<QTypePtr> types; types.reserve(slots.size()); for (const auto& slot : slots) { types.push_back(slot.GetType()); } return types; } absl::Status TypedSlot::VerifyType(const std::type_info& tpe) const { if (GetType()->type_info() != tpe) { return absl::InvalidArgumentError(absl::StrFormat( "slot type does not match C++ type: expected %s, got %s", TypeName(tpe), TypeName(GetType()->type_info()))); } return absl::OkStatus(); } absl::flat_hash_map<std::string, QTypePtr> SlotsToTypes( const absl::flat_hash_map<std::string, TypedSlot>& slots) { absl::flat_hash_map<std::string, QTypePtr> types; types.reserve(slots.size()); for (const auto& kv : slots) { types[kv.first] = kv.second.GetType(); } return types; } std::vector<TypedSlot> AddSlots(absl::Span<const QTypePtr> types, FrameLayout::Builder* layout_builder) { std::vector<TypedSlot> slots; slots.reserve(types.size()); for (const auto* type : types) { slots.push_back(AddSlot(type, layout_builder)); } return slots; } std::vector<std::pair<std::string, TypedSlot>> AddNamedSlots( absl::Span<const std::pair<std::string, QTypePtr>> types, FrameLayout::Builder* layout_builder) { std::vector<std::pair<std::string, TypedSlot>> slots; slots.reserve(types.size()); for (const auto& [name, type] : types) { slots.emplace_back(name, AddSlot(type, layout_builder)); } return slots; } absl::flat_hash_map<std::string, TypedSlot> AddSlotsMap( const absl::flat_hash_map<std::string, const QType*>& types, FrameLayout::Builder* layout_builder) { absl::flat_hash_map<std::string, TypedSlot> slots; slots.reserve(types.size()); for (const auto& name_type : types) { slots.insert({name_type.first, AddSlot(name_type.second, layout_builder)}); } return slots; } absl::Status RegisterUnsafeSlots(absl::Span<const TypedSlot> slots, FrameLayout::Builder* layout_builder) { for (const auto& slot : slots) { RETURN_IF_ERROR(layout_builder->RegisterUnsafeSlot( slot.byte_offset(), slot.GetType()->type_layout().AllocSize(), slot.GetType()->type_info())); } return absl::OkStatus(); } absl::Status RegisterUnsafeSlotsMap( const absl::flat_hash_map<std::string, TypedSlot>& slots, FrameLayout::Builder* layout_builder) { for (const auto& name_slot : slots) { const auto& slot = name_slot.second; RETURN_IF_ERROR(layout_builder->RegisterUnsafeSlot( slot.byte_offset(), slot.GetType()->type_layout().AllocSize(), slot.GetType()->type_info())); } return absl::OkStatus(); } absl::StatusOr<std::vector<std::optional<TypedSlot>>> MaybeFindSlotsAndVerifyTypes( absl::Span<const std::pair<std::string, QTypePtr>> types_in_order, const absl::flat_hash_map<std::string, TypedSlot>& slots) { std::vector<std::string> type_mismatch; std::vector<std::optional<TypedSlot>> res_slots; res_slots.reserve(types_in_order.size()); for (const auto& [name, type] : types_in_order) { auto it = slots.find(name); if (it == slots.end()) { res_slots.push_back(std::nullopt); continue; } res_slots.push_back({it->second}); if (it->second.GetType() != type) { type_mismatch.push_back( TypeMismatchError(name, type, it->second.GetType())); } } RETURN_IF_ERROR(SlotTypesError({}, std::move(type_mismatch), {})); return {std::move(res_slots)}; } absl::StatusOr<std::vector<TypedSlot>> FindSlotsAndVerifyTypes( absl::Span<const std::pair<std::string, QTypePtr>> types_in_order, const absl::flat_hash_map<std::string, TypedSlot>& slots) { std::vector<std::string> missed_slots; std::vector<std::string> type_mismatch; std::vector<TypedSlot> res_slots; res_slots.reserve(types_in_order.size()); for (const auto& [name, type] : types_in_order) { auto it = slots.find(name); if (it == slots.end()) { missed_slots.push_back(name); continue; } res_slots.push_back({it->second}); if (it->second.GetType() != type) { type_mismatch.push_back( TypeMismatchError(name, type, it->second.GetType())); } } RETURN_IF_ERROR(SlotTypesError(std::move(missed_slots), std::move(type_mismatch), {})); return {std::move(res_slots)}; } absl::Status VerifySlotTypes( const absl::flat_hash_map<std::string, QTypePtr>& types, const absl::flat_hash_map<std::string, TypedSlot>& slots, bool verify_unwanted_slots, bool verify_missed_slots) { std::vector<std::string> missed_slots; std::vector<std::string> type_mismatch; std::vector<std::string> unwanted_slots; for (const auto& [name, type] : types) { auto it = slots.find(name); if (it == slots.end()) { if (verify_missed_slots) { missed_slots.push_back(name); } continue; } if (it->second.GetType() != type) { type_mismatch.push_back( TypeMismatchError(name, type, it->second.GetType())); } } if (verify_unwanted_slots) { for (const auto& [name, _] : slots) { if (!types.contains(name)) { unwanted_slots.push_back(name); } } } return SlotTypesError(std::move(missed_slots), std::move(type_mismatch), std::move(unwanted_slots)); } }
#include "arolla/qtype/typed_slot.h" #include <cstdint> #include <optional> #include <sstream> #include <string> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/container/flat_hash_map.h" #include "absl/status/status.h" #include "arolla/memory/frame.h" #include "arolla/memory/memory_allocation.h" #include "arolla/memory/optional_value.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/util/bytes.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla { namespace { using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::testing::ElementsAre; using ::testing::Eq; using ::testing::HasSubstr; using ::testing::MatchesRegex; using ::testing::Pair; using ::testing::StrEq; using ::testing::UnorderedElementsAre; TEST(TypedSlotTest, Copy) { FrameLayout::Builder layout_builder; auto slot = layout_builder.AddSlot<int>(); auto slot2 = layout_builder.AddSlot<float>(); auto typed_slot = TypedSlot::FromSlot(slot); auto typed_slot2 = TypedSlot::FromSlot(slot2); auto typed_slot_copy = typed_slot; EXPECT_EQ(typed_slot.GetType(), typed_slot_copy.GetType()); EXPECT_EQ(typed_slot, typed_slot_copy); typed_slot_copy = typed_slot2; EXPECT_EQ(typed_slot2.GetType(), typed_slot_copy.GetType()); EXPECT_EQ(typed_slot2, typed_slot_copy); } TEST(TypedSlotTest, PrimitiveTypes) { FrameLayout::Builder layout_builder; auto slot = layout_builder.AddSlot<int32_t>(); auto typed_slot = TypedSlot::FromSlot(slot); EXPECT_EQ(typed_slot.GetType(), GetQType<int32_t>()); FrameLayout::Slot<int32_t> new_slot = typed_slot.ToSlot<int32_t>().value(); EXPECT_EQ(slot.byte_offset(), new_slot.byte_offset()); EXPECT_THAT(typed_slot.ToSlot<int64_t>().status(), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST(TypedSlotTest, SlotsToTypes) { FrameLayout::Builder layout_builder; auto slot1 = layout_builder.AddSlot<int32_t>(); auto slot2 = layout_builder.AddSlot<float>(); auto typed_slot1 = TypedSlot::FromSlot(slot1); auto typed_slot2 = TypedSlot::FromSlot(slot2); EXPECT_THAT(SlotsToTypes(std::vector<TypedSlot>{typed_slot1, typed_slot2}), ElementsAre(GetQType<int32_t>(), GetQType<float>())); EXPECT_THAT(SlotsToTypes(absl::flat_hash_map<std::string, TypedSlot>{ {"X", typed_slot1}, {"Y", typed_slot2}}), UnorderedElementsAre(Pair("X", GetQType<int32_t>()), Pair("Y", GetQType<float>()))); } TEST(TypedSlotTest, UnsafeFromOffset) { const QType* i32 = GetQType<int32_t>(); auto typed_slot = TypedSlot::UnsafeFromOffset(i32, 10); EXPECT_EQ(typed_slot.byte_offset(), 10); EXPECT_EQ(typed_slot.GetType(), i32); } TEST(TypedSlotTest, AddSlots) { FrameLayout::Builder layout_builder; const QType* i32 = GetQType<int32_t>(); const QType* i64 = GetQType<int64_t>(); std::vector<TypedSlot> slots = AddSlots({i32, i64}, &layout_builder); ASSERT_EQ(slots.size(), 2); EXPECT_EQ(i32, slots[0].GetType()); EXPECT_EQ(i64, slots[1].GetType()); } TEST(TypedSlotTest, AddNamedSlots) { FrameLayout::Builder layout_builder; const QType* i32 = GetQType<int32_t>(); const QType* i64 = GetQType<int64_t>(); std::vector<std::pair<std::string, TypedSlot>> slots = AddNamedSlots({{"c", i32}, {"b", i64}}, &layout_builder); ASSERT_EQ(slots.size(), 2); EXPECT_EQ("c", slots[0].first); EXPECT_EQ(i32, slots[0].second.GetType()); EXPECT_EQ("b", slots[1].first); EXPECT_EQ(i64, slots[1].second.GetType()); } TEST(TypedSlotTest, AddSlotsMap) { FrameLayout::Builder layout_builder; const QType* i32 = GetQType<int32_t>(); const QType* i64 = GetQType<int64_t>(); absl::flat_hash_map<std::string, TypedSlot> slots = AddSlotsMap({{"a", i32}, {"b", i64}}, &layout_builder); ASSERT_EQ(slots.size(), 2); EXPECT_EQ(i32, slots.at("a").GetType()); EXPECT_EQ(i64, slots.at("b").GetType()); } TEST(TypedSlotTest, RegisterUnsafeSlots) { FrameLayout::Builder layout_builder; layout_builder.AddSlot<int64_t>(); const QType* i32 = GetQType<int32_t>(); const QType* f32 = GetQType<float>(); auto slot_i32 = TypedSlot::UnsafeFromOffset(i32, 0); auto slot_f32 = TypedSlot::UnsafeFromOffset(f32, 4); ASSERT_OK(RegisterUnsafeSlots({slot_i32, slot_f32}, &layout_builder)); #ifndef NDEBUG ASSERT_FALSE(RegisterUnsafeSlots({slot_i32}, &layout_builder).ok()); #endif auto layout = std::move(layout_builder).Build(); layout.HasField(0, typeid(int32_t)); layout.HasField(4, typeid(float)); } TEST(TypedSlotTest, RegisterUnsafeSlotsMap) { FrameLayout::Builder layout_builder; layout_builder.AddSlot<int64_t>(); const QType* i32 = GetQType<int32_t>(); const QType* f32 = GetQType<float>(); auto slot_i32 = TypedSlot::UnsafeFromOffset(i32, 0); auto slot_f32 = TypedSlot::UnsafeFromOffset(f32, 4); ASSERT_OK(RegisterUnsafeSlotsMap({{"a", slot_i32}, {"b", slot_f32}}, &layout_builder)); #ifndef NDEBUG ASSERT_FALSE(RegisterUnsafeSlotsMap({{"a", slot_i32}}, &layout_builder).ok()); #endif auto layout = std::move(layout_builder).Build(); layout.HasField(0, typeid(int32_t)); layout.HasField(4, typeid(float)); } TEST(TypedSlotTest, GetSubslots) { FrameLayout::Builder layout_builder; auto opt_float_slot = layout_builder.AddSlot<OptionalValue<float>>(); auto opt_int32_slot = layout_builder.AddSlot<OptionalValue<int32_t>>(); auto float64_slot = layout_builder.AddSlot<double>(); FrameLayout layout = std::move(layout_builder).Build(); TypedSlot opt_float_tslot = TypedSlot::FromSlot(opt_float_slot); TypedSlot opt_int32_tslot = TypedSlot::FromSlot(opt_int32_slot); TypedSlot float64_tslot = TypedSlot::FromSlot(float64_slot); EXPECT_EQ(opt_float_tslot.SubSlotCount(), 2); EXPECT_EQ(opt_int32_tslot.SubSlotCount(), 2); EXPECT_EQ(float64_tslot.SubSlotCount(), 0); EXPECT_EQ(opt_float_tslot.SubSlot(0), TypedSlot::FromSlot(opt_float_slot.GetSubslot<0>())); EXPECT_EQ(opt_float_tslot.SubSlot(1), TypedSlot::FromSlot(opt_float_slot.GetSubslot<1>())); EXPECT_EQ(opt_int32_tslot.SubSlot(0), TypedSlot::FromSlot(opt_int32_slot.GetSubslot<0>())); EXPECT_EQ(opt_int32_tslot.SubSlot(1), TypedSlot::FromSlot(opt_int32_slot.GetSubslot<1>())); MemoryAllocation alloc_holder(&layout); FramePtr frame = alloc_holder.frame(); frame.Set(opt_float_slot, OptionalValue<float>(1.0)); frame.Set(opt_int32_slot, OptionalValue<int32_t>()); auto float_present_slot = opt_float_tslot.SubSlot(0).ToSlot<bool>().value(); auto int32_present_slot = opt_int32_tslot.SubSlot(0).ToSlot<bool>().value(); EXPECT_EQ(frame.Get(float_present_slot), true); EXPECT_EQ(frame.Get(int32_present_slot), false); auto int32_value_slot = opt_int32_tslot.SubSlot(1).ToSlot<int32_t>().value(); frame.Set(int32_present_slot, true); frame.Set(int32_value_slot, 2); EXPECT_EQ(frame.Get(opt_int32_slot), OptionalValue<int32_t>(2)); } TEST(TypedSlotTest, DebugPrintTypedSlot) { FrameLayout::Builder layout_builder; auto slot1 = layout_builder.AddSlot<int32_t>(); auto slot2 = layout_builder.AddSlot<float>(); auto slot3 = layout_builder.AddSlot<Bytes>(); auto typed_slot1 = TypedSlot::FromSlot(slot1); auto typed_slot2 = TypedSlot::FromSlot(slot2); auto typed_slot3 = TypedSlot::FromSlot(slot3); std::stringstream buffer; buffer << "typed_slot1 is: " << typed_slot1 << ", "; buffer << "typed_slot2 is: " << typed_slot2 << ", "; buffer << "typed_slot3 is: " << typed_slot3 << "."; EXPECT_THAT(buffer.str(), StrEq("typed_slot1 is: TypedSlot<INT32>@0, " "typed_slot2 is: TypedSlot<FLOAT32>@4, " "typed_slot3 is: TypedSlot<BYTES>@8.")); } TEST(TypedSlotTest, ToSlots) { FrameLayout::Builder layout_builder; auto slot1 = layout_builder.AddSlot<int32_t>(); auto slot2 = layout_builder.AddSlot<float>(); ASSERT_OK_AND_ASSIGN( auto slots_tuple, (TypedSlot::ToSlots<int32_t, float>( {TypedSlot::FromSlot(slot1), TypedSlot::FromSlot(slot2)}))); EXPECT_THAT(std::get<0>(slots_tuple).byte_offset(), Eq(slot1.byte_offset())); EXPECT_THAT(std::get<1>(slots_tuple).byte_offset(), Eq(slot2.byte_offset())); EXPECT_THAT(TypedSlot::ToSlots<float>({TypedSlot::FromSlot(slot1)}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("slot type does not match C++ type"))); EXPECT_THAT( (TypedSlot::ToSlots<int32_t, float>({TypedSlot::FromSlot(slot1)})), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("wrong number of slots: expected 2, got 1"))); } TEST(TypedSlotTest, MaybeFindSlotsAndVerifyTypesErrors) { FrameLayout::Builder layout_builder; auto float_slot = layout_builder.AddSlot<float>(); EXPECT_THAT( MaybeFindSlotsAndVerifyTypes({{"a", GetQType<int>()}}, {{"a", TypedSlot::FromSlot(float_slot)}}), StatusIs(absl::StatusCode::kFailedPrecondition, MatchesRegex(".*slot types " "mismatch.*a.*expected:INT32.*actual:FLOAT32.*"))); } TEST(TypedSlotTest, MaybeFindSlotsAndVerifyTypes) { FrameLayout::Builder layout_builder; auto int_slot = layout_builder.AddSlot<int>(); auto float_slot = layout_builder.AddSlot<float>(); EXPECT_THAT( MaybeFindSlotsAndVerifyTypes( {{"a", GetQType<int>()}, {"c", GetQType<float>()}}, {{"b", TypedSlot::FromSlot(float_slot)}, {"a", TypedSlot::FromSlot(int_slot)}}), IsOkAndHolds(ElementsAre(TypedSlot::FromSlot(int_slot), std::nullopt))); } TEST(TypedSlotTest, FindSlotsAndVerifyTypesErrors) { FrameLayout::Builder layout_builder; auto float_slot = layout_builder.AddSlot<float>(); EXPECT_THAT( FindSlotsAndVerifyTypes({{"NAME", GetQType<int>()}}, {{"NAME", TypedSlot::FromSlot(float_slot)}}), StatusIs( absl::StatusCode::kFailedPrecondition, MatchesRegex(".*slot types " "mismatch.*NAME.*expected:INT32.*actual:FLOAT32.*"))); EXPECT_THAT(FindSlotsAndVerifyTypes({{"FAKE", GetQType<int>()}}, {{"b", TypedSlot::FromSlot(float_slot)}}), StatusIs(absl::StatusCode::kFailedPrecondition, MatchesRegex(".*missed slots:.*FAKE.*"))); EXPECT_THAT( FindSlotsAndVerifyTypes( {{"NAME", GetQType<int>()}, {"FAKE", GetQType<int>()}}, {{"NAME", TypedSlot::FromSlot(float_slot)}}), StatusIs( absl::StatusCode::kFailedPrecondition, MatchesRegex(".*missed slots:.*FAKE.*slot types mismatch:.*NAME.*"))); } TEST(TypedSlotTest, FindSlotsAndVerifyTypes) { FrameLayout::Builder layout_builder; auto int_slot = layout_builder.AddSlot<int>(); auto float_slot = layout_builder.AddSlot<float>(); auto int8_slot = layout_builder.AddSlot<int32_t>(); EXPECT_THAT(FindSlotsAndVerifyTypes( {{"c", GetQType<float>()}, {"a", GetQType<int>()}}, {{"c", TypedSlot::FromSlot(float_slot)}, {"b", TypedSlot::FromSlot(int8_slot)}, {"a", TypedSlot::FromSlot(int_slot)}}), IsOkAndHolds(ElementsAre(TypedSlot::FromSlot(float_slot), TypedSlot::FromSlot(int_slot)))); } TEST(TypedSlotTest, VerifySlotTypes) { FrameLayout::Builder layout_builder; auto int_slot = layout_builder.AddSlot<int>(); auto float_slot = layout_builder.AddSlot<float>(); EXPECT_OK(VerifySlotTypes({{"a", GetQType<int>()}, {"c", GetQType<float>()}}, {{"c", TypedSlot::FromSlot(float_slot)}, {"a", TypedSlot::FromSlot(int_slot)}})); EXPECT_OK(VerifySlotTypes({{"a", GetQType<int>()}, {"c", GetQType<float>()}}, {{"c", TypedSlot::FromSlot(float_slot)}}, true, false)); EXPECT_OK(VerifySlotTypes({{"a", GetQType<int>()}}, {{"c", TypedSlot::FromSlot(float_slot)}, {"a", TypedSlot::FromSlot(int_slot)}}, false)); EXPECT_THAT( VerifySlotTypes({{"a", GetQType<int>()}}, {{"a", TypedSlot::FromSlot(float_slot)}}), StatusIs(absl::StatusCode::kFailedPrecondition, MatchesRegex(".*slot types " "mismatch.*a.*expected:INT32.*actual:FLOAT32.*"))); EXPECT_THAT( VerifySlotTypes({{"a", GetQType<int>()}, {"c", GetQType<float>()}}, {{"a", TypedSlot::FromSlot(float_slot)}}), StatusIs(absl::StatusCode::kFailedPrecondition, MatchesRegex(".*missed slots:.*c.*slot types mismatch:.*a.*"))); EXPECT_THAT( VerifySlotTypes({{"d", GetQType<int>()}}, {{"a", TypedSlot::FromSlot(float_slot)}}), StatusIs(absl::StatusCode::kFailedPrecondition, MatchesRegex(".*missed slots:.*d.*unwanted slots:.*a.*"))); } } }
2,353
#ifndef AROLLA_QTYPE_SIMPLE_TYPE_H_ #define AROLLA_QTYPE_SIMPLE_TYPE_H_ #include <cstddef> #include <cstdint> #include <optional> #include <string> #include <type_traits> #include <utility> #include <vector> #include "absl/base/attributes.h" #include "absl/container/flat_hash_map.h" #include "absl/log/check.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/memory/frame.h" #include "arolla/qtype/named_field_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_slot.h" #include "arolla/util/fingerprint.h" #include "arolla/util/indestructible.h" #include "arolla/util/meta.h" #include "arolla/util/repr.h" #include "arolla/util/struct_field.h" namespace arolla { class SimpleQType : public QType, public NamedFieldQTypeInterface { public: template <typename CppType> ABSL_ATTRIBUTE_ALWAYS_INLINE SimpleQType( meta::type<CppType>, std::string type_name, const QType* value_qtype = nullptr, std::string qtype_specialization_key = "") : QType(ConstructorArgs{ .name = std::move(type_name), .type_info = typeid(CppType), .type_layout = MakeTypeLayout<CppType>(), .type_fields = GenTypeFields<CppType>(), .value_qtype = value_qtype, .qtype_specialization_key = std::move(qtype_specialization_key), }), field_names_(GenFieldNames<CppType>()) { CHECK_OK(InitNameMap()); if constexpr (std::is_invocable_v<ReprTraits<CppType>, CppType>) { unsafe_repr_token_fn_ = [](const void* source) { return ReprTraits<CppType>()(*static_cast<const CppType*>(source)); }; } unsafe_copy_fn_ = [](const void* source, void* destination) { *static_cast<CppType*>(destination) = *static_cast<const CppType*>(source); }; unsafe_combine_to_fingerprint_hasher_fn_ = [](const void* source, FingerprintHasher* hasher) { hasher->Combine(*static_cast<const CppType*>(source)); }; } protected: ReprToken UnsafeReprToken(const void* source) const override { if (unsafe_repr_token_fn_) { return unsafe_repr_token_fn_(source); } else { return QType::UnsafeReprToken(source); } } private: absl::Status InitNameMap(); absl::Span<const std::string> GetFieldNames() const final; std::optional<int64_t> GetFieldIndexByName( absl::string_view field_name) const final; void UnsafeCopy(const void* source, void* destination) const final { if (source != destination) { return unsafe_copy_fn_(source, destination); } } void UnsafeCombineToFingerprintHasher(const void* source, FingerprintHasher* hasher) const final { return unsafe_combine_to_fingerprint_hasher_fn_(source, hasher); } template <typename CppType> ABSL_ATTRIBUTE_ALWAYS_INLINE static std::vector<std::string> GenFieldNames() { std::vector<std::string> result; result.reserve(StructFieldCount<CppType>()); meta::foreach_tuple_element(GetStructFields<CppType>(), [&](const auto& struct_field) { result.emplace_back(struct_field.field_name); }); return result; } template <typename CppType> ABSL_ATTRIBUTE_ALWAYS_INLINE static std::vector<TypedSlot> GenTypeFields() { std::vector<TypedSlot> result; result.reserve(StructFieldCount<CppType>()); meta::foreach_tuple_element( GetStructFields<CppType>(), [&](const auto& struct_field) { result.push_back(TypedSlot::FromSlot( FrameLayout::Slot< typename std::decay_t<decltype(struct_field)>::field_type>:: UnsafeSlotFromOffset(struct_field.field_offset))); }); return result; } private: using UnsafeReprTokenFn = ReprToken (*)(const void* source); using UnsafeCopyFn = void (*)(const void* source, void* destination); using UnsafeCombineToFingerprintHasherFn = void (*)(const void* source, FingerprintHasher* hasher); using Name2IdMap = absl::flat_hash_map<std::string, size_t>; Name2IdMap name2index_; std::vector<std::string> field_names_; UnsafeReprTokenFn unsafe_repr_token_fn_ = nullptr; UnsafeCopyFn unsafe_copy_fn_ = nullptr; UnsafeCombineToFingerprintHasherFn unsafe_combine_to_fingerprint_hasher_fn_ = nullptr; }; #define AROLLA_DECLARE_SIMPLE_QTYPE(NAME, ...) \ AROLLA_DECLARE_QTYPE(__VA_ARGS__); #define AROLLA_DEFINE_SIMPLE_QTYPE(NAME, ...) \ QTypePtr QTypeTraits<__VA_ARGS__>::type() { \ static const Indestructible<SimpleQType> result(meta::type<__VA_ARGS__>(), \ #NAME); \ return result.get(); \ } } #endif #include "arolla/qtype/simple_qtype.h" #include <cstdint> #include <optional> #include <string> #include "absl/status/status.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" namespace arolla { absl::Status SimpleQType::InitNameMap() { name2index_.reserve(field_names_.size()); for (const auto& field_name : field_names_) { if (bool inserted = name2index_.emplace(field_name, name2index_.size()).second; !inserted) { return absl::FailedPreconditionError(absl::StrCat( "duplicated name field for QType ", name(), ": ", field_name)); } } return absl::OkStatus(); } absl::Span<const std::string> SimpleQType::GetFieldNames() const { return field_names_; } std::optional<int64_t> SimpleQType::GetFieldIndexByName( absl::string_view field_name) const { if (auto it = name2index_.find(field_name); it != name2index_.end()) { return it->second; } return std::nullopt; } }
#include "arolla/qtype/simple_qtype.h" #include <cstdint> #include <optional> #include <string> #include <tuple> #include <utility> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/named_field_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/util/fingerprint.h" #include "arolla/util/indestructible.h" #include "arolla/util/meta.h" #include "arolla/util/repr.h" #include "arolla/util/struct_field.h" #include "arolla/util/testing/repr_token_eq.h" namespace arolla { namespace { using ::arolla::testing::ReprTokenEq; using ::testing::ElementsAre; using ::testing::IsEmpty; using ::testing::MatchesRegex; struct TypeWithRepr {}; struct TypeWithoutRepr {}; struct FullFeaturedType { int32_t state; }; struct TypeWithNamedFields { float x; double y; constexpr static auto ArollaStructFields() { using CppType = TypeWithNamedFields; return std::tuple{ AROLLA_DECLARE_STRUCT_FIELD(x), AROLLA_DECLARE_STRUCT_FIELD(y), }; } void ArollaFingerprint(FingerprintHasher* hasher) const { CombineStructFields(hasher, *this); } }; } AROLLA_DECLARE_QTYPE(TypeWithRepr); AROLLA_DECLARE_QTYPE(TypeWithoutRepr); AROLLA_DECLARE_QTYPE(FullFeaturedType); AROLLA_DECLARE_QTYPE(TypeWithNamedFields); AROLLA_DECLARE_FINGERPRINT_HASHER_TRAITS(TypeWithRepr); void FingerprintHasherTraits<TypeWithRepr>::operator()( FingerprintHasher*, const TypeWithRepr&) const {} AROLLA_DECLARE_FINGERPRINT_HASHER_TRAITS(TypeWithoutRepr); void FingerprintHasherTraits<TypeWithoutRepr>::operator()( FingerprintHasher*, const TypeWithoutRepr&) const {} AROLLA_DECLARE_FINGERPRINT_HASHER_TRAITS(FullFeaturedType); void FingerprintHasherTraits<FullFeaturedType>::operator()( FingerprintHasher* hasher, const FullFeaturedType& value) const { hasher->Combine(value.state); } AROLLA_DECLARE_REPR(TypeWithRepr); ReprToken ReprTraits<TypeWithRepr>::operator()(const TypeWithRepr&) const { return ReprToken{"type_with_repr", {10, 50}}; } AROLLA_DECLARE_REPR(FullFeaturedType); ReprToken ReprTraits<FullFeaturedType>::operator()( const FullFeaturedType& value) const { return ReprToken{absl::StrFormat("FullFeaturedType{%d}", value.state), {31, 27}}; } AROLLA_DEFINE_SIMPLE_QTYPE(TYPE_WITH_REPR, TypeWithRepr); AROLLA_DEFINE_SIMPLE_QTYPE(TYPE_WITHOUT_REPR, TypeWithoutRepr); AROLLA_DEFINE_SIMPLE_QTYPE(TYPE_WITH_NAMED_FIELDS, TypeWithNamedFields); QTypePtr QTypeTraits<FullFeaturedType>::type() { struct FullFeaturedTypeQType final : SimpleQType { FullFeaturedTypeQType() : SimpleQType( meta::type<FullFeaturedType>(), "FullFeaturedType", GetQType<TypeWithoutRepr>(), "::arolla::FullFeaturedQType") {} absl::string_view UnsafePyQValueSpecializationKey( const void* ) const final { return "::arolla::FullFeaturedQValue"; } }; static const Indestructible<FullFeaturedTypeQType> result; return result.get(); } namespace { TEST(SimpleQType, TypeWithRepr) { TypeWithRepr x; EXPECT_THAT(GetQType<TypeWithRepr>()->UnsafeReprToken(&x), ReprTokenEq("type_with_repr", {10, 50})); } TEST(SimpleQType, TypeWithoutRepr) { TypeWithoutRepr x; const auto repr_result = GetQType<TypeWithoutRepr>()->UnsafeReprToken(&x); EXPECT_THAT(repr_result.str, MatchesRegex("<value of TYPE_WITHOUT_REPR at 0x[0-9a-f]+>")); EXPECT_THAT(repr_result.precedence.left, -1); EXPECT_THAT(repr_result.precedence.right, -1); } TEST(SimpleQType, FullFeaturedQType) { auto qtype = GetQType<FullFeaturedType>(); const FullFeaturedType x{4}; EXPECT_EQ(qtype->value_qtype(), GetQType<TypeWithoutRepr>()); EXPECT_EQ(qtype->qtype_specialization_key(), "::arolla::FullFeaturedQType"); EXPECT_THAT(qtype->UnsafeReprToken(&x), ReprTokenEq("FullFeaturedType{4}", {31, 27})); EXPECT_EQ(qtype->UnsafePyQValueSpecializationKey(&x), "::arolla::FullFeaturedQValue"); FingerprintHasher hx("salt"); FingerprintHasher hy("salt"); const FullFeaturedType y{3}; qtype->UnsafeCombineToFingerprintHasher(&x, &hx); qtype->UnsafeCombineToFingerprintHasher(&y, &hy); EXPECT_NE(std::move(hx).Finish(), std::move(hy).Finish()); } TEST(SimpleQType, TypeWithNames) { QTypePtr qtype = GetQType<TypeWithNamedFields>(); EXPECT_THAT(GetFieldNames(qtype), ElementsAre("x", "y")); EXPECT_EQ(GetFieldIndexByName(qtype, "x"), 0); EXPECT_EQ(GetFieldIndexByName(qtype, "y"), 1); EXPECT_EQ(GetFieldIndexByName(qtype, "z"), std::nullopt); } TEST(SimpleQType, TypeWithNamesErrors) { QTypePtr qtype = GetQType<int>(); EXPECT_THAT(GetFieldNames(qtype), IsEmpty()); EXPECT_EQ(GetFieldIndexByName(qtype, "y"), std::nullopt); EXPECT_EQ(GetFieldIndexByName(qtype, "x"), std::nullopt); } } }
2,354
#ifndef AROLLA_QTYPE_UNSPECIFIED_QTYPE_H_ #define AROLLA_QTYPE_UNSPECIFIED_QTYPE_H_ #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_value.h" namespace arolla { QTypePtr GetUnspecifiedQType(); const TypedValue& GetUnspecifiedQValue(); } #endif #include "arolla/qtype/unspecified_qtype.h" #include "absl/strings/string_view.h" #include "arolla/memory/frame.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/fingerprint.h" #include "arolla/util/indestructible.h" #include "arolla/util/repr.h" namespace arolla { namespace { struct Unspecified {}; class UnspecifiedQType final : public QType { public: UnspecifiedQType() : QType(ConstructorArgs{.name = "UNSPECIFIED", .type_info = typeid(Unspecified), .type_layout = MakeTypeLayout<Unspecified>()}) {} ReprToken UnsafeReprToken(const void* source) const override { return ReprToken{"unspecified"}; } void UnsafeCopy(const void* , void* ) const override {} void UnsafeCombineToFingerprintHasher( const void* , FingerprintHasher* hasher) const override { hasher->Combine(absl::string_view("::arolla::UnspecifiedQValue")); } }; } QTypePtr GetUnspecifiedQType() { static const Indestructible<UnspecifiedQType> result; return result.get(); } const TypedValue& GetUnspecifiedQValue() { static const Indestructible<TypedValue> result( TypedValue::UnsafeFromTypeDefaultConstructed(GetUnspecifiedQType())); return *result; } }
#include "arolla/qtype/unspecified_qtype.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/repr_token_eq.h" namespace arolla { namespace { using ::arolla::testing::ReprTokenEq; class UnspecifiedQTypeTest : public ::testing::Test { void SetUp() override { ASSERT_OK(InitArolla()); } }; TEST_F(UnspecifiedQTypeTest, UnspecifiedQType) { const auto unspecified_qtype = GetUnspecifiedQType(); EXPECT_EQ(unspecified_qtype->name(), "UNSPECIFIED"); EXPECT_EQ(unspecified_qtype->type_layout().AllocSize(), 1); EXPECT_EQ(unspecified_qtype->type_layout().AllocAlignment().value, 1); EXPECT_TRUE(unspecified_qtype->type_fields().empty()); EXPECT_EQ(unspecified_qtype->value_qtype(), nullptr); } TEST_F(UnspecifiedQTypeTest, UnspecifiedQValue) { const auto unspecified_qvalue = GetUnspecifiedQValue(); EXPECT_EQ(unspecified_qvalue.GetType(), GetUnspecifiedQType()); EXPECT_THAT(unspecified_qvalue.GenReprToken(), ReprTokenEq("unspecified")); } } }
2,355
#ifndef AROLLA_JAGGED_SHAPE_DENSE_ARRAY_QTYPE_QTYPE_H_ #define AROLLA_JAGGED_SHAPE_DENSE_ARRAY_QTYPE_QTYPE_H_ #include "arolla/jagged_shape/dense_array/jagged_shape.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/util/fingerprint.h" #include "arolla/util/repr.h" namespace arolla { AROLLA_DECLARE_QTYPE(JaggedDenseArrayShapePtr); AROLLA_DECLARE_FINGERPRINT_HASHER_TRAITS(JaggedDenseArrayShapePtr); AROLLA_DECLARE_REPR(JaggedDenseArrayShapePtr); } #endif #include "arolla/jagged_shape/dense_array/qtype/qtype.h" #include "arolla/dense_array/edge.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/jagged_shape/dense_array/jagged_shape.h" #include "arolla/jagged_shape/qtype/qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/util/fingerprint.h" #include "arolla/util/indestructible.h" #include "arolla/util/init_arolla.h" #include "arolla/util/meta.h" #include "arolla/util/repr.h" namespace arolla { namespace { class JaggedDenseArrayShapeQType final : public JaggedShapeQType { public: static const JaggedDenseArrayShapeQType* GetInstance() { static Indestructible<JaggedDenseArrayShapeQType> result; return result.get(); } JaggedDenseArrayShapeQType() : JaggedShapeQType(meta::type<JaggedDenseArrayShapePtr>(), "JAGGED_DENSE_ARRAY_SHAPE") {} QTypePtr edge_qtype() const override { return GetQType<DenseArrayEdge>(); }; }; } QTypePtr QTypeTraits<JaggedDenseArrayShapePtr>::type() { return JaggedDenseArrayShapeQType::GetInstance(); } void FingerprintHasherTraits<JaggedDenseArrayShapePtr>::operator()( FingerprintHasher* hasher, const JaggedDenseArrayShapePtr& value) const { hasher->Combine(*value); } ReprToken ReprTraits<JaggedDenseArrayShapePtr>::operator()( const JaggedDenseArrayShapePtr& value) const { return GenReprToken(*value); } AROLLA_REGISTER_ANONYMOUS_INITIALIZER(kHighest, [] { return SetEdgeQTypeToJaggedShapeQType(GetQType<DenseArrayEdge>(), GetQType<JaggedDenseArrayShapePtr>()); }) }
#include "arolla/jagged_shape/dense_array/qtype/qtype.h" #include <cstdint> #include <string> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/edge.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/jagged_shape/array/jagged_shape.h" #include "arolla/jagged_shape/array/qtype/qtype.h" #include "arolla/jagged_shape/dense_array/jagged_shape.h" #include "arolla/jagged_shape/qtype/qtype.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/repr_token_eq.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla { namespace { using ::arolla::testing::ReprTokenEq; using ::arolla::testing::StatusIs; TEST(QTypeTest, TypedValueRepr) { ASSERT_OK_AND_ASSIGN(auto edge, DenseArrayEdge::FromSplitPoints( CreateDenseArray<int64_t>({0, 2}))); ASSERT_OK_AND_ASSIGN(auto shape, JaggedDenseArrayShape::FromEdges({edge})); auto tv = TypedValue::FromValue(shape); EXPECT_THAT(tv.GenReprToken(), ReprTokenEq("JaggedShape(2)")); } TEST(QTypeTest, JaggedDenseArrayShapeQType) { QTypePtr type = GetQType<JaggedDenseArrayShapePtr>(); EXPECT_NE(type, nullptr); EXPECT_EQ(type->name(), "JAGGED_DENSE_ARRAY_SHAPE"); EXPECT_EQ(type->type_info(), typeid(JaggedDenseArrayShapePtr)); EXPECT_EQ(type->value_qtype(), nullptr); EXPECT_TRUE(IsJaggedShapeQType(type)); EXPECT_EQ(type, GetQType<JaggedDenseArrayShapePtr>()); EXPECT_NE(type, GetQType<JaggedArrayShapePtr>()); } TEST(QTypeTest, JaggedDenseArrayShapeFingerprint) { ASSERT_OK_AND_ASSIGN(auto edge1, DenseArrayEdge::FromSplitPoints( CreateDenseArray<int64_t>({0, 2}))); ASSERT_OK_AND_ASSIGN(auto edge2, DenseArrayEdge::FromSplitPoints( CreateDenseArray<int64_t>({0, 1, 3}))); ASSERT_OK_AND_ASSIGN(auto shape1, JaggedDenseArrayShape::FromEdges({edge1, edge2})); ASSERT_OK_AND_ASSIGN(auto shape2, JaggedDenseArrayShape::FromEdges({edge1, edge2})); auto tv1 = TypedValue::FromValue(shape1); auto tv2 = TypedValue::FromValue(shape2); EXPECT_EQ(tv1.GetFingerprint(), tv2.GetFingerprint()); ASSERT_OK_AND_ASSIGN(auto edge3, DenseArrayEdge::FromSplitPoints( CreateDenseArray<int64_t>({0, 1, 4}))); ASSERT_OK_AND_ASSIGN(auto shape3, JaggedDenseArrayShape::FromEdges({edge1, edge3})); auto tv3 = TypedValue::FromValue(shape3); EXPECT_NE(tv1.GetFingerprint(), tv3.GetFingerprint()); } TEST(QTypeTest, CopyTo) { ASSERT_OK_AND_ASSIGN(auto edge1, DenseArrayEdge::FromSplitPoints( CreateDenseArray<int64_t>({0, 2}))); ASSERT_OK_AND_ASSIGN(auto edge2, DenseArrayEdge::FromSplitPoints( CreateDenseArray<int64_t>({0, 1, 3}))); ASSERT_OK_AND_ASSIGN(auto shape, JaggedDenseArrayShape::FromEdges({edge1, edge2})); auto tv = TypedValue::FromValue(shape); auto tv_copy = TypedValue(tv.AsRef()); EXPECT_EQ(tv.GetFingerprint(), tv_copy.GetFingerprint()); } TEST(QTypeTest, JaggedShapeQTypeFromEdgeQType) { ASSERT_OK(InitArolla()); { ASSERT_OK_AND_ASSIGN(auto shape_qtype, GetJaggedShapeQTypeFromEdgeQType( GetQType<DenseArrayEdge>())); EXPECT_EQ(shape_qtype, GetQType<JaggedDenseArrayShapePtr>()); } { EXPECT_THAT( GetJaggedShapeQTypeFromEdgeQType(GetQType<DenseArrayGroupScalarEdge>()), StatusIs(absl::StatusCode::kInvalidArgument, "DENSE_ARRAY_TO_SCALAR_EDGE key is not registered")); } { EXPECT_THAT( SetEdgeQTypeToJaggedShapeQType(GetQType<DenseArrayEdge>(), GetQType<DenseArrayGroupScalarEdge>()), StatusIs(absl::StatusCode::kInvalidArgument, "DENSE_ARRAY_EDGE key is already registered")); } } TEST(QTypeTest, EdgeQType) { auto type = GetQType<JaggedDenseArrayShapePtr>(); auto shape_qtype = dynamic_cast<const JaggedShapeQType*>(type); EXPECT_EQ(shape_qtype->edge_qtype(), GetQType<DenseArrayEdge>()); } } }
2,356
#ifndef AROLLA_QTYPE_OPTIONAL_QTYPE_H_ #define AROLLA_QTYPE_OPTIONAL_QTYPE_H_ #include "absl/log/check.h" #include "absl/status/statusor.h" #include "arolla/memory/frame.h" #include "arolla/memory/optional_value.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/simple_qtype.h" #include "arolla/qtype/typed_ref.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/indestructible.h" #include "arolla/util/meta.h" namespace arolla { template <typename T> QTypePtr GetOptionalQType() { return GetQType<OptionalValue<T>>(); } bool IsOptionalQType(const QType* qtype); absl::StatusOr<QTypePtr> ToOptionalQType(QTypePtr qtype); const QType* DecayOptionalQType(const QType* qtype); absl::StatusOr<FrameLayout::Slot<bool>> GetPresenceSubslotFromOptional( TypedSlot slot); inline FrameLayout::Slot<bool> UnsafePresenceSubslotFromOptional( TypedSlot slot) { DCHECK(IsOptionalQType(slot.GetType())); return slot.SubSlot(0).UnsafeToSlot<bool>(); } template <typename T> FrameLayout::Slot<bool> GetPresenceSubslotFromOptional( FrameLayout::Slot<OptionalValue<T>> slot) { return slot.template GetSubslot<0>(); } absl::StatusOr<TypedSlot> GetValueSubslotFromOptional(TypedSlot slot); inline TypedSlot UnsafeValueSubslotFromOptional(TypedSlot slot) { DCHECK(IsOptionalQType(slot.GetType())); DCHECK_EQ(slot.SubSlotCount(), 2); return slot.SubSlot(1); } inline bool UnsafeIsPresent(TypedRef optional) { DCHECK(IsOptionalQType(optional.GetType())); DCHECK_GE(optional.GetFieldCount(), 1); return optional.GetField(0).UnsafeAs<bool>(); } template <typename T> FrameLayout::Slot<T> GetValueSubslotFromOptional( FrameLayout::Slot<OptionalValue<T>> slot) { return slot.template GetSubslot<1>(); } absl::StatusOr<TypedValue> CreateMissingValue(QTypePtr optional_qtype); void RegisterOptionalQType(QTypePtr optional_qtype); #define AROLLA_DECLARE_OPTIONAL_QTYPE(NAME, ...) \ AROLLA_DECLARE_QTYPE(OptionalValue<__VA_ARGS__>) #define AROLLA_DEFINE_OPTIONAL_QTYPE(NAME, ...) \ QTypePtr QTypeTraits<OptionalValue<__VA_ARGS__>>::type() { \ static const Indestructible<SimpleQType> result( \ meta::type<OptionalValue<__VA_ARGS__>>(), ("OPTIONAL_" #NAME), \ GetQType<__VA_ARGS__>()); \ return result.get(); \ } \ static const int optional_##NAME##_registered = \ (RegisterOptionalQType(GetOptionalQType<__VA_ARGS__>()), 1); } #endif #include "arolla/qtype/optional_qtype.h" #include "absl/base/thread_annotations.h" #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "absl/log/check.h" #include "absl/log/log.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/synchronization/mutex.h" #include "arolla/memory/frame.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/indestructible.h" #include "arolla/util/unit.h" namespace arolla { namespace { class OptionalQTypeMaps { public: void Register(QTypePtr qtype, QTypePtr optional_qtype) { absl::MutexLock l(&lock_); to_optional_[qtype] = optional_qtype; to_optional_[optional_qtype] = optional_qtype; optional_qtypes_.insert(optional_qtype); } absl::StatusOr<QTypePtr> ToOptionalQType(QTypePtr qtype) { absl::ReaderMutexLock l(&lock_); auto iter = to_optional_.find(qtype); if (iter == to_optional_.end()) { return absl::InvalidArgumentError( absl::StrCat("no optional qtype for ", qtype->name())); } return iter->second; } bool IsOptionalQType(QTypePtr qtype) { absl::ReaderMutexLock l(&lock_); return optional_qtypes_.contains(qtype); } private: absl::Mutex lock_; absl::flat_hash_map<QTypePtr, QTypePtr> to_optional_ ABSL_GUARDED_BY(lock_); absl::flat_hash_set<QTypePtr> optional_qtypes_ ABSL_GUARDED_BY(lock_); }; OptionalQTypeMaps* GetOptionalQTypeMaps() { static Indestructible<OptionalQTypeMaps> instance; return instance.get(); } } void RegisterOptionalQType(QTypePtr optional_qtype) { const auto* value_qtype = optional_qtype->value_qtype(); DCHECK(value_qtype != nullptr); const auto& sub_slots = optional_qtype->type_fields(); DCHECK_GT(sub_slots.size(), 0); DCHECK(sub_slots[0].GetType()->type_info() == typeid(bool)); DCHECK_EQ(sub_slots[0].byte_offset(), 0); if (sub_slots.size() == 1) { DCHECK_EQ(value_qtype, GetQType<Unit>()); } else if (sub_slots.size() == 2) { DCHECK_EQ(sub_slots[1].GetType(), value_qtype); } else { LOG(FATAL) << "Unexpected number of subslots in optional: " << sub_slots.size(); } GetOptionalQTypeMaps()->Register(value_qtype, optional_qtype); } absl::StatusOr<QTypePtr> ToOptionalQType(QTypePtr qtype) { return GetOptionalQTypeMaps()->ToOptionalQType(qtype); } const QType* DecayOptionalQType(const QType* qtype) { return IsOptionalQType(qtype) ? qtype->value_qtype() : qtype; } bool IsOptionalQType(const QType* qtype) { return GetOptionalQTypeMaps()->IsOptionalQType(qtype); } absl::StatusOr<FrameLayout::Slot<bool>> GetPresenceSubslotFromOptional( TypedSlot slot) { if (!IsOptionalQType(slot.GetType())) { return absl::InvalidArgumentError( absl::StrCat("'", slot.GetType()->name(), "' is not optional qtype.")); } if (slot.SubSlotCount() == 0) { return absl::InternalError("optional value has no subslots."); } return slot.SubSlot(0).ToSlot<bool>(); } absl::StatusOr<TypedSlot> GetValueSubslotFromOptional(TypedSlot slot) { if (!IsOptionalQType(slot.GetType())) { return absl::InvalidArgumentError( absl::StrCat("'", slot.GetType()->name(), "' is not optional qtype.")); } if (slot.SubSlotCount() != 2) { return absl::InvalidArgumentError(absl::StrCat( "'", slot.GetType()->name(), "' does not have a value subslot.")); } return slot.SubSlot(1); } absl::StatusOr<TypedValue> CreateMissingValue(QTypePtr optional_qtype) { if (!IsOptionalQType(optional_qtype)) { return absl::InvalidArgumentError(absl::StrFormat( "cannot create a missing value for non-optional qtype `%s`", optional_qtype->name())); } return TypedValue::UnsafeFromTypeDefaultConstructed(optional_qtype); } }
#include "arolla/qtype/optional_qtype.h" #include <cstdint> #include <optional> #include <utility> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "arolla/memory/frame.h" #include "arolla/memory/memory_allocation.h" #include "arolla/memory/optional_value.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/testing/qtype.h" #include "arolla/qtype/typed_ref.h" #include "arolla/qtype/typed_slot.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla { namespace { using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::arolla::testing::TypedValueWith; using ::testing::FloatEq; using ::testing::IsFalse; using ::testing::IsTrue; template <typename T> using Slot = FrameLayout::Slot<T>; TEST(OptionalQType, SplitOptionalUnitSlot) { FrameLayout::Builder layout_builder; auto slot = layout_builder.AddSlot<OptionalUnit>(); auto layout = std::move(layout_builder).Build(); Slot<bool> presence_slot1 = GetPresenceSubslotFromOptional(slot); auto typed_slot = TypedSlot::FromSlot(slot); ASSERT_OK_AND_ASSIGN(Slot<bool> presence_slot2, GetPresenceSubslotFromOptional(typed_slot)); Slot<bool> presence_slot3 = UnsafePresenceSubslotFromOptional(typed_slot); EXPECT_THAT(GetValueSubslotFromOptional(typed_slot), StatusIs(absl::StatusCode::kInvalidArgument)); MemoryAllocation alloc(&layout); FramePtr frame = alloc.frame(); frame.Set(slot, kPresent); EXPECT_TRUE(frame.Get(presence_slot1)); EXPECT_TRUE(frame.Get(presence_slot2)); EXPECT_TRUE(frame.Get(presence_slot3)); frame.Set(slot, kMissing); EXPECT_FALSE(frame.Get(presence_slot1)); EXPECT_FALSE(frame.Get(presence_slot2)); EXPECT_FALSE(frame.Get(presence_slot3)); } TEST(OptionalQType, SplitOptionalFloatSlot) { FrameLayout::Builder layout_builder; auto slot = layout_builder.AddSlot<OptionalValue<float>>(); auto layout = std::move(layout_builder).Build(); Slot<bool> presence_slot1 = GetPresenceSubslotFromOptional(slot); Slot<float> value_slot1 = GetValueSubslotFromOptional(slot); auto typed_slot = TypedSlot::FromSlot(slot); ASSERT_OK_AND_ASSIGN(Slot<bool> presence_slot2, GetPresenceSubslotFromOptional(typed_slot)); ASSERT_OK_AND_ASSIGN(TypedSlot typed_value_slot2, GetValueSubslotFromOptional(typed_slot)); ASSERT_OK_AND_ASSIGN(Slot<float> value_slot2, typed_value_slot2.ToSlot<float>()); Slot<bool> presence_slot3 = UnsafePresenceSubslotFromOptional(typed_slot); Slot<float> value_slot3 = UnsafeValueSubslotFromOptional(typed_slot).UnsafeToSlot<float>(); MemoryAllocation alloc(&layout); FramePtr frame = alloc.frame(); frame.Set(slot, 17.5f); EXPECT_TRUE(frame.Get(presence_slot1)); EXPECT_TRUE(frame.Get(presence_slot2)); EXPECT_TRUE(frame.Get(presence_slot3)); EXPECT_THAT(frame.Get(value_slot1), FloatEq(17.5f)); EXPECT_THAT(frame.Get(value_slot2), FloatEq(17.5f)); EXPECT_THAT(frame.Get(value_slot3), FloatEq(17.5f)); frame.Set(slot, std::nullopt); EXPECT_FALSE(frame.Get(presence_slot1)); EXPECT_FALSE(frame.Get(presence_slot2)); EXPECT_FALSE(frame.Get(presence_slot3)); } TEST(OptionalQType, CreateMissingValue) { EXPECT_THAT( CreateMissingValue(GetOptionalQType<int64_t>()), IsOkAndHolds(TypedValueWith<OptionalValue<int64_t>>(std::nullopt))); EXPECT_THAT( CreateMissingValue(GetQType<int64_t>()), StatusIs(absl::StatusCode::kInvalidArgument, "cannot create a missing value for non-optional qtype `INT64`")); } TEST(OptionalQType, UnsafeIsPresent) { EXPECT_THAT(UnsafeIsPresent(TypedRef::FromValue(kPresent)), IsTrue()); EXPECT_THAT(UnsafeIsPresent(TypedRef::FromValue(kMissing)), IsFalse()); OptionalValue<float> present_float = 1; EXPECT_THAT(UnsafeIsPresent(TypedRef::FromValue(present_float)), IsTrue()); OptionalValue<float> missing_float = std::nullopt; EXPECT_THAT(UnsafeIsPresent(TypedRef::FromValue(missing_float)), IsFalse()); ASSERT_OK_AND_ASSIGN(TypedValue typed_missing_float, CreateMissingValue(GetOptionalQType<float>())); EXPECT_THAT(UnsafeIsPresent(typed_missing_float.AsRef()), IsFalse()); } } }
2,357
#ifndef AROLLA_QTYPE_STANDARD_TYPE_PROPERTIES_COMMON_QTYPE_H_ #define AROLLA_QTYPE_STANDARD_TYPE_PROPERTIES_COMMON_QTYPE_H_ #include "absl/types/span.h" #include "arolla/qtype/qtype.h" namespace arolla { const QType* CommonQType(const QType* lhs_qtype, const QType* rhs_qtype, bool enable_broadcasting); const QType* CommonQType(absl::Span<const QType* const> qtypes, bool enable_broadcasting); bool CanCastImplicitly(const QType* from_qtype, const QType* to_qtype, bool enable_broadcasting); const QType* BroadcastQType(absl::Span<QType const* const> target_qtypes, const QType* qtype); } #endif #include "arolla/qtype/standard_type_properties/common_qtype.h" #include <algorithm> #include <array> #include <cstdint> #include "absl/algorithm/container.h" #include "absl/types/span.h" #include "arolla/qtype/array_like/array_like_qtype.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/shape_qtype.h" #include "arolla/qtype/standard_type_properties/properties.h" #include "arolla/util/status_macros_backport.h" namespace arolla { namespace { const QType* CommonScalarQType(const QType* lhs_qtype, const QType* rhs_qtype) { if (lhs_qtype == rhs_qtype) { return lhs_qtype; } { static const std::array integral_qtypes = {GetQType<int64_t>(), GetQType<int32_t>()}; auto lhs_it = absl::c_find(integral_qtypes, lhs_qtype); auto rhs_it = absl::c_find(integral_qtypes, rhs_qtype); if (lhs_it != integral_qtypes.end() && rhs_it != integral_qtypes.end()) { return *std::min(lhs_it, rhs_it); } } { static const std::array floating_point_qtypes = { GetQType<double>(), GetQType<float>(), GetWeakFloatQType(), }; auto lhs_it = absl::c_find(floating_point_qtypes, lhs_qtype); auto rhs_it = absl::c_find(floating_point_qtypes, rhs_qtype); if (lhs_it != floating_point_qtypes.end() && rhs_it != floating_point_qtypes.end()) { return *std::min(lhs_it, rhs_it); } } return nullptr; } const ShapeQType* CommonShapeQType(const ShapeQType* lhs_qtype, const ShapeQType* rhs_qtype, bool enable_broadcasting) { if (lhs_qtype == rhs_qtype) { return rhs_qtype; } if (!enable_broadcasting && (IsArrayLikeShapeQType(lhs_qtype) || IsArrayLikeShapeQType(rhs_qtype))) { return nullptr; } if (lhs_qtype == GetQType<ScalarShape>()) { return rhs_qtype; } if (rhs_qtype == GetQType<ScalarShape>()) { return lhs_qtype; } if (lhs_qtype == GetQType<OptionalScalarShape>()) { return rhs_qtype; } if (rhs_qtype == GetQType<OptionalScalarShape>()) { return lhs_qtype; } return nullptr; } } const QType* CommonQType(const QType* lhs_qtype, const QType* rhs_qtype, bool enable_broadcasting) { if (lhs_qtype == nullptr || rhs_qtype == nullptr) { return nullptr; } if (lhs_qtype == rhs_qtype) { return lhs_qtype; } ASSIGN_OR_RETURN(auto lhs_scalar_qtype, GetScalarQType(lhs_qtype), nullptr); ASSIGN_OR_RETURN(auto rhs_scalar_qtype, GetScalarQType(rhs_qtype), nullptr); const auto* scalar_qtype = CommonScalarQType(lhs_scalar_qtype, rhs_scalar_qtype); if (!scalar_qtype) { return nullptr; } ASSIGN_OR_RETURN(auto lhs_shape_qtype, GetShapeQType(lhs_qtype), nullptr); ASSIGN_OR_RETURN(auto rhs_shape_qtype, GetShapeQType(rhs_qtype), nullptr); const auto* shape_qtype = CommonShapeQType(lhs_shape_qtype, rhs_shape_qtype, enable_broadcasting); if (!shape_qtype) { return nullptr; } return shape_qtype->WithValueQType(scalar_qtype).value_or(nullptr); } bool CanCastImplicitly(QTypePtr from_qtype, QTypePtr to_qtype, bool enable_broadcasting) { return to_qtype != nullptr && CommonQType(from_qtype, to_qtype, enable_broadcasting) == to_qtype; } const QType* CommonQType(absl::Span<const QType* const> qtypes, bool enable_broadcasting) { if (qtypes.empty()) { return nullptr; } const QType* result = qtypes[0]; for (const QType* qtype : qtypes.subspan(1)) { result = CommonQType(result, qtype, enable_broadcasting); } return result; } const QType* BroadcastQType(absl::Span<QType const* const> target_qtypes, const QType* qtype) { if (absl::c_any_of(target_qtypes, [](auto* qtype) { return qtype == nullptr; }) || qtype == nullptr) { return nullptr; } const ShapeQType* shape_qtype = GetShapeQType(qtype).value_or(nullptr); for (const auto* target_qtype : target_qtypes) { shape_qtype = CommonShapeQType( shape_qtype, GetShapeQType(target_qtype).value_or(nullptr), true); } if (shape_qtype == nullptr) { return nullptr; } ASSIGN_OR_RETURN(auto scalar_qtype, GetScalarQType(qtype), nullptr); return shape_qtype->WithValueQType(scalar_qtype).value_or(nullptr); } }
#include "arolla/qtype/standard_type_properties/common_qtype.h" #include <algorithm> #include <cstdint> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "arolla/array/qtype/types.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/tuple_qtype.h" #include "arolla/qtype/weak_qtype.h" #include "arolla/util/bytes.h" #include "arolla/util/meta.h" #include "arolla/util/unit.h" namespace arolla { namespace { using ::testing::IsFalse; using ::testing::IsNull; using ::testing::IsTrue; const QType* ReferenceCommonQType(const QType* arg0, const QType* arg1, bool enable_broadcasting_) { if (arg0 == arg1) { return arg0; } const QType* result = nullptr; const auto gen_result = [&](QTypePtr a0, QTypePtr a1, QTypePtr r) { if (a0 == arg0 && a1 == arg1) { result = r; } }; const auto gen_results = [&](QTypePtr a0, QTypePtr a1, QTypePtr r) { ASSERT_OK_AND_ASSIGN(auto a0_optional, ToOptionalQType(a0)); ASSERT_OK_AND_ASSIGN(auto a0_dense_array, GetDenseArrayQTypeByValueQType(a0)); ASSERT_OK_AND_ASSIGN(auto a0_array, GetArrayQTypeByValueQType(a0)); ASSERT_OK_AND_ASSIGN(auto a1_optional, ToOptionalQType(a1)); ASSERT_OK_AND_ASSIGN(auto a1_dense_array, GetDenseArrayQTypeByValueQType(a1)); ASSERT_OK_AND_ASSIGN(auto a1_array, GetArrayQTypeByValueQType(a1)); ASSERT_OK_AND_ASSIGN(auto r_optional, ToOptionalQType(r)); ASSERT_OK_AND_ASSIGN(auto r_dense_array, GetDenseArrayQTypeByValueQType(r)); ASSERT_OK_AND_ASSIGN(auto r_array, GetArrayQTypeByValueQType(r)); gen_result(a0, a1, r); gen_result(a0, a1_optional, r_optional); gen_result(a0_optional, a1_optional, r_optional); gen_result(a0_optional, a1, r_optional); gen_result(a0_dense_array, a1_dense_array, r_dense_array); gen_result(a0_array, a1_array, r_array); if (enable_broadcasting_) { gen_result(a0, a1_dense_array, r_dense_array); gen_result(a0_optional, a1_dense_array, r_dense_array); gen_result(a0, a1_array, r_array); gen_result(a0_optional, a1_array, r_array); gen_result(a0_dense_array, a1_optional, r_dense_array); gen_result(a0_dense_array, a1, r_dense_array); gen_result(a0_array, a1_optional, r_array); gen_result(a0_array, a1, r_array); } }; meta::foreach_type<ScalarTypes>([&](auto meta_type) { auto x = GetQType<typename decltype(meta_type)::type>(); gen_results(x, x, x); }); static const auto integral_qtypes = { GetQType<int32_t>(), GetQType<int64_t>(), }; for (auto it = integral_qtypes.begin(); result == nullptr && it != integral_qtypes.end(); ++it) { for (auto jt = integral_qtypes.begin(); result == nullptr && jt != integral_qtypes.end(); ++jt) { gen_results(*it, *jt, *std::max(it, jt)); } } static const auto floating_qtypes = { GetWeakFloatQType(), GetQType<float>(), GetQType<double>(), }; for (auto it = floating_qtypes.begin(); result == nullptr && it != floating_qtypes.end(); ++it) { for (auto jt = floating_qtypes.begin(); result == nullptr && jt != floating_qtypes.end(); ++jt) { gen_results(*it, *jt, *std::max(it, jt)); } } return result; } class CommonQTypeMultipleParametersTests : public ::testing::TestWithParam<bool> { protected: CommonQTypeMultipleParametersTests() { meta::foreach_type<ScalarTypes>([&](auto meta_type) { using T = typename decltype(meta_type)::type; known_qtypes_.push_back(GetQType<T>()); known_qtypes_.push_back(GetOptionalQType<T>()); known_qtypes_.push_back(GetDenseArrayQType<T>()); known_qtypes_.push_back(GetArrayQType<T>()); }); known_qtypes_.push_back(nullptr); known_qtypes_.push_back(GetDenseArrayWeakFloatQType()); known_qtypes_.push_back(GetArrayWeakFloatQType()); known_qtypes_.push_back(MakeTupleQType({})); enable_broadcasting_ = GetParam(); } std::vector<const QType*> known_qtypes_; bool enable_broadcasting_; }; TEST_P(CommonQTypeMultipleParametersTests, VsReferenceImplementation) { for (auto lhs : known_qtypes_) { for (auto rhs : known_qtypes_) { EXPECT_EQ(CommonQType(lhs, rhs, enable_broadcasting_), ReferenceCommonQType(lhs, rhs, enable_broadcasting_)) << "lhs=" << (lhs ? lhs->name() : "nullptr") << ", rhs=" << (rhs ? rhs->name() : "nullptr"); } } } TEST_P(CommonQTypeMultipleParametersTests, SemiLatticeProperties) { for (auto arg_0 : known_qtypes_) { EXPECT_EQ( CommonQType(arg_0, arg_0, enable_broadcasting_), arg_0); for (auto arg_1 : known_qtypes_) { EXPECT_EQ( CommonQType(arg_0, arg_1, enable_broadcasting_), CommonQType(arg_1, arg_0, enable_broadcasting_)); for (auto arg_2 : known_qtypes_) { EXPECT_EQ( CommonQType(CommonQType(arg_0, arg_1, enable_broadcasting_), arg_2, enable_broadcasting_), CommonQType(arg_0, CommonQType(arg_1, arg_2, enable_broadcasting_), enable_broadcasting_)); } } } } INSTANTIATE_TEST_SUITE_P(CommonQTypeTests, CommonQTypeMultipleParametersTests, ::testing::Values(false, true)); class CommonQTypeTest : public ::testing::Test { protected: static void SetUpTestCase() { meta::foreach_type<ScalarTypes>([&](auto meta_type) { GetQType<typename decltype(meta_type)::type>(); GetOptionalQType<typename decltype(meta_type)::type>(); GetDenseArrayQType<typename decltype(meta_type)::type>(); }); } }; TEST_F(CommonQTypeTest, OnSpans) { EXPECT_THAT(CommonQType({}, true), IsNull()); EXPECT_EQ(CommonQType({GetQType<int64_t>()}, true), GetQType<int64_t>()); EXPECT_THAT( CommonQType({nullptr, GetQType<int64_t>()}, true), IsNull()); EXPECT_THAT( CommonQType({GetQType<int64_t>(), nullptr}, true), IsNull()); EXPECT_EQ(CommonQType({GetQType<int64_t>(), GetOptionalQType<int32_t>()}, true), GetOptionalQType<int64_t>()); EXPECT_EQ(CommonQType({GetQType<int64_t>(), GetOptionalQType<int32_t>(), GetDenseArrayQType<int32_t>()}, true), GetDenseArrayQType<int64_t>()); EXPECT_EQ( CommonQType(GetDenseArrayQType<int32_t>(), GetOptionalQType<int64_t>(), true), GetDenseArrayQType<int64_t>()); EXPECT_THAT(CommonQType({GetQType<int64_t>(), GetOptionalQType<int32_t>(), GetDenseArrayQType<int32_t>()}, false), IsNull()); } TEST_F(CommonQTypeTest, WeakQType) { EXPECT_EQ(CommonQType(GetQType<double>(), GetWeakFloatQType(), true), GetQType<double>()); EXPECT_EQ(CommonQType(GetQType<float>(), GetWeakFloatQType(), true), GetQType<float>()); EXPECT_EQ(CommonQType(GetWeakFloatQType(), GetWeakFloatQType(), true), GetWeakFloatQType()); EXPECT_EQ(CommonQType(GetOptionalWeakFloatQType(), GetWeakFloatQType(), true), GetOptionalWeakFloatQType()); EXPECT_EQ(CommonQType(GetOptionalWeakFloatQType(), GetQType<double>(), true), GetOptionalQType<double>()); EXPECT_EQ(CommonQType(GetOptionalWeakFloatQType(), GetQType<float>(), true), GetOptionalQType<float>()); EXPECT_EQ(CommonQType(GetWeakFloatQType(), GetOptionalQType<double>(), true), GetOptionalQType<double>()); EXPECT_EQ(CommonQType(GetWeakFloatQType(), GetOptionalQType<float>(), true), GetOptionalQType<float>()); EXPECT_EQ(CommonQType(GetOptionalWeakFloatQType(), GetOptionalQType<double>(), true), GetOptionalQType<double>()); EXPECT_EQ(CommonQType(GetOptionalWeakFloatQType(), GetOptionalQType<float>(), true), GetOptionalQType<float>()); EXPECT_EQ(CommonQType(GetWeakFloatQType(), GetArrayQType<double>(), true), GetArrayQType<double>()); EXPECT_EQ(CommonQType(GetWeakFloatQType(), GetArrayQType<float>(), true), GetArrayQType<float>()); EXPECT_EQ(CommonQType(GetOptionalWeakFloatQType(), GetArrayQType<double>(), true), GetArrayQType<double>()); EXPECT_EQ(CommonQType(GetOptionalWeakFloatQType(), GetArrayQType<float>(), true), GetArrayQType<float>()); } class CanCastImplicitlyTest : public ::testing::Test { protected: static void SetUpTestCase() { meta::foreach_type<ScalarTypes>([&](auto meta_type) { GetQType<typename decltype(meta_type)::type>(); GetOptionalQType<typename decltype(meta_type)::type>(); GetDenseArrayQType<typename decltype(meta_type)::type>(); }); } }; TEST_F(CanCastImplicitlyTest, OnScalars) { EXPECT_THAT(CanCastImplicitly(GetQType<int32_t>(), GetQType<int64_t>(), false), IsTrue()); EXPECT_THAT(CanCastImplicitly(GetQType<float>(), GetQType<double>(), false), IsTrue()); EXPECT_THAT(CanCastImplicitly(GetQType<float>(), GetOptionalQType<float>(), false), IsTrue()); EXPECT_THAT(CanCastImplicitly(GetQType<float>(), GetOptionalQType<double>(), false), IsTrue()); EXPECT_THAT(CanCastImplicitly(GetQType<int64_t>(), GetQType<int32_t>(), false), IsFalse()); EXPECT_THAT(CanCastImplicitly(GetQType<int32_t>(), GetQType<float>(), false), IsFalse()); EXPECT_THAT(CanCastImplicitly(GetQType<int32_t>(), GetQType<uint64_t>(), false), IsFalse()); EXPECT_THAT(CanCastImplicitly(GetQType<int32_t>(), nullptr, false), IsFalse()); EXPECT_THAT(CanCastImplicitly(nullptr, GetQType<int32_t>(), false), IsFalse()); EXPECT_THAT(CanCastImplicitly(nullptr, nullptr, false), IsFalse()); } TEST_F(CanCastImplicitlyTest, WithBroadcasting) { EXPECT_THAT( CanCastImplicitly(GetQType<int32_t>(), GetDenseArrayQType<int32_t>(), false), IsFalse()); EXPECT_THAT(CanCastImplicitly(GetOptionalQType<int32_t>(), GetDenseArrayQType<int32_t>(), false), IsFalse()); EXPECT_THAT( CanCastImplicitly(GetQType<int32_t>(), GetDenseArrayQType<int32_t>(), true), IsTrue()); EXPECT_THAT(CanCastImplicitly(GetOptionalQType<int32_t>(), GetDenseArrayQType<int32_t>(), true), IsTrue()); } TEST_F(CanCastImplicitlyTest, WeakQType) { EXPECT_THAT(CanCastImplicitly(GetQType<float>(), GetWeakFloatQType(), false), IsFalse()); EXPECT_THAT(CanCastImplicitly(GetQType<double>(), GetWeakFloatQType(), false), IsFalse()); EXPECT_THAT( CanCastImplicitly(GetQType<int32_t>(), GetWeakFloatQType(), false), IsFalse()); EXPECT_THAT(CanCastImplicitly(GetWeakFloatQType(), GetQType<float>(), false), IsTrue()); EXPECT_THAT(CanCastImplicitly(GetWeakFloatQType(), GetQType<double>(), false), IsTrue()); EXPECT_THAT( CanCastImplicitly(GetWeakFloatQType(), GetQType<int32_t>(), false), IsFalse()); EXPECT_THAT( CanCastImplicitly(GetWeakFloatQType(), GetOptionalQType<float>(), false), IsTrue()); EXPECT_THAT(CanCastImplicitly(GetOptionalWeakFloatQType(), GetOptionalQType<double>(), false), IsTrue()); EXPECT_THAT(CanCastImplicitly(GetWeakFloatQType(), GetArrayWeakFloatQType(), false), IsFalse()); EXPECT_THAT(CanCastImplicitly(GetWeakFloatQType(), GetArrayWeakFloatQType(), true), IsTrue()); EXPECT_THAT( CanCastImplicitly(GetOptionalWeakFloatQType(), GetArrayWeakFloatQType(), true), IsTrue()); EXPECT_THAT( CanCastImplicitly(GetWeakFloatQType(), GetDenseArrayQType<float>(), true), IsTrue()); EXPECT_THAT( CanCastImplicitly(GetWeakFloatQType(), GetDenseArrayQType<double>(), true), IsTrue()); } class BroadcastQTypeTests : public ::testing::Test { protected: static void SetUpTestCase() { meta::foreach_type<ScalarTypes>([&](auto meta_type) { using T = typename decltype(meta_type)::type; GetQType<T>(); GetOptionalQType<T>(); GetDenseArrayQType<T>(); GetArrayQType<T>(); }); GetDenseArrayWeakFloatQType(); GetArrayWeakFloatQType(); } }; TEST_F(BroadcastQTypeTests, Empty) { ASSERT_THAT(BroadcastQType({}, nullptr), IsNull()); } TEST_F(BroadcastQTypeTests, SingleScalarType) { ASSERT_EQ(BroadcastQType({}, GetQType<int32_t>()), GetQType<int32_t>()); } TEST_F(BroadcastQTypeTests, NullHandling) { ASSERT_THAT(BroadcastQType({nullptr}, GetQType<int32_t>()), IsNull()); ASSERT_THAT(BroadcastQType({GetQType<int32_t>()}, nullptr), IsNull()); ASSERT_THAT( BroadcastQType({GetQType<int32_t>(), nullptr}, GetQType<int32_t>()), IsNull()); } TEST_F(BroadcastQTypeTests, ScalarAndOptional) { ASSERT_EQ(BroadcastQType({GetOptionalQType<int32_t>()}, GetQType<int64_t>()), GetOptionalQType<int64_t>()); ASSERT_EQ(BroadcastQType({GetQType<int64_t>()}, GetOptionalQType<int32_t>()), GetOptionalQType<int32_t>()); } TEST_F(BroadcastQTypeTests, ArrayAndDenseArray) { EXPECT_THAT( BroadcastQType({GetArrayQType<float>()}, GetDenseArrayQType<float>()), IsNull()); EXPECT_THAT( BroadcastQType({GetArrayQType<float>(), GetDenseArrayQType<float>()}, GetQType<float>()), IsNull()); } TEST_F(BroadcastQTypeTests, Basic) { ASSERT_EQ( BroadcastQType({GetOptionalQType<float>(), GetDenseArrayQType<Bytes>()}, GetQType<int32_t>()), GetDenseArrayQType<int32_t>()); } TEST_F(BroadcastQTypeTests, WeakFloat) { ASSERT_EQ(BroadcastQType({GetDenseArrayQType<Unit>()}, GetWeakFloatQType()), GetDenseArrayWeakFloatQType()); ASSERT_EQ( BroadcastQType({GetDenseArrayQType<Unit>()}, GetOptionalWeakFloatQType()), GetDenseArrayWeakFloatQType()); ASSERT_EQ(BroadcastQType({GetArrayQType<Unit>()}, GetWeakFloatQType()), GetArrayWeakFloatQType()); ASSERT_EQ( BroadcastQType({GetArrayQType<Unit>()}, GetOptionalWeakFloatQType()), GetArrayWeakFloatQType()); } } }
2,358
#ifndef AROLLA_QTYPE_STANDARD_TYPE_PROPERTIES_PROPERTIES_H_ #define AROLLA_QTYPE_STANDARD_TYPE_PROPERTIES_PROPERTIES_H_ #include "absl/status/statusor.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/shape_qtype.h" namespace arolla { absl::StatusOr<QTypePtr> GetScalarQType(QTypePtr qtype); absl::StatusOr<const ShapeQType*> GetShapeQType(QTypePtr qtype); QTypePtr DecayContainerQType(QTypePtr qtype); absl::StatusOr<QTypePtr> WithScalarQType(QTypePtr qtype, QTypePtr new_scalar_qtype); absl::StatusOr<QTypePtr> GetPresenceQType(QTypePtr qtype); bool IsOptionalLikeQType(const QType* qtype); absl::StatusOr<QTypePtr> ToOptionalLikeQType(QTypePtr qtype); } #endif #include "arolla/qtype/standard_type_properties/properties.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "arolla/qtype/array_like/array_like_qtype.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/shape_qtype.h" #include "arolla/util/status_macros_backport.h" namespace arolla { absl::StatusOr<QTypePtr> GetScalarQType(QTypePtr qtype) { DCHECK(qtype); if (IsScalarQType(qtype)) { return qtype; } if (qtype->value_qtype() != nullptr) { return qtype->value_qtype(); } return absl::InvalidArgumentError(absl::StrFormat( "there is no corresponding scalar type for %s", qtype->name())); } absl::StatusOr<const ShapeQType*> GetShapeQType(QTypePtr qtype) { DCHECK(qtype); if (IsScalarQType(qtype)) { return static_cast<const ShapeQType*>(GetQType<ScalarShape>()); } if (IsOptionalQType(qtype)) { return static_cast<const ShapeQType*>(GetQType<OptionalScalarShape>()); } if (auto* array_qtype = dynamic_cast<const ArrayLikeQType*>(qtype)) { return array_qtype->shape_qtype(); } return absl::InvalidArgumentError( absl::StrFormat("no shape type for %s", qtype->name())); } QTypePtr DecayContainerQType(QTypePtr qtype) { DCHECK(qtype); if (qtype->value_qtype() != nullptr) { return qtype->value_qtype(); } return qtype; } absl::StatusOr<QTypePtr> WithScalarQType(QTypePtr qtype, QTypePtr new_scalar_qtype) { DCHECK(qtype); DCHECK(new_scalar_qtype); if (!IsScalarQType(new_scalar_qtype)) { return absl::InvalidArgumentError(absl::StrFormat( "unable to replace scalar type in %s with a non-scalar type %s", qtype->name(), new_scalar_qtype->name())); } if (auto shape_qtype = GetShapeQType(qtype); shape_qtype.ok()) { return (**shape_qtype).WithValueQType(new_scalar_qtype); } return absl::InvalidArgumentError( absl::StrFormat("unable to replace scalar type in %s", qtype->name())); } absl::StatusOr<QTypePtr> GetPresenceQType(QTypePtr qtype) { DCHECK(qtype); if (auto shape_qtype = GetShapeQType(qtype); shape_qtype.ok()) { return (**shape_qtype).presence_qtype(); } return absl::InvalidArgumentError( absl::StrFormat("no type to represent presence in %s", qtype->name())); } bool IsOptionalLikeQType(const QType* qtype) { return IsOptionalQType(qtype) || IsArrayLikeQType(qtype); } absl::StatusOr<QTypePtr> ToOptionalLikeQType(QTypePtr qtype) { DCHECK(qtype); if (IsOptionalLikeQType(qtype)) { return qtype; } if (IsScalarQType(qtype)) { return ToOptionalQType(qtype); } if (auto* array_qtype = dynamic_cast<const ArrayLikeQType*>(qtype)) { ASSIGN_OR_RETURN(auto optional_qtype, ToOptionalQType(array_qtype->value_qtype())); return array_qtype->WithValueQType(optional_qtype); } return absl::InvalidArgumentError( absl::StrFormat("no optional-like qtype for %s", qtype->name())); } }
#include "arolla/qtype/standard_type_properties/properties.h" #include <cstdint> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "arolla/array/array.h" #include "arolla/array/qtype/types.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/memory/optional_value.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/shape_qtype.h" #include "arolla/qtype/tuple_qtype.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/unit.h" namespace arolla { namespace { using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::testing::MatchesRegex; TEST(TypeProperties, GetScalarQType) { EXPECT_THAT(GetScalarQType(GetQType<int64_t>()), IsOkAndHolds(GetQType<int64_t>())); EXPECT_THAT(GetScalarQType(GetOptionalQType<int64_t>()), IsOkAndHolds(GetQType<int64_t>())); EXPECT_THAT(GetScalarQType(GetDenseArrayQType<int64_t>()), IsOkAndHolds(GetQType<int64_t>())); EXPECT_THAT(GetScalarQType(GetDenseArrayWeakFloatQType()), IsOkAndHolds(GetWeakFloatQType())); EXPECT_THAT(GetScalarQType(GetArrayWeakFloatQType()), IsOkAndHolds(GetWeakFloatQType())); EXPECT_THAT( GetScalarQType(MakeTupleQType({GetQType<int64_t>()})), StatusIs(absl::StatusCode::kInvalidArgument, MatchesRegex("there is no corresponding scalar type for .*"))); } TEST(TypeProperties, GetShapeQType) { EXPECT_THAT(GetShapeQType(GetQType<int64_t>()), IsOkAndHolds(GetQType<ScalarShape>())); EXPECT_THAT(GetShapeQType(GetOptionalQType<int64_t>()), IsOkAndHolds(GetQType<OptionalScalarShape>())); EXPECT_THAT(GetShapeQType(GetDenseArrayQType<int64_t>()), IsOkAndHolds(GetQType<DenseArrayShape>())); EXPECT_THAT(GetShapeQType(GetDenseArrayWeakFloatQType()), IsOkAndHolds(GetQType<DenseArrayShape>())); EXPECT_THAT(GetShapeQType(GetArrayWeakFloatQType()), IsOkAndHolds(GetQType<ArrayShape>())); EXPECT_THAT(GetShapeQType(MakeTupleQType({GetQType<int64_t>()})), StatusIs(absl::StatusCode::kInvalidArgument, MatchesRegex("no shape type for .*"))); } TEST(TypeProperties, WithScalarQType) { EXPECT_THAT(WithScalarQType(GetQType<int64_t>(), GetQType<float>()), IsOkAndHolds(GetQType<float>())); EXPECT_THAT(WithScalarQType(GetOptionalQType<int64_t>(), GetQType<float>()), IsOkAndHolds(GetOptionalQType<float>())); EXPECT_THAT(WithScalarQType(GetDenseArrayQType<int64_t>(), GetQType<float>()), IsOkAndHolds(GetDenseArrayQType<float>())); EXPECT_THAT( WithScalarQType(GetDenseArrayQType<int64_t>(), GetWeakFloatQType()), IsOkAndHolds(GetDenseArrayWeakFloatQType())); EXPECT_THAT(WithScalarQType(GetArrayQType<int64_t>(), GetWeakFloatQType()), IsOkAndHolds(GetArrayWeakFloatQType())); EXPECT_THAT(WithScalarQType(MakeTupleQType({GetQType<int64_t>()}), GetOptionalQType<float>()), StatusIs(absl::StatusCode::kInvalidArgument, MatchesRegex("unable to replace scalar type in .* with " "a non-scalar type .*"))); EXPECT_THAT( WithScalarQType(MakeTupleQType({GetQType<int64_t>()}), GetQType<float>()), StatusIs(absl::StatusCode::kInvalidArgument, MatchesRegex("unable to replace scalar type in .*"))); } TEST(TypeProperties, GetPresenceQType) { EXPECT_THAT(GetPresenceQType(GetQType<int64_t>()), IsOkAndHolds(GetQType<Unit>())); EXPECT_THAT(GetPresenceQType(GetOptionalQType<int64_t>()), IsOkAndHolds(GetQType<OptionalUnit>())); EXPECT_THAT(GetPresenceQType(GetDenseArrayQType<int64_t>()), IsOkAndHolds(GetDenseArrayQType<Unit>())); EXPECT_THAT(GetPresenceQType(GetDenseArrayWeakFloatQType()), IsOkAndHolds(GetDenseArrayQType<Unit>())); EXPECT_THAT(GetPresenceQType(GetArrayWeakFloatQType()), IsOkAndHolds(GetArrayQType<Unit>())); EXPECT_THAT(GetPresenceQType(MakeTupleQType({GetQType<int64_t>()})), StatusIs(absl::StatusCode::kInvalidArgument, MatchesRegex("no type to represent presence in .*"))); } TEST(TypeProperties, IsOptionalLikeQType) { EXPECT_FALSE(IsOptionalLikeQType(GetQType<int64_t>())); EXPECT_TRUE(IsOptionalLikeQType(GetOptionalQType<int64_t>())); EXPECT_TRUE(IsOptionalLikeQType(GetDenseArrayQType<int64_t>())); EXPECT_TRUE(IsOptionalLikeQType(GetDenseArrayWeakFloatQType())); EXPECT_TRUE(IsOptionalLikeQType(GetArrayWeakFloatQType())); } TEST(TypeProperties, ToOptionalLikeQType) { EXPECT_THAT(ToOptionalLikeQType(GetQType<int64_t>()), IsOkAndHolds(GetOptionalQType<int64_t>())); EXPECT_THAT(ToOptionalLikeQType(GetOptionalQType<int64_t>()), IsOkAndHolds(GetOptionalQType<int64_t>())); EXPECT_THAT(ToOptionalLikeQType(GetDenseArrayQType<int64_t>()), IsOkAndHolds(GetDenseArrayQType<int64_t>())); EXPECT_THAT(ToOptionalLikeQType(GetDenseArrayWeakFloatQType()), IsOkAndHolds(GetDenseArrayWeakFloatQType())); EXPECT_THAT(ToOptionalLikeQType(GetArrayWeakFloatQType()), IsOkAndHolds(GetArrayWeakFloatQType())); } } }
2,359
#ifndef AROLLA_QTYPE_ARRAY_LIKE_FRAME_ITER_H_ #define AROLLA_QTYPE_ARRAY_LIKE_FRAME_ITER_H_ #include <algorithm> #include <cstddef> #include <cstdint> #include <functional> #include <memory> #include <optional> #include <vector> #include "absl/log/check.h" #include "absl/status/statusor.h" #include "absl/synchronization/barrier.h" #include "absl/types/span.h" #include "arolla/memory/frame.h" #include "arolla/memory/raw_buffer_factory.h" #include "arolla/qtype/array_like/array_like_qtype.h" #include "arolla/qtype/typed_ref.h" #include "arolla/qtype/typed_slot.h" #include "arolla/util/threading.h" namespace arolla { class FrameIterator { public: FrameIterator(const FrameIterator&) = delete; FrameIterator(FrameIterator&&) = default; ~FrameIterator(); struct Options { static constexpr Options Default() { return {}; } std::optional<int64_t> row_count; int64_t frame_buffer_count = 64; RawBufferFactory* buffer_factory = nullptr; }; static absl::StatusOr<FrameIterator> Create( absl::Span<const TypedRef> input_arrays, absl::Span<const TypedSlot> input_scalar_slots, absl::Span<const TypedSlot> output_array_slots, absl::Span<const TypedSlot> output_scalar_slots, const FrameLayout* scalar_layout, Options options = Options::Default()); template <class Fn> void CustomFrameInitialization(Fn&& fn) { for (auto& frame : frames_) fn(frame); } int64_t row_count() const { return row_count_; } template <typename Fn> void ForEachFrame(Fn&& fn) { for (int64_t offset = 0; offset < row_count_; offset += frames_.size()) { int64_t count = std::min<int64_t>(frames_.size(), row_count_ - offset); PreloadFrames(count); for (int64_t i = 0; i < count; ++i) { fn(frames_[i]); } SaveOutputsOfProcessedFrames(count); } } template <typename Fn> void ForEachFrame(Fn&& fn, ThreadingInterface& threading, int thread_count) { DCHECK_GE(thread_count, 1); const int frames_per_worker = (frames_.size() + thread_count - 1) / thread_count; auto barrier1 = std::make_unique<absl::Barrier>(thread_count); auto barrier2 = std::make_unique<absl::Barrier>(thread_count); auto BarrierSync = [thread_count](std::unique_ptr<absl::Barrier>& b) { if (b->Block()) { b = std::make_unique<absl::Barrier>(thread_count); } }; auto worker_fn = [&](int worker_id) { for (int64_t offset = 0; offset < row_count_; offset += frames_.size()) { int64_t count = std::min<int64_t>(frames_.size(), row_count_ - offset); if (worker_id == 0) { PreloadFrames(count); } BarrierSync(barrier1); for (int64_t i = worker_id * frames_per_worker; i < std::min<int64_t>(count, (worker_id + 1) * frames_per_worker); ++i) { fn(frames_[i]); } BarrierSync(barrier2); if (worker_id == 0) { SaveOutputsOfProcessedFrames(count); } } }; threading.WithThreading([&] { std::vector<std::function<void()>> join_fns; join_fns.reserve(thread_count - 1); for (int i = 1; i < thread_count; ++i) { join_fns.push_back( threading.StartThread([&worker_fn, i] { worker_fn(i); })); } worker_fn(0); for (auto& join : join_fns) join(); }); } absl::Status StoreOutput(FramePtr output_frame); private: void* GetAllocByIndex(size_t index) { return buffer_.data() + index * dense_scalar_layout_size_; } void PreloadFrames(size_t frames_count); void SaveOutputsOfProcessedFrames(size_t frames_count); FrameIterator( std::vector<std::unique_ptr<BatchToFramesCopier>>&& input_copiers, std::vector<std::unique_ptr<BatchFromFramesCopier>>&& output_copiers, size_t row_count, size_t frame_buffer_count, const FrameLayout* scalar_layout); int64_t row_count_; std::vector<std::unique_ptr<BatchToFramesCopier>> input_copiers_; std::vector<std::unique_ptr<BatchFromFramesCopier>> output_copiers_; std::vector<FramePtr> frames_; std::vector<ConstFramePtr> const_frames_; std::vector<char> buffer_; const FrameLayout* scalar_layout_; size_t dense_scalar_layout_size_; }; } #endif #include "arolla/qtype/array_like/frame_iter.h" #include <algorithm> #include <cstddef> #include <cstdint> #include <memory> #include <optional> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/log/check.h" #include "absl/log/log.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/types/span.h" #include "arolla/memory/frame.h" #include "arolla/memory/raw_buffer_factory.h" #include "arolla/qtype/array_like/array_like_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_ref.h" #include "arolla/util/status_macros_backport.h" namespace arolla { namespace { absl::StatusOr<std::vector<std::unique_ptr<BatchToFramesCopier>>> CreateInputCopiers(absl::Span<const TypedRef> input_arrays, absl::Span<const TypedSlot> input_scalar_slots) { if (input_arrays.size() != input_scalar_slots.size()) { return absl::InvalidArgumentError( absl::StrFormat("size of input_arrays and input_scalar_slots should be " "the same: %d vs %d", input_arrays.size(), input_scalar_slots.size())); } absl::flat_hash_map<QTypePtr, std::unique_ptr<BatchToFramesCopier>> input_copiers; for (size_t i = 0; i < input_arrays.size(); ++i) { QTypePtr array_type = input_arrays[i].GetType(); if (!input_copiers.contains(array_type)) { ASSIGN_OR_RETURN(input_copiers[array_type], CreateBatchToFramesCopier(array_type)); } RETURN_IF_ERROR(input_copiers[array_type]->AddMapping( input_arrays[i], input_scalar_slots[i])); } std::vector<std::unique_ptr<BatchToFramesCopier>> input_copiers_vector; for (auto& [_, v] : input_copiers) input_copiers_vector.push_back(std::move(v)); return input_copiers_vector; } absl::StatusOr<std::vector<std::unique_ptr<BatchFromFramesCopier>>> CreateOutputCopiers(absl::Span<const TypedSlot> output_array_slots, absl::Span<const TypedSlot> output_scalar_slots, RawBufferFactory* buffer_factory) { if (output_array_slots.size() != output_scalar_slots.size()) { return absl::InvalidArgumentError(absl::StrFormat( "size of output_array_slots and output_scalar_slots should be " "the same: %d vs %d", output_array_slots.size(), output_scalar_slots.size())); } absl::flat_hash_map<QTypePtr, std::unique_ptr<BatchFromFramesCopier>> output_copiers; for (size_t i = 0; i < output_array_slots.size(); ++i) { QTypePtr array_type = output_array_slots[i].GetType(); if (!output_copiers.contains(array_type)) { ASSIGN_OR_RETURN(output_copiers[array_type], CreateBatchFromFramesCopier(array_type, buffer_factory)); } RETURN_IF_ERROR(output_copiers[array_type]->AddMapping( output_scalar_slots[i], output_array_slots[i])); } std::vector<std::unique_ptr<BatchFromFramesCopier>> output_copiers_vector; for (auto& [_, v] : output_copiers) output_copiers_vector.push_back(std::move(v)); return output_copiers_vector; } } absl::StatusOr<FrameIterator> FrameIterator::Create( absl::Span<const TypedRef> input_arrays, absl::Span<const TypedSlot> input_scalar_slots, absl::Span<const TypedSlot> output_array_slots, absl::Span<const TypedSlot> output_scalar_slots, const FrameLayout* scalar_layout, FrameIterator::Options options) { ASSIGN_OR_RETURN( std::vector<std::unique_ptr<BatchToFramesCopier>> input_copiers, CreateInputCopiers(input_arrays, input_scalar_slots)); RawBufferFactory* buf_factory = options.buffer_factory; if (!buf_factory) buf_factory = GetHeapBufferFactory(); ASSIGN_OR_RETURN( std::vector<std::unique_ptr<BatchFromFramesCopier>> output_copiers, CreateOutputCopiers(output_array_slots, output_scalar_slots, buf_factory)); std::optional<int64_t> row_count = std::nullopt; for (const auto& copier : input_copiers) { if (!copier->row_count() || (row_count && *row_count != *copier->row_count())) { return absl::InvalidArgumentError( absl::StrFormat("input arrays have different sizes: %d vs %d", *row_count, *copier->row_count())); } row_count = copier->row_count(); } if (!row_count.has_value()) { if (!options.row_count.has_value()) { return absl::InvalidArgumentError( "options.row_count can not be missed if there is no input arrays"); } row_count = options.row_count; } else if (options.row_count.has_value() && *options.row_count != *row_count) { return absl::InvalidArgumentError( absl::StrFormat("sizes of input arrays don't correspond " "to options.row_count: %d vs %d", *row_count, *options.row_count)); } return FrameIterator(std::move(input_copiers), std::move(output_copiers), *row_count, options.frame_buffer_count, scalar_layout); } FrameIterator::FrameIterator( std::vector<std::unique_ptr<BatchToFramesCopier>>&& input_copiers, std::vector<std::unique_ptr<BatchFromFramesCopier>>&& output_copiers, size_t row_count, size_t frame_buffer_count, const FrameLayout* scalar_layout) : row_count_(row_count), input_copiers_(std::move(input_copiers)), output_copiers_(std::move(output_copiers)), scalar_layout_(scalar_layout) { frame_buffer_count = std::min(row_count, frame_buffer_count); dense_scalar_layout_size_ = (scalar_layout_->AllocSize() + 7) & ~7; buffer_.resize(dense_scalar_layout_size_ * frame_buffer_count); for (size_t i = 0; i < frame_buffer_count; ++i) { void* alloc_ptr = GetAllocByIndex(i); scalar_layout->InitializeAlignedAlloc(alloc_ptr); frames_.emplace_back(alloc_ptr, scalar_layout); const_frames_.emplace_back(alloc_ptr, scalar_layout); } for (auto& copier : input_copiers_) copier->Start(); for (auto& copier : output_copiers_) copier->Start(row_count); } FrameIterator::~FrameIterator() { for (size_t i = 0; i < frames_.size(); ++i) { scalar_layout_->DestroyAlloc(GetAllocByIndex(i)); } } absl::Status FrameIterator::StoreOutput(FramePtr output_frame) { for (std::unique_ptr<BatchFromFramesCopier>& copier : output_copiers_) { RETURN_IF_ERROR(copier->Finalize(output_frame)); } return absl::OkStatus(); } void FrameIterator::PreloadFrames(size_t frames_count) { for (auto& copier : input_copiers_) { copier->CopyNextBatch({frames_.data(), frames_count}); } } void FrameIterator::SaveOutputsOfProcessedFrames(size_t frames_count) { for (auto& copier : output_copiers_) { absl::Status status = copier->CopyNextBatch({const_frames_.data(), frames_count}); DCHECK_OK(status); } } }
#include "arolla/qtype/array_like/frame_iter.h" #include <cstdint> #include <optional> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/memory/frame.h" #include "arolla/memory/memory_allocation.h" #include "arolla/memory/optional_value.h" #include "arolla/qtype/typed_ref.h" #include "arolla/qtype/typed_slot.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/threading.h" namespace arolla { namespace { using ::arolla::testing::StatusIs; using ::testing::ElementsAre; using ::testing::HasSubstr; using ::testing::Test; TEST(FrameIterator, Iterate) { FrameLayout::Builder scalar_bldr; auto scalar_f_slot1 = scalar_bldr.AddSlot<OptionalValue<float>>(); auto scalar_i_slot1 = scalar_bldr.AddSlot<OptionalValue<int64_t>>(); auto scalar_i_slot2 = scalar_bldr.AddSlot<OptionalValue<int64_t>>(); auto scalar_f_slot2 = scalar_bldr.AddSlot<OptionalValue<float>>(); auto scalar_layout = std::move(scalar_bldr).Build(); std::vector<TypedSlot> scalar_slots = { TypedSlot::FromSlot(scalar_f_slot1), TypedSlot::FromSlot(scalar_i_slot1), TypedSlot::FromSlot(scalar_i_slot2), TypedSlot::FromSlot(scalar_f_slot2)}; DenseArray<float> arr_f1 = CreateDenseArray<float>({1.5, std::nullopt, 2.5, 3.5}); DenseArray<int64_t> arr_i1 = CreateDenseArray<int64_t>({3, 4, 5, 6}); DenseArray<int64_t> arr_i2 = CreateDenseArray<int64_t>({2, std::nullopt, 0, std::nullopt}); DenseArray<float> arr_f2 = CreateDenseArray<float>({3.2, 2.2, std::nullopt, 1.2}); FrameLayout::Builder vector_bldr; auto arr_output_f1 = vector_bldr.AddSlot<DenseArray<float>>(); auto arr_output_i1 = vector_bldr.AddSlot<DenseArray<int64_t>>(); auto arr_output_i2 = vector_bldr.AddSlot<DenseArray<int64_t>>(); auto arr_output_f2 = vector_bldr.AddSlot<DenseArray<float>>(); auto output_vector_layout = std::move(vector_bldr).Build(); std::vector<TypedRef> input_refs = { TypedRef::FromValue(arr_f1), TypedRef::FromValue(arr_i1), TypedRef::FromValue(arr_i2), TypedRef::FromValue(arr_f2)}; std::vector<TypedSlot> output_slots = { TypedSlot::FromSlot(arr_output_f1), TypedSlot::FromSlot(arr_output_i1), TypedSlot::FromSlot(arr_output_i2), TypedSlot::FromSlot(arr_output_f2)}; auto scalar_processing_fn = [&](FramePtr frame) { OptionalValue<float> f1 = frame.Get(scalar_f_slot1); OptionalValue<float> f2 = frame.Get(scalar_f_slot2); if (f1.present) frame.Set(scalar_f_slot1, f1.value + 1.0); if (f2.present) frame.Set(scalar_f_slot2, f2.value + 2.0); OptionalValue<int64_t> i1 = frame.Get(scalar_i_slot1); OptionalValue<int64_t> i2 = frame.Get(scalar_i_slot2); if (i1.present) frame.Set(scalar_i_slot1, i1.value + 3); if (i2.present) frame.Set(scalar_i_slot2, i2.value + 4); }; auto check_output_fn = [&](FrameIterator& frame_iterator) { MemoryAllocation alloc(&output_vector_layout); FramePtr output_frame = alloc.frame(); EXPECT_OK(frame_iterator.StoreOutput(output_frame)); EXPECT_THAT(output_frame.Get(arr_output_f1), ElementsAre(2.5, std::nullopt, 3.5, 4.5)); EXPECT_THAT(output_frame.Get(arr_output_f2), ElementsAre(5.2, 4.2, std::nullopt, 3.2)); EXPECT_THAT(output_frame.Get(arr_output_i1), ElementsAre(6, 7, 8, 9)); EXPECT_THAT(output_frame.Get(arr_output_i2), ElementsAre(6, std::nullopt, 4, std::nullopt)); }; { ASSERT_OK_AND_ASSIGN( auto frame_iterator, FrameIterator::Create(input_refs, scalar_slots, output_slots, scalar_slots, &scalar_layout, {.frame_buffer_count = 2})); frame_iterator.ForEachFrame(scalar_processing_fn); check_output_fn(frame_iterator); } StdThreading threading(4); for (int threads = 1; threads <= 4; ++threads) { ASSERT_OK_AND_ASSIGN( auto frame_iterator, FrameIterator::Create(input_refs, scalar_slots, output_slots, scalar_slots, &scalar_layout, {.frame_buffer_count = 3})); frame_iterator.ForEachFrame(scalar_processing_fn, threading, threads); check_output_fn(frame_iterator); } } TEST(FrameIterator, EmptyArrays) { FrameLayout::Builder scalar_bldr; auto scalar_slot = scalar_bldr.AddSlot<OptionalValue<float>>(); auto scalar_layout = std::move(scalar_bldr).Build(); std::vector<TypedSlot> scalar_slots = {TypedSlot::FromSlot(scalar_slot)}; FrameLayout::Builder arrays_layout_bldr; auto arr_output = arrays_layout_bldr.AddSlot<DenseArray<float>>(); auto output_arrays_layout = std::move(arrays_layout_bldr).Build(); DenseArray<float> arr; std::vector<TypedRef> input_refs = {TypedRef::FromValue(arr)}; std::vector<TypedSlot> output_slots = {TypedSlot::FromSlot(arr_output)}; auto scalar_processing_fn = [&](FramePtr frame) { ADD_FAILURE(); }; ASSERT_OK_AND_ASSIGN(auto frame_iterator, FrameIterator::Create( input_refs, scalar_slots, output_slots, scalar_slots, &scalar_layout, {.frame_buffer_count = 2})); frame_iterator.ForEachFrame(scalar_processing_fn); MemoryAllocation alloc(&output_arrays_layout); FramePtr output_frame = alloc.frame(); EXPECT_OK(frame_iterator.StoreOutput(output_frame)); EXPECT_EQ(output_frame.Get(arr_output).size(), 0); } TEST(FrameIterator, EmptyInputAndOutput) { FrameLayout::Builder scalar_bldr; auto scalar_layout = std::move(scalar_bldr).Build(); { auto frame_iterator_or_status = FrameIterator::Create({}, {}, {}, {}, &scalar_layout); EXPECT_THAT( frame_iterator_or_status, StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("options.row_count can not be missed if there " "is no input arrays"))); } { ASSERT_OK_AND_ASSIGN(auto frame_iterator, FrameIterator::Create({}, {}, {}, {}, &scalar_layout, {.row_count = 4})); EXPECT_EQ(frame_iterator.row_count(), 4); } } TEST(FrameIterator, IncorrectInputType) { FrameLayout::Builder scalar_bldr; auto scalar_slot = scalar_bldr.AddSlot<float>(); auto scalar_layout = std::move(scalar_bldr).Build(); std::vector<TypedSlot> scalar_slots = {TypedSlot::FromSlot(scalar_slot)}; DenseArray<int64_t> arr = CreateDenseArray<int64_t>({1, std::nullopt, 2, 3}); auto frame_iterator_or_status = FrameIterator::Create( {TypedRef::FromValue(arr)}, scalar_slots, {}, {}, &scalar_layout); EXPECT_THAT(frame_iterator_or_status, StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("slot type does not match"))); } TEST(FrameIterator, IncorrectOutputType) { FrameLayout::Builder vector_bldr; auto vector_slot = vector_bldr.AddSlot<DenseArray<float>>(); auto vector_layout = std::move(vector_bldr).Build(); FrameLayout::Builder scalar_bldr; auto scalar_slot = scalar_bldr.AddSlot<int64_t>(); auto scalar_layout = std::move(scalar_bldr).Build(); auto frame_iterator_or_status = FrameIterator::Create({}, {}, {TypedSlot::FromSlot(vector_slot)}, {TypedSlot::FromSlot(scalar_slot)}, &scalar_layout); EXPECT_THAT(frame_iterator_or_status, StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("slot type does not match"))); } TEST(FrameIterator, WrongSize) { FrameLayout::Builder scalar_bldr; auto scalar_f_slot1 = scalar_bldr.AddSlot<OptionalValue<float>>(); auto scalar_i_slot1 = scalar_bldr.AddSlot<OptionalValue<int64_t>>(); auto scalar_layout = std::move(scalar_bldr).Build(); std::vector<TypedSlot> scalar_slots = {TypedSlot::FromSlot(scalar_f_slot1), TypedSlot::FromSlot(scalar_i_slot1)}; DenseArray<float> arr_f1 = CreateDenseArray<float>({1.5, std::nullopt, 2.5, 3.5}); DenseArray<int64_t> arr_i1 = CreateDenseArray<int64_t>({3, 4, 5}); auto frame_iterator_or_status = FrameIterator::Create( {TypedRef::FromValue(arr_f1), TypedRef::FromValue(arr_i1)}, scalar_slots, {}, {}, &scalar_layout); EXPECT_THAT(frame_iterator_or_status, StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("input arrays have different sizes"))); } } }
2,360
#ifndef AROLLA_QTYPE_STRINGS_REGEX_H_ #define AROLLA_QTYPE_STRINGS_REGEX_H_ #include <memory> #include <ostream> #include <utility> #include "absl/log/check.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/simple_qtype.h" #include "arolla/util/fingerprint.h" #include "re2/re2.h" namespace arolla { class Regex { public: Regex() {} static absl::StatusOr<Regex> FromPattern(absl::string_view pattern); bool has_value() const { return impl_ != nullptr; } const RE2& value() const { return has_value() ? *impl_ : default_value(); } private: static const RE2& default_value(); explicit Regex(std::shared_ptr<RE2> impl) : impl_(std::move(impl)) { DCHECK(impl_->ok()); } std::shared_ptr<const RE2> impl_; }; std::ostream& operator<<(std::ostream& stream, const Regex& regex); AROLLA_DECLARE_FINGERPRINT_HASHER_TRAITS(Regex); AROLLA_DECLARE_SIMPLE_QTYPE(REGEX, Regex); AROLLA_DECLARE_OPTIONAL_QTYPE(REGEX, Regex); } #endif #include "arolla/qtype/strings/regex.h" #include <memory> #include <ostream> #include <utility> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/simple_qtype.h" #include "arolla/util/fingerprint.h" #include "re2/re2.h" namespace arolla { absl::StatusOr<Regex> Regex::FromPattern(absl::string_view pattern) { auto value = std::make_shared<RE2>(pattern, RE2::Quiet); if (value->ok()) { return Regex(std::move(value)); } else { return absl::InvalidArgumentError(absl::StrFormat( "Invalid regular expression: \"%s\"; %s.", pattern, value->error())); } } const RE2& Regex::default_value() { static LazyRE2 value = {".^"}; return *value; } std::ostream& operator<<(std::ostream& stream, const Regex& regex) { if (regex.has_value()) { return stream << "Regex{\"" << regex.value().pattern() << "\"}"; } else { return stream << "Regex{}"; } } void FingerprintHasherTraits<Regex>::operator()(FingerprintHasher* hasher, const Regex& value) const { hasher->Combine(value.value().pattern()); } AROLLA_DEFINE_SIMPLE_QTYPE(REGEX, Regex); AROLLA_DEFINE_OPTIONAL_QTYPE(REGEX, Regex); }
#include "arolla/qtype/strings/regex.h" #include <sstream> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "arolla/util/testing/status_matchers_backport.h" #include "re2/re2.h" using ::arolla::testing::StatusIs; using ::testing::HasSubstr; namespace arolla { namespace { TEST(Regex, DefaultConstructor) { Regex regex; EXPECT_FALSE(regex.has_value()); std::stringstream out; out << regex; EXPECT_EQ(out.str(), "Regex{}"); EXPECT_FALSE(RE2::PartialMatch("some string", regex.value())); } TEST(Regex, FromPattern) { ASSERT_OK_AND_ASSIGN(auto regex, Regex::FromPattern("\\d+ bottles of beer")); EXPECT_TRUE(regex.has_value()); EXPECT_TRUE(RE2::FullMatch("100 bottles of beer", regex.value())); std::stringstream out; out << regex; EXPECT_EQ(out.str(), "Regex{\"\\d+ bottles of beer\"}"); EXPECT_THAT(Regex::FromPattern("ab\\αcd"), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("Invalid regular expression: \"ab\\αcd\"; "))); } } }
2,361
#ifndef AROLLA_QTYPE_DICT_DICT_TYPES_H_ #define AROLLA_QTYPE_DICT_DICT_TYPES_H_ #include <cstdint> #include <initializer_list> #include <memory> #include <sstream> #include <type_traits> #include <utility> #include <vector> #include "absl/base/attributes.h" #include "absl/container/flat_hash_map.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "arolla/memory/optional_value.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/simple_qtype.h" #include "arolla/util/bytes.h" #include "arolla/util/fingerprint.h" #include "arolla/util/indestructible.h" #include "arolla/util/map.h" #include "arolla/util/meta.h" #include "arolla/util/repr.h" #include "arolla/util/text.h" #include "arolla/util/unit.h" #include "arolla/util/view_types.h" namespace arolla { bool IsDictQType(const QType* qtype); template <typename Key> class KeyToRowDict { using KeyViewHashTable = absl::flat_hash_map<view_type_t<Key>, int64_t>; using Hasher = typename KeyViewHashTable::hasher; using KeyEqual = typename KeyViewHashTable::key_equal; public: using Map = absl::flat_hash_map<Key, int64_t, Hasher, KeyEqual>; KeyToRowDict() = default; explicit KeyToRowDict(Map dict) : dict_(std::make_shared<Map>(std::move(dict))) {} KeyToRowDict(std::initializer_list<typename Map::value_type> dict) : dict_(std::make_shared<Map>(std::move(dict))) {} const Map& map() const { static const Indestructible<Map> empty; return dict_ != nullptr ? *dict_ : *empty; } private: std::shared_ptr<const Map> dict_; }; namespace dict_impl { void RegisterKeyToRowDictQType(QTypePtr key_type, QTypePtr dict_type); } absl::StatusOr<QTypePtr> GetKeyToRowDictQType(QTypePtr key_type); template <typename Key> QTypePtr GetKeyToRowDictQType() { return GetQType<KeyToRowDict<Key>>(); } bool IsKeyToRowDictQType(QTypePtr type); absl::StatusOr<QTypePtr> GetDictQType(QTypePtr key_type, QTypePtr value_type); const QType* GetDictKeyQTypeOrNull(QTypePtr dict_type); const QType* GetDictValueQTypeOrNull(QTypePtr dict_type); template <typename Key> struct QTypeTraits<KeyToRowDict<Key>> { static_assert(!std::is_same_v<Key, Unit>); static_assert(!std::is_same_v<Key, float>); static_assert(!std::is_same_v<Key, double>); static_assert(is_scalar_type_v<strip_optional_t<Key>>); static QTypePtr type() { static const Indestructible<SimpleQType> result( meta::type<KeyToRowDict<Key>>(), absl::StrCat("DICT_", GetQType<Key>()->name()), GetQType<Key>(), "::arolla::KeyToRowDict"); static const int ABSL_ATTRIBUTE_UNUSED dict_registered = (dict_impl::RegisterKeyToRowDictQType(GetQType<Key>(), result.get()), 1); return result.get(); } }; template <class Key> struct ReprTraits<KeyToRowDict<Key>, std::enable_if_t<std::is_invocable_v<ReprTraits<Key>, Key>>> { ReprToken operator()(const KeyToRowDict<Key>& dict) const { std::ostringstream oss; oss << "dict{"; for (const auto& key : SortedMapKeys(dict.map())) { oss << Repr(Key(key)) << ":" << Repr(dict.map().at(key)) << ","; } oss << "}"; return ReprToken{std::move(oss).str()}; } }; template <class Key> struct FingerprintHasherTraits<KeyToRowDict<Key>> { void operator()(FingerprintHasher* hasher, const KeyToRowDict<Key>& dict) const { std::vector<std::pair<view_type_t<Key>, int64_t>> elements( dict.map().begin(), dict.map().end()); std::sort(elements.begin(), elements.end()); hasher->Combine(elements.size()); for (const auto& [k, v] : elements) { hasher->Combine(k, v); } } }; extern template struct QTypeTraits<KeyToRowDict<bool>>; extern template struct QTypeTraits<KeyToRowDict<int32_t>>; extern template struct QTypeTraits<KeyToRowDict<int64_t>>; extern template struct QTypeTraits<KeyToRowDict<Bytes>>; extern template struct QTypeTraits<KeyToRowDict<Text>>; } #endif #include "arolla/qtype/dict/dict_types.h" #include <cstdint> #include <memory> #include <string> #include <utility> #include "absl/base/thread_annotations.h" #include "absl/container/flat_hash_map.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/synchronization/mutex.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/qtype/derived_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/tuple_qtype.h" #include "arolla/util/bytes.h" #include "arolla/util/fast_dynamic_downcast_final.h" #include "arolla/util/indestructible.h" #include "arolla/util/text.h" #include "arolla/util/status_macros_backport.h" namespace arolla { namespace { class KeyToRowDictTypeRegistry { public: static KeyToRowDictTypeRegistry& instance() { static Indestructible<KeyToRowDictTypeRegistry> result; return *result; } absl::Status Register(QTypePtr key_qtype, QTypePtr dict_qtype) { absl::MutexLock l(&lock_); auto [iter, inserted] = dict_types_.emplace(key_qtype, dict_qtype); if (!inserted) { return absl::FailedPreconditionError(absl::StrFormat( "attempt to register %s dict twice", dict_qtype->name())); } return absl::OkStatus(); } absl::StatusOr<QTypePtr> Get(QTypePtr qtype) { absl::ReaderMutexLock l(&lock_); auto iter = dict_types_.find(qtype); if (iter == dict_types_.end()) { return absl::NotFoundError( absl::StrFormat("no dict with %s keys found", qtype->name())); } return iter->second; } private: absl::Mutex lock_; absl::flat_hash_map<QTypePtr, QTypePtr> dict_types_ ABSL_GUARDED_BY(lock_); }; class DictQType final : public BasicDerivedQType { public: DictQType(std::string name, QTypePtr dict_type, QTypePtr values_array_type) : BasicDerivedQType(ConstructorArgs{ .name = std::move(name), .base_qtype = MakeTupleQType({dict_type, values_array_type}), .qtype_specialization_key = "::arolla::DictQType", }) {} }; class DictQTypeRegistry { public: static DictQTypeRegistry& instance() { static Indestructible<DictQTypeRegistry> result; return *result; } absl::StatusOr<QTypePtr> GetQType(QTypePtr key_type, QTypePtr value_type) { { absl::ReaderMutexLock guard(&lock_); if (const auto it = registry_.find({key_type, value_type}); it != registry_.end()) { return it->second.get(); } } ASSIGN_OR_RETURN(QTypePtr dict_type, GetKeyToRowDictQType(key_type)); ASSIGN_OR_RETURN(QTypePtr values_array_type, GetDenseArrayQTypeByValueQType(value_type)); auto kv_dict_type = std::make_unique<DictQType>( absl::StrFormat("Dict<%s,%s>", key_type->name(), value_type->name()), dict_type, values_array_type); absl::MutexLock guard(&lock_); return registry_ .emplace(std::make_pair(key_type, value_type), std::move(kv_dict_type)) .first->second.get(); } private: absl::Mutex lock_; absl::flat_hash_map<std::pair<QTypePtr, QTypePtr>, std::unique_ptr<QType>> registry_ ABSL_GUARDED_BY(lock_); }; } namespace dict_impl { void RegisterKeyToRowDictQType(QTypePtr key_type, QTypePtr dict_type) { auto status = KeyToRowDictTypeRegistry::instance().Register(key_type, dict_type); DCHECK_OK(status); } } absl::StatusOr<QTypePtr> GetKeyToRowDictQType(QTypePtr key_type) { return KeyToRowDictTypeRegistry::instance().Get(key_type); } bool IsKeyToRowDictQType(QTypePtr type) { if (type->value_qtype() == nullptr) { return false; } ASSIGN_OR_RETURN(QTypePtr dict_type, GetKeyToRowDictQType(type->value_qtype()), false); return dict_type == type; } absl::StatusOr<QTypePtr> GetDictQType(QTypePtr key_type, QTypePtr value_type) { return DictQTypeRegistry::instance().GetQType(key_type, value_type); } const QType* GetDictKeyQTypeOrNull(QTypePtr dict_type) { auto d = fast_dynamic_downcast_final<const DictQType*>(dict_type); return d != nullptr ? d->type_fields()[0].GetType()->value_qtype() : nullptr; } const QType* GetDictValueQTypeOrNull(QTypePtr dict_type) { auto d = fast_dynamic_downcast_final<const DictQType*>(dict_type); return d != nullptr ? d->type_fields()[1].GetType()->value_qtype() : nullptr; } bool IsDictQType(const QType* qtype) { return fast_dynamic_downcast_final<const DictQType*>(qtype) != nullptr; } template struct QTypeTraits<KeyToRowDict<bool>>; template struct QTypeTraits<KeyToRowDict<int32_t>>; template struct QTypeTraits<KeyToRowDict<int64_t>>; template struct QTypeTraits<KeyToRowDict<Bytes>>; template struct QTypeTraits<KeyToRowDict<Text>>; }
#include "arolla/qtype/dict/dict_types.h" #include <cstdint> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_slot.h" #include "arolla/util/bytes.h" #include "arolla/util/repr.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/unit.h" namespace arolla { namespace { using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::testing::ElementsAre; using ::testing::Eq; using ::testing::HasSubstr; using ::testing::Ne; using ::testing::Property; TEST(DictTypes, GetKeyToRowDictQType) { GetKeyToRowDictQType<int64_t>(); EXPECT_THAT(GetKeyToRowDictQType<int64_t>()->value_qtype(), Eq(GetQType<int64_t>())); EXPECT_THAT(GetKeyToRowDictQType(GetQType<int64_t>()), IsOkAndHolds(GetQType<KeyToRowDict<int64_t>>())); EXPECT_THAT(GetKeyToRowDictQType(GetQType<int64_t>()), IsOkAndHolds(GetKeyToRowDictQType<int64_t>())); EXPECT_THAT(GetKeyToRowDictQType(GetQType<KeyToRowDict<int64_t>>()), StatusIs(absl::StatusCode::kNotFound, HasSubstr("no dict with DICT_INT64 keys found"))); } TEST(DictTypes, GetDictQType) { GetKeyToRowDictQType<int64_t>(); GetDenseArrayQType<float>(); GetDenseArrayQType<double>(); ASSERT_OK_AND_ASSIGN(QTypePtr int_to_float_dict, GetDictQType(GetQType<int64_t>(), GetQType<float>())); EXPECT_THAT(int_to_float_dict->name(), Eq("Dict<INT64,FLOAT32>")); EXPECT_THAT(GetDictKeyQTypeOrNull(int_to_float_dict), Eq(GetQType<int64_t>())); EXPECT_THAT(GetDictValueQTypeOrNull(int_to_float_dict), Eq(GetQType<float>())); EXPECT_THAT( int_to_float_dict->type_fields(), ElementsAre( Property(&TypedSlot::GetType, Eq(GetKeyToRowDictQType<int64_t>())), Property(&TypedSlot::GetType, Eq(GetDenseArrayQType<float>())))); EXPECT_THAT(GetDictQType(GetQType<int64_t>(), GetQType<float>()), IsOkAndHolds(Eq(int_to_float_dict))); EXPECT_THAT(GetDictQType(GetQType<int64_t>(), GetQType<double>()), IsOkAndHolds(Ne(int_to_float_dict))); } TEST(DictTypes, IsDictQType) { GetKeyToRowDictQType<int64_t>(); GetDenseArrayQType<float>(); GetDenseArrayQType<Unit>(); { ASSERT_OK_AND_ASSIGN(QTypePtr int_to_float_dict, GetDictQType(GetQType<int64_t>(), GetQType<float>())); ASSERT_TRUE(IsDictQType(int_to_float_dict)); } { ASSERT_OK_AND_ASSIGN(QTypePtr int_to_unit_dict, GetDictQType(GetQType<int64_t>(), GetQType<Unit>())); ASSERT_TRUE(IsDictQType(int_to_unit_dict)); } { EXPECT_THAT(GetDictQType(GetQType<Unit>(), GetQType<float>()), StatusIs(absl::StatusCode::kNotFound, HasSubstr("no dict with UNIT keys found"))); } { EXPECT_THAT(GetDictQType(GetQType<float>(), GetQType<float>()), StatusIs(absl::StatusCode::kNotFound, HasSubstr("no dict with FLOAT32 keys found"))); } } TEST(DictTypes, ReprTraits) { EXPECT_EQ(Repr(KeyToRowDict<float>{}), "dict{}"); EXPECT_EQ(Repr(KeyToRowDict<float>{{{0.5, 1}}}), "dict{0.5:int64{1},}"); EXPECT_EQ(Repr(KeyToRowDict<float>{{{0.5, 1}, {2.5, 3}}}), "dict{0.5:int64{1},2.5:int64{3},}"); EXPECT_EQ(Repr(KeyToRowDict<Bytes>{{{Bytes("key"), 2}}}), "dict{b'key':int64{2},}"); } } }
2,362
#ifndef AROLLA_SERVING_INPLACE_EXPR_COMPILER_H_ #define AROLLA_SERVING_INPLACE_EXPR_COMPILER_H_ #include <functional> #include <memory> #include <string> #include <type_traits> #include <utility> #include "absl/container/flat_hash_map.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "arolla/expr/expr_node.h" #include "arolla/io/input_loader.h" #include "arolla/io/slot_listener.h" #include "arolla/io/struct_io.h" #include "arolla/memory/frame.h" #include "arolla/qexpr/eval_context.h" #include "arolla/qexpr/evaluation_engine.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_slot.h" #include "arolla/util/status_macros_backport.h" namespace arolla { namespace inplace_expr_compiler_impl { using TypedSlotMap = absl::flat_hash_map<std::string, TypedSlot>; TypedSlotMap CollectInternalSlots(TypedSlot root_slot); struct IoSlots { TypedSlotMap input_slots; TypedSlot output_slot; TypedSlotMap named_output_slots; }; absl::StatusOr<IoSlots> CollectIoSlots(QTypePtr qtype, const CompiledExpr& compiled_expr, absl::string_view final_output_name); } template <class T> using InplaceModelFunction = std::function<absl::Status(T&)>; template <typename T> absl::StatusOr<InplaceModelFunction<T>> CompileInplaceExprOnStruct( const InplaceCompiledExpr& compiled_expr, absl::string_view final_output_name) { static_assert( std::is_standard_layout<T>::value, "Data must be standard layout to be used with CompileExprInplace."); QTypePtr qtype = GetQType<T>(); ASSIGN_OR_RETURN(inplace_expr_compiler_impl::IoSlots slots, inplace_expr_compiler_impl::CollectIoSlots( qtype, compiled_expr, final_output_name)); ASSIGN_OR_RETURN(auto executable, compiled_expr.InplaceBind( slots.input_slots, slots.output_slot, slots.named_output_slots)); return [qtype, executable(std::shared_ptr<BoundExpr>(std::move(executable)))]( T& input) -> absl::Status { FramePtr frame(&input, &qtype->type_layout()); EvaluationContext ctx; executable->Execute(&ctx, frame); return ctx.status(); }; } template <typename Struct> absl::StatusOr<InputLoaderPtr<Struct>> CreateStructInputLoader() { return StructInputLoader<Struct>::Create( inplace_expr_compiler_impl::CollectInternalSlots( TypedSlot::UnsafeFromOffset(GetQType<Struct>(), 0))); } template <typename Struct> absl::StatusOr<std::unique_ptr<SlotListener<Struct>>> CreateStructSlotListener() { return StructSlotListener<Struct>::Create( inplace_expr_compiler_impl::CollectInternalSlots( TypedSlot::UnsafeFromOffset(GetQType<Struct>(), 0))); } } #endif #include "arolla/serving/inplace_expr_compiler.h" #include <cstddef> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "arolla/naming/table.h" #include "arolla/qexpr/evaluation_engine.h" #include "arolla/qtype/named_field_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_slot.h" #include "arolla/util/status_macros_backport.h" namespace arolla::inplace_expr_compiler_impl { TypedSlotMap CollectInternalSlots(TypedSlot root_slot) { TypedSlotMap result; if (GetFieldNames(root_slot.GetType()).empty()) { return result; } std::vector<std::pair<TypedSlot, naming::TablePath>> stack{{root_slot, {}}}; while (!stack.empty()) { auto [slot, table] = stack.back(); stack.pop_back(); auto field_names = GetFieldNames(slot.GetType()); for (size_t i = 0; i < field_names.size(); ++i) { const auto& field_name = field_names[i]; const TypedSlot& field_slot = slot.SubSlot(i); result.emplace(table.Column(naming::FieldAccess(field_name)).FullName(), field_slot); if (!GetFieldNames(field_slot.GetType()).empty()) { stack.emplace_back(field_slot, table.Child(naming::FieldAccess(field_name))); } } } return result; } namespace { absl::Status CheckField(QTypePtr qtype, const TypedSlotMap& slot_map, QTypePtr field_qtype, absl::string_view field_name) { if (GetFieldNames(qtype).empty()) { return absl::FailedPreconditionError( absl::StrCat("no registered field names for ", qtype->name(), " in Compile.*ExprOnStructInput")); } if (!slot_map.contains(field_name)) { return absl::FailedPreconditionError( absl::StrCat("input `", field_name, "` not found in ", qtype->name(), " in Compile.*ExprOnStructInput")); } QTypePtr result_type = slot_map.at(field_name).GetType(); if (result_type != field_qtype) { return absl::FailedPreconditionError(absl::StrCat( "input `", field_name, "` type mismatch for ", qtype->name(), " in Compile.*ExprOnStructInput, expected in struct: ", result_type->name(), ", found in expr: ", field_qtype->name())); } return absl::OkStatus(); } absl::StatusOr<TypedSlotMap> CollectInputSlots( QTypePtr qtype, const TypedSlotMap& struct_slot_map, const CompiledExpr& compiled_expr) { TypedSlotMap input_slots; input_slots.reserve(compiled_expr.input_types().size()); for (const auto& [name, field_qtype] : compiled_expr.input_types()) { RETURN_IF_ERROR(CheckField(qtype, struct_slot_map, field_qtype, name)); input_slots.emplace(name, struct_slot_map.at(name)); } return input_slots; } } absl::StatusOr<IoSlots> CollectIoSlots(QTypePtr qtype, const CompiledExpr& compiled_expr, absl::string_view final_output_name) { TypedSlotMap struct_slot_map = CollectInternalSlots(TypedSlot::UnsafeFromOffset(qtype, 0)); ASSIGN_OR_RETURN(TypedSlotMap input_slots, CollectInputSlots(qtype, struct_slot_map, compiled_expr)); RETURN_IF_ERROR(CheckField(qtype, struct_slot_map, compiled_expr.output_type(), final_output_name)); if (compiled_expr.input_types().contains(final_output_name)) { return absl::FailedPreconditionError(absl::StrCat( final_output_name, " present both as an input and as final output")); } if (compiled_expr.named_output_types().contains(final_output_name)) { return absl::FailedPreconditionError( absl::StrCat(final_output_name, " present both as final output and as named output")); } for (const auto& [name, field_qtype] : compiled_expr.input_types()) { if (compiled_expr.named_output_types().contains(name)) { return absl::FailedPreconditionError( absl::StrCat(name, " present both as an input and as named output")); } } for (const auto& [name, field_qtype] : compiled_expr.named_output_types()) { RETURN_IF_ERROR(CheckField(qtype, struct_slot_map, field_qtype, name)); } absl::flat_hash_map<std::string, TypedSlot> named_output_slots; named_output_slots.reserve(compiled_expr.named_output_types().size()); for (const auto& [name, _] : compiled_expr.named_output_types()) { named_output_slots.emplace(name, struct_slot_map.at(name)); } return IoSlots{.input_slots = input_slots, .output_slot = struct_slot_map.at(final_output_name), .named_output_slots = named_output_slots}; } }
#include "arolla/serving/inplace_expr_compiler.h" #include <array> #include <cstdint> #include <functional> #include <memory> #include <optional> #include <string> #include <tuple> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/container/flat_hash_map.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_node.h" #include "arolla/memory/frame.h" #include "arolla/memory/optional_value.h" #include "arolla/qexpr/eval_context.h" #include "arolla/qexpr/evaluation_engine.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/simple_qtype.h" #include "arolla/qtype/typed_slot.h" #include "arolla/serving/expr_compiler.h" #include "arolla/util/bytes.h" #include "arolla/util/fingerprint.h" #include "arolla/util/init_arolla.h" #include "arolla/util/struct_field.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/text.h" #include "arolla/util/status_macros_backport.h" namespace arolla { namespace { using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::testing::HasSubstr; using ::testing::MatchesRegex; struct UnsupportedType {}; struct TestOutputStruct { double x_plus_y; double x_times_y; UnsupportedType unsupported_type_field; double unused; static auto ArollaStructFields() { using CppType = TestOutputStruct; return std::tuple{ AROLLA_DECLARE_STRUCT_FIELD(x_plus_y), AROLLA_DECLARE_STRUCT_FIELD(x_times_y), AROLLA_SKIP_STRUCT_FIELD(unsupported_type_field), AROLLA_DECLARE_STRUCT_FIELD(unused), }; } void ArollaFingerprint(FingerprintHasher* hasher) const { CombineStructFields(hasher, *this); } }; struct TestStruct { float x; double y; void* unsupported_field; TestOutputStruct side_outputs; static auto ArollaStructFields() { using CppType = TestStruct; return std::tuple{ AROLLA_DECLARE_STRUCT_FIELD(x), AROLLA_DECLARE_STRUCT_FIELD(y), AROLLA_SKIP_STRUCT_FIELD(unsupported_field), AROLLA_DECLARE_STRUCT_FIELD(side_outputs), }; } void ArollaFingerprint(FingerprintHasher* hasher) const { CombineStructFields(hasher, *this); } }; struct TestStructWithOptional { OptionalValue<float> x; OptionalValue<double> y; std::array<int, 6> skip_me; OptionalValue<double> x_plus_y; constexpr static auto ArollaStructFields() { using CppType = TestStructWithOptional; return std::tuple{ AROLLA_DECLARE_STRUCT_FIELD(x), AROLLA_DECLARE_STRUCT_FIELD(y), AROLLA_SKIP_STRUCT_FIELD(skip_me), AROLLA_DECLARE_STRUCT_FIELD(x_plus_y), }; } void ArollaFingerprint(FingerprintHasher* hasher) const { CombineStructFields(hasher, *this); } }; struct TestStructWithString { std::string title; UnsupportedType it_is_not_supported; OptionalValue<::arolla::Bytes> name; UnsupportedType not_supported_sorry; std::string full_name; static auto ArollaStructFields() { using CppType = TestStructWithString; return std::tuple{ AROLLA_DECLARE_STRUCT_FIELD(title), AROLLA_SKIP_STRUCT_FIELD(it_is_not_supported), AROLLA_DECLARE_STRUCT_FIELD(name), AROLLA_SKIP_STRUCT_FIELD(not_supported_sorry), AROLLA_DECLARE_STRUCT_FIELD(full_name), }; } void ArollaFingerprint(FingerprintHasher* hasher) const { CombineStructFields(hasher, *this); } }; } AROLLA_DECLARE_SIMPLE_QTYPE(TEST_OUTPUT_STRUCT, TestOutputStruct); AROLLA_DEFINE_SIMPLE_QTYPE(TEST_OUTPUT_STRUCT, TestOutputStruct); AROLLA_DECLARE_SIMPLE_QTYPE(TEST_STRUCT, TestStruct); AROLLA_DEFINE_SIMPLE_QTYPE(TEST_STRUCT, TestStruct); AROLLA_DECLARE_SIMPLE_QTYPE(TEST_STRUCT_WITH_OPTIONAL, TestStructWithOptional); AROLLA_DEFINE_SIMPLE_QTYPE(TEST_STRUCT_WITH_OPTIONAL, TestStructWithOptional); AROLLA_DECLARE_SIMPLE_QTYPE(TEST_STRUCT_WITH_STRING, TestStructWithString); AROLLA_DEFINE_SIMPLE_QTYPE(TEST_STRUCT_WITH_STRING, TestStructWithString); namespace { class FailingCompiledExpr : public InplaceCompiledExpr { public: using InplaceCompiledExpr::InplaceCompiledExpr; absl::StatusOr<std::unique_ptr<BoundExpr>> InplaceBind( const absl::flat_hash_map<std::string, TypedSlot>& slots, TypedSlot output_slot, const absl::flat_hash_map<std::string, TypedSlot>& ) const final { return absl::InternalError("Fake:("); } }; TEST(CompileInplaceExprOnStruct, NoFieldNames) { FailingCompiledExpr compiled_expr({}, GetQType<double>(), {}); EXPECT_THAT( CompileInplaceExprOnStruct<int32_t>(compiled_expr, "/final_output"), StatusIs(absl::StatusCode::kFailedPrecondition, MatchesRegex(".*registered field.*INT32.*"))); } TEST(CompileInplaceExprOnStruct, NoFinalOutputName) { FailingCompiledExpr compiled_expr({}, GetQType<double>(), {}); EXPECT_THAT( CompileInplaceExprOnStruct<TestStruct>(compiled_expr, "/final_output"), StatusIs(absl::StatusCode::kFailedPrecondition, MatchesRegex(".*input.*/final_output.*TEST_STRUCT.*"))); } TEST(CompileInplaceExprOnStruct, InputTypeMismatch) { FailingCompiledExpr compiled_expr({}, GetQType<double>(), {}); EXPECT_THAT( CompileInplaceExprOnStruct<TestStruct>(compiled_expr, "/x"), StatusIs(absl::StatusCode::kFailedPrecondition, MatchesRegex( ".*/x.*TEST_STRUCT.*expected.*FLOAT32.*found.*FLOAT64"))); } TEST(CompileInplaceExprOnStruct, InputTypeUnknown) { FailingCompiledExpr compiled_expr({}, GetQType<double>(), {}); EXPECT_THAT(CompileInplaceExprOnStruct<TestStruct>(compiled_expr, "/qq"), StatusIs(absl::StatusCode::kFailedPrecondition, MatchesRegex(".*input.*/qq.*TEST_STRUCT.*"))); } TEST(CompileInplaceExprOnStruct, FinalOutputTypeMismatch) { FailingCompiledExpr compiled_expr({{"/x", GetQType<double>()}}, GetQType<double>(), {}); EXPECT_THAT( CompileInplaceExprOnStruct<TestStruct>(compiled_expr, "/side_outputs/x_plus_y"), StatusIs(absl::StatusCode::kFailedPrecondition, MatchesRegex( ".*/x.*TEST_STRUCT.*expected.*FLOAT32.*found.*FLOAT64"))); } TEST(CompileInplaceExprOnStruct, SideOutputTypeMismatch) { FailingCompiledExpr compiled_expr( {{"/x", GetQType<float>()}}, GetQType<double>(), {{"/side_outputs/x_times_y", GetQType<float>()}}); EXPECT_THAT( CompileInplaceExprOnStruct<TestStruct>(compiled_expr, "/side_outputs/x_plus_y"), StatusIs( absl::StatusCode::kFailedPrecondition, MatchesRegex( ".*/side_outputs/" "x_times_y.*TEST_STRUCT.*expected.*FLOAT64.*found.*FLOAT32"))); } TEST(CompileInplaceExprOnStruct, SideOutputUnknown) { FailingCompiledExpr compiled_expr( {{"/x", GetQType<float>()}}, GetQType<double>(), {{"/side_outputs/x_power_y", GetQType<double>()}}); EXPECT_THAT( CompileInplaceExprOnStruct<TestStruct>(compiled_expr, "/side_outputs/x_plus_y"), StatusIs( absl::StatusCode::kFailedPrecondition, MatchesRegex(".*/side_outputs/x_power_y.*not found.*TEST_STRUCT.*"))); } TEST(CompileInplaceExprOnStruct, CompiledExprBindingFailure) { FailingCompiledExpr compiled_expr({{"/x", GetQType<float>()}}, GetQType<double>(), {}); EXPECT_THAT(CompileInplaceExprOnStruct<TestStruct>(compiled_expr, "/side_outputs/x_plus_y"), StatusIs(absl::StatusCode::kInternal, "Fake:(")); } TEST(CompileInplaceExprOnStruct, InputSideOutputCollision) { FailingCompiledExpr compiled_expr({{"/y", GetQType<double>()}}, GetQType<double>(), {{"/y", GetQType<double>()}}); EXPECT_THAT(CompileInplaceExprOnStruct<TestStruct>(compiled_expr, "/side_outputs/x_plus_y"), StatusIs(absl::StatusCode::kFailedPrecondition, MatchesRegex(".*/y.*input.*named output.*"))); } TEST(CompileInplaceExprOnStruct, InputFinalOutputCollision) { FailingCompiledExpr compiled_expr( {{"/y", GetQType<double>()}}, GetQType<double>(), {{"/side_outputs/x_plus_y", GetQType<double>()}}); EXPECT_THAT(CompileInplaceExprOnStruct<TestStruct>(compiled_expr, "/y"), StatusIs(absl::StatusCode::kFailedPrecondition, MatchesRegex(".*/y.*input.*final output.*"))); } TEST(CompileInplaceExprOnStruct, SideOutputFinalOutputCollision) { FailingCompiledExpr compiled_expr( {{"/y", GetQType<double>()}}, GetQType<double>(), {{"/side_outputs/x_plus_y", GetQType<double>()}}); EXPECT_THAT( CompileInplaceExprOnStruct<TestStruct>(compiled_expr, "/side_outputs/x_plus_y"), StatusIs(absl::StatusCode::kFailedPrecondition, MatchesRegex( ".*/side_outputs/x_plus_y.*final output.*named output.*"))); } class TestBoundExpr final : public BoundExpr { public: TestBoundExpr(FrameLayout::Slot<float> x, FrameLayout::Slot<double> y, FrameLayout::Slot<double> x_plus_y, FrameLayout::Slot<double> x_times_y) : BoundExpr( {{"/x", TypedSlot::FromSlot(x)}, {"/y", TypedSlot::FromSlot(y)}}, TypedSlot::FromSlot(x_plus_y), {{"/side_outputs/x_times_y", TypedSlot::FromSlot(x_times_y)}}), x_(x), y_(y), x_plus_y_(x_plus_y), x_times_y_(x_times_y) {} void InitializeLiterals(EvaluationContext*, FramePtr) const final {} void Execute(EvaluationContext*, FramePtr frame) const final { frame.Set(x_plus_y_, frame.Get(x_) + frame.Get(y_)); frame.Set(x_times_y_, frame.Get(x_) * frame.Get(y_)); } private: FrameLayout::Slot<float> x_; FrameLayout::Slot<double> y_; FrameLayout::Slot<double> x_plus_y_; FrameLayout::Slot<double> x_times_y_; }; class TestCompiledExpr : public InplaceCompiledExpr { public: TestCompiledExpr() : InplaceCompiledExpr( {{"/x", GetQType<float>()}, {"/y", GetQType<double>()}}, GetQType<double>(), {{"/side_outputs/x_times_y", GetQType<double>()}}) {} absl::StatusOr<std::unique_ptr<BoundExpr>> InplaceBind( const absl::flat_hash_map<std::string, TypedSlot>& slots, TypedSlot output_slot, const absl::flat_hash_map<std::string, TypedSlot>& named_output_slots) const final { RETURN_IF_ERROR(VerifySlotTypes(input_types(), slots)); return std::make_unique<TestBoundExpr>( slots.at("/x").ToSlot<float>().value(), slots.at("/y").ToSlot<double>().value(), output_slot.ToSlot<double>().value(), named_output_slots.at("/side_outputs/x_times_y") .ToSlot<double>() .value()); } }; TEST(CompileInplaceExprOnStructTest, SuccessXPlusY) { TestCompiledExpr compiled_expr; ASSERT_OK_AND_ASSIGN(std::function<absl::Status(TestStruct&)> eval_fn, CompileInplaceExprOnStruct<TestStruct>( compiled_expr, "/side_outputs/x_plus_y")); TestStruct input{ .x = 5.f, .y = 7., .side_outputs = {.x_plus_y = -1, .x_times_y = -1, .unused = -1}}; ASSERT_OK(eval_fn(input)); EXPECT_EQ(input.side_outputs.x_plus_y, 12); EXPECT_EQ(input.side_outputs.x_times_y, 35.); EXPECT_EQ(input.x, 5); EXPECT_EQ(input.y, 7); EXPECT_EQ(input.side_outputs.unused, -1.); } class TestBoundExprWithOptionals final : public BoundExpr { public: TestBoundExprWithOptionals(FrameLayout::Slot<OptionalValue<float>> x, FrameLayout::Slot<OptionalValue<double>> y, FrameLayout::Slot<OptionalValue<double>> x_plus_y) : BoundExpr( {{"/x", TypedSlot::FromSlot(x)}, {"/y", TypedSlot::FromSlot(y)}}, TypedSlot::FromSlot(x_plus_y), {}), x_(x), y_(y), x_plus_y_(x_plus_y) {} void InitializeLiterals(EvaluationContext*, FramePtr) const final {} void Execute(EvaluationContext*, FramePtr frame) const final { if (frame.Get(x_).present && frame.Get(y_).present) { frame.Set(x_plus_y_, frame.Get(x_).value + frame.Get(y_).value); } else { frame.Set(x_plus_y_, std::nullopt); } } private: FrameLayout::Slot<OptionalValue<float>> x_; FrameLayout::Slot<OptionalValue<double>> y_; FrameLayout::Slot<OptionalValue<double>> x_plus_y_; }; class TestCompiledExprWithOptionals : public InplaceCompiledExpr { public: TestCompiledExprWithOptionals() : InplaceCompiledExpr({{"/x", GetQType<OptionalValue<float>>()}, {"/y", GetQType<OptionalValue<double>>()}}, GetQType<OptionalValue<double>>(), {}) {} absl::StatusOr<std::unique_ptr<BoundExpr>> InplaceBind( const absl::flat_hash_map<std::string, TypedSlot>& slots, TypedSlot output_slot, const absl::flat_hash_map<std::string, TypedSlot>& ) const final { RETURN_IF_ERROR(VerifySlotTypes(input_types(), slots)); return std::make_unique<TestBoundExprWithOptionals>( slots.at("/x").ToSlot<OptionalValue<float>>().value(), slots.at("/y").ToSlot<OptionalValue<double>>().value(), output_slot.ToSlot<OptionalValue<double>>().value()); } }; TEST(CompileInplaceExprOnStructTest, SuccessXPlusYWithOptionals) { TestCompiledExprWithOptionals compiled_expr; ASSERT_OK_AND_ASSIGN( std::function<absl::Status(TestStructWithOptional&)> eval_fn, CompileInplaceExprOnStruct<TestStructWithOptional>(compiled_expr, "/x_plus_y")); TestStructWithOptional input{.x = 5.f, .y = 7., .x_plus_y = -1}; ASSERT_OK(eval_fn(input)); EXPECT_EQ(input.x_plus_y, 12.); EXPECT_EQ(input.x, 5.f); EXPECT_EQ(input.y, 7.); } class TestBoundExprWithStrings final : public BoundExpr { public: TestBoundExprWithStrings(FrameLayout::Slot<arolla::Bytes> title, FrameLayout::Slot<OptionalValue<arolla::Bytes>> name, FrameLayout::Slot<arolla::Bytes> output) : BoundExpr({{"/title", TypedSlot::FromSlot(title)}, {"/name", TypedSlot::FromSlot(name)}}, TypedSlot::FromSlot(output), {}), title_(title), name_(name), output_(output) {} void InitializeLiterals(EvaluationContext*, FramePtr) const final {} void Execute(EvaluationContext*, FramePtr frame) const final { if (!frame.Get(name_).present) { frame.Set(output_, "UNKNOWN"); return; } frame.Set(output_, absl::StrCat(frame.Get(title_), " ", frame.Get(name_).value)); } private: FrameLayout::Slot<arolla::Bytes> title_; FrameLayout::Slot<OptionalValue<arolla::Bytes>> name_; FrameLayout::Slot<arolla::Bytes> output_; }; class TestCompiledExprWithStrings : public InplaceCompiledExpr { public: TestCompiledExprWithStrings() : InplaceCompiledExpr( {{"/title", GetQType<arolla::Bytes>()}, {"/name", GetQType<OptionalValue<arolla::Bytes>>()}}, GetQType<arolla::Bytes>(), {}) {} absl::StatusOr<std::unique_ptr<BoundExpr>> InplaceBind( const absl::flat_hash_map<std::string, TypedSlot>& slots, TypedSlot output_slot, const absl::flat_hash_map<std::string, TypedSlot>& ) const final { RETURN_IF_ERROR(VerifySlotTypes(input_types(), slots)); return std::make_unique<TestBoundExprWithStrings>( slots.at("/title").ToSlot<arolla::Bytes>().value(), slots.at("/name").ToSlot<OptionalValue<arolla::Bytes>>().value(), output_slot.ToSlot<arolla::Bytes>().value()); } }; TEST(CompileInplaceExprOnStructTest, SuccessStringsIO) { TestCompiledExprWithStrings compiled_expr; ASSERT_OK_AND_ASSIGN( std::function<absl::Status(TestStructWithString&)> eval_fn, CompileInplaceExprOnStruct<TestStructWithString>(compiled_expr, "/full_name")); TestStructWithString input{ .title = "Mr.", .name = arolla::Bytes("Abc"), .full_name = "????"}; ASSERT_OK(eval_fn(input)); EXPECT_EQ(input.full_name, "Mr. Abc"); input.name = std::nullopt; ASSERT_OK(eval_fn(input)); EXPECT_EQ(input.full_name, "UNKNOWN"); } TEST(CompileDynamicExprOnStructInputTest, TypeError) { ASSERT_OK(InitArolla()); ASSERT_OK_AND_ASSIGN( expr::ExprNodePtr expr, expr::CallOp("annotation.qtype", {expr::Leaf("/x"), expr::Literal(GetQType<int>())})); EXPECT_THAT((ExprCompiler<TestStruct, std::optional<double>>()) .SetInputLoader(CreateStructInputLoader<TestStruct>()) .Compile(expr) .status(), StatusIs(absl::StatusCode::kFailedPrecondition, MatchesRegex(".*inconsistent.*qtype.*INT32.*"))); } TEST(CompileDynamicExprOnStructInputTest, UnknownLeaf) { ASSERT_OK(InitArolla()); expr::ExprNodePtr expr = expr::Leaf("/unknown"); EXPECT_THAT((ExprCompiler<TestStruct, std::optional<double>>()) .SetInputLoader(CreateStructInputLoader<TestStruct>()) .Compile(expr) .status(), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("unknown inputs: /unknown"))); } TEST(CompileDynamicExprOnStructInputTest, TypeErrorOnCodegenModel) { ASSERT_OK(InitArolla()); TestCompiledExprWithOptionals compiled_expr; EXPECT_THAT((ExprCompiler<TestStruct, std::optional<double>>()) .SetInputLoader(CreateStructInputLoader<TestStruct>()) .Compile(compiled_expr) .status(), StatusIs(absl::StatusCode::kFailedPrecondition, MatchesRegex(".*slot types mismatch.*"))); } TEST(CompileDynamicExprOnStructInputTest, Nested) { ASSERT_OK(InitArolla()); ASSERT_OK_AND_ASSIGN( expr::ExprNodePtr expr, expr::CallOp("math.add", {expr::Leaf("/x"), expr::Leaf("/side_outputs/x_plus_y")})); ASSERT_OK_AND_ASSIGN( std::function<absl::StatusOr<double>(const TestStruct&)> eval_fn, (ExprCompiler<TestStruct, double>()) .SetInputLoader(CreateStructInputLoader<TestStruct>()) .Compile(expr)); TestStruct input{ .x = 5.f, .y = -1., .side_outputs = {.x_plus_y = 7., .x_times_y = -1, .unused = -1}}; EXPECT_THAT(eval_fn(input), IsOkAndHolds(12.)); } TEST(CompileDynamicExprOnStructInputTest, SuccessXPlusYWithOptionals) { ASSERT_OK(InitArolla()); ASSERT_OK_AND_ASSIGN( expr::ExprNodePtr expr, expr::CallOp("math.add", {expr::Leaf("/x"), expr::Leaf("/y")})); ASSERT_OK_AND_ASSIGN( std::function<absl::StatusOr<std::optional<double>>( const TestStructWithOptional&)> eval_fn, (ExprCompiler<TestStructWithOptional, std::optional<double>>()) .SetInputLoader(CreateStructInputLoader<TestStructWithOptional>()) .Compile(expr)); TestStructWithOptional input{.x = 5.f, .y = 7., .x_plus_y = -1}; EXPECT_THAT(eval_fn(input), IsOkAndHolds(12.)); input.x = std::nullopt; EXPECT_THAT(eval_fn(input), IsOkAndHolds(std::nullopt)); } TEST(CompileDynamicExprOnStructInputTest, ErrorStatus) { ASSERT_OK(InitArolla()); absl::StatusOr<expr::ExprNodePtr> status_or_expr = absl::InternalError("input error"); auto result = ExprCompiler<TestStructWithOptional, std::optional<double>>() .SetInputLoader(CreateStructInputLoader<TestStructWithOptional>()) .Compile(status_or_expr); EXPECT_THAT(result, StatusIs(absl::StatusCode::kInternal, MatchesRegex("input error"))); } TEST(CompileDynamicExprOnStructInputTest, SuccessXPlusYOnCodegenModel) { ASSERT_OK(InitArolla()); TestCompiledExpr compiled_expr; ASSERT_OK_AND_ASSIGN( std::function<absl::StatusOr<double>(const TestStruct&)> eval_fn, (ExprCompiler<TestStruct, double>()) .SetInputLoader(CreateStructInputLoader<TestStruct>()) .Compile(compiled_expr)); TestStruct input{.x = 5.f, .y = 7.}; EXPECT_THAT(eval_fn(input), IsOkAndHolds(12.)); } TEST(CompileDynamicExprOnStructInputTest, SuccessSideOutputOnCodegenModel) { ASSERT_OK(InitArolla()); TestCompiledExpr compiled_expr; ASSERT_OK_AND_ASSIGN( std::function<absl::StatusOr<double>(const TestStruct&, TestStruct*)> eval_fn, (ExprCompiler<TestStruct, double, TestStruct>()) .SetInputLoader(CreateStructInputLoader<TestStruct>()) .SetSlotListener(CreateStructSlotListener<TestStruct>()) .Compile(compiled_expr)); TestStruct input{.x = 5.f, .y = 7.}; EXPECT_THAT(eval_fn(input, nullptr), IsOkAndHolds(12.)); EXPECT_THAT(eval_fn(input, &input), IsOkAndHolds(12.)); EXPECT_EQ(input.side_outputs.x_times_y, 35); } TEST(CompileDynamicExprOnStructWithBytesInputTest, SuccessUpper) { ASSERT_OK(InitArolla()); ASSERT_OK_AND_ASSIGN(expr::ExprNodePtr title, expr::CallOp("strings.decode", {expr::Leaf("/title")})); ASSERT_OK_AND_ASSIGN( expr::ExprNodePtr name, expr::CallOp("strings.upper", {expr::CallOp("strings.decode", {expr::Leaf("/name")})})); ASSERT_OK_AND_ASSIGN( expr::ExprNodePtr expr, expr::CallOp("strings.join", {title, expr::Literal(Text(" ")), name})); ASSERT_OK_AND_ASSIGN(expr, expr::CallOp("core.get_optional_value", {expr::CallOp("strings.encode", {expr})})); ASSERT_OK_AND_ASSIGN( std::function<absl::StatusOr<arolla::Bytes>(const TestStructWithString&)> eval_fn, (ExprCompiler<TestStructWithString, arolla::Bytes>()) .SetInputLoader(CreateStructInputLoader<TestStructWithString>()) .Compile(expr)); TestStructWithString input{.title = "Mr.", .name = Bytes("abc")}; EXPECT_THAT(eval_fn(input), IsOkAndHolds(Bytes("Mr. ABC"))); input.name = std::nullopt; EXPECT_THAT(eval_fn(input), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("expects present value"))); } } }
2,363
#ifndef AROLLA_SERVING_EXPR_COMPILER_H_ #define AROLLA_SERVING_EXPR_COMPILER_H_ #include <cstddef> #include <cstdint> #include <functional> #include <memory> #include <optional> #include <string> #include <tuple> #include <type_traits> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/types/span.h" #include "arolla/expr/eval/model_executor.h" #include "arolla/expr/eval/thread_safe_model_executor.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/optimization/optimizer.h" #include "arolla/io/input_loader.h" #include "arolla/io/slot_listener.h" #include "arolla/io/tuple_input_loader.h" #include "arolla/io/typed_refs_input_loader.h" #include "arolla/qexpr/evaluation_engine.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_ref.h" #include "arolla/util/indestructible.h" #include "arolla/util/status_macros_backport.h" namespace arolla { using ModelFunctionOptions = ::arolla::expr::ModelEvaluationOptions; struct ExprCompilerFlags { static constexpr int kDefault = 0; static constexpr int kEvalWithOptions = 1; }; namespace serving_impl { template <typename Input, typename Output, typename SideOutput> struct ToModelFunction { using without_options = std::function<absl::StatusOr<Output>(const Input&, SideOutput*)>; using with_options = std::function<absl::StatusOr<Output>( const ModelFunctionOptions&, const Input&, SideOutput*)>; }; template <typename Input, typename Output> struct ToModelFunction<Input, Output, void> { using without_options = std::function<absl::StatusOr<Output>(const Input&)>; using with_options = std::function<absl::StatusOr<Output>( const ModelFunctionOptions&, const Input&)>; }; class ExprCompilerDefaultOptimizer { public: static const std::optional<expr::Optimizer>& get() { return *optimizer_; } private: friend class ExprCompilerDefaultOptimizerInitializer; static Indestructible<std::optional<expr::Optimizer>> optimizer_; }; } template <typename Subclass, typename Input, typename Output, typename SideOutput> class ExprCompilerBase { using ModelExecutor = expr::ModelExecutor<Input, Output, SideOutput>; using ThreadSafePoolModelExecutor = expr::ThreadSafePoolModelExecutor<Input, Output, SideOutput>; using CopyableThreadUnsafeModelExecutor = expr::CopyableThreadUnsafeModelExecutor<Input, Output, SideOutput>; using ToFunctionHelper = serving_impl::ToModelFunction<Input, Output, SideOutput>; protected: template <int Flags> using Func = std::conditional_t<Flags & ExprCompilerFlags::kEvalWithOptions, typename ToFunctionHelper::with_options, typename ToFunctionHelper::without_options>; public: using Function = Func<ExprCompilerFlags::kDefault>; using FunctionWithOptions = Func<ExprCompilerFlags::kEvalWithOptions>; using input_type = Input; using output_type = Output; using side_output_type = SideOutput; ExprCompilerBase(ExprCompilerBase&&) = default; ExprCompilerBase& operator=(ExprCompilerBase&&) = default; ExprCompilerBase(const ExprCompilerBase&) = delete; ExprCompilerBase& operator=(const ExprCompilerBase&) = delete; ExprCompilerBase() { const std::optional<expr::Optimizer>& opt = serving_impl::ExprCompilerDefaultOptimizer::get(); if (opt.has_value()) { SetExprOptimizer(*opt); } } Subclass& SetInputLoader( absl::StatusOr<InputLoaderPtr<Input>> input_loader_or) & { ASSIGN_OR_RETURN(input_loader_, std::move(input_loader_or), RegisterError(_ << "in ExprCompiler::SetInputLoader")); return subclass(); } Subclass&& SetInputLoader( absl::StatusOr<InputLoaderPtr<Input>> input_loader_or) && { return std::move(SetInputLoader(std::move(input_loader_or))); } Subclass& SetSlotListener( absl::StatusOr<std::unique_ptr<const SlotListener<SideOutput>>> slot_listener_or) & { ASSIGN_OR_RETURN(slot_listener_, std::move(slot_listener_or), RegisterError(_ << "in ExprCompiler::SlotListener")); return subclass(); } Subclass&& SetSlotListener( absl::StatusOr<std::unique_ptr<const SlotListener<SideOutput>>> slot_listener_or) && { return std::move(SetSlotListener(std::move(slot_listener_or))); } Subclass& SetAlwaysCloneThreadSafetyPolicy() & { thread_safety_policy_ = ThreadSafetyPolicy::kAlwaysClone; return subclass(); } Subclass&& SetAlwaysCloneThreadSafetyPolicy() && { return std::move(SetAlwaysCloneThreadSafetyPolicy()); } Subclass& SetPoolThreadSafetyPolicy() & { thread_safety_policy_ = ThreadSafetyPolicy::kPool; return subclass(); } Subclass&& SetPoolThreadSafetyPolicy() && { return std::move(SetPoolThreadSafetyPolicy()); } Subclass& SetThreadUnsafe_I_SWEAR_TO_COPY_MODEL_FUNCTION_BEFORE_CALL() & { thread_safety_policy_ = ThreadSafetyPolicy::kUnsafe; return subclass(); } Subclass&& SetThreadUnsafe_I_SWEAR_TO_COPY_MODEL_FUNCTION_BEFORE_CALL() && { return std::move( SetThreadUnsafe_I_SWEAR_TO_COPY_MODEL_FUNCTION_BEFORE_CALL()); } Subclass& SetExperimentalArenaAllocator(int64_t page_size_bytes = (64 << 10)) & { model_executor_options_.arena_page_size = page_size_bytes; return subclass(); } Subclass&& SetExperimentalArenaAllocator( int64_t page_size_bytes = (64 << 10)) && { return std::move(SetExperimentalArenaAllocator(page_size_bytes)); } Subclass& SetExprOptimizer(absl::StatusOr<expr::Optimizer> optimizer_or) & { ASSIGN_OR_RETURN(auto optimizer, std::move(optimizer_or), RegisterError(_ << "in ExprCompiler::SetExprOptimizer")); model_executor_options_.eval_options.optimizer = std::move(optimizer); return subclass(); } Subclass&& SetExprOptimizer(absl::StatusOr<expr::Optimizer> optimizer_or) && { return std::move(SetExprOptimizer(std::move(optimizer_or))); } Subclass& ForceNonOptionalOutput() & { model_executor_options_.force_non_optional_output = true; return subclass(); } Subclass&& ForceNonOptionalOutput() && { return std::move(ForceNonOptionalOutput()); } Subclass& AllowOutputCasting() & { model_executor_options_.allow_output_casting = true; return subclass(); } Subclass&& AllowOutputCasting() && { return std::move(AllowOutputCasting()); } Subclass& AllowSideOutputsCasting() & { model_executor_options_.allow_side_outputs_casting = true; return subclass(); } Subclass&& AllowSideOutputsCasting() && { return std::move(AllowSideOutputsCasting()); } Subclass& IgnoreNotListenedNamedOutputs() & { model_executor_options_.ignore_not_listened_named_outputs = true; return subclass(); } Subclass&& IgnoreNotListenedNamedOutputs() && { return std::move(IgnoreNotListenedNamedOutputs()); } template <int Flags = ExprCompilerFlags::kDefault> absl::StatusOr<Func<Flags>> Compile(const CompiledExpr& compiled_expr) const { RETURN_IF_ERROR(Validate()); ASSIGN_OR_RETURN( auto model_executor, ModelExecutor::Bind(compiled_expr, *input_loader_, nullptr, slot_listener_.get(), model_executor_options_)); ThreadSafetyPolicy thread_safety_policy = thread_safety_policy_; if (thread_safety_policy == ThreadSafetyPolicy::kUnspecified && dynamic_cast<const InplaceCompiledExpr*>(&compiled_expr) != nullptr) { thread_safety_policy = ThreadSafetyPolicy::kAlwaysClone; } return MakeFunction<Flags>(std::move(model_executor), thread_safety_policy); } template <int Flags = ExprCompilerFlags::kDefault> absl::StatusOr<Func<Flags>> Compile(const expr::ExprNodePtr& expr) const { RETURN_IF_ERROR(Validate()); ASSIGN_OR_RETURN( auto model_executor, ModelExecutor::Compile(expr, *input_loader_, slot_listener_.get(), model_executor_options_)); return MakeFunction<Flags>(std::move(model_executor), thread_safety_policy_); } template <int Flags = ExprCompilerFlags::kDefault> absl::StatusOr<Func<Flags>> Compile( const absl::StatusOr<expr::ExprNodePtr>& expr) const { RETURN_IF_ERROR(expr.status()); return Compile<Flags>(*expr); } template <int Flags = ExprCompilerFlags::kDefault> absl::StatusOr<Func<Flags>> CompileOperator( absl::StatusOr<expr::ExprOperatorPtr> op) const { RETURN_IF_ERROR(ValidateCompileOperator()); constexpr size_t arg_count = std::tuple_size_v<Input>; std::vector<std::string> arg_names(arg_count); std::vector<absl::StatusOr<expr::ExprNodePtr>> args(arg_count); for (size_t i = 0; i < arg_count; ++i) { arg_names[i] = absl::StrCat("a", i); args[i] = expr::Leaf(arg_names[i]); } ASSIGN_OR_RETURN(expr::ExprNodePtr expr, expr::CallOp(std::move(op), std::move(args))); ASSIGN_OR_RETURN(InputLoaderPtr<Input> input_loader, TupleInputLoader<Input>::Create(std::move(arg_names))); ASSIGN_OR_RETURN( auto model_executor, ModelExecutor::Compile(expr, *input_loader, slot_listener_.get(), model_executor_options_)); return MakeFunction<Flags>(std::move(model_executor), thread_safety_policy_); } template <int Flags = ExprCompilerFlags::kDefault> absl::StatusOr<Func<Flags>> CompileOperator( absl::StatusOr<expr::ExprOperatorPtr> op, absl::Span<const QTypePtr> input_types) const { static_assert(std::is_same_v<Input, absl::Span<const TypedRef>>, "CompilerOperator(op, types) requires Input to be " "absl::Span<const TypedRef>"); RETURN_IF_ERROR(ValidateCompileOperator()); std::vector<std::pair<std::string, QTypePtr>> args(input_types.size()); std::vector<absl::StatusOr<expr::ExprNodePtr>> arg_exprs(args.size()); for (size_t i = 0; i < input_types.size(); ++i) { args[i] = {absl::StrCat("a", i), input_types[i]}; arg_exprs[i] = expr::Leaf(args[i].first); } ASSIGN_OR_RETURN(expr::ExprNodePtr expr, expr::CallOp(std::move(op), std::move(arg_exprs))); InputLoaderPtr<Input> input_loader = CreateTypedRefsInputLoader(args); ASSIGN_OR_RETURN( auto model_executor, ModelExecutor::Compile(expr, *input_loader, slot_listener_.get(), model_executor_options_)); return MakeFunction<Flags>(std::move(model_executor), thread_safety_policy_); } protected: Subclass& RegisterError(absl::Status error) { if (first_error_.ok()) { first_error_ = std::move(error); } return subclass(); } private: enum class ThreadSafetyPolicy { kUnspecified, kAlwaysClone, kPool, kUnsafe }; static constexpr size_t kMaxStackSize = 1024; Subclass& subclass() { return *static_cast<Subclass*>(this); } template <size_t kStackSize, int Flags> static Func<Flags> MakeStackBasedFunction( std::shared_ptr<ModelExecutor> executor) { if constexpr (Flags & ExprCompilerFlags::kEvalWithOptions) { if constexpr (std::is_same_v<SideOutput, void>) { return [executor(std::move(executor))]( const ModelFunctionOptions& options, const Input& input) -> absl::StatusOr<Output> { return executor->template ExecuteOnStack<kStackSize>(options, input, nullptr); }; } else { return [executor(std::move(executor))]( const ModelFunctionOptions& options, const Input& input, SideOutput* side_output) -> absl::StatusOr<Output> { return executor->template ExecuteOnStack<kStackSize>(options, input, side_output); }; } } else { if constexpr (std::is_same_v<SideOutput, void>) { return [executor(std::move(executor))]( const Input& input) -> absl::StatusOr<Output> { return executor->template ExecuteOnStack<kStackSize>({}, input, nullptr); }; } else { return [executor(std::move(executor))]( const Input& input, SideOutput* side_output) -> absl::StatusOr<Output> { return executor->template ExecuteOnStack<kStackSize>({}, input, side_output); }; } } } template <int Flags> static Func<Flags> MakeAlwaysCloneFunction(ModelExecutor&& executor) { auto shared_executor = std::make_shared<ModelExecutor>(std::move(executor)); if (shared_executor->CanExecuteOnStack(kMaxStackSize)) { return MakeStackBasedFunction<kMaxStackSize, Flags>( std::move(shared_executor)); } if constexpr (Flags & ExprCompilerFlags::kEvalWithOptions) { if constexpr (std::is_same_v<SideOutput, void>) { return [executor(std::move(shared_executor))]( const ModelFunctionOptions& options, const Input& input) -> absl::StatusOr<Output> { return executor->ExecuteOnHeap(options, input, nullptr); }; } else { return [executor(std::move(shared_executor))]( const ModelFunctionOptions& options, const Input& input, SideOutput* side_output) -> absl::StatusOr<Output> { return executor->ExecuteOnHeap(options, input, side_output); }; } } else { if constexpr (std::is_same_v<SideOutput, void>) { return [executor(std::move(shared_executor))]( const Input& input) -> absl::StatusOr<Output> { return executor->ExecuteOnHeap({}, input, nullptr); }; } else { return [executor(std::move(shared_executor))]( const Input& input, SideOutput* side_output) -> absl::StatusOr<Output> { return executor->ExecuteOnHeap({}, input, side_output); }; } } } template <bool EvalWithOptions> static absl::StatusOr<Func<EvalWithOptions>> MakeFunction( ModelExecutor&& executor, ThreadSafetyPolicy thread_safety_policy) { switch (thread_safety_policy) { case ThreadSafetyPolicy::kAlwaysClone: return MakeAlwaysCloneFunction<EvalWithOptions>(std::move(executor)); case ThreadSafetyPolicy::kUnspecified: case ThreadSafetyPolicy::kPool: return Func<EvalWithOptions>( ThreadSafePoolModelExecutor(std::move(executor))); case ThreadSafetyPolicy::kUnsafe: return Func<EvalWithOptions>( CopyableThreadUnsafeModelExecutor(std::move(executor))); } return absl::InternalError( absl::StrCat("Unsupported ThreadSafetyPolicy: ", thread_safety_policy)); } absl::Status Validate() const { RETURN_IF_ERROR(first_error_); if (input_loader_ == nullptr) { return absl::FailedPreconditionError( "InputLoader is not specified, use ExprCompiler::SetInputLoader()"); } if (!std::is_same_v<SideOutput, void> && slot_listener_ == nullptr) { return absl::FailedPreconditionError( "SlotListener is not specified, use ExprCompiler::SetSlotListener() " "or ExprCompiler<...> without SideOutput template parameter"); } if (std::is_same_v<SideOutput, void> && slot_listener_ != nullptr) { return absl::FailedPreconditionError( "SlotListener with SideOutput==void is not supported by " "ExprCompiler"); } return absl::OkStatus(); } absl::Status ValidateCompileOperator() const { RETURN_IF_ERROR(first_error_); static_assert(std::is_same_v<SideOutput, void>, "SideOutput can not be used together with " "ExprCompiler::CompilerOperator"); if (input_loader_ != nullptr) { return absl::FailedPreconditionError( "InputLoader is specified, but not needed for " "ExprCompiler::CompilerOperator"); } return absl::OkStatus(); } absl::Status first_error_; InputLoaderPtr<Input> input_loader_ = nullptr; std::unique_ptr<const SlotListener<SideOutput>> slot_listener_ = nullptr; ThreadSafetyPolicy thread_safety_policy_ = ThreadSafetyPolicy::kUnspecified; expr::ModelExecutorOptions model_executor_options_; }; template <typename Input, typename Output, typename SideOutput = void> class ExprCompiler final : public ExprCompilerBase<ExprCompiler<Input, Output, SideOutput>, Input, Output, SideOutput> {}; template <typename Compiler, typename Model> absl::StatusOr<absl::flat_hash_map<std::string, typename Compiler::Function>> CompileExprSet(const Compiler& compiler, absl::flat_hash_map<std::string, Model> model_set) { using Function = typename Compiler::Function; absl::flat_hash_map<std::string, Function> compiled_models; compiled_models.reserve(model_set.size()); for (const auto& [name, model] : model_set) { ASSIGN_OR_RETURN(compiled_models[name], compiler.Compile(model), _ << "while initializing model \"" << name << "\""); } return compiled_models; } } #endif #include "arolla/serving/expr_compiler.h" #include <optional> #include "arolla/expr/optimization/optimizer.h" #include "arolla/util/indestructible.h" namespace arolla::serving_impl { Indestructible<std::optional<expr::Optimizer>> ExprCompilerDefaultOptimizer::optimizer_; }
#include "arolla/serving/expr_compiler.h" #include <functional> #include <memory> #include <optional> #include <string> #include <tuple> #include <type_traits> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/container/flat_hash_map.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/types/span.h" #include "arolla/expr/eval/eval.h" #include "arolla/expr/eval/thread_safe_model_executor.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/registered_expr_operator.h" #include "arolla/expr/testing/testing.h" #include "arolla/io/accessors_input_loader.h" #include "arolla/io/accessors_slot_listener.h" #include "arolla/io/input_loader.h" #include "arolla/io/slot_listener.h" #include "arolla/io/tuple_input_loader.h" #include "arolla/memory/optional_value.h" #include "arolla/qexpr/evaluation_engine.h" #include "arolla/qexpr/operators.h" #include "arolla/qexpr/simple_executable.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_ref.h" #include "arolla/qtype/typed_slot.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/status_macros_backport.h" namespace { using ::arolla::CompiledExpr; using ::arolla::GetQType; using ::arolla::InputLoaderPtr; using ::arolla::SlotListener; using ::arolla::expr::CallOp; using ::arolla::expr::ExprNodePtr; using ::arolla::expr::Leaf; using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::arolla::testing::WithExportValueAnnotation; using ::testing::_; using ::testing::Eq; using ::testing::HasSubstr; using ::testing::IsNull; using ::testing::NotNull; using ::testing::Pair; using ::testing::UnorderedElementsAre; struct TestInput { float x; float y; }; struct TestSideOutput { std::optional<float> subtract; }; absl::StatusOr<std::unique_ptr<arolla::InputLoader<TestInput>>> CreateInputLoader() { return ::arolla::CreateAccessorsInputLoader<TestInput>( "x", [](const auto& x) { return x.x; }, "y", [](const auto& x) { return x.y; }); } absl::StatusOr<std::unique_ptr<SlotListener<TestSideOutput>>> CreateSlotListener() { return ::arolla::CreateAccessorsSlotListener<TestSideOutput>( "subtract", [](float x, TestSideOutput* out) { out->subtract = x; }); } absl::StatusOr<ExprNodePtr> CreateExpr() { ASSIGN_OR_RETURN(auto add_expr, CallOp("math.add", {Leaf("x"), Leaf("y")})); ASSIGN_OR_RETURN(auto subtract_expr, CallOp("math.subtract", {Leaf("x"), Leaf("y")})); return WithExportValueAnnotation(add_expr, "subtract", subtract_expr); } absl::StatusOr<std::unique_ptr<CompiledExpr>> CreateCompiledExpr() { ASSIGN_OR_RETURN(auto add_expr, CallOp("math.add", {Leaf("x"), Leaf("y")})); ASSIGN_OR_RETURN(auto subtract_expr, CallOp("math.subtract", {Leaf("x"), Leaf("y")})); return ::arolla::expr::CompileForDynamicEvaluation( ::arolla::expr::DynamicEvaluationEngineOptions(), add_expr, {{"x", GetQType<float>()}, {"y", GetQType<float>()}}, {{"subtract", subtract_expr}}); } } namespace arolla { namespace { class TestInplaceCompiledExpr : public InplaceCompiledExpr { public: TestInplaceCompiledExpr() : InplaceCompiledExpr( {}, GetQType<float>(), {}) {} absl::StatusOr<std::unique_ptr<BoundExpr>> InplaceBind( const absl::flat_hash_map<std::string, TypedSlot>& input_slots, TypedSlot output_slot, const absl::flat_hash_map<std::string, TypedSlot>& named_output_slots) const final { return std::make_unique<SimpleBoundExpr>( input_slots, output_slot, std::vector<std::unique_ptr<BoundOperator>>{}, std::vector<std::unique_ptr<BoundOperator>>{}, named_output_slots); } }; class ExprCompilerTest : public ::testing::Test { public: void SetUp() override { ASSERT_OK(InitArolla()); ASSERT_OK_AND_ASSIGN(auto add_expr, expr::CallOp("math.add", {Leaf("x"), Leaf("y")})); ASSERT_OK_AND_ASSIGN(auto subtract_expr, expr::CallOp("math.subtract", {Leaf("x"), Leaf("y")})); ASSERT_OK_AND_ASSIGN(expr_, CreateExpr()); ASSERT_OK_AND_ASSIGN(compiled_expr_, CreateCompiledExpr()); } expr::ExprNodePtr expr_; std::unique_ptr<const CompiledExpr> compiled_expr_; }; TEST_F(ExprCompilerTest, CompileExprNodePtr) { ASSERT_OK_AND_ASSIGN(auto model, (ExprCompiler<TestInput, std::optional<float>>()) .SetInputLoader(CreateInputLoader()) .AllowOutputCasting() .Compile(expr_)); ASSERT_OK_AND_ASSIGN( auto model_with_options, (ExprCompiler<TestInput, std::optional<float>>()) .SetInputLoader(CreateInputLoader()) .AllowOutputCasting() .Compile<ExprCompilerFlags::kEvalWithOptions>(expr_)); static_assert( std::is_same_v<decltype(model), std::function<absl::StatusOr<std::optional<float>>( const TestInput&)>>); static_assert( std::is_same_v<decltype(model_with_options), std::function<absl::StatusOr<std::optional<float>>( const ModelFunctionOptions&, const TestInput&)>>); TestInput input{.x = 28, .y = 29}; EXPECT_THAT(model(input), IsOkAndHolds(57)); EXPECT_THAT(model_with_options({}, input), IsOkAndHolds(57)); } TEST_F(ExprCompilerTest, CompileExprNodePtrWithSideOutput) { ASSERT_OK_AND_ASSIGN( auto model, (ExprCompiler<TestInput, std::optional<float>, TestSideOutput>()) .SetInputLoader(CreateInputLoader()) .SetSlotListener(CreateSlotListener()) .AllowOutputCasting() .Compile(expr_)); static_assert( std::is_same_v<decltype(model), std::function<absl::StatusOr<std::optional<float>>( const TestInput&, TestSideOutput*)>>); TestInput input{.x = 28, .y = 29}; EXPECT_THAT(model(input, nullptr), IsOkAndHolds(57)); TestSideOutput side_output; EXPECT_THAT(model(input, &side_output), IsOkAndHolds(57)); EXPECT_THAT(side_output.subtract, Eq(-1)); } TEST_F(ExprCompilerTest, CompileCompiledExpr) { ASSERT_OK_AND_ASSIGN(auto model, (ExprCompiler<TestInput, std::optional<float>>()) .SetInputLoader(CreateInputLoader()) .AllowOutputCasting() .Compile(*compiled_expr_)); static_assert( std::is_same_v<decltype(model), std::function<absl::StatusOr<std::optional<float>>( const TestInput&)>>); TestInput input{.x = 28, .y = 29}; EXPECT_THAT(model(input), IsOkAndHolds(57)); } TEST_F(ExprCompilerTest, CompileCompiledExprForceNonOptionalOutput) { ASSERT_OK_AND_ASSIGN(auto model, (ExprCompiler<TestInput, float>()) .SetInputLoader(CreateInputLoader()) .ForceNonOptionalOutput() .Compile(*compiled_expr_)); static_assert( std::is_same_v<decltype(model), std::function<absl::StatusOr<float>(const TestInput&)>>); TestInput input{.x = 28, .y = 29}; EXPECT_THAT(model(input), IsOkAndHolds(57)); } TEST_F(ExprCompilerTest, CompileCompiledExprWithSideOutput) { ASSERT_OK_AND_ASSIGN( auto model, (ExprCompiler<TestInput, std::optional<float>, TestSideOutput>()) .SetInputLoader(CreateInputLoader()) .SetSlotListener(CreateSlotListener()) .AllowOutputCasting() .Compile(*compiled_expr_)); static_assert( std::is_same_v<decltype(model), std::function<absl::StatusOr<std::optional<float>>( const TestInput&, TestSideOutput*)>>); TestInput input{.x = 28, .y = 29}; EXPECT_THAT(model(input, nullptr), IsOkAndHolds(57)); TestSideOutput side_output; EXPECT_THAT(model(input, &side_output), IsOkAndHolds(57)); EXPECT_THAT(side_output.subtract, Eq(-1)); } TEST_F(ExprCompilerTest, CompileExprOperatorWithTuple) { ASSERT_OK_AND_ASSIGN(auto model, (ExprCompiler<std::tuple<float, float>, float>()) .CompileOperator(expr::LookupOperator("math.add"))); static_assert( std::is_same_v<decltype(model), std::function<absl::StatusOr<float>( const std::tuple<float, float>&)>>); EXPECT_THAT(model({28, 29}), IsOkAndHolds(57)); } TEST_F(ExprCompilerTest, CompileExprOperatorWithTypedRefs) { ASSERT_OK_AND_ASSIGN( auto model, (ExprCompiler<absl::Span<const TypedRef>, TypedValue>()) .CompileOperator(expr::LookupOperator("math.add"), {GetQType<float>(), GetQType<float>()})); static_assert( std::is_same_v<decltype(model), std::function<absl::StatusOr<TypedValue>( const absl::Span<const TypedRef>&)>>); auto a = TypedValue::FromValue<float>(28); auto b = TypedValue::FromValue<float>(29); std::vector<TypedRef> args{a.AsRef(), b.AsRef()}; ASSERT_OK_AND_ASSIGN(TypedValue res, model(args)); EXPECT_THAT(res.As<float>(), IsOkAndHolds(57)); } TEST_F(ExprCompilerTest, Ownership) { ExprCompiler<TestInput, std::optional<float>, TestSideOutput> mc; mc.SetInputLoader(CreateInputLoader()); ExprCompiler<TestInput, std::optional<float>, TestSideOutput> other_mc = std::move(mc); other_mc.SetSlotListener(CreateSlotListener()); mc = std::move(other_mc); mc.AllowOutputCasting(); ASSERT_OK(mc.Compile(expr_)); } TEST_F(ExprCompilerTest, Move) { auto set_input_loader = [](auto mc) { return std::move(mc).SetInputLoader(CreateInputLoader()); }; ASSERT_OK_AND_ASSIGN( auto model, set_input_loader( ExprCompiler<TestInput, std::optional<float>, TestSideOutput>() .SetSlotListener(CreateSlotListener())) .SetExperimentalArenaAllocator() .AllowOutputCasting() .Compile(expr_)); TestInput input{.x = 28, .y = 29}; EXPECT_THAT(model(input, nullptr), IsOkAndHolds(57)); } TEST_F(ExprCompilerTest, Optimizer) { auto replace_add_with_subtract = [](expr::ExprNodePtr x) -> absl::StatusOr<expr::ExprNodePtr> { if (expr::IsBackendOperator(*expr::DecayRegisteredOperator(x->op()), "math.add")) { return expr::WithNewOperator(std::move(x), *expr::LookupOperator("math.subtract")); } return x; }; ASSERT_OK_AND_ASSIGN(auto model, (ExprCompiler<TestInput, std::optional<float>>()) .SetInputLoader(CreateInputLoader()) .SetExprOptimizer(replace_add_with_subtract) .AllowOutputCasting() .Compile(expr_)); TestInput input{.x = 28, .y = 29}; EXPECT_THAT(model(input), IsOkAndHolds(-1)); } TEST_F(ExprCompilerTest, OtherOptionsSmokeTest) { ASSERT_OK_AND_ASSIGN( auto model, (ExprCompiler<TestInput, std::optional<float>, TestSideOutput>()) .SetInputLoader(CreateInputLoader()) .SetSlotListener(CreateSlotListener()) .SetExperimentalArenaAllocator() .SetAlwaysCloneThreadSafetyPolicy() .AllowOutputCasting() .Compile(expr_)); TestInput input{.x = 28, .y = 29}; EXPECT_THAT(model(input, nullptr), IsOkAndHolds(57)); TestSideOutput side_output; EXPECT_THAT(model(input, &side_output), IsOkAndHolds(57)); EXPECT_THAT(side_output.subtract, Eq(-1)); } TEST_F(ExprCompilerTest, DefaultThreadSafetyPolicy) { ASSERT_OK_AND_ASSIGN( auto model, (ExprCompiler<TestInput, std::optional<float>, TestSideOutput>()) .SetInputLoader(CreateInputLoader()) .SetSlotListener(CreateSlotListener()) .AllowOutputCasting() .Compile(expr_)); TestInput input{.x = 28, .y = 29}; TestSideOutput side_output; EXPECT_THAT(model(input, &side_output), IsOkAndHolds(57)); EXPECT_THAT(side_output.subtract, Eq(-1)); EXPECT_THAT((model.target<expr::ThreadSafePoolModelExecutor< TestInput, std::optional<float>, TestSideOutput>>()), NotNull()); } TEST_F(ExprCompilerTest, DefaultThreadSafetyPolicy_Codegen) { ASSERT_OK_AND_ASSIGN(auto eval_model, (ExprCompiler<TestInput, float>()) .SetInputLoader(CreateInputLoader()) .Compile(*compiled_expr_)); ASSERT_OK_AND_ASSIGN(auto codegen_model, (ExprCompiler<TestInput, float>()) .SetInputLoader(CreateInputLoader()) .Compile(TestInplaceCompiledExpr())); EXPECT_THAT( (eval_model .target<expr::ThreadSafePoolModelExecutor<TestInput, float>>()), NotNull()); EXPECT_THAT( (codegen_model .target<expr::ThreadSafePoolModelExecutor<TestInput, float>>()), IsNull()); } TEST_F(ExprCompilerTest, PoolThreadSafetyPolicy) { ASSERT_OK_AND_ASSIGN( auto model, (ExprCompiler<TestInput, std::optional<float>, TestSideOutput>()) .SetInputLoader(CreateInputLoader()) .SetSlotListener(CreateSlotListener()) .SetPoolThreadSafetyPolicy() .AllowOutputCasting() .Compile(expr_)); TestInput input{.x = 28, .y = 29}; TestSideOutput side_output; EXPECT_THAT(model(input, &side_output), IsOkAndHolds(57)); EXPECT_THAT(side_output.subtract, Eq(-1)); EXPECT_THAT((model.target<expr::ThreadSafePoolModelExecutor< TestInput, std::optional<float>, TestSideOutput>>()), NotNull()); } TEST_F(ExprCompilerTest, AlwaysCloneThreadSafetyPolicy) { ASSERT_OK_AND_ASSIGN( auto model, (ExprCompiler<TestInput, std::optional<float>, TestSideOutput>()) .SetInputLoader(CreateInputLoader()) .SetSlotListener(CreateSlotListener()) .SetAlwaysCloneThreadSafetyPolicy() .AllowOutputCasting() .Compile(expr_)); TestInput input{.x = 28, .y = 29}; TestSideOutput side_output; EXPECT_THAT(model(input, &side_output), IsOkAndHolds(57)); EXPECT_THAT(side_output.subtract, Eq(-1)); } TEST_F(ExprCompilerTest, ThreadUnsafe) { ASSERT_OK_AND_ASSIGN( auto model, (ExprCompiler<TestInput, std::optional<float>, TestSideOutput>()) .SetInputLoader(CreateInputLoader()) .SetSlotListener(CreateSlotListener()) .SetThreadUnsafe_I_SWEAR_TO_COPY_MODEL_FUNCTION_BEFORE_CALL() .AllowOutputCasting() .Compile(expr_)); TestInput input{.x = 28, .y = 29}; TestSideOutput side_output; EXPECT_THAT(model(input, &side_output), IsOkAndHolds(57)); EXPECT_THAT(side_output.subtract, Eq(-1)); } TEST_F(ExprCompilerTest, ForceNonOptionalOutput) { ASSERT_OK_AND_ASSIGN(auto expr, CallOp("math.neg", {Leaf("x")})); ASSERT_OK_AND_ASSIGN( auto input_loader, ::arolla::CreateAccessorsInputLoader<std::optional<float>>( "x", [](const auto& x) { return OptionalValue<float>(x); })); ASSERT_OK_AND_ASSIGN( auto model, (ExprCompiler<std::optional<float>, std::optional<float>>()) .SetInputLoader(MakeNotOwningInputLoader(input_loader.get())) .Compile(expr)); EXPECT_THAT(model(std::nullopt), IsOkAndHolds(std::nullopt)); EXPECT_THAT((ExprCompiler<std::optional<float>, float>()) .SetInputLoader(MakeNotOwningInputLoader(input_loader.get())) .AllowOutputCasting() .Compile(expr), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("model output is deduced to optional, while " "non-optional is requested"))); ASSERT_OK_AND_ASSIGN( auto full_model, (ExprCompiler<std::optional<float>, float>()) .SetInputLoader(MakeNotOwningInputLoader(input_loader.get())) .ForceNonOptionalOutput() .Compile(expr)); EXPECT_THAT(full_model(-57), IsOkAndHolds(57)); EXPECT_THAT(full_model(std::nullopt), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("expects a present value, got missing"))); } class VoidSlotListener : public StaticSlotListener<void> { public: VoidSlotListener(): StaticSlotListener<void>({}) {} absl::StatusOr<BoundSlotListener<Output>> BindImpl( const absl::flat_hash_map<std::string, TypedSlot>& input_slots) const final { return absl::UnimplementedError("unimplemented"); } private: }; TEST_F(ExprCompilerTest, Errors) { EXPECT_THAT((ExprCompiler<TestInput, std::optional<float>, TestSideOutput>()) .SetSlotListener(CreateSlotListener()) .Compile(expr_), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("InputLoader is not specified, use " "ExprCompiler::SetInputLoader()"))); EXPECT_THAT( (ExprCompiler<TestInput, std::optional<float>, TestSideOutput>()) .SetInputLoader(CreateInputLoader()) .Compile(expr_), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("SlotListener is not specified, use " "ExprCompiler::SetSlotListener() or ExprCompiler<...> " "without SideOutput template parameter"))); EXPECT_THAT((ExprCompiler<TestInput, std::optional<float>, void>()) .SetInputLoader(CreateInputLoader()) .SetSlotListener(std::unique_ptr<SlotListener<void>>( new VoidSlotListener())) .Compile(expr_), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("SlotListener with SideOutput==void is not " "supported by ExprCompiler"))); EXPECT_THAT( (ExprCompiler<std::tuple<float, float>, std::optional<float>>()) .SetInputLoader( TupleInputLoader<std::tuple<float, float>>::Create({"x", "y"})) .CompileOperator(nullptr), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("InputLoader is specified, but not needed for " "ExprCompiler::CompilerOperator"))); } TEST_F(ExprCompilerTest, CompileExprSet) { ASSERT_OK_AND_ASSIGN( auto models, CompileExprSet( ExprCompiler<TestInput, std::optional<float>>() .SetInputLoader(CreateInputLoader()) .AllowOutputCasting(), absl::flat_hash_map<std::string, absl::StatusOr<expr::ExprNodePtr>>{ {"first", expr_}, {"second", expr_}})); ASSERT_THAT(models, UnorderedElementsAre(Pair("first", _), Pair("second", _))); static_assert( std::is_same_v<std::decay_t<decltype(models[""])>, std::function<absl::StatusOr<std::optional<float>>( const TestInput&)>>); TestInput input{.x = 28, .y = 29}; EXPECT_THAT(models["first"](input), IsOkAndHolds(57)); } TEST_F(ExprCompilerTest, CompileExprSet_Errors) { EXPECT_THAT( CompileExprSet( ExprCompiler<TestInput, std::optional<float>>() .SetInputLoader(CreateInputLoader()) .AllowOutputCasting(), absl::flat_hash_map<std::string, absl::StatusOr<expr::ExprNodePtr>>{ {"first", expr_}, {"bad_model", absl::FailedPreconditionError("very bad model")}}), StatusIs(absl::StatusCode::kFailedPrecondition, "very bad model; while initializing model \"bad_model\"")); } } }
2,364
#ifndef AROLLA_QEXPR_OPERATOR_ERRORS_H_ #define AROLLA_QEXPR_OPERATOR_ERRORS_H_ #include <string> #include "absl/status/status.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/qexpr/qexpr_operator_signature.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_ref.h" #include "arolla/qtype/typed_value.h" namespace arolla { absl::Status OperatorNotDefinedError(absl::string_view operator_name, absl::Span<const QTypePtr> input_types, absl::string_view extra_message = ""); absl::Status VerifyInputSlotTypes(absl::Span<const TypedSlot> slots, absl::Span<const QTypePtr> expected_types, absl::string_view operator_name); absl::Status VerifyOutputSlotType(TypedSlot slot, QTypePtr expected_type, absl::string_view operator_name); absl::Status VerifyInputValueTypes(absl::Span<const TypedValue> values, absl::Span<const QTypePtr> expected_types, absl::string_view operator_name); absl::Status VerifyInputValueTypes(absl::Span<const TypedRef> values, absl::Span<const QTypePtr> expected_types, absl::string_view operator_name); absl::Status VerifyOutputValueType(const TypedValue& value, QTypePtr expected_type, absl::string_view operator_name); std::string GuessLibraryName(absl::string_view operator_name); std::string GuessOperatorLibraryName(absl::string_view operator_name); std::string SuggestMissingDependency(); std::string SuggestAvailableOverloads( absl::string_view operator_name, absl::Span<const QExprOperatorSignature* const> supported_qtypes); } #endif #include "arolla/qexpr/operator_errors.h" #include <cstddef> #include <initializer_list> #include <string> #include <vector> #include "absl/status/status.h" #include "absl/strings/ascii.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/strings/str_join.h" #include "absl/strings/str_replace.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/qexpr/qexpr_operator_signature.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_ref.h" #include "arolla/qtype/typed_value.h" namespace arolla { namespace { absl::Status SlotTypesMismatchError(absl::string_view operator_name, absl::string_view slots_kind, absl::Span<const QTypePtr> expected_types, absl::Span<const QTypePtr> got_types) { return absl::FailedPreconditionError(absl::StrFormat( "incorrect %s types for operator %s: expected %s, got %s", slots_kind, operator_name, FormatTypeVector(expected_types), FormatTypeVector(got_types))); } template <typename T> std::vector<QTypePtr> GetQTypes(absl::Span<const T> objects) { std::vector<QTypePtr> types; types.reserve(objects.size()); for (const auto& o : objects) { types.push_back(o.GetType()); } return types; } template <typename T> absl::Status VerifyTypes(absl::Span<const T> objects, absl::Span<const QTypePtr> expected_types, absl::string_view operator_name, absl::string_view slots_kind) { if (objects.size() != expected_types.size()) { return SlotTypesMismatchError(operator_name, slots_kind, expected_types, GetQTypes(objects)); } for (size_t i = 0; i < objects.size(); ++i) { if (objects[i].GetType() != expected_types[i]) { return SlotTypesMismatchError(operator_name, slots_kind, expected_types, GetQTypes(objects)); } } return absl::OkStatus(); } } absl::Status OperatorNotDefinedError(absl::string_view operator_name, absl::Span<const QTypePtr> input_types, absl::string_view extra_message) { return absl::NotFoundError(absl::StrCat( "operator ", operator_name, " is not defined for argument types ", FormatTypeVector(input_types), extra_message.empty() ? "" : ": ", extra_message)); } absl::Status VerifyInputSlotTypes(absl::Span<const TypedSlot> slots, absl::Span<const QTypePtr> expected_types, absl::string_view operator_name) { return VerifyTypes(slots, expected_types, operator_name, "input"); } absl::Status VerifyOutputSlotType(TypedSlot slot, QTypePtr expected_type, absl::string_view operator_name) { return VerifyTypes<TypedSlot>({slot}, {expected_type}, operator_name, "output"); } absl::Status VerifyInputValueTypes(absl::Span<const TypedValue> values, absl::Span<const QTypePtr> expected_types, absl::string_view operator_name) { return VerifyTypes(values, expected_types, operator_name, "input"); } absl::Status VerifyInputValueTypes(absl::Span<const TypedRef> values, absl::Span<const QTypePtr> expected_types, absl::string_view operator_name) { return VerifyTypes(values, expected_types, operator_name, "input"); } absl::Status VerifyOutputValueType(const TypedValue& value, QTypePtr expected_type, absl::string_view operator_name) { return VerifyTypes<TypedValue>({value}, {expected_type}, operator_name, "output"); } std::string GuessLibraryName(absl::string_view operator_name) { std::string path = absl::StrReplaceAll( operator_name.substr(0, operator_name.rfind('.')), {{".", "/"}}); return absl::StrCat(" } std::string GuessOperatorLibraryName(absl::string_view operator_name) { return absl::StrFormat("%s:operator_%s", GuessLibraryName(operator_name), absl::AsciiStrToLower(operator_name.substr( operator_name.rfind('.') + 1))); } std::string SuggestMissingDependency() { return "adding \"@arolla: "build dependency may help"; } std::string SuggestAvailableOverloads( absl::string_view operator_name, absl::Span<const QExprOperatorSignature* const> supported_qtypes) { std::vector<std::string> available_overloads; for (const auto type : supported_qtypes) { available_overloads.push_back(absl::StrFormat( "%s(%s) -> %s", operator_name, JoinTypeNames(type->input_types()), type->output_type()->name())); } return absl::StrFormat("available overloads:\n %s", absl::StrJoin(available_overloads, ",\n ")); } }
#include "arolla/qexpr/operator_errors.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/strings/string_view.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/memory/frame.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_slot.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla { namespace { using ::arolla::testing::IsOk; using ::arolla::testing::StatusIs; using ::testing::Eq; TEST(OperatorErrorsTest, OperatorNotDefinedError) { absl::string_view op_name = "test.Not"; EXPECT_THAT( OperatorNotDefinedError(op_name, {GetQType<int>(), GetQType<float>()}), StatusIs(absl::StatusCode::kNotFound, "operator test.Not is not defined for argument types " "(INT32,FLOAT32)")); EXPECT_THAT(OperatorNotDefinedError(op_name, {GetQType<int>()}, "Oops"), StatusIs(absl::StatusCode::kNotFound, "operator test.Not is not defined for argument types " "(INT32): Oops")); } TEST(OperatorErrorsTest, VerifySlotTypes) { absl::string_view op_name = "test.Not"; FrameLayout::Builder builder; auto int_slot = builder.AddSlot<int>(); auto double_slot = builder.AddSlot<double>(); EXPECT_THAT( VerifyInputSlotTypes(ToTypedSlots(int_slot, double_slot), {GetQType<int>(), GetQType<double>()}, op_name), IsOk()); EXPECT_THAT( VerifyInputSlotTypes(ToTypedSlots(int_slot, double_slot), {GetQType<int>(), GetQType<float>()}, op_name), StatusIs(absl::StatusCode::kFailedPrecondition, "incorrect input types for operator test.Not: expected " "(INT32,FLOAT32), got (INT32,FLOAT64)")); } TEST(OperatorErrorsTest, VerifyValueTypes) { absl::string_view op_name = "test.Not"; auto int_value = TypedValue::FromValue(57); auto double_value = TypedValue::FromValue(5.7); EXPECT_THAT( VerifyInputValueTypes({int_value, double_value}, {GetQType<int>(), GetQType<double>()}, op_name), IsOk()); EXPECT_THAT( VerifyInputValueTypes({int_value, double_value}, {GetQType<int>(), GetQType<float>()}, op_name), StatusIs(absl::StatusCode::kFailedPrecondition, "incorrect input types for operator test.Not: expected " "(INT32,FLOAT32), got (INT32,FLOAT64)")); } TEST(OperatorErrorsTest, GuessLibraryName) { EXPECT_THAT(GuessLibraryName("math.add"), Eq(" EXPECT_THAT(GuessLibraryName("math.complex.add"), Eq(" } TEST(OperatorErrorsTest, GuessOperatorLibraryName) { EXPECT_THAT(GuessOperatorLibraryName("math.add"), Eq(" EXPECT_THAT( GuessOperatorLibraryName("math.complex.add"), Eq(" } } }
2,365
#ifndef AROLLA_EXPR_EVAL_CASTING_H_ #define AROLLA_EXPR_EVAL_CASTING_H_ #include "absl/status/statusor.h" #include "arolla/expr/eval/eval.h" #include "arolla/expr/expr_node.h" namespace arolla::expr::eval_internal { absl::StatusOr<ExprNodePtr> CastingTransformation( const DynamicEvaluationEngineOptions& options, ExprNodePtr expr); } #endif #include "arolla/expr/eval/casting.h" #include <cstddef> #include <memory> #include <optional> #include <utility> #include <vector> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/types/span.h" #include "arolla/expr/derived_qtype_cast_operator.h" #include "arolla/expr/eval/eval.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_debug_string.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/operators/casting_registry.h" #include "arolla/expr/registered_expr_operator.h" #include "arolla/qexpr/operators.h" #include "arolla/qtype/array_like/array_like_qtype.h" #include "arolla/qtype/derived_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr::eval_internal { namespace { absl::StatusOr<std::vector<QTypePtr>> GetQTypesFromNodeDeps( const ExprNodePtr& expr) { std::vector<QTypePtr> qtypes; qtypes.reserve(expr->node_deps().size()); for (int i = 0; i < expr->node_deps().size(); i++) { const auto* qtype = expr->node_deps()[i]->qtype(); if (qtype == nullptr) { return absl::InternalError( absl::StrFormat("QType not set for %i-th argument of node %s", i, ToDebugString(expr))); } qtypes.push_back(qtype); } return qtypes; } absl::StatusOr<std::optional<ExprNodePtr>> GetShapeForBroadcasting( absl::Span<const ExprNodePtr> deps) { ExprNodePtr array_dep_or = nullptr; for (const auto& dep : deps) { if (IsArrayLikeQType(dep->qtype())) { array_dep_or = dep; break; } } if (array_dep_or != nullptr) { return CallOp("core.shape_of", {array_dep_or}); } return std::nullopt; } absl::StatusOr<std::vector<ExprNodePtr>> BuildNodeDepsWithCasts( absl::Span<const ExprNodePtr> deps, absl::Span<const QTypePtr> dep_types, absl::Span<const QTypePtr> required_types) { const auto* casting_registry = expr_operators::CastingRegistry::GetInstance(); ASSIGN_OR_RETURN(std::optional<ExprNodePtr> shape_for_broadcasting, GetShapeForBroadcasting(deps)); std::vector<ExprNodePtr> new_deps; new_deps.reserve(deps.size()); for (size_t i = 0; i < deps.size(); ++i) { auto dep = deps[i]; if (dep->qtype() != required_types[i]) { ASSIGN_OR_RETURN(dep, casting_registry->GetCast(dep, required_types[i], true, shape_for_broadcasting), _ << "while casting arguments " << FormatTypeVector(dep_types) << " into " << FormatTypeVector(required_types)); } new_deps.push_back(std::move(dep)); } return new_deps; } } absl::StatusOr<ExprNodePtr> CastingTransformation( const DynamicEvaluationEngineOptions& options, ExprNodePtr expr) { const OperatorDirectory& backend_operators = options.operator_directory != nullptr ? *options.operator_directory : *OperatorRegistry::GetInstance(); if (!expr->is_op()) { return expr; } ASSIGN_OR_RETURN(auto op, DecayRegisteredOperator(expr->op())); if (!HasBackendExprOperatorTag(op)) { return expr; } auto backend_op_name = op->display_name(); ASSIGN_OR_RETURN(auto dep_types, GetQTypesFromNodeDeps(expr)); QTypePtr result_qtype = expr->qtype(); if (result_qtype == nullptr) { return absl::InternalError( "all QTypes must be known before the casting compilation step"); } ASSIGN_OR_RETURN( auto backend_op, backend_operators.LookupOperator(backend_op_name, dep_types, result_qtype), expr); auto* backend_op_signature = backend_op->signature(); if (backend_op_signature->input_types() != dep_types) { ASSIGN_OR_RETURN(auto cast_deps, BuildNodeDepsWithCasts( expr->node_deps(), dep_types, backend_op_signature->input_types())); ASSIGN_OR_RETURN(expr, WithNewDependencies(expr, std::move(cast_deps))); if (expr->qtype() != DecayDerivedQType(result_qtype)) { return absl::FailedPreconditionError(absl::StrFormat( "expr output QType changed after input casting: was %s, became %s", result_qtype->name(), expr->qtype()->name())); } } if (backend_op_signature->output_type() == result_qtype) { return expr; } if (backend_op_signature->output_type() == DecayDerivedQType(result_qtype)) { auto downcast_op = std::make_shared<expr::DerivedQTypeDowncastOperator>(result_qtype); return CallOp(downcast_op, {expr}); } return absl::FailedPreconditionError(absl::StrFormat( "inconsistent output types for QExpr and expr %s operator: %s", backend_op_name, JoinTypeNames({result_qtype, backend_op_signature->output_type()}))); } }
#include "arolla/expr/eval/casting.h" #include <memory> #include <utility> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/expr/derived_qtype_cast_operator.h" #include "arolla/expr/eval/eval.h" #include "arolla/expr/expr.h" #include "arolla/expr/testing/testing.h" #include "arolla/qexpr/operator_factory.h" #include "arolla/qexpr/operators.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_value.h" #include "arolla/qtype/weak_qtype.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/text.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr::eval_internal { namespace { using ::arolla::testing::EqualsExpr; using ::arolla::testing::WithQTypeAnnotation; using ::testing::Test; template <typename T> absl::Status AddFakeAddOperator(OperatorRegistry& registry) { ASSIGN_OR_RETURN( auto op, OperatorFactory().WithName("math.add").BuildFromFunction([](T x, T) { return x; })); return registry.RegisterOperator(std::move(op)); } absl::Status AddFakeLowerOperator(OperatorRegistry& registry) { ASSIGN_OR_RETURN( auto op, OperatorFactory().WithName("strings.lower").BuildFromFunction([](Text x) { return x; })); return registry.RegisterOperator(std::move(op)); } class CastingTest : public Test { protected: void SetUp() override { ASSERT_OK(InitArolla()); backend_directory_ = std::make_shared<OperatorRegistry>(); ASSERT_OK(AddFakeAddOperator<float>(*backend_directory_)); ASSERT_OK(AddFakeAddOperator<double>(*backend_directory_)); ASSERT_OK(AddFakeAddOperator<DenseArray<float>>(*backend_directory_)); ASSERT_OK(AddFakeAddOperator<DenseArray<double>>(*backend_directory_)); ASSERT_OK(AddFakeLowerOperator(*backend_directory_)); options_ = DynamicEvaluationEngineOptions{.operator_directory = backend_directory_.get()}; } const QTypePtr f32_ = GetQType<float>(); const QTypePtr f64_ = GetQType<double>(); const QTypePtr of64_ = GetOptionalQType<double>(); const QTypePtr text_ = GetQType<Text>(); std::shared_ptr<OperatorRegistry> backend_directory_; DynamicEvaluationEngineOptions options_; }; TEST_F(CastingTest, Basic) { ASSERT_OK_AND_ASSIGN(auto expr, CallOp("math.add", {Literal<double>(2.), Literal<float>(1.f)})); ASSERT_OK_AND_ASSIGN( auto cast_expr, CallOp("math.add", {Literal<double>(2.), CallOp("core.to_float64", {Literal<float>(1.f)})})); ASSERT_OK_AND_ASSIGN(auto actual_expr, CastingTransformation(options_, expr)); EXPECT_THAT(actual_expr, EqualsExpr(cast_expr)); } TEST_F(CastingTest, WithOutputCasting_WeakFloat) { ASSERT_OK_AND_ASSIGN(auto weak_1, TypedValue::FromValueWithQType(1., GetWeakFloatQType())); ASSERT_OK_AND_ASSIGN(auto weak_2, TypedValue::FromValueWithQType(2., GetWeakFloatQType())); ASSERT_OK_AND_ASSIGN(auto expr, CallOp("math.add", {Literal(weak_1), Literal(weak_2)})); const auto upcast_op = std::make_shared<expr::DerivedQTypeUpcastOperator>(GetWeakFloatQType()); const auto downcast_op = std::make_shared<expr::DerivedQTypeDowncastOperator>(GetWeakFloatQType()); ASSERT_OK_AND_ASSIGN( auto cast_expr, CallOp(downcast_op, {CallOp("math.add", {CallOp(upcast_op, {Literal(weak_1)}), CallOp(upcast_op, {Literal(weak_2)})})})); ASSERT_OK_AND_ASSIGN(auto actual_expr, CastingTransformation(options_, expr)); EXPECT_THAT(actual_expr, EqualsExpr(cast_expr)); } TEST_F(CastingTest, WithOutputCasting_WeakFloatArray) { auto x = WithQTypeAnnotation(Leaf("x"), GetDenseArrayWeakFloatQType()); auto y = WithQTypeAnnotation(Leaf("y"), GetDenseArrayWeakFloatQType()); ASSERT_OK_AND_ASSIGN(auto expr, CallOp("math.add", {x, y})); const auto upcast_op = std::make_shared<expr::DerivedQTypeUpcastOperator>( GetDenseArrayWeakFloatQType()); const auto downcast_op = std::make_shared<expr::DerivedQTypeDowncastOperator>( GetDenseArrayWeakFloatQType()); ASSERT_OK_AND_ASSIGN( auto cast_expr, CallOp(downcast_op, {CallOp("math.add", {CallOp(upcast_op, {x}), CallOp(upcast_op, {y})})})); ASSERT_OK_AND_ASSIGN(auto actual_expr, CastingTransformation(options_, expr)); EXPECT_THAT(actual_expr, EqualsExpr(cast_expr)); } TEST_F(CastingTest, PassThroughSupportedOperator) { auto x = WithQTypeAnnotation(Leaf("x"), GetDenseArrayQType<double>()); auto y = WithQTypeAnnotation(Leaf("x"), GetDenseArrayQType<double>()); ASSERT_OK_AND_ASSIGN(auto expr, CallOp("math.add", {x, y})); EXPECT_THAT(CastingTransformation(options_, expr), IsOkAndHolds(EqualsExpr(expr))); } TEST_F(CastingTest, CastDenseArrayToDoubleOperator) { auto x = WithQTypeAnnotation(Leaf("x"), GetDenseArrayQType<float>()); auto y = WithQTypeAnnotation(Leaf("x"), GetDenseArrayQType<double>()); ASSERT_OK_AND_ASSIGN(auto expr, CallOp("math.add", {x, y})); ASSERT_OK_AND_ASSIGN(auto expected_expr, CallOp("math.add", {CallOp("core.to_float64", {x}), y})); EXPECT_THAT(CastingTransformation(options_, expr), IsOkAndHolds(EqualsExpr(expected_expr))); } TEST_F(CastingTest, Broadcasting) { auto x = WithQTypeAnnotation(Leaf("x"), f64_); auto y = WithQTypeAnnotation(Leaf("x"), GetDenseArrayQType<double>()); ASSERT_OK_AND_ASSIGN(auto expr, CallOp("math.add", {x, y})); EXPECT_THAT(CastingTransformation(options_, expr), IsOkAndHolds(EqualsExpr( CallOp("math.add", {CallOp("core.const_with_shape", {CallOp("core.shape_of", {y}), x}), y})))); } TEST_F(CastingTest, BroadcastingWithCasting) { auto x = WithQTypeAnnotation(Leaf("x"), f32_); auto y = WithQTypeAnnotation(Leaf("x"), GetDenseArrayQType<double>()); ASSERT_OK_AND_ASSIGN(auto expr, CallOp("math.add", {x, y})); EXPECT_THAT(CastingTransformation(options_, expr), IsOkAndHolds(EqualsExpr( CallOp("math.add", {CallOp("core.const_with_shape", {CallOp("core.shape_of", {y}), CallOp("core.to_float64", {x})}), y})))); } TEST_F(CastingTest, BroadcastingWithCastingToOptional) { auto x = WithQTypeAnnotation(Leaf("x"), of64_); auto y = WithQTypeAnnotation(Leaf("x"), GetDenseArrayQType<double>()); ASSERT_OK_AND_ASSIGN(auto expr, CallOp("math.add", {x, y})); EXPECT_THAT(CastingTransformation(options_, expr), IsOkAndHolds(EqualsExpr( CallOp("math.add", {CallOp("core.const_with_shape", {CallOp("core.shape_of", {y}), x}), y})))); } } }
2,366
#ifndef AROLLA_QEXPR_OPERATOR_FACTORY_H_ #define AROLLA_QEXPR_OPERATOR_FACTORY_H_ #include <cstddef> #include <memory> #include <string> #include <tuple> #include <type_traits> #include <utility> #include <vector> #include "absl/log/check.h" #include "absl/meta/type_traits.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/memory/frame.h" #include "arolla/qexpr/bound_operators.h" #include "arolla/qexpr/eval_context.h" #include "arolla/qexpr/operators.h" #include "arolla/qexpr/qexpr_operator_signature.h" #include "arolla/qexpr/result_type_traits.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/tuple_qtype.h" #include "arolla/qtype/typed_slot.h" #include "arolla/util/demangle.h" #include "arolla/util/meta.h" #include "arolla/util/status_macros_backport.h" namespace arolla { class OperatorFactory { public: OperatorFactory& WithName(std::string name); template <typename FUNC> absl::StatusOr<OperatorPtr> BuildFromFunction(FUNC func) const; template <typename FUNC> absl::StatusOr<OperatorPtr> BuildFromFunction( FUNC func, const QExprOperatorSignature* signature) const; template <typename FUNC, typename... ARG_Ts> absl::StatusOr<OperatorPtr> BuildFromFunctor() const; private: template <typename CTX_FUNC, typename... ARGs> absl::StatusOr<OperatorPtr> BuildFromFunctionImpl( CTX_FUNC func, const QExprOperatorSignature* signature, meta::type_list<ARGs...>) const; absl::StatusOr<std::string> name_; }; namespace operator_factory_impl { template <typename T> using Slot = FrameLayout::Slot<T>; template <typename FUNC, typename... OTHER_ARGs> struct ContextFunc : private FUNC { explicit ContextFunc(FUNC func) : FUNC(std::move(func)) {} auto operator()(EvaluationContext*, OTHER_ARGs... args) const { return static_cast<const FUNC&>(*this)(args...); } }; template <typename FUNC, typename... OTHER_ARGs> struct ContextFunc<FUNC, EvaluationContext*, OTHER_ARGs...> : FUNC { explicit ContextFunc(FUNC func) : FUNC(std::move(func)) {} }; template <typename FUNC, typename... FUNC_ARGs> auto WrapIntoContextFunc(FUNC func, meta::type_list<FUNC_ARGs...>) { if constexpr (std::is_class_v<FUNC>) { return ContextFunc<FUNC, FUNC_ARGs...>(std::move(func)); } else { auto fn = [func = std::forward<FUNC>(func)](FUNC_ARGs... args) { return func(args...); }; return ContextFunc<decltype(fn), FUNC_ARGs...>(std::move(fn)); } } template <typename... Ts> struct QTypesVerifier; template <typename T, typename... Ts> struct QTypesVerifier<T, Ts...> { static absl::Status Verify(absl::Span<const QTypePtr> qtypes) { if (qtypes.size() != sizeof...(Ts) + 1) { return absl::Status( absl::StatusCode::kInvalidArgument, absl::StrFormat( "unexpected number of types: expected %d types %s, got %d", qtypes.size(), FormatTypeVector(qtypes), sizeof...(Ts) + 1)); } DCHECK_GT(qtypes.size(), size_t{0}); if (qtypes[0]->type_info() != typeid(T)) { return absl::Status( absl::StatusCode::kInvalidArgument, absl::StrFormat( "unexpected type: expected %s with C++ type %s, got %s", qtypes[0]->name(), TypeName(qtypes[0]->type_info()), TypeName<T>())); } return QTypesVerifier<Ts...>::Verify(qtypes.subspan(1)); } }; template <> struct QTypesVerifier<> { static absl::Status Verify(absl::Span<const QTypePtr> qtypes) { if (!qtypes.empty()) { return absl::Status( absl::StatusCode::kInvalidArgument, absl::StrFormat( "unexpected number of types: expected %d types %s, got 0", qtypes.size(), FormatTypeVector(qtypes))); } return absl::OkStatus(); } }; template <typename... Ts> struct QTypesVerifier<meta::type_list<Ts...>> { static absl::Status Verify(absl::Span<const QTypePtr> qtypes) { return QTypesVerifier<Ts...>::Verify(qtypes); } }; template <typename Slots, std::size_t... Is> Slots UnsafeToSlotsTupleImpl(absl::Span<const TypedSlot> slots, std::index_sequence<Is...>) { DCHECK_EQ(slots.size(), sizeof...(Is)); return { slots[Is] .UnsafeToSlot< typename std::tuple_element<Is, Slots>::type::value_type>()...}; } template <typename Slots> Slots UnsafeToSlotsTuple(absl::Span<const TypedSlot> slots) { return UnsafeToSlotsTupleImpl<Slots>( slots, std::make_index_sequence<std::tuple_size<Slots>::value>{}); } template <typename FUNC, typename RES, typename... ARGs> const QExprOperatorSignature* DeduceOperatorSignatureImpl( meta::type_list<RES>, meta::type_list<ARGs...>) { return QExprOperatorSignature::Get( {GetQType<std::decay_t<ARGs>>()...}, qexpr_impl::ResultTypeTraits<RES>::GetOutputType()); } template <typename FUNC> const QExprOperatorSignature* DeduceOperatorSignature() { return DeduceOperatorSignatureImpl<FUNC>( meta::type_list<typename meta::function_traits<FUNC>::return_type>(), meta::tail_t<typename meta::function_traits<FUNC>::arg_types>()); } template <typename FUNC> absl::Status VerifyOperatorSignature(const QExprOperatorSignature* signature) { RETURN_IF_ERROR(QTypesVerifier<meta::tail_t<typename meta::function_traits< FUNC>::arg_types>>::Verify(signature->input_types())) << "in input types of " << signature << "."; std::vector<QTypePtr> output_types = {signature->output_type()}; if (IsTupleQType(signature->output_type())) { output_types = SlotsToTypes(signature->output_type()->type_fields()); } RETURN_IF_ERROR( QTypesVerifier<typename qexpr_impl::ResultTypeTraits< typename meta::function_traits<FUNC>::return_type>::Types>:: Verify(output_types)) << "in output types of " << signature << "."; return absl::OkStatus(); } template <typename CTX_FUNC, typename RES, typename... ARGs> class OpImpl : public QExprOperator { public: OpImpl(std::string name, const QExprOperatorSignature* qtype, CTX_FUNC func) : QExprOperator(std::move(name), qtype), func_(std::move(func)) {} private: absl::StatusOr<std::unique_ptr<BoundOperator>> DoBind( absl::Span<const TypedSlot> input_slots, TypedSlot output_slot) const override { auto inputs = UnsafeToSlotsTuple<InputSlots>(input_slots); auto outputs = qexpr_impl::ResultTypeTraits<RES>::UnsafeToSlots(output_slot); return MakeBoundOperator( [data = BoundOpData(func_, std::move(inputs), std::move(outputs))]( EvaluationContext* ctx, FramePtr frame) { RunImpl(data, ctx, frame, std::index_sequence_for<ARGs...>{}); }); } private: using InputSlots = std::tuple<Slot<absl::decay_t<ARGs>>...>; using OutputSlots = typename qexpr_impl::ResultTypeTraits<RES>::Slots; struct BoundOpData : private CTX_FUNC { BoundOpData(CTX_FUNC func, InputSlots input_slots, OutputSlots output_slots) : CTX_FUNC(std::move(func)), input_slots(input_slots), output_slots(output_slots) {} const CTX_FUNC& func() const { return static_cast<const CTX_FUNC&>(*this); } const InputSlots input_slots; const OutputSlots output_slots; }; template <std::size_t... Is> static void RunImpl(const BoundOpData& data, EvaluationContext* ctx, FramePtr frame, std::index_sequence<Is...>) { qexpr_impl::ResultTypeTraits<RES>::SaveAndReturn( ctx, frame, data.output_slots, data.func()(ctx, frame.Get(std::get<Is>(data.input_slots))...)); } const CTX_FUNC func_; }; } template <typename FUNC> absl::StatusOr<OperatorPtr> OperatorFactory::BuildFromFunction( FUNC func) const { auto context_func = operator_factory_impl::WrapIntoContextFunc( std::move(func), typename meta::function_traits<FUNC>::arg_types()); using CtxFunc = decltype(context_func); const QExprOperatorSignature* qtype = operator_factory_impl::DeduceOperatorSignature<CtxFunc>(); return BuildFromFunctionImpl( std::move(context_func), qtype, meta::tail_t<typename meta::function_traits<CtxFunc>::arg_types>()); } template <typename FUNC> absl::StatusOr<OperatorPtr> OperatorFactory::BuildFromFunction( FUNC func, const QExprOperatorSignature* qtype) const { auto context_func = operator_factory_impl::WrapIntoContextFunc( std::move(func), typename meta::function_traits<FUNC>::arg_types()); using CtxFunc = decltype(context_func); RETURN_IF_ERROR( operator_factory_impl::VerifyOperatorSignature<CtxFunc>(qtype)); return BuildFromFunctionImpl( std::move(context_func), qtype, meta::tail_t<typename meta::function_traits<CtxFunc>::arg_types>()); } template <typename FUNC, typename... ARG_Ts> absl::StatusOr<OperatorPtr> OperatorFactory::BuildFromFunctor() const { return BuildFromFunction([](EvaluationContext* ctx, const ARG_Ts&... args) { if constexpr (std::is_invocable_v<FUNC, ARG_Ts...>) { ((void)(ctx)); return FUNC()(args...); } else { return FUNC()(ctx, args...); } }); } template <typename CTX_FUNC, typename... ARGs> absl::StatusOr<OperatorPtr> OperatorFactory::BuildFromFunctionImpl( CTX_FUNC func, const QExprOperatorSignature* qtype, meta::type_list<ARGs...>) const { if (name_.status().code() == absl::StatusCode::kUnknown) { return absl::Status(absl::StatusCode::kFailedPrecondition, "operator name should be specified"); } RETURN_IF_ERROR(name_.status()); return OperatorPtr{std::make_shared<operator_factory_impl::OpImpl< CTX_FUNC, typename meta::function_traits<CTX_FUNC>::return_type, ARGs...>>(*name_, qtype, std::move(func))}; } } #endif #include "arolla/qexpr/operator_factory.h" #include <string> #include <utility> #include "absl/status/status.h" #include "absl/strings/str_format.h" #include "arolla/util/operator_name.h" namespace arolla { OperatorFactory& OperatorFactory::WithName(std::string name) { if (IsOperatorName(name)) { name_ = std::move(name); } else { name_ = absl::InvalidArgumentError( absl::StrFormat("incorrect operator name \"%s\"", name)); } return *this; } }
#include "arolla/qexpr/operator_factory.h" #include <cstdint> #include <tuple> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "arolla/qexpr/eval_context.h" #include "arolla/qexpr/qexpr_operator_signature.h" #include "arolla/qexpr/testing/operator_fixture.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/simple_qtype.h" #include "arolla/qtype/tuple_qtype.h" #include "arolla/util/fingerprint.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla { using ::arolla::testing::IsOk; using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::testing::Eq; using ::testing::Field; using ::testing::MatchesRegex; struct CopyCounter { CopyCounter() = default; CopyCounter(const CopyCounter& other) { count = other.count + 1; } CopyCounter& operator=(const CopyCounter& other) { count = other.count + 1; return *this; } CopyCounter(CopyCounter&& other) = default; CopyCounter& operator=(CopyCounter&& other) = default; int count = 0; }; AROLLA_DECLARE_FINGERPRINT_HASHER_TRAITS(CopyCounter); void FingerprintHasherTraits<CopyCounter>::operator()( FingerprintHasher* hasher, const CopyCounter& value) const { hasher->Combine(value.count); } AROLLA_DECLARE_SIMPLE_QTYPE(COPY_COUNTER, CopyCounter); AROLLA_DEFINE_SIMPLE_QTYPE(COPY_COUNTER, CopyCounter); namespace { TEST(OperatorFactory, SimpleOperator) { ASSERT_OK_AND_ASSIGN( auto op, OperatorFactory() .WithName("test.mul") .BuildFromFunction([](int64_t a, int64_t b) { return a * b; })); ASSERT_THAT(op->signature(), Eq(QExprOperatorSignature::Get( {GetQType<int64_t>(), GetQType<int64_t>()}, GetQType<int64_t>()))); ASSERT_OK_AND_ASSIGN( auto fixture, (OperatorFixture<std::tuple<int64_t, int64_t>, int64_t>::Create(*op))); EXPECT_THAT(fixture.Call(3, 19), IsOkAndHolds(Eq(57))); } int64_t Multiply(int64_t a, int64_t b) { return a * b; } TEST(OperatorFactory, NotAFunctor) { ASSERT_OK_AND_ASSIGN( auto op, OperatorFactory().WithName("test.mul").BuildFromFunction(Multiply)); ASSERT_THAT(op->signature(), Eq(QExprOperatorSignature::Get( {GetQType<int64_t>(), GetQType<int64_t>()}, GetQType<int64_t>()))); ASSERT_OK_AND_ASSIGN( auto fixture, (OperatorFixture<std::tuple<int64_t, int64_t>, int64_t>::Create(*op))); EXPECT_THAT(fixture.Call(3, 19), IsOkAndHolds(Eq(57))); } TEST(OperatorFactory, MultiOutputOperator) { using Pair = std::tuple<int64_t, int64_t>; ASSERT_OK_AND_ASSIGN(auto op, OperatorFactory() .WithName("test.EuclidsStep") .BuildFromFunction([](int64_t a, int64_t b) { return std::make_tuple(b, a % b); })); ASSERT_THAT(op->signature(), Eq(QExprOperatorSignature::Get( {GetQType<int64_t>(), GetQType<int64_t>()}, MakeTupleQType({GetQType<int64_t>(), GetQType<int64_t>()})))); ASSERT_OK_AND_ASSIGN(auto fixture, (OperatorFixture<Pair, Pair>::Create(*op))); EXPECT_THAT(fixture.Call(57, 20), IsOkAndHolds(Eq(std::make_tuple(20, 17)))); } TEST(OperatorFactory, ReturnsStatusOr) { ASSERT_OK_AND_ASSIGN( auto op, OperatorFactory() .WithName("test.AlwaysFail") .BuildFromFunction([]() -> absl::StatusOr<int64_t> { return absl::Status(absl::StatusCode::kFailedPrecondition, "failed"); })); ASSERT_THAT(op->signature(), Eq(QExprOperatorSignature::Get({}, GetQType<int64_t>()))); ASSERT_OK_AND_ASSIGN(auto fixture, (OperatorFixture<std::tuple<>, int64_t>::Create(*op))); EXPECT_THAT(fixture.Call(), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST(OperatorFactory, ReturnsStatusOrMultipleOutputs) { using Pair = std::tuple<int64_t, int64_t>; ASSERT_OK_AND_ASSIGN( auto op, OperatorFactory() .WithName("test.EuclidsStep") .BuildFromFunction([](int64_t a, int64_t b) -> absl::StatusOr<Pair> { if (b == 0) { return absl::Status(absl::StatusCode::kInvalidArgument, "b is 0"); } return std::make_tuple(b, a % b); })); EXPECT_THAT(op->signature(), Eq(QExprOperatorSignature::Get( {GetQType<int64_t>(), GetQType<int64_t>()}, MakeTupleQType({GetQType<int64_t>(), GetQType<int64_t>()})))); ASSERT_OK_AND_ASSIGN(auto fixture, (OperatorFixture<Pair, Pair>::Create(*op))); EXPECT_THAT(fixture.Call(57, 20), IsOkAndHolds(Eq(std::tuple(20, 17)))); EXPECT_THAT(fixture.Call(57, 0), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST(OperatorFactory, ReturnsStatusOrTuple) { using Pair = std::tuple<int64_t, int64_t>; auto qtype = QExprOperatorSignature::Get( {GetQType<int64_t>(), GetQType<int64_t>()}, MakeTupleQType({GetQType<int64_t>(), GetQType<int64_t>()})); ASSERT_OK_AND_ASSIGN( auto op, OperatorFactory() .WithName("test.EuclidsStep") .BuildFromFunction( [](int64_t a, int64_t b) -> absl::StatusOr<Pair> { if (b == 0) { return absl::Status( absl::StatusCode::kInvalidArgument, "b is 0"); } return std::make_tuple(b, a % b); }, qtype)); EXPECT_THAT(op->signature(), Eq(QExprOperatorSignature::Get( {GetQType<int64_t>(), GetQType<int64_t>()}, MakeTupleQType({GetQType<int64_t>(), GetQType<int64_t>()})))); ASSERT_OK_AND_ASSIGN(auto fixture, (OperatorFixture<Pair, Pair>::Create(*op))); EXPECT_THAT(fixture.Call(57, 20), IsOkAndHolds(Eq(std::tuple(20, 17)))); EXPECT_THAT(fixture.Call(57, 0), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST(OperatorFactory, NumberOfCopies) { using Fixture = OperatorFixture<std::tuple<CopyCounter>, CopyCounter>; ASSERT_OK_AND_ASSIGN( auto by_ref_with_eval_context_op, OperatorFactory().WithName("test.Op").BuildFromFunction( [](EvaluationContext*, const CopyCounter& c) { return c; })); ASSERT_OK_AND_ASSIGN(auto by_ref_with_eval_context_op_fixture, Fixture::Create(*by_ref_with_eval_context_op)); EXPECT_THAT(by_ref_with_eval_context_op_fixture.Call(CopyCounter()), IsOkAndHolds(Field(&CopyCounter::count, 1))); ASSERT_OK_AND_ASSIGN(auto by_ref_without_eval_context_op, OperatorFactory().WithName("test.Op").BuildFromFunction( [](const CopyCounter& c) { return c; })); ASSERT_OK_AND_ASSIGN(auto by_ref_without_eval_context_op_fixture, Fixture::Create(*by_ref_without_eval_context_op)); EXPECT_THAT(by_ref_without_eval_context_op_fixture.Call(CopyCounter()), IsOkAndHolds(Field(&CopyCounter::count, 1))); ASSERT_OK_AND_ASSIGN( auto by_val_with_eval_context_op, OperatorFactory().WithName("test.Op").BuildFromFunction( [](EvaluationContext*, CopyCounter c) { return c; })); ASSERT_OK_AND_ASSIGN(auto by_val_with_eval_context_op_fixture, Fixture::Create(*by_val_with_eval_context_op)); EXPECT_THAT(by_val_with_eval_context_op_fixture.Call(CopyCounter()), IsOkAndHolds(Field(&CopyCounter::count, 1))); ASSERT_OK_AND_ASSIGN(auto by_val_without_eval_context_op, OperatorFactory().WithName("test.Op").BuildFromFunction( [](CopyCounter c) { return c; })); ASSERT_OK_AND_ASSIGN(auto by_val_without_eval_context_op_fixture, Fixture::Create(*by_val_without_eval_context_op)); EXPECT_THAT(by_val_without_eval_context_op_fixture.Call(CopyCounter()), IsOkAndHolds(Field(&CopyCounter::count, 2))); ASSERT_OK_AND_ASSIGN( auto returns_tuple_op, OperatorFactory().WithName("test.Op").BuildFromFunction( [](const CopyCounter& c) { return std::make_tuple(c); })); ASSERT_OK_AND_ASSIGN(auto returns_tuple_op_fixture, Fixture::Create(*returns_tuple_op)); EXPECT_THAT(returns_tuple_op_fixture.Call(CopyCounter()), IsOkAndHolds(Field(&CopyCounter::count, 1))); ASSERT_OK_AND_ASSIGN( auto returns_status_or_tuple_op, OperatorFactory().WithName("test.Op").BuildFromFunction( [](const CopyCounter& c) { return absl::StatusOr<std::tuple<CopyCounter>>(std::make_tuple(c)); })); ASSERT_OK_AND_ASSIGN(auto returns_status_or_tuple_op_fixture, Fixture::Create(*returns_status_or_tuple_op)); EXPECT_THAT(returns_status_or_tuple_op_fixture.Call(CopyCounter()), IsOkAndHolds(Field(&CopyCounter::count, 1))); } TEST(OperatorFactory, TakesContext) { ASSERT_OK_AND_ASSIGN( auto op, OperatorFactory() .WithName("test.ContextOp") .BuildFromFunction([](EvaluationContext* ctx, float x) { ctx->buffer_factory().CreateRawBuffer(0); return std::tuple<>(); })); ASSERT_OK_AND_ASSIGN( auto fixture, (OperatorFixture<std::tuple<float>, std::tuple<>>::Create(*op))); EXPECT_THAT(fixture.Call(5.7), IsOk()); } struct AddOp { template <typename T> T operator()(T a, T b) const { return a + b; } }; struct Int64AddOp { int64_t operator()(int64_t a, int64_t b) const { return a + b; } }; struct ContextAddOp { template <typename T> T operator()(EvaluationContext* ctx, T a, T b) const { return a + b; } }; TEST(OperatorFactory, FromFunctor) { ASSERT_OK_AND_ASSIGN(auto op, (OperatorFactory() .WithName("test.add") .BuildFromFunctor<AddOp, int64_t, int64_t>())); EXPECT_THAT(op->name(), Eq("test.add")); ASSERT_OK_AND_ASSIGN(auto non_template_op, (OperatorFactory() .WithName("test.add") .BuildFromFunctor<Int64AddOp, int64_t, int64_t>())); EXPECT_THAT(non_template_op->name(), Eq("test.add")); ASSERT_OK_AND_ASSIGN( auto context_op, (OperatorFactory() .WithName("test.add") .BuildFromFunctor<ContextAddOp, int64_t, int64_t>())); EXPECT_THAT(context_op->name(), Eq("test.add")); } TEST(OperatorFactory, Errors) { EXPECT_THAT(OperatorFactory().BuildFromFunction( [](int64_t a, int64_t b) { return a * b; }), StatusIs(absl::StatusCode::kFailedPrecondition, "operator name should be specified")); auto qtype = QExprOperatorSignature::Get( {GetQType<float>(), GetQType<int32_t>()}, GetQType<int>()); EXPECT_THAT( OperatorFactory() .WithName("test.MakeOp") .BuildFromFunction( [](float arg1, float arg2) -> int32_t { return 57; }, qtype), StatusIs( absl::StatusCode::kInvalidArgument, MatchesRegex("unexpected type: expected INT32 with C\\+\\+ type int, " "got float; in input types of .*->.*\\."))); } } }
2,367
#ifndef AROLLA_QEXPR_SIMPLE_EXECUTABLE_H_ #define AROLLA_QEXPR_SIMPLE_EXECUTABLE_H_ #include <memory> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "arolla/memory/frame.h" #include "arolla/qexpr/eval_context.h" #include "arolla/qexpr/evaluation_engine.h" #include "arolla/qexpr/operators.h" #include "arolla/qtype/typed_slot.h" namespace arolla { class SimpleBoundExpr : public BoundExpr { public: SimpleBoundExpr( absl::flat_hash_map<std::string, TypedSlot> input_slots, TypedSlot output_slot, std::vector<std::unique_ptr<BoundOperator>> init_ops, std::vector<std::unique_ptr<BoundOperator>> eval_ops, absl::flat_hash_map<std::string, TypedSlot> named_output_slots = {}) : BoundExpr(std::move(input_slots), output_slot, std::move(named_output_slots)), init_ops_(std::move(init_ops)), eval_ops_(std::move(eval_ops)) {} void InitializeLiterals(EvaluationContext* ctx, FramePtr frame) const override; void Execute(EvaluationContext* ctx, FramePtr frame) const override; private: std::vector<std::unique_ptr<BoundOperator>> init_ops_; std::vector<std::unique_ptr<BoundOperator>> eval_ops_; }; class CombinedBoundExpr : public BoundExpr { public: CombinedBoundExpr( absl::flat_hash_map<std::string, TypedSlot> input_slots, TypedSlot output_slot, absl::flat_hash_map<std::string, TypedSlot> named_output_slots, std::vector<std::unique_ptr<BoundExpr>> subexprs) : BoundExpr(std::move(input_slots), output_slot, std::move(named_output_slots)), subexprs_(std::move(subexprs)) {} void InitializeLiterals(EvaluationContext* ctx, FramePtr frame) const override; void Execute(EvaluationContext* ctx, FramePtr frame) const override; private: std::vector<std::unique_ptr<BoundExpr>> subexprs_; }; } #endif #include "arolla/qexpr/simple_executable.h" #include <memory> #include "absl/status/status.h" #include "arolla/memory/frame.h" #include "arolla/qexpr/bound_operators.h" #include "arolla/qexpr/eval_context.h" #include "arolla/qexpr/evaluation_engine.h" namespace arolla { void SimpleBoundExpr::InitializeLiterals(EvaluationContext* ctx, FramePtr frame) const { RunBoundOperators(init_ops_, ctx, frame); } void SimpleBoundExpr::Execute(EvaluationContext* ctx, FramePtr frame) const { RunBoundOperators(eval_ops_, ctx, frame); } void CombinedBoundExpr::InitializeLiterals(EvaluationContext* ctx, FramePtr frame) const { for (const auto& e : subexprs_) { if (e->InitializeLiterals(ctx, frame); !ctx->status().ok()) { break; } } } void CombinedBoundExpr::Execute(EvaluationContext* ctx, FramePtr frame) const { for (const auto& e : subexprs_) { if (e->Execute(ctx, frame); !ctx->status().ok()) { break; } } } }
#include "arolla/qexpr/simple_executable.h" #include <memory> #include <string> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/container/flat_hash_map.h" #include "arolla/memory/frame.h" #include "arolla/qexpr/bound_operators.h" #include "arolla/qexpr/eval_context.h" #include "arolla/qexpr/evaluation_engine.h" #include "arolla/qexpr/operators.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_slot.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/unit.h" namespace arolla { namespace { using ::arolla::testing::IsOk; using ::testing::Eq; std::unique_ptr<BoundExpr> CreateCountingBoundExpr( FrameLayout::Slot<int> init_counter, FrameLayout::Slot<int> exec_counter) { std::vector<std::unique_ptr<BoundOperator>> init_ops; init_ops.push_back(MakeBoundOperator([=](EvaluationContext*, FramePtr frame) { ++(*frame.GetMutable(init_counter)); })); std::vector<std::unique_ptr<BoundOperator>> exec_ops; exec_ops.push_back(MakeBoundOperator([=](EvaluationContext*, FramePtr frame) { ++(*frame.GetMutable(exec_counter)); })); return std::make_unique<SimpleBoundExpr>( absl::flat_hash_map<std::string, TypedSlot>{}, TypedSlot::UnsafeFromOffset(GetQType<Unit>(), 0), std::move(init_ops), std::move(exec_ops)); } TEST(SimpleExecutableTest, CombinedBoundExpr) { FrameLayout::Builder builder; std::vector<std::unique_ptr<BoundExpr>> subexprs; auto init_1_called = builder.AddSlot<int>(); auto exec_1_called = builder.AddSlot<int>(); subexprs.push_back(CreateCountingBoundExpr(init_1_called, exec_1_called)); auto init_2_called = builder.AddSlot<int>(); auto exec_2_called = builder.AddSlot<int>(); subexprs.push_back(CreateCountingBoundExpr(init_2_called, exec_2_called)); std::unique_ptr<BoundExpr> combined_expr = std::make_unique<CombinedBoundExpr>( absl::flat_hash_map<std::string, TypedSlot>{}, TypedSlot::UnsafeFromOffset(GetQType<Unit>(), 0), absl::flat_hash_map<std::string, TypedSlot>{}, std::move(subexprs)); FrameLayout layout = std::move(builder).Build(); RootEvaluationContext ctx(&layout); ctx.Set(init_1_called, 0); ctx.Set(init_2_called, 0); ctx.Set(exec_1_called, 0); ctx.Set(exec_2_called, 0); ASSERT_THAT(combined_expr->InitializeLiterals(&ctx), IsOk()); EXPECT_THAT(ctx.Get(init_1_called), Eq(1)); EXPECT_THAT(ctx.Get(init_2_called), Eq(1)); EXPECT_THAT(ctx.Get(exec_1_called), Eq(0)); EXPECT_THAT(ctx.Get(exec_2_called), Eq(0)); ASSERT_THAT(combined_expr->Execute(&ctx), IsOk()); EXPECT_THAT(ctx.Get(init_1_called), Eq(1)); EXPECT_THAT(ctx.Get(init_2_called), Eq(1)); EXPECT_THAT(ctx.Get(exec_1_called), Eq(1)); EXPECT_THAT(ctx.Get(exec_2_called), Eq(1)); } } }
2,368
#ifndef AROLLA_BLOCK_TESTING_BOUND_OPERATORS_H #define AROLLA_BLOCK_TESTING_BOUND_OPERATORS_H #include <memory> #include "arolla/dense_array/dense_array.h" #include "arolla/memory/frame.h" #include "arolla/qexpr/operators.h" namespace arolla { std::unique_ptr<BoundOperator> DenseArrayAddOperator( FrameLayout::Slot<DenseArray<float>> arg1, FrameLayout::Slot<DenseArray<float>> arg2, FrameLayout::Slot<DenseArray<float>> result); std::unique_ptr<BoundOperator> DenseArrayEigenAddOperator( FrameLayout::Slot<DenseArray<float>> arg1, FrameLayout::Slot<DenseArray<float>> arg2, FrameLayout::Slot<DenseArray<float>> result); std::unique_ptr<BoundOperator> DenseArrayUnionAddOperator( FrameLayout::Slot<DenseArray<float>> arg1, FrameLayout::Slot<DenseArray<float>> arg2, FrameLayout::Slot<DenseArray<float>> result); } #endif #include "arolla/dense_array/testing/bound_operators.h" #include <memory> #include "absl/status/status.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/ops/dense_ops.h" #include "arolla/memory/frame.h" #include "arolla/memory/optional_value.h" #include "arolla/qexpr/eval_context.h" #include "arolla/qexpr/operators.h" #include "arolla/qexpr/operators/math/batch_arithmetic.h" namespace arolla { namespace { class TestAdd : public BoundOperator { public: explicit TestAdd(FrameLayout::Slot<DenseArray<float>> arg1, FrameLayout::Slot<DenseArray<float>> arg2, FrameLayout::Slot<DenseArray<float>> result) : arg1_(arg1), arg2_(arg2), result_(result) {} void Run(EvaluationContext* ctx, FramePtr frame) const override { if (frame.Get(arg1_).size() != frame.Get(arg2_).size()) { ctx->set_status(absl::InvalidArgumentError("size mismatch")); } else { auto op = CreateDenseOp<DenseOpFlags::kRunOnMissing | DenseOpFlags::kNoBitmapOffset | DenseOpFlags::kNoSizeValidation>( [](float a, float b) { return a + b; }, &ctx->buffer_factory()); *frame.GetMutable(result_) = op(frame.Get(arg1_), frame.Get(arg2_)); } } private: FrameLayout::Slot<DenseArray<float>> arg1_; FrameLayout::Slot<DenseArray<float>> arg2_; FrameLayout::Slot<DenseArray<float>> result_; }; class TestEigenAdd : public BoundOperator { public: explicit TestEigenAdd(FrameLayout::Slot<DenseArray<float>> arg1, FrameLayout::Slot<DenseArray<float>> arg2, FrameLayout::Slot<DenseArray<float>> result) : arg1_(arg1), arg2_(arg2), result_(result) {} void Run(EvaluationContext* ctx, FramePtr frame) const override { if (frame.Get(arg1_).size() != frame.Get(arg2_).size()) { ctx->set_status(absl::InvalidArgumentError("size mismatch")); } else { auto op = CreateDenseBinaryOpFromSpanOp<float, DenseOpFlags::kNoBitmapOffset | DenseOpFlags::kNoSizeValidation>( BatchAdd<float>(), &ctx->buffer_factory()); *frame.GetMutable(result_) = op(frame.Get(arg1_), frame.Get(arg2_)); } } private: FrameLayout::Slot<DenseArray<float>> arg1_; FrameLayout::Slot<DenseArray<float>> arg2_; FrameLayout::Slot<DenseArray<float>> result_; }; class TestUnionAdd : public BoundOperator { public: explicit TestUnionAdd(FrameLayout::Slot<DenseArray<float>> arg1, FrameLayout::Slot<DenseArray<float>> arg2, FrameLayout::Slot<DenseArray<float>> result) : arg1_(arg1), arg2_(arg2), result_(result) {} void Run(EvaluationContext* ctx, FramePtr frame) const override { if (frame.Get(arg1_).size() != frame.Get(arg2_).size()) { ctx->set_status(absl::InvalidArgumentError("size mismatch")); } else { auto fn = [](OptionalValue<float> a, OptionalValue<float> b) { OptionalValue<float> res; res.present = a.present || b.present; res.value = (a.present ? a.value : 0.f) + (b.present ? b.value : 0.f); return res; }; auto op = CreateDenseOp<DenseOpFlags::kNoBitmapOffset | DenseOpFlags::kNoSizeValidation>( fn, &ctx->buffer_factory()); *frame.GetMutable(result_) = op(frame.Get(arg1_), frame.Get(arg2_)); } } private: FrameLayout::Slot<DenseArray<float>> arg1_; FrameLayout::Slot<DenseArray<float>> arg2_; FrameLayout::Slot<DenseArray<float>> result_; }; } std::unique_ptr<BoundOperator> DenseArrayAddOperator( FrameLayout::Slot<DenseArray<float>> arg1, FrameLayout::Slot<DenseArray<float>> arg2, FrameLayout::Slot<DenseArray<float>> result) { return std::make_unique<TestAdd>(arg1, arg2, result); } std::unique_ptr<BoundOperator> DenseArrayEigenAddOperator( FrameLayout::Slot<DenseArray<float>> arg1, FrameLayout::Slot<DenseArray<float>> arg2, FrameLayout::Slot<DenseArray<float>> result) { return std::make_unique<TestEigenAdd>(arg1, arg2, result); } std::unique_ptr<BoundOperator> DenseArrayUnionAddOperator( FrameLayout::Slot<DenseArray<float>> arg1, FrameLayout::Slot<DenseArray<float>> arg2, FrameLayout::Slot<DenseArray<float>> result) { return std::make_unique<TestUnionAdd>(arg1, arg2, result); } }
#include "arolla/qexpr/bound_operators.h" #include <cstdint> #include <memory> #include <optional> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/types/span.h" #include "arolla/memory/frame.h" #include "arolla/memory/memory_allocation.h" #include "arolla/memory/optional_value.h" #include "arolla/qexpr/eval_context.h" #include "arolla/qexpr/operators.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_slot.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/status_macros_backport.h" namespace arolla { namespace { using ::arolla::testing::IsOk; using ::arolla::testing::StatusIs; using ::testing::Eq; template <typename T> using Slot = FrameLayout::Slot<T>; absl::StatusOr<std::unique_ptr<BoundOperator>> CreateAddFloatsBoundOp( absl::Span<const TypedSlot> input_slots, Slot<OptionalValue<float>> output_slot) { std::vector<Slot<bool>> input_cond_slots; std::vector<Slot<float>> input_value_slots; for (const auto& typed_input_slot : input_slots) { QTypePtr input_type = typed_input_slot.GetType(); if (IsOptionalQType(input_type)) { ASSIGN_OR_RETURN(auto input_slot, typed_input_slot.ToSlot<OptionalValue<float>>()); input_cond_slots.push_back(GetPresenceSubslotFromOptional(input_slot)); input_value_slots.push_back(GetValueSubslotFromOptional(input_slot)); } else { ASSIGN_OR_RETURN(auto value_slot, typed_input_slot.ToSlot<float>()); input_value_slots.push_back(value_slot); } } Slot<bool> output_presence_slot = output_slot.GetSubslot<0>(); Slot<float> output_value_slot = output_slot.GetSubslot<1>(); auto add_op = FunctorBoundOperator([input_value_slots, output_value_slot]( EvaluationContext* ctx, FramePtr frame) { float result = 0.0f; for (auto input_value_slot : input_value_slots) { result += frame.Get(input_value_slot); } frame.Set(output_value_slot, result); }); return std::unique_ptr<BoundOperator>(new WhereAllBoundOperator( input_cond_slots, output_presence_slot, add_op)); } TEST(BoundOperators, RunBoundOperators) { FrameLayout::Builder layout_builder; Slot<int32_t> x_slot = layout_builder.AddSlot<int32_t>(); FrameLayout layout = std::move(layout_builder).Build(); MemoryAllocation alloc(&layout); ASSERT_THAT(alloc.frame().Get(x_slot), Eq(0)); auto make_increment_operator = [x_slot](int32_t increment) { return MakeBoundOperator( [x_slot, increment](EvaluationContext* ctx, FramePtr frame) { frame.Set(x_slot, frame.Get(x_slot) + increment); }); }; std::vector<std::unique_ptr<BoundOperator>> bound_operators; bound_operators.push_back(make_increment_operator(1)); bound_operators.push_back(make_increment_operator(10)); bound_operators.push_back(make_increment_operator(100)); EvaluationContext ctx; EXPECT_EQ(RunBoundOperators(bound_operators, &ctx, alloc.frame()), 2); EXPECT_THAT(alloc.frame().Get(x_slot), Eq(111)); EXPECT_THAT(ctx.status(), IsOk()); } TEST(BoundOperators, RunBoundOperators_WithError) { FrameLayout::Builder layout_builder; Slot<int32_t> x_slot = layout_builder.AddSlot<int32_t>(); FrameLayout layout = std::move(layout_builder).Build(); MemoryAllocation alloc(&layout); ASSERT_THAT(alloc.frame().Get(x_slot), Eq(0)); auto make_increment_operator = [x_slot](int32_t increment) { return MakeBoundOperator( [x_slot, increment](EvaluationContext* ctx, FramePtr frame) { frame.Set(x_slot, frame.Get(x_slot) + increment); }); }; std::vector<std::unique_ptr<BoundOperator>> bound_operators; bound_operators.push_back(make_increment_operator(1)); bound_operators.push_back(make_increment_operator(10)); bound_operators.push_back( MakeBoundOperator([](EvaluationContext* ctx, FramePtr frame) { ctx->set_status(absl::InvalidArgumentError("foo")); })); bound_operators.push_back(make_increment_operator(100)); EvaluationContext ctx; EXPECT_EQ(RunBoundOperators(bound_operators, &ctx, alloc.frame()), 2); EXPECT_THAT(alloc.frame().Get(x_slot), Eq(11)); EXPECT_THAT(ctx.status(), StatusIs(absl::StatusCode::kInvalidArgument, "foo")); } TEST(BoundOperators, RunBoundOperators_WithJump) { FrameLayout::Builder layout_builder; Slot<int32_t> x_slot = layout_builder.AddSlot<int32_t>(); FrameLayout layout = std::move(layout_builder).Build(); MemoryAllocation alloc(&layout); ASSERT_THAT(alloc.frame().Get(x_slot), Eq(0)); auto make_increment_operator = [x_slot](int32_t increment) { return MakeBoundOperator( [x_slot, increment](EvaluationContext* ctx, FramePtr frame) { frame.Set(x_slot, frame.Get(x_slot) + increment); }); }; std::vector<std::unique_ptr<BoundOperator>> bound_operators; bound_operators.push_back(make_increment_operator(1)); bound_operators.push_back(JumpBoundOperator(1)); bound_operators.push_back(make_increment_operator(10)); bound_operators.push_back(make_increment_operator(100)); EvaluationContext ctx; EXPECT_EQ(RunBoundOperators(bound_operators, &ctx, alloc.frame()), 3); EXPECT_THAT(alloc.frame().Get(x_slot), Eq(101)); EXPECT_THAT(ctx.status(), IsOk()); } TEST(BoundOperators, WhereAll) { FrameLayout::Builder layout_builder; auto input1 = layout_builder.AddSlot<OptionalValue<float>>(); auto input2 = layout_builder.AddSlot<OptionalValue<float>>(); auto input3 = layout_builder.AddSlot<float>(); auto input4 = layout_builder.AddSlot<float>(); auto result = layout_builder.AddSlot<OptionalValue<float>>(); ASSERT_OK_AND_ASSIGN( auto op1, CreateAddFloatsBoundOp( ToTypedSlots(input1, input2, input3, input4), result)); FrameLayout layout = std::move(layout_builder).Build(); RootEvaluationContext root_ctx(&layout); root_ctx.Set(input1, 1.0f); root_ctx.Set(input2, 10.0f); root_ctx.Set(input3, 100.0f); root_ctx.Set(input4, 1000.0f); EvaluationContext ctx(root_ctx); op1->Run(&ctx, root_ctx.frame()); EXPECT_OK(ctx.status()); EXPECT_EQ(root_ctx.Get(result), OptionalValue<float>{1111.0f}); root_ctx.Set(input2, std::nullopt); root_ctx.Set(result, 0.0f); op1->Run(&ctx, root_ctx.frame()); EXPECT_OK(ctx.status()); EXPECT_EQ(root_ctx.Get(result), OptionalValue<float>{}); EXPECT_EQ(root_ctx.Get(result).value, 0.0f); } } }
2,369
#ifndef AROLLA_QEXPR_OPERATOR_METADATA_H_ #define AROLLA_QEXPR_OPERATOR_METADATA_H_ #include <optional> #include <set> #include <string> #include <vector> #include "absl/base/thread_annotations.h" #include "absl/container/flat_hash_map.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/synchronization/mutex.h" #include "absl/types/span.h" #include "arolla/qtype/qtype.h" namespace arolla { struct OpClassDetails { bool returns_status_or; bool accepts_context; std::vector<int> arg_as_function_ids; }; struct BuildDetails { std::string build_target; std::string op_class; std::optional<OpClassDetails> op_class_details; std::string op_family_class; std::vector<std::string> hdrs; std::vector<std::string> deps; }; struct QExprOperatorMetadata { std::string name; std::vector<QTypePtr> input_qtypes; BuildDetails build_details; }; struct QExprOperatorFamilyMetadata { std::string name; BuildDetails family_build_details = {}; }; class QExprOperatorMetadataRegistry final { public: QExprOperatorMetadataRegistry() = default; absl::Status AddOperatorFamilyMetadata(QExprOperatorFamilyMetadata metadata); absl::Status AddOperatorMetadata(QExprOperatorMetadata metadata); absl::StatusOr<QExprOperatorMetadata> LookupOperatorMetadata( absl::string_view op_name, absl::Span<const QTypePtr> input_qtypes) const; absl::flat_hash_map<std::string, std::set<std::string>> OperatorBuildDependencies() const; static QExprOperatorMetadataRegistry& GetInstance(); private: using TypeToMetadata = absl::flat_hash_map<std::vector<QTypePtr>, QExprOperatorMetadata>; absl::flat_hash_map<std::string, QExprOperatorFamilyMetadata> family_metadatas_ ABSL_GUARDED_BY(mutex_); absl::flat_hash_map<std::string, TypeToMetadata> operator_metadatas_ ABSL_GUARDED_BY(mutex_); mutable absl::Mutex mutex_; }; int RegisterOperatorFamilyMetadataOrDie(QExprOperatorFamilyMetadata metadata); int RegisterOperatorMetadataOrDie(QExprOperatorMetadata metadata); } #endif #include "arolla/qexpr/operator_metadata.h" #include <set> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/log/log.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "absl/synchronization/mutex.h" #include "absl/types/span.h" #include "arolla/qtype/qtype.h" #include "arolla/util/indestructible.h" namespace arolla { absl::Status QExprOperatorMetadataRegistry::AddOperatorFamilyMetadata( QExprOperatorFamilyMetadata metadata) { absl::WriterMutexLock lock(&mutex_); if (family_metadatas_.contains(metadata.name) || operator_metadatas_.contains(metadata.name)) { return absl::Status( absl::StatusCode::kAlreadyExists, absl::StrFormat("trying to register individual operator or operator " "family metadata twice under the same name %s", metadata.name)); } family_metadatas_.emplace(metadata.name, std::move(metadata)); return absl::OkStatus(); } absl::Status QExprOperatorMetadataRegistry::AddOperatorMetadata( QExprOperatorMetadata metadata) { absl::WriterMutexLock lock(&mutex_); if (family_metadatas_.contains(metadata.name)) { return absl::Status( absl::StatusCode::kAlreadyExists, absl::StrFormat("trying to register individual operator or operator " "family metadata twice under the same name %s", metadata.name)); } auto [iter, inserted] = operator_metadatas_.emplace(metadata.name, TypeToMetadata{}); if (iter->second.contains(metadata.input_qtypes)) { return absl::Status( absl::StatusCode::kAlreadyExists, absl::StrFormat("trying to register operator metadata twice " "for operator %s with input types %s", metadata.name, FormatTypeVector(metadata.input_qtypes))); } iter->second.emplace(metadata.input_qtypes, std::move(metadata)); return absl::OkStatus(); } absl::StatusOr<QExprOperatorMetadata> QExprOperatorMetadataRegistry::LookupOperatorMetadata( absl::string_view op_name, absl::Span<const QTypePtr> input_qtypes) const { absl::ReaderMutexLock lock(&mutex_); std::vector<QTypePtr> input_qtypes_vector(input_qtypes.begin(), input_qtypes.end()); if (auto m = family_metadatas_.find(op_name); m != family_metadatas_.end()) { return QExprOperatorMetadata{ .name = std::string(m->second.name), .input_qtypes = std::move(input_qtypes_vector), .build_details = m->second.family_build_details}; } if (auto oms = operator_metadatas_.find(op_name); oms != operator_metadatas_.end()) { if (auto m = oms->second.find(input_qtypes_vector); m != oms->second.end()) { return m->second; } } return absl::Status( absl::StatusCode::kNotFound, absl::StrFormat( "no metadata is available for operator %s with input types %s", op_name, FormatTypeVector(input_qtypes))); } QExprOperatorMetadataRegistry& QExprOperatorMetadataRegistry::GetInstance() { static Indestructible<QExprOperatorMetadataRegistry> instance; return *instance; } absl::flat_hash_map<std::string, std::set<std::string>> QExprOperatorMetadataRegistry::OperatorBuildDependencies() const { absl::flat_hash_map<std::string, std::set<std::string>> result; absl::ReaderMutexLock lock(&mutex_); for (const auto& [_, metadata] : family_metadatas_) { result[absl::StrCat(metadata.name, "(...)")].insert( metadata.family_build_details.build_target); } for (const auto& [name, type_to_meta] : operator_metadatas_) { for (const auto& [types, metadata] : type_to_meta) { std::string name_with_types = absl::StrCat(name, ::arolla::FormatTypeVector(types)); result[name_with_types].insert(metadata.build_details.build_target); } } return result; } int RegisterOperatorFamilyMetadataOrDie(QExprOperatorFamilyMetadata metadata) { auto status = QExprOperatorMetadataRegistry::GetInstance().AddOperatorFamilyMetadata( std::move(metadata)); if (!status.ok()) { LOG(FATAL) << status; } return 57; } int RegisterOperatorMetadataOrDie(QExprOperatorMetadata metadata) { auto status = QExprOperatorMetadataRegistry::GetInstance().AddOperatorMetadata( std::move(metadata)); if (!status.ok()) { LOG(FATAL) << status; } return 57; } }
#include "arolla/qexpr/operator_metadata.h" #include <cstdint> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/util/operator_name.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla { namespace { using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::testing::Eq; using ::testing::Field; using ::testing::MatchesRegex; TEST(OperatorMetadataTest, OperatorMetadata) { auto i32 = GetQType<int32_t>(); auto f32 = GetQType<float>(); QExprOperatorMetadata add_ints_meta; add_ints_meta.name = AROLLA_OPERATOR_NAME("test.add"); add_ints_meta.input_qtypes = {i32, i32}; add_ints_meta.build_details.op_class = "Add<int>"; QExprOperatorMetadata add_floats_meta; add_floats_meta.name = AROLLA_OPERATOR_NAME("test.add"); add_floats_meta.input_qtypes = {f32, f32}; add_floats_meta.build_details.op_class = "Add<float>"; QExprOperatorMetadataRegistry registry; ASSERT_OK(registry.AddOperatorMetadata(add_ints_meta)); ASSERT_OK(registry.AddOperatorMetadata(add_floats_meta)); EXPECT_THAT( registry.AddOperatorMetadata(add_ints_meta), StatusIs(absl::StatusCode::kAlreadyExists, MatchesRegex("trying to register operator metadata twice for " "operator test.add with input types .*"))); EXPECT_THAT( registry.AddOperatorFamilyMetadata(QExprOperatorFamilyMetadata{ .name = add_ints_meta.name, .family_build_details = {}}), StatusIs(absl::StatusCode::kAlreadyExists, Eq("trying to register individual operator or operator family " "metadata twice under the same name test.add"))); EXPECT_THAT(registry.LookupOperatorMetadata(add_ints_meta.name, {i32, i32}), IsOkAndHolds(Field(&QExprOperatorMetadata::build_details, Field(&BuildDetails::op_class, "Add<int>")))); } TEST(OperatorMetadataTest, OperatorFamilyMetadata) { auto i32 = GetQType<int32_t>(); ::arolla::BuildDetails family_build_details; family_build_details.op_family_class = "AddFamily"; QExprOperatorFamilyMetadata add_meta{ .name = "test.add", .family_build_details = family_build_details}; QExprOperatorMetadataRegistry registry; ASSERT_OK(registry.AddOperatorFamilyMetadata(add_meta)); EXPECT_THAT( registry.AddOperatorMetadata(QExprOperatorMetadata{ .name = "test.add", .input_qtypes = {i32, i32}}), StatusIs(absl::StatusCode::kAlreadyExists, Eq("trying to register individual operator or operator family " "metadata twice under the same name test.add"))); EXPECT_THAT( registry.AddOperatorFamilyMetadata(add_meta), StatusIs(absl::StatusCode::kAlreadyExists, Eq("trying to register individual operator or operator family " "metadata twice under the same name test.add"))); EXPECT_THAT( registry.LookupOperatorMetadata(add_meta.name, {i32, i32}), IsOkAndHolds(Field(&QExprOperatorMetadata::build_details, Field(&BuildDetails::op_family_class, "AddFamily")))); } } }
2,370
#ifndef AROLLA_QEXPR_OPERATORS_H_ #define AROLLA_QEXPR_OPERATORS_H_ #include <memory> #include <string> #include <utility> #include <vector> #include "absl/base/thread_annotations.h" #include "absl/container/flat_hash_map.h" #include "absl/log/log.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/synchronization/mutex.h" #include "absl/types/span.h" #include "arolla/memory/frame.h" #include "arolla/qexpr/eval_context.h" #include "arolla/qexpr/qexpr_operator_signature.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/status_macros_backport.h" namespace arolla { class BoundOperator { public: virtual ~BoundOperator() = default; virtual void Run(EvaluationContext* ctx, FramePtr frame) const = 0; }; class QExprOperator { public: template <typename T> using Slot = FrameLayout::Slot<T>; virtual ~QExprOperator() = default; explicit QExprOperator(std::string name, const QExprOperatorSignature* signature) : name_(std::move(name)), signature_(signature) {} const QExprOperatorSignature* signature() const { return signature_; } absl::string_view name() const { return name_; } absl::StatusOr<std::unique_ptr<BoundOperator>> Bind( absl::Span<const TypedSlot> input_slots, TypedSlot output_slot) const; private: virtual absl::StatusOr<std::unique_ptr<BoundOperator>> DoBind( absl::Span<const TypedSlot> input_slots, TypedSlot output_slot) const = 0; std::string name_; const QExprOperatorSignature* signature_; }; class InlineOperator : public QExprOperator { using QExprOperator::QExprOperator; }; absl::StatusOr<TypedValue> InvokeOperator(const QExprOperator& op, absl::Span<const TypedValue> args); absl::StatusOr<TypedValue> InvokeOperator(absl::string_view op_name, absl::Span<const TypedValue> args, QTypePtr output_qtype); template <typename OutputType, typename... InputTypes> absl::StatusOr<OutputType> InvokeOperator(absl::string_view op_name, InputTypes&&... inputs) { ASSIGN_OR_RETURN( auto output, InvokeOperator( op_name, {TypedValue::FromValue(std::forward<InputTypes>(inputs))...}, GetQType<OutputType>())); ASSIGN_OR_RETURN(auto result_ref, output.template As<OutputType>()); return result_ref.get(); } using OperatorPtr = std::shared_ptr<const QExprOperator>; class OperatorFamily { public: virtual ~OperatorFamily() = default; absl::StatusOr<OperatorPtr> GetOperator( absl::Span<const QTypePtr> input_types, QTypePtr output_type) const { return DoGetOperator(input_types, output_type); } private: virtual absl::StatusOr<OperatorPtr> DoGetOperator( absl::Span<const QTypePtr> input_types, QTypePtr output_type) const = 0; }; absl::StatusOr<OperatorPtr> EnsureOutputQTypeMatches( absl::StatusOr<OperatorPtr> op_or, absl::Span<const QTypePtr> input_types, QTypePtr output_type); class OperatorDirectory { public: absl::StatusOr<OperatorPtr> LookupOperator( absl::string_view name, absl::Span<const QTypePtr> input_types, QTypePtr output_type) const { return DoLookupOperator(name, input_types, output_type); } virtual ~OperatorDirectory() = default; private: virtual absl::StatusOr<OperatorPtr> DoLookupOperator( absl::string_view name, absl::Span<const QTypePtr> input_types, QTypePtr output_type) const = 0; }; class OperatorRegistry final : public OperatorDirectory { public: absl::Status RegisterOperatorFamily( absl::string_view name, std::unique_ptr<OperatorFamily> operation); absl::Status RegisterOperator(OperatorPtr op); std::vector<std::string> ListRegisteredOperators(); static OperatorRegistry* GetInstance(); private: absl::StatusOr<OperatorPtr> DoLookupOperator( absl::string_view name, absl::Span<const QTypePtr> input_types, QTypePtr output_type) const final; absl::StatusOr<const OperatorFamily*> LookupOperatorFamily( absl::string_view name) const; absl::flat_hash_map<std::string, std::unique_ptr<OperatorFamily>> families_ ABSL_GUARDED_BY(mutex_); mutable absl::Mutex mutex_; }; constexpr absl::string_view kCoreOperatorsNamespace = "core"; template <typename T> int RegisterOperatorFamily(absl::string_view name) { auto status = OperatorRegistry::GetInstance()->RegisterOperatorFamily( name, std::make_unique<T>()); if (!status.ok()) { LOG(FATAL) << status; } return 57; } } #endif #include "arolla/qexpr/operators.h" #include <cstddef> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/log/log.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "absl/synchronization/mutex.h" #include "absl/types/span.h" #include "arolla/memory/frame.h" #include "arolla/qexpr/casting.h" #include "arolla/qexpr/eval_context.h" #include "arolla/qexpr/operator_errors.h" #include "arolla/qexpr/qexpr_operator_signature.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_slot.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/indestructible.h" #include "arolla/util/operator_name.h" #include "arolla/util/status_macros_backport.h" namespace arolla { namespace { class CombinedOperatorFamily : public OperatorFamily { public: explicit CombinedOperatorFamily(std::string name) : name_(std::move(name)) {} absl::StatusOr<OperatorPtr> DoGetOperator( absl::Span<const QTypePtr> input_types, QTypePtr output_type) const override { auto it = operators_.find(input_types); if (it != operators_.end() && it->second->signature()->output_type() == output_type) { return it->second; } ASSIGN_OR_RETURN(const QExprOperatorSignature* matching_signature, FindMatchingSignature( QExprOperatorSignature::Get(input_types, output_type), supported_signatures_, name_)); return operators_.at(matching_signature->input_types()); } absl::Status Insert(OperatorPtr op) { auto* signature = op->signature(); if (!operators_.emplace(signature->input_types(), std::move(op)).second) { return absl::OkStatus(); } supported_signatures_.push_back(signature); return absl::OkStatus(); } private: std::string name_; absl::flat_hash_map<absl::Span<const QTypePtr>, OperatorPtr> operators_; std::vector<const QExprOperatorSignature*> supported_signatures_; }; } absl::Status OperatorRegistry::RegisterOperatorFamily( absl::string_view name, std::unique_ptr<OperatorFamily> operation) { absl::WriterMutexLock lock(&mutex_); if (!IsOperatorName(name)) { return absl::InvalidArgumentError( absl::StrFormat("incorrect operator name \"%s\"", name)); } auto inserted = families_.emplace(name, std::move(operation)); if (!inserted.second) { return absl::Status( absl::StatusCode::kAlreadyExists, absl::StrFormat( "trying to register non-static QExpr operator family %s twice", name)); } return absl::OkStatus(); } absl::Status OperatorRegistry::RegisterOperator(OperatorPtr op) { absl::WriterMutexLock lock(&mutex_); if (!IsOperatorName(op->name())) { return absl::InvalidArgumentError( absl::StrFormat("incorrect operator name \"%s\"", op->name())); } auto found = families_.find(op->name()); if (found == families_.end()) { auto inserted = families_.emplace( op->name(), std::make_unique<CombinedOperatorFamily>(std::string(op->name()))); found = inserted.first; } if (auto* combined_family = dynamic_cast<CombinedOperatorFamily*>(found->second.get())) { return combined_family->Insert(std::move(op)); } else { return absl::Status( absl::StatusCode::kAlreadyExists, absl::StrFormat("trying to register a single QExpr operator and an " "operator family under the same name %s", op->name())); } } std::vector<std::string> OperatorRegistry::ListRegisteredOperators() { absl::ReaderMutexLock lock(&mutex_); std::vector<std::string> names; names.reserve(families_.size()); for (const auto& [name, family] : families_) { names.push_back(name); } return names; } absl::StatusOr<const OperatorFamily*> OperatorRegistry::LookupOperatorFamily( absl::string_view name) const { absl::ReaderMutexLock lock(&mutex_); auto iter = families_.find(name); if (iter == families_.end()) { return absl::Status(absl::StatusCode::kNotFound, absl::StrFormat("QExpr operator %s not found; %s", name, SuggestMissingDependency())); } return iter->second.get(); } absl::StatusOr<OperatorPtr> OperatorRegistry::DoLookupOperator( absl::string_view name, absl::Span<const QTypePtr> input_types, QTypePtr output_type) const { ASSIGN_OR_RETURN(auto family, LookupOperatorFamily(name)); return family->GetOperator(input_types, output_type); } OperatorRegistry* OperatorRegistry::GetInstance() { static Indestructible<OperatorRegistry> instance( [](auto* self) { new (self) OperatorRegistry; }); return instance.get(); } namespace { struct BoundOperatorState { std::unique_ptr<BoundOperator> op; std::vector<TypedSlot> input_slots; TypedSlot output_slot; FrameLayout layout; }; absl::StatusOr<BoundOperatorState> BindToNewLayout(const QExprOperator& op) { FrameLayout::Builder layout_builder; auto input_slots = AddSlots(op.signature()->input_types(), &layout_builder); auto output_slot = AddSlot(op.signature()->output_type(), &layout_builder); ASSIGN_OR_RETURN(auto bound_op, op.Bind(input_slots, output_slot)); return BoundOperatorState{std::move(bound_op), input_slots, output_slot, std::move(layout_builder).Build()}; } absl::Status VerifyOperatorSlots(const QExprOperator& op, absl::Span<const TypedSlot> input_slots, TypedSlot output_slot) { auto signature = op.signature(); RETURN_IF_ERROR( VerifyInputSlotTypes(input_slots, signature->input_types(), op.name())); return VerifyOutputSlotType(output_slot, signature->output_type(), op.name()); } } absl::StatusOr<OperatorPtr> EnsureOutputQTypeMatches( absl::StatusOr<OperatorPtr> op_or, absl::Span<const QTypePtr> input_types, QTypePtr output_type) { ASSIGN_OR_RETURN(auto op, op_or); if (op->signature()->output_type() != output_type) { return absl::Status( absl::StatusCode::kNotFound, absl::StrFormat( "operator %s%s->%s not found: unexpected output type %s", op->name(), FormatTypeVector(input_types), output_type->name(), op->signature()->output_type()->name())); } return op; } absl::StatusOr<TypedValue> InvokeOperator(const QExprOperator& op, absl::Span<const TypedValue> args) { RETURN_IF_ERROR( VerifyInputValueTypes(args, op.signature()->input_types(), op.name())); ASSIGN_OR_RETURN(auto bound, BindToNewLayout(op)); RootEvaluationContext root_ctx(&bound.layout); for (size_t i = 0; i < args.size(); ++i) { RETURN_IF_ERROR(args[i].CopyToSlot(bound.input_slots[i], root_ctx.frame())); } EvaluationContext ctx(root_ctx); bound.op->Run(&ctx, root_ctx.frame()); if (!ctx.status().ok()) { return std::move(ctx).status(); } return TypedValue::FromSlot(bound.output_slot, root_ctx.frame()); } absl::StatusOr<TypedValue> InvokeOperator(absl::string_view op_name, absl::Span<const TypedValue> args, QTypePtr output_qtype) { std::vector<QTypePtr> arg_types; arg_types.reserve(args.size()); for (const auto& arg : args) { arg_types.push_back(arg.GetType()); } ASSIGN_OR_RETURN(auto op, OperatorRegistry::GetInstance()->LookupOperator( op_name, arg_types, output_qtype)); return InvokeOperator(*op, args); } absl::StatusOr<std::unique_ptr<BoundOperator>> QExprOperator::Bind( absl::Span<const TypedSlot> input_slots, TypedSlot output_slot) const { RETURN_IF_ERROR(VerifyOperatorSlots(*this, input_slots, output_slot)); return DoBind(input_slots, output_slot); } }
#include "arolla/qexpr/operators.h" #include <algorithm> #include <cstdint> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/strings/str_cat.h" #include "arolla/codegen/qexpr/testing/test_operators.h" #include "arolla/memory/frame.h" #include "arolla/qexpr/eval_context.h" #include "arolla/qexpr/qexpr_operator_signature.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/tuple_qtype.h" #include "arolla/qtype/typed_slot.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla { namespace { using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::testing::ContainsRegex; using ::testing::ElementsAre; using ::testing::Eq; using ::testing::HasSubstr; using ::testing::Property; class OperatorsTest : public ::testing::Test { void SetUp() final { ASSERT_OK(InitArolla()); } }; TEST_F(OperatorsTest, LookupTestOperator) { QTypePtr f32_type = GetQType<float>(); auto op = OperatorRegistry::GetInstance() ->LookupOperator("test.add", {f32_type, f32_type}, f32_type) .value(); EXPECT_EQ(op->signature(), QExprOperatorSignature::Get({f32_type, f32_type}, f32_type)); FrameLayout::Builder layout_builder; auto arg1_slot = layout_builder.AddSlot<float>(); auto arg2_slot = layout_builder.AddSlot<float>(); auto result_slot = layout_builder.AddSlot<float>(); auto bound_op = op->Bind(ToTypedSlots(arg1_slot, arg2_slot), TypedSlot::FromSlot(result_slot)) .value(); FrameLayout memory_layout = std::move(layout_builder).Build(); RootEvaluationContext root_ctx(&memory_layout); EvaluationContext ctx(root_ctx); root_ctx.Set(arg1_slot, 2.0f); root_ctx.Set(arg2_slot, 3.0f); bound_op->Run(&ctx, root_ctx.frame()); EXPECT_OK(ctx.status()); float result = root_ctx.Get(result_slot); EXPECT_THAT(result, Eq(5.0f)); } TEST_F(OperatorsTest, LookupOperator_WithOutputType) { QTypePtr f32_type = GetQType<float>(); auto op_float = OperatorRegistry::GetInstance() ->LookupOperator("test.add", {f32_type, f32_type}, f32_type) .value(); EXPECT_EQ(op_float->signature(), QExprOperatorSignature::Get({f32_type, f32_type}, f32_type)); QTypePtr f64_type = GetQType<float>(); auto op_double = OperatorRegistry::GetInstance() ->LookupOperator("test.add", {f32_type, f32_type}, f64_type) .value(); EXPECT_EQ(op_double->signature(), QExprOperatorSignature::Get({f64_type, f64_type}, f64_type)); EXPECT_THAT( OperatorRegistry::GetInstance()->LookupOperator( "test.add", {f32_type, f32_type}, GetQType<int32_t>()), StatusIs( absl::StatusCode::kNotFound, HasSubstr( "QExpr operator test.add(FLOAT32,FLOAT32)->INT32 not found"))); } TEST_F(OperatorsTest, Bind) { QTypePtr float_type = GetQType<float>(); auto op = OperatorRegistry::GetInstance() ->LookupOperator("test.add", {float_type, float_type}, float_type) .value(); EXPECT_EQ(op->signature(), QExprOperatorSignature::Get({float_type, float_type}, float_type)); FrameLayout::Builder layout_builder; auto arg1_slot = layout_builder.AddSlot<float>(); auto arg2_slot = layout_builder.AddSlot<float>(); auto double_slot = layout_builder.AddSlot<double>(); auto result_slot = layout_builder.AddSlot<float>(); auto bound_op = op->Bind(ToTypedSlots(arg1_slot, arg2_slot), TypedSlot::FromSlot(result_slot)) .value(); EXPECT_THAT( op->Bind(ToTypedSlots(arg1_slot), TypedSlot::FromSlot(result_slot)), StatusIs(absl::StatusCode::kFailedPrecondition, "incorrect input types for operator test.add: expected " "(FLOAT32,FLOAT32), got (FLOAT32)")); EXPECT_THAT(op->Bind(ToTypedSlots(arg1_slot, double_slot), TypedSlot::FromSlot(result_slot)), StatusIs(absl::StatusCode::kFailedPrecondition, "incorrect input types for operator test.add: expected " "(FLOAT32,FLOAT32), got (FLOAT32,FLOAT64)")); EXPECT_THAT(op->Bind(ToTypedSlots(arg1_slot, arg2_slot), TypedSlot::FromSlot(double_slot)), StatusIs(absl::StatusCode::kFailedPrecondition, "incorrect output types for operator test.add: " "expected (FLOAT32), got (FLOAT64)")); FrameLayout memory_layout = std::move(layout_builder).Build(); RootEvaluationContext root_ctx(&memory_layout); EvaluationContext ctx(root_ctx); root_ctx.Set(arg1_slot, 2.0f); root_ctx.Set(arg2_slot, 3.0f); bound_op->Run(&ctx, root_ctx.frame()); EXPECT_OK(ctx.status()); float result = root_ctx.Get(result_slot); EXPECT_THAT(result, Eq(5.0f)); } TEST_F(OperatorsTest, TestUserDefinedDataType) { QTypePtr f64_type = GetQType<double>(); QTypePtr v3_type = GetQType<testing::Vector3<double>>(); auto op1 = OperatorRegistry::GetInstance() ->LookupOperator("test.vector3", {f64_type, f64_type, f64_type}, v3_type) .value(); EXPECT_EQ(op1->signature(), QExprOperatorSignature::Get( {f64_type, f64_type, f64_type}, v3_type)); auto op2 = OperatorRegistry::GetInstance() ->LookupOperator("test.dot_prod", {v3_type, v3_type}, f64_type) .value(); EXPECT_EQ(op2->signature(), QExprOperatorSignature::Get({v3_type, v3_type}, f64_type)); FrameLayout::Builder layout_builder; auto x_slot = layout_builder.AddSlot<double>(); auto y_slot = layout_builder.AddSlot<double>(); auto z_slot = layout_builder.AddSlot<double>(); auto v_slot = layout_builder.AddSlot<testing::Vector3<double>>(); auto v_typed_slot = TypedSlot::FromSlot(v_slot, v3_type); auto result_slot = layout_builder.AddSlot<double>(); auto bound_op1 = op1->Bind(ToTypedSlots(x_slot, y_slot, z_slot), v_typed_slot).value(); auto bound_op2 = op2->Bind({v_typed_slot, v_typed_slot}, TypedSlot::FromSlot(result_slot)) .value(); FrameLayout memory_layout = std::move(layout_builder).Build(); RootEvaluationContext root_ctx(&memory_layout); EvaluationContext ctx(root_ctx); root_ctx.Set(x_slot, 3.0); root_ctx.Set(y_slot, 4.0); root_ctx.Set(z_slot, 5.0); bound_op1->Run(&ctx, root_ctx.frame()); EXPECT_OK(ctx.status()); bound_op2->Run(&ctx, root_ctx.frame()); EXPECT_OK(ctx.status()); double result = root_ctx.Get(result_slot); EXPECT_THAT(result, Eq(50.0)); } TEST_F(OperatorsTest, OperatorNotFound) { auto error = OperatorRegistry::GetInstance()->LookupOperator( "test.halts", {}, GetQType<int64_t>()); EXPECT_THAT(error, StatusIs(absl::StatusCode::kNotFound, ContainsRegex( "QExpr operator test.halts not found; adding " "\".*\" build dependency may help"))); } TEST_F(OperatorsTest, OperatorOverloadNotFound) { QTypePtr bool_type = GetQType<bool>(); QTypePtr float_type = GetQType<float>(); EXPECT_THAT( OperatorRegistry::GetInstance()->LookupOperator( "test.add", {bool_type, float_type}, float_type), StatusIs( absl::StatusCode::kNotFound, ContainsRegex("QExpr operator test.add\\(BOOLEAN,FLOAT32\\)->FLOAT32 " "not found; adding \".*\" build dependency may help"))); } TEST_F(OperatorsTest, InvokeOperator) { ASSERT_OK_AND_ASSIGN( auto mul_op, OperatorRegistry::GetInstance()->LookupOperator( "test.mul", {GetQType<int64_t>(), GetQType<int64_t>()}, GetQType<int64_t>())); EXPECT_THAT( InvokeOperator(*mul_op, {TypedValue::FromValue(int64_t{3}), TypedValue::FromValue(int64_t{19})}), IsOkAndHolds(Property(&TypedValue::As<int64_t>, IsOkAndHolds(Eq(57))))); EXPECT_THAT(InvokeOperator(*mul_op, {TypedValue::FromValue(3.0), TypedValue::FromValue(int64_t{19})}), StatusIs(absl::StatusCode::kFailedPrecondition, "incorrect input types for operator test.mul: expected " "(INT64,INT64), got (FLOAT64,INT64)")); } TEST_F(OperatorsTest, QExprOperatorSignatureTypeAndName) { auto i32 = GetQType<int32_t>(); auto f64 = GetQType<double>(); auto fn = QExprOperatorSignature::Get({i32}, f64); EXPECT_EQ(absl::StrCat(fn), "(INT32)->FLOAT64"); } TEST_F(OperatorsTest, GetQExprOperatorSignature) { auto i32 = GetQType<int32_t>(); auto f64 = GetQType<double>(); const QExprOperatorSignature* fn = QExprOperatorSignature::Get({i32}, f64); EXPECT_THAT(fn->input_types(), ElementsAre(i32)); EXPECT_THAT(fn->output_type(), Eq(f64)); } TEST_F(OperatorsTest, QExprOperatorSignatureInputsAreStored) { auto i32 = GetQType<int32_t>(); std::vector<QTypePtr> types(100, i32); auto fn_type = QExprOperatorSignature::Get(types, i32); auto f64 = GetQType<double>(); std::fill(types.begin(), types.end(), f64); std::vector<QTypePtr> types2(100, i32); auto fn2_type = QExprOperatorSignature::Get(types2, i32); ASSERT_EQ(fn_type, fn2_type); } TEST_F(OperatorsTest, QExprOperatorSignatureSingleton) { auto i32 = GetQType<int32_t>(); auto f64 = GetQType<double>(); EXPECT_TRUE(QExprOperatorSignature::Get({f64}, i32) == QExprOperatorSignature::Get({f64}, i32)); auto get_complex_fn = [&]() { return QExprOperatorSignature::Get({f64, i32, MakeTupleQType({f64, i32})}, MakeTupleQType({f64, i32, f64})); }; EXPECT_TRUE(get_complex_fn() == get_complex_fn()); } } }
2,371
#ifndef AROLLA_QEXPR_OPERATORS_DENSE_ARRAY_DENSE_ARRAY_OPS_H_ #define AROLLA_QEXPR_OPERATORS_DENSE_ARRAY_DENSE_ARRAY_OPS_H_ #include <algorithm> #include <cstddef> #include <cstdint> #include <optional> #include <utility> #include "absl/base/optimization.h" #include "absl/container/flat_hash_set.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/types/span.h" #include "arolla/dense_array/bitmap.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/ops/dense_ops.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/memory/buffer.h" #include "arolla/memory/optional_value.h" #include "arolla/qexpr/eval_context.h" #include "arolla/util/unit.h" #include "arolla/util/view_types.h" #include "arolla/util/status_macros_backport.h" namespace arolla { struct DenseArrayAtOp { template <typename T> OptionalValue<T> operator()(EvaluationContext* ctx, const DenseArray<T>& arr, int64_t id) const { if (ABSL_PREDICT_FALSE(id < 0 || id >= arr.size())) { ReportIndexOutOfRangeError(ctx, id, arr.size()); return std::nullopt; } return {arr.present(id), T{arr.values[id]}}; } template <typename T> OptionalValue<T> operator()(EvaluationContext* ctx, const DenseArray<T>& arr, OptionalValue<int64_t> id) const { return id.present ? (*this)(ctx, arr, id.value) : std::nullopt; } template <typename T> DenseArray<T> operator()(EvaluationContext* ctx, const DenseArray<T>& arr, const DenseArray<int64_t>& ids) const { auto fn = [ctx, &arr](int64_t id) -> OptionalValue<view_type_t<T>> { if (ABSL_PREDICT_FALSE(id < 0 || id >= arr.size())) { ReportIndexOutOfRangeError(ctx, id, arr.size()); return std::nullopt; } if (!arr.present(id)) { return std::nullopt; } return arr.values[id]; }; auto op = CreateDenseOp<DenseOpFlags::kNoBitmapOffset, decltype(fn), T>( fn, &ctx->buffer_factory()); return op(ids); } private: static void ReportIndexOutOfRangeError(EvaluationContext* ctx, int64_t index, int64_t size); }; struct DenseArraySliceOp { template <typename T> absl::StatusOr<DenseArray<T>> operator()(EvaluationContext* ctx, const DenseArray<T>& array, int64_t offset, int64_t size) const { if (offset < 0 || offset > array.size()) { return absl::InvalidArgumentError(absl::StrFormat( "expected `offset` in [0, %d], but got %d", array.size(), offset)); } if (size < -1 || size > array.size() - offset) { return absl::InvalidArgumentError( absl::StrFormat("expected `size` in [0, %d], but got %d", array.size() - offset, size)); } if (size == -1) { size = array.size() - offset; } return array.Slice(offset, size) .ForceNoBitmapBitOffset(&ctx->buffer_factory()); } }; struct DenseArrayConcatOp { template <typename T> DenseArray<T> operator()(EvaluationContext* ctx, const DenseArray<T>& arr1, const DenseArray<T>& arr2) const { typename Buffer<T>::Builder values_bldr(arr1.size() + arr2.size(), &ctx->buffer_factory()); auto values_inserter = values_bldr.GetInserter(); for (const auto& v : arr1.values) values_inserter.Add(v); for (const auto& v : arr2.values) values_inserter.Add(v); if (arr1.bitmap.empty() && arr2.bitmap.empty()) { return {std::move(values_bldr).Build()}; } size_t bitmap_size = bitmap::BitmapSize(arr1.size() + arr2.size()); bitmap::Bitmap::Builder bitmap_bldr(bitmap_size, &ctx->buffer_factory()); absl::Span<bitmap::Word> bitmap = bitmap_bldr.GetMutableSpan(); std::fill(bitmap.begin(), bitmap.end(), bitmap::kFullWord); if (!arr1.bitmap.empty()) { CopyBits<bitmap::Word>(arr1.size(), arr1.bitmap.begin(), arr1.bitmap_bit_offset, bitmap.begin(), 0); } if (!arr2.bitmap.empty()) { size_t offset = arr1.size(); CopyBits<bitmap::Word>(arr2.size(), arr2.bitmap.begin(), arr2.bitmap_bit_offset, bitmap.begin() + offset / bitmap::kWordBitCount, offset % bitmap::kWordBitCount); } return {std::move(values_bldr).Build(), std::move(bitmap_bldr).Build()}; } }; class DenseArrayPresentIndicesOp { public: DenseArray<int64_t> operator()(EvaluationContext* ctx, const DenseArray<Unit>& input) const { const int64_t count = bitmap::CountBits(input.bitmap, input.bitmap_bit_offset, input.size()); Buffer<int64_t>::Builder buffer_builder(count, &ctx->buffer_factory()); auto inserter = buffer_builder.GetInserter(); input.ForEach([&](int64_t index, bool present, const auto& ) { if (present) { inserter.Add(index); } }); return DenseArray<int64_t>{std::move(buffer_builder).Build(count)}; } }; class DenseArrayPresentValuesOp { public: template <typename T> DenseArray<T> operator()(EvaluationContext* ctx, const DenseArray<T>& input) const { const int64_t count = bitmap::CountBits(input.bitmap, input.bitmap_bit_offset, input.size()); typename Buffer<T>::Builder buffer_builder(count, &ctx->buffer_factory()); auto inserter = buffer_builder.GetInserter(); input.ForEach([&](int64_t , bool present, const auto& value) { if (present) { inserter.Add(value); } }); return DenseArray<T>{std::move(buffer_builder).Build(count)}; } }; class DenseArrayFromIndicesAndValues { public: template <typename T> DenseArray<T> operator()(EvaluationContext* ctx, const DenseArray<int64_t>& indices, const DenseArray<T>& values, int64_t size) const { if (!ValidateInputs(ctx, indices, values.size(), size)) { return DenseArray<T>{Buffer<T>(), Buffer<bitmap::Word>()}; } DenseArrayBuilder<T> builder(size, &ctx->buffer_factory()); const int64_t n = indices.size(); for (int64_t i = 0; i < n; ++i) { if (values.present(i)) { builder.Set(indices.values[i], values.values[i]); } } return std::move(builder).Build(); } private: static bool ValidateInputs(EvaluationContext* ctx, const DenseArray<int64_t>& indices, int64_t values_size, int64_t size); }; struct DenseArrayUniqueOp { template <typename T> DenseArray<T> operator()(EvaluationContext* ctx, const DenseArray<T>& input) const { typename Buffer<T>::Builder bldr(input.size(), &ctx->buffer_factory()); auto inserter = bldr.GetInserter(); absl::flat_hash_set<view_type_t<T>> unique_values; input.ForEachPresent([&](int64_t , const auto& value) { if (auto [it, inserted] = unique_values.insert(value); inserted) { inserter.Add(value); } }); return DenseArray<T>{std::move(bldr).Build(unique_values.size())}; } }; struct DenseArraySelectOp { template <typename T> absl::StatusOr<DenseArray<T>> operator()( EvaluationContext* ctx, const DenseArray<T>& input, const DenseArray<Unit>& filter) const { if (ABSL_PREDICT_FALSE(input.size() != filter.size())) { return SizeMismatchError({input.size(), filter.size()}); } if (filter.bitmap.empty()) { return input; } const int64_t count = filter.PresentCount(); if (count == 0) { return DenseArray<T>(); } DenseArrayBuilder<T> builder(count); int64_t offset = 0; using view_type = arolla::view_type_t<T>; auto fn = [&](int64_t id, Unit mask, OptionalValue<view_type> value) { builder.Set(offset++, value); }; RETURN_IF_ERROR(DenseArraysForEachPresent(fn, filter, input)); return std::move(builder).Build(); } }; } #endif #include "arolla/qexpr/operators/dense_array/array_ops.h" #include <cstdint> #include "absl/status/status.h" #include "absl/strings/str_format.h" #include "arolla/dense_array/dense_array.h" #include "arolla/qexpr/eval_context.h" namespace arolla { void DenseArrayAtOp::ReportIndexOutOfRangeError(EvaluationContext* ctx, int64_t index, int64_t size) { if (ctx->status().ok()) { ctx->set_status(absl::InvalidArgumentError( absl::StrFormat("array index %d out of range [0, %d)", index, size))); } } bool DenseArrayFromIndicesAndValues::ValidateInputs( EvaluationContext* ctx, const DenseArray<int64_t>& indices, int64_t values_size, int64_t size) { if (indices.size() != values_size) { ctx->set_status(absl::InvalidArgumentError( absl::StrFormat("expected arrays of the same sizes, got " "indices.size=%d, values.size=%d", indices.size(), values_size))); return false; } if (size < 0) { ctx->set_status(absl::InvalidArgumentError( absl::StrFormat("expected a non-negative integer, got size=%d", size))); return false; } if (!indices.IsFull()) { ctx->set_status( absl::InvalidArgumentError("missing indices are not supported")); return false; } int64_t last_index = -1; for (int64_t index : indices.values) { if (index <= last_index) { if (index < 0) { ctx->set_status(absl::InvalidArgumentError(absl::StrFormat( "expected non-negative indices, got index=%d", index))); return false; } else { ctx->set_status(absl::InvalidArgumentError( absl::StrFormat("expected a strictly increasing sequence of " "indices, got [..., %d, %d, ...]", last_index, index))); return false; } } else if (index >= size) { ctx->set_status(absl::InvalidArgumentError(absl::StrFormat( "index is out of range, index=%d >= size=%d", index, size))); return false; } last_index = index; } return true; } }
#include <cstdint> #include <optional> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/edge.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/memory/optional_value.h" #include "arolla/qexpr/operators.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla::testing { namespace { using ::arolla::testing::StatusIs; using ::testing::ElementsAre; class ArrayOpsTest : public ::testing::Test { void SetUp() final { ASSERT_OK(InitArolla()); } }; TEST_F(ArrayOpsTest, DenseArrayAtOp) { using OF = OptionalValue<float>; using OI = OptionalValue<int64_t>; auto arr = CreateDenseArray<float>({1, 2, 3, std::nullopt}); EXPECT_THAT(InvokeOperator<OF>("array.at", arr, int64_t{1}), IsOkAndHolds(OF(2))); EXPECT_THAT(InvokeOperator<OF>("array.at", arr, OI(2)), IsOkAndHolds(OF(3))); EXPECT_THAT(InvokeOperator<OF>("array.at", arr, OI(3)), IsOkAndHolds(OF())); EXPECT_THAT(InvokeOperator<OF>("array.at", arr, OI(4)), StatusIs(absl::StatusCode::kInvalidArgument, "array index 4 out of range [0, 4)")); EXPECT_THAT(InvokeOperator<OF>("array.at", arr, OI(-1)), StatusIs(absl::StatusCode::kInvalidArgument, "array index -1 out of range [0, 4)")); EXPECT_THAT(InvokeOperator<OF>("array.at", arr, OI()), IsOkAndHolds(OF())); EXPECT_THAT( InvokeOperator<DenseArray<float>>( "array.at", arr, CreateDenseArray<int64_t>({2, 3, std::nullopt, 0})), IsOkAndHolds(ElementsAre(3.f, std::nullopt, std::nullopt, 1.f))); EXPECT_THAT( InvokeOperator<DenseArray<float>>( "array.at", arr, CreateDenseArray<int64_t>({2, 3, std::nullopt, 4})), StatusIs(absl::StatusCode::kInvalidArgument, "array index 4 out of range [0, 4)")); } TEST_F(ArrayOpsTest, TestArrayTakeOver) { auto x = CreateDenseArray<int>({1, 2, 3, std::nullopt, 5, 6, 7, 8}); auto offsets = CreateDenseArray<int64_t>({0, 3, 2, 1, 4, 5, 6, std::nullopt}); auto splits = CreateDenseArray<int64_t>({0, 8}); ASSERT_OK_AND_ASSIGN(auto edge, DenseArrayEdge::FromSplitPoints(splits)); EXPECT_THAT( InvokeOperator<DenseArray<int>>("array._take_over", x, offsets, edge), IsOkAndHolds(ElementsAre(1, std::nullopt, 3, 2, 5, 6, 7, std::nullopt))); } TEST_F(ArrayOpsTest, TestArrayTakeOverSplitPoints) { auto x = CreateDenseArray<int>({1, 2, 3, std::nullopt, 5, 6, 7, 8}); auto offsets = CreateDenseArray<int64_t>({0, 2, 1, 0, 1, 1, 0, std::nullopt}); auto splits = CreateDenseArray<int64_t>({0, 3, 3, 5, 7, 8}); ASSERT_OK_AND_ASSIGN(auto edge, DenseArrayEdge::FromSplitPoints(splits)); EXPECT_THAT( InvokeOperator<DenseArray<int>>("array._take_over", x, offsets, edge), IsOkAndHolds(ElementsAre(1, 3, 2, std::nullopt, 5, 7, 6, std::nullopt))); } TEST_F(ArrayOpsTest, TestArrayTakeMapping) { auto x = CreateDenseArray<int>({1, 2, 3, std::nullopt, 5, 6, 7, 8}); auto offsets = CreateDenseArray<int64_t>({0, 2, 1, 0, 1, 1, 0, std::nullopt}); auto mapping = CreateDenseArray<int64_t>({0, 1, 1, 1, 1, 0, std::nullopt, 0}); ASSERT_OK_AND_ASSIGN(auto edge, DenseArrayEdge::FromMapping(mapping, 3)); EXPECT_THAT( InvokeOperator<DenseArray<int>>("array._take_over", x, offsets, edge), IsOkAndHolds(ElementsAre(1, std::nullopt, 3, 2, 3, 6, std::nullopt, std::nullopt))); } TEST_F(ArrayOpsTest, TestArrayTakeOverErrors) { auto x = CreateDenseArray<int>({1, 2, 3, std::nullopt, 5, 6, 7, 8}); auto offsets = CreateDenseArray<int64_t>({0, 2, 1, 0, 1, 1, 0, std::nullopt}); auto splits = CreateDenseArray<int64_t>({0, 1}); ASSERT_OK_AND_ASSIGN(auto edge, DenseArrayEdge::FromSplitPoints(splits)); EXPECT_THAT( InvokeOperator<DenseArray<int>>("array._take_over", x, offsets, edge), StatusIs(absl::StatusCode::kInvalidArgument, ::testing::HasSubstr("argument sizes mismatch"))); x = CreateDenseArray<int>({1}); EXPECT_THAT( InvokeOperator<DenseArray<int>>("array._take_over", x, offsets, edge), StatusIs(absl::StatusCode::kInvalidArgument, ::testing::HasSubstr("argument sizes mismatch"))); } TEST_F(ArrayOpsTest, TestArrayTakeOverOver) { auto x = CreateDenseArray<int>({1, 2, 3, std::nullopt, 5, 6, 7, 8}); auto offsets = CreateDenseArray<int64_t>({0, 3, 1, 3, 1, std::nullopt}); auto x_splits = CreateDenseArray<int64_t>({0, 4, 8}); ASSERT_OK_AND_ASSIGN(auto x_edge, DenseArrayEdge::FromSplitPoints(x_splits)); auto offsets_splits = CreateDenseArray<int64_t>({0, 3, 6}); ASSERT_OK_AND_ASSIGN(auto offsets_edge, DenseArrayEdge::FromSplitPoints(offsets_splits)); EXPECT_THAT( InvokeOperator<DenseArray<int>>("array._take_over_over", x, offsets, x_edge, offsets_edge), IsOkAndHolds(ElementsAre(1, std::nullopt, 2, 8, 6, std::nullopt))); EXPECT_THAT( InvokeOperator<DenseArray<int>>("array._take_over_over", x, offsets, x_edge, x_edge), StatusIs(absl::StatusCode::kInvalidArgument, ::testing::HasSubstr("argument sizes mismatch: (8, 6)"))); } TEST_F(ArrayOpsTest, Slice) { auto x = CreateDenseArray<int>({1, 2, 3, std::nullopt, 5, 6, 7, 8}); ASSERT_OK_AND_ASSIGN(DenseArray<int> sliced, InvokeOperator<DenseArray<int>>("array.slice", x, int64_t{3}, int64_t{4})); EXPECT_THAT(sliced, ElementsAre(std::nullopt, 5, 6, 7)); EXPECT_EQ(sliced.bitmap_bit_offset, 0); EXPECT_THAT(InvokeOperator<DenseArray<int>>("array.slice", x, int64_t{5}, int64_t{-1}), IsOkAndHolds(ElementsAre(6, 7, 8))); EXPECT_THAT(InvokeOperator<DenseArray<int>>("array.slice", x, int64_t{-3}, int64_t{4}), StatusIs(absl::StatusCode::kInvalidArgument, ::testing::HasSubstr( "expected `offset` in [0, 8], but got -3"))); EXPECT_THAT( InvokeOperator<DenseArray<int>>("array.slice", x, int64_t{3}, int64_t{8}), StatusIs(absl::StatusCode::kInvalidArgument, ::testing::HasSubstr("expected `size` in [0, 5], but got 8"))); } TEST_F(ArrayOpsTest, Concat) { auto x = CreateDenseArray<int>({1, 2, 3}); auto y = CreateDenseArray<int>({std::nullopt, 4}); auto z = CreateDenseArray<int>({}); EXPECT_THAT(InvokeOperator<DenseArray<int>>("array.concat", x, x), IsOkAndHolds(ElementsAre(1, 2, 3, 1, 2, 3))); EXPECT_THAT(InvokeOperator<DenseArray<int>>("array.concat", x, y), IsOkAndHolds(ElementsAre(1, 2, 3, std::nullopt, 4))); EXPECT_THAT(InvokeOperator<DenseArray<int>>("array.concat", y, y), IsOkAndHolds(ElementsAre(std::nullopt, 4, std::nullopt, 4))); EXPECT_THAT(InvokeOperator<DenseArray<int>>("array.concat", x, z), IsOkAndHolds(ElementsAre(1, 2, 3))); EXPECT_THAT(InvokeOperator<DenseArray<int>>("array.concat", z, y), IsOkAndHolds(ElementsAre(std::nullopt, 4))); } } }
2,372
#ifndef AROLLA_QEXPR_OPERATORS_DENSE_ARRAY_FACTORY_OPS_H_ #define AROLLA_QEXPR_OPERATORS_DENSE_ARRAY_FACTORY_OPS_H_ #include <cstdint> #include <numeric> #include <utility> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/types/span.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/memory/buffer.h" #include "arolla/memory/optional_value.h" #include "arolla/qexpr/eval_context.h" #include "arolla/qexpr/operators.h" #include "arolla/qtype/qtype.h" #include "arolla/util/unit.h" namespace arolla { struct DenseArrayShapeOfOp { DenseArrayShape operator()(const DenseArray<Unit>& array) const { return {array.size()}; } }; struct DenseArrayShapeSizeOp { int64_t operator()(DenseArrayShape shape) const { return shape.size; } }; struct DenseArrayResizeShapeOp { absl::StatusOr<DenseArrayShape> operator()(DenseArrayShape, int64_t size) const { if (size < 0) { return absl::InvalidArgumentError(absl::StrFormat("bad size: %d", size)); } return DenseArrayShape{size}; } }; struct DenseArrayConstWithShapeOp { template <typename T> DenseArray<T> operator()(EvaluationContext* ctx, const DenseArrayShape& shape, const T& fill_value) const { return CreateConstDenseArray<T>(shape.size, fill_value, &ctx->buffer_factory()); } template <typename T> DenseArray<T> operator()(EvaluationContext* ctx, const DenseArrayShape& shape, const OptionalValue<T>& fill_value) const { if (fill_value.present) { return CreateConstDenseArray<T>(shape.size, fill_value.value, &ctx->buffer_factory()); } else { return CreateEmptyDenseArray<T>(shape.size, &ctx->buffer_factory()); } } }; struct DenseArrayIotaOp { DenseArray<int64_t> operator()(EvaluationContext* ctx, const DenseArrayShape& shape) const { Buffer<int64_t>::Builder bldr(shape.size, &ctx->buffer_factory()); std::iota(bldr.GetMutableSpan().begin(), bldr.GetMutableSpan().end(), int64_t{0}); return {std::move(bldr).Build()}; } }; class MakeDenseArrayOperatorFamily : public OperatorFamily { absl::StatusOr<OperatorPtr> DoGetOperator( absl::Span<const QTypePtr> input_types, QTypePtr output_type) const final; }; } #endif #include "arolla/qexpr/operators/dense_array/factory_ops.h" #include <cstddef> #include <cstdint> #include <memory> #include <vector> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/types/span.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/memory/frame.h" #include "arolla/memory/optional_value.h" #include "arolla/qexpr/bound_operators.h" #include "arolla/qexpr/eval_context.h" #include "arolla/qexpr/operators.h" #include "arolla/qexpr/qexpr_operator_signature.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/derived_qtype.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/util/bytes.h" #include "arolla/util/text.h" #include "arolla/util/unit.h" #include "arolla/util/status_macros_backport.h" namespace arolla { namespace { template <typename T> class MakeDenseArrayOperator : public QExprOperator { public: explicit MakeDenseArrayOperator(size_t tuple_size) : QExprOperator( "array.make_dense_array", QExprOperatorSignature::Get( std::vector<QTypePtr>(tuple_size, ::arolla::GetQType<T>()), GetDenseArrayQType<strip_optional_t<T>>())) {} private: absl::StatusOr<std::unique_ptr<BoundOperator>> DoBind( absl::Span<const TypedSlot> input_slots, TypedSlot output_slot) const final { return MakeBoundOperator( [input_slots = std::vector<TypedSlot>(input_slots.begin(), input_slots.end()), output_slot](EvaluationContext* ctx, FramePtr frame) { DenseArrayBuilder<strip_optional_t<T>> builder( input_slots.size(), &ctx->buffer_factory()); for (size_t i = 0; i < input_slots.size(); ++i) { const T& value = frame.Get(input_slots[i].UnsafeToSlot<T>()); if constexpr (is_optional_v<T>) { if (value.present) { builder.Add(i, value.value); } } else { builder.Add(i, value); } } frame.Set(output_slot.UnsafeToSlot<DenseArray<strip_optional_t<T>>>(), std::move(builder).Build()); }); } }; absl::StatusOr<OperatorPtr> ConstructMakeDenseArrayOperator(QTypePtr value_type, size_t size) { #define CONSTRUCT_OPERATOR_IF(t) \ if (value_type == GetQType<t>()) { \ return OperatorPtr(std::make_shared<MakeDenseArrayOperator<t>>(size)); \ } CONSTRUCT_OPERATOR_IF(OptionalValue<Unit>); CONSTRUCT_OPERATOR_IF(OptionalValue<bool>); CONSTRUCT_OPERATOR_IF(OptionalValue<int32_t>); CONSTRUCT_OPERATOR_IF(OptionalValue<int64_t>); CONSTRUCT_OPERATOR_IF(OptionalValue<uint64_t>); CONSTRUCT_OPERATOR_IF(OptionalValue<float>); CONSTRUCT_OPERATOR_IF(OptionalValue<double>); CONSTRUCT_OPERATOR_IF(OptionalValue<Bytes>); CONSTRUCT_OPERATOR_IF(OptionalValue<Text>); #undef CONSTRUCT_OPERATOR_IF return absl::UnimplementedError( absl::StrFormat("array.make_dense_array operator is not implemented " "for %s arguments", value_type->name())); } } absl::StatusOr<OperatorPtr> MakeDenseArrayOperatorFamily::DoGetOperator( absl::Span<const QTypePtr> input_types, QTypePtr output_type) const { QTypePtr value_qtype = DecayDerivedQType(output_type)->value_qtype(); if (value_qtype == nullptr) { return absl::InvalidArgumentError(absl::StrFormat( "unexpected return type for array.make_dense_array operator: %s", output_type->name())); } ASSIGN_OR_RETURN(auto arg_type, ToOptionalQType(value_qtype)); return ConstructMakeDenseArrayOperator(arg_type, input_types.size()); } }
#include <cstdint> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/memory/buffer.h" #include "arolla/qexpr/operators.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/unit.h" namespace arolla { namespace { using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::testing::ElementsAre; using ::testing::Eq; class FactoryOpsTest : public ::testing::Test { protected: void SetUp() final { ASSERT_OK(InitArolla()); } }; TEST_F(FactoryOpsTest, DenseArrayShapeOfOp) { EXPECT_THAT(InvokeOperator<DenseArrayShape>("core._array_shape_of", DenseArray<Unit>{VoidBuffer(3)}), IsOkAndHolds(DenseArrayShape{3})); } TEST_F(FactoryOpsTest, DenseArrayConstWithShapeOp) { ASSERT_OK_AND_ASSIGN(auto res, InvokeOperator<DenseArray<int>>( "core.const_with_shape._array_shape", DenseArrayShape{3}, 57)); EXPECT_THAT(res, ElementsAre(57, 57, 57)); } TEST_F(FactoryOpsTest, ArrayShapeSize_DenseArray) { EXPECT_THAT( InvokeOperator<int64_t>("array.array_shape_size", DenseArrayShape{3}), IsOkAndHolds(Eq(3))); } TEST_F(FactoryOpsTest, ResizeArrayShape_DenseArray) { EXPECT_THAT(InvokeOperator<DenseArrayShape>("array.resize_array_shape", DenseArrayShape{3}, int64_t{5}), IsOkAndHolds(DenseArrayShape{5})); EXPECT_THAT(InvokeOperator<DenseArrayShape>("array.resize_array_shape", DenseArrayShape{3}, int64_t{-1}), StatusIs(absl::StatusCode::kInvalidArgument, "bad size: -1")); } } }
2,373
#ifndef AROLLA_QEXPR_OPERATORS_STRINGS_JOIN_H_ #define AROLLA_QEXPR_OPERATORS_STRINGS_JOIN_H_ #include <type_traits> #include "absl/status/statusor.h" #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/memory/optional_value.h" #include "arolla/qexpr/operators.h" #include "arolla/qtype/qtype.h" #include "arolla/util/bytes.h" #include "arolla/util/text.h" namespace arolla { constexpr absl::string_view kJoinOperatorName = "strings._join_with_separator"; class JoinOperatorFamily : public OperatorFamily { public: template <class Delimiter, class... Args> auto operator()(const Delimiter& delimiter, const Args&... args) const { static_assert(sizeof...(Args) > 0, "expected at least 2 arguments"); static_assert( std::is_same_v<Delimiter, Bytes> || std::is_same_v<Delimiter, Text>, "delimiter must be either Bytes or Text"); auto fn = [&delimiter](const strip_optional_t<Args>&... args) { return Delimiter(absl::StrJoin({args...}, delimiter)); }; if constexpr ((::arolla::is_optional_v<Args> || ...)) { return WrapFnToAcceptOptionalArgs(fn)(args...); } else { return fn(args...); } } private: absl::StatusOr<OperatorPtr> DoGetOperator( absl::Span<const QTypePtr> input_types, QTypePtr output_type) const final; }; } #endif #include "arolla/qexpr/operators/strings/join.h" #include <memory> #include <string> #include <vector> #include "absl/container/inlined_vector.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/memory/frame.h" #include "arolla/memory/optional_value.h" #include "arolla/qexpr/bound_operators.h" #include "arolla/qexpr/eval_context.h" #include "arolla/qexpr/operator_errors.h" #include "arolla/qexpr/operators.h" #include "arolla/qexpr/qexpr_operator_signature.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/util/bytes.h" #include "arolla/util/text.h" #include "arolla/util/status_macros_backport.h" namespace arolla { namespace { using std::unique_ptr; template <typename T> using Slot = FrameLayout::Slot<T>; template <class StringType> class JoinBoundOperator : public BoundOperator { public: JoinBoundOperator(Slot<StringType> delimiter_slot, std::vector<Slot<StringType>> part_slots, Slot<StringType> output_slot) : delimiter_slot_(delimiter_slot), part_slots_(std::move(part_slots)), output_slot_(output_slot) {} void Run(EvaluationContext* ctx, FramePtr frame) const override { absl::InlinedVector<absl::string_view, 10> parts; parts.reserve(part_slots_.size()); for (auto& s : part_slots_) { parts.push_back(frame.Get(s)); } frame.Set(output_slot_, StringType(absl::StrJoin(parts.begin(), parts.end(), frame.Get(delimiter_slot_)))); } private: Slot<StringType> delimiter_slot_; std::vector<Slot<StringType>> part_slots_; Slot<StringType> output_slot_; }; template <class StringType> class JoinOperator : public QExprOperator { public: explicit JoinOperator(const QExprOperatorSignature* type) : QExprOperator(std::string(kJoinOperatorName), type) {} private: absl::StatusOr<std::unique_ptr<BoundOperator>> DoBind( absl::Span<const TypedSlot> typed_input_slots, TypedSlot typed_output_slot) const final { ASSIGN_OR_RETURN(Slot<StringType> delimiter_slot, typed_input_slots[0].ToSlot<StringType>()); std::vector<Slot<StringType>> part_slots; part_slots.reserve(typed_input_slots.size() - 1); std::vector<Slot<bool>> presence_slots; presence_slots.reserve(typed_input_slots.size() - 1); for (const auto& s : typed_input_slots.subspan(1)) { if (IsOptionalQType(s.GetType())) { ASSIGN_OR_RETURN(auto input_slot, s.ToSlot<OptionalValue<StringType>>()); presence_slots.push_back(GetPresenceSubslotFromOptional(input_slot)); part_slots.push_back(GetValueSubslotFromOptional(input_slot)); } else { ASSIGN_OR_RETURN(Slot<StringType> part_slot, s.ToSlot<StringType>()); part_slots.push_back(part_slot); } } if (presence_slots.empty()) { ASSIGN_OR_RETURN(Slot<StringType> output_slot, typed_output_slot.ToSlot<StringType>()); return {std::make_unique<JoinBoundOperator<StringType>>( delimiter_slot, std::move(part_slots), output_slot)}; } else { ASSIGN_OR_RETURN(auto output_slot, typed_output_slot.ToSlot<OptionalValue<StringType>>()); auto join_op = JoinBoundOperator<StringType>( delimiter_slot, std::move(part_slots), GetValueSubslotFromOptional(output_slot)); return {unique_ptr<BoundOperator>(new WhereAllBoundOperator( presence_slots, GetPresenceSubslotFromOptional(output_slot), std::move(join_op)))}; } } }; } template <class StringType> absl::StatusOr<OperatorPtr> GetJoinOperator( absl::Span<const QTypePtr> input_types) { bool has_optional = std::any_of(input_types.begin(), input_types.end(), [](QTypePtr qtype) { return IsOptionalQType(qtype); }); const QTypePtr part_type = DecayOptionalQType(input_types[1]); QTypePtr output_type = part_type; if (has_optional) { ASSIGN_OR_RETURN(output_type, ToOptionalQType(output_type)); } auto operator_qtype = QExprOperatorSignature::Get(input_types, output_type); auto scalar_qtype = GetQType<StringType>(); if (part_type == scalar_qtype) { return OperatorPtr( std::make_unique<JoinOperator<StringType>>(operator_qtype)); } else { return OperatorNotDefinedError( kJoinOperatorName, input_types, absl::StrFormat("with a separator of type %s, joined parts must be %s", scalar_qtype->name(), scalar_qtype->name())); } } absl::StatusOr<OperatorPtr> JoinOperatorFamily::DoGetOperator( absl::Span<const QTypePtr> input_types, QTypePtr output_type) const { if (input_types.size() < 2) { return OperatorNotDefinedError(kJoinOperatorName, input_types, "expected at least 2 arguments."); } if (input_types[0] != GetQType<Text>() && input_types[0] != GetQType<Bytes>()) { return OperatorNotDefinedError( kJoinOperatorName, input_types, absl::StrFormat("first argument must be TEXT or BYTES but was %s.", input_types[0]->name())); } const QTypePtr part_type = DecayOptionalQType(input_types[1]); for (const QTypePtr t : input_types.subspan(2)) { if (DecayOptionalQType(t) != part_type) { return OperatorNotDefinedError(kJoinOperatorName, input_types, "joined parts must have same type."); } } if (input_types[0] == GetQType<Text>()) { return EnsureOutputQTypeMatches(GetJoinOperator<Text>(input_types), input_types, output_type); } else { return EnsureOutputQTypeMatches(GetJoinOperator<Bytes>(input_types), input_types, output_type); } } }
#include "arolla/qexpr/operators/strings/join.h" #include <tuple> #include <type_traits> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "arolla/memory/optional_value.h" #include "arolla/qexpr/operators.h" #include "arolla/qtype/base_types.h" #include "arolla/util/bytes.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/text.h" using ::testing::HasSubstr; namespace arolla { using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; namespace { template <typename TypeParam> class JoinStringsTest : public ::testing::Test { public: using StringType = std::tuple_element_t<0, TypeParam>; using EvalAsFunctor = std::tuple_element_t<1, TypeParam>; template <typename... Args> absl::StatusOr<StringType> InvokeOperator(const Args&... args) { if constexpr (EvalAsFunctor::value) { auto result = JoinOperatorFamily{}(args...); static_assert(std::is_same_v<decltype(result), StringType>); return result; } else { return ::arolla::InvokeOperator<StringType>( "strings._join_with_separator", args...); } } template <typename... Args> absl::StatusOr<OptionalValue<StringType>> InvokeOperatorOptional( const Args&... args) { if constexpr (EvalAsFunctor::value) { auto result = JoinOperatorFamily{}(args...); static_assert( std::is_same_v<decltype(result), OptionalValue<StringType>>); return result; } else { return ::arolla::InvokeOperator<OptionalValue<StringType>>( "strings._join_with_separator", args...); } } }; TYPED_TEST_SUITE_P(JoinStringsTest); TYPED_TEST_P(JoinStringsTest, JoinScalars) { using StringType = typename JoinStringsTest<TypeParam>::StringType; StringType first_part("first"); StringType second_part("second"); StringType third_part("third"); StringType delimiter("/"); EXPECT_THAT(this->InvokeOperator(delimiter, first_part), IsOkAndHolds(StringType("first"))); EXPECT_THAT( this->InvokeOperator(delimiter, first_part, second_part, third_part), IsOkAndHolds(StringType("first/second/third"))); EXPECT_THAT( this->InvokeOperator(delimiter, first_part, second_part, third_part), IsOkAndHolds(StringType("first/second/third"))); } TYPED_TEST_P(JoinStringsTest, JoinScalarsErrors) { if constexpr (!JoinStringsTest<TypeParam>::EvalAsFunctor::value) { using StringType = typename JoinStringsTest<TypeParam>::StringType; using OtherType = std::conditional_t<std::is_same_v<StringType, Text>, Bytes, Text>; StringType first_part("first"); StringType second_part("second"); StringType delimiter("/"); EXPECT_THAT(this->InvokeOperator(delimiter), StatusIs(absl::StatusCode::kNotFound, HasSubstr("expected at least 2 arguments."))); EXPECT_THAT(this->InvokeOperator(delimiter, first_part, second_part, OtherType("third")), StatusIs(absl::StatusCode::kNotFound, HasSubstr("joined parts must have same type."))); EXPECT_THAT(this->InvokeOperator(0, 1, 2), StatusIs(absl::StatusCode::kNotFound, HasSubstr("first argument must be"))); } } TYPED_TEST_P(JoinStringsTest, JoinOptionalScalars) { using StringType = typename JoinStringsTest<TypeParam>::StringType; OptionalValue<StringType> first_part(StringType("first")); OptionalValue<StringType> second_part(StringType("second")); StringType third_part("third"); StringType delimiter("/"); OptionalValue<StringType> expected1(StringType("first/second/third")); EXPECT_THAT(this->InvokeOperatorOptional(delimiter, first_part, second_part, third_part), IsOkAndHolds(expected1)); OptionalValue<StringType> expected2; EXPECT_THAT( this->InvokeOperatorOptional(delimiter, first_part, OptionalValue<StringType>{}, third_part), IsOkAndHolds(expected2)); } REGISTER_TYPED_TEST_SUITE_P(JoinStringsTest, JoinScalars, JoinOptionalScalars, JoinScalarsErrors); using BytesEvalNormally = std::tuple<Bytes, std::bool_constant<false>>; INSTANTIATE_TYPED_TEST_SUITE_P(Bytes, JoinStringsTest, BytesEvalNormally); using TextEvalNormally = std::tuple<Bytes, std::bool_constant<false>>; INSTANTIATE_TYPED_TEST_SUITE_P(Text, JoinStringsTest, TextEvalNormally); using BytesEvalFunctor = std::tuple<Bytes, std::bool_constant<true>>; INSTANTIATE_TYPED_TEST_SUITE_P(BytesFunctor, JoinStringsTest, BytesEvalFunctor); using TextEvalFunctor = std::tuple<Bytes, std::bool_constant<true>>; INSTANTIATE_TYPED_TEST_SUITE_P(TextFunctor, JoinStringsTest, TextEvalFunctor); } }
2,374
#ifndef AROLLA_QEXPR_OPERATORS_STRINGS_STRINGS_H_ #define AROLLA_QEXPR_OPERATORS_STRINGS_STRINGS_H_ #include <bitset> #include <cctype> #include <charconv> #include <cstdint> #include <limits> #include <optional> #include <string> #include <system_error> #include <utility> #include "absl/container/flat_hash_set.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/ascii.h" #include "absl/strings/charconv.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "icu4c/source/common/unicode/uchar.h" #include "icu4c/source/common/unicode/unistr.h" #include "icu4c/source/common/unicode/utf16.h" #include "icu4c/source/common/unicode/utf8.h" #include "icu4c/source/common/unicode/utypes.h" #include "arolla/memory/optional_value.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/strings/regex.h" #include "arolla/util/bytes.h" #include "arolla/util/text.h" #include "arolla/util/unit.h" #include "arolla/util/status_macros_backport.h" namespace arolla { struct LowerOp { absl::StatusOr<Text> operator()( absl::string_view in, std::optional<absl::string_view> locale = std::nullopt) const; absl::StatusOr<Text> operator()(const Text& in) const { return this->operator()(absl::string_view(in)); } absl::StatusOr<Text> operator()(const Text& in, const Text& locale) const { return this->operator()(absl::string_view(in), absl::string_view(locale)); } }; struct UpperOp { absl::StatusOr<Text> operator()( absl::string_view in, std::optional<absl::string_view> locale = std::nullopt) const; absl::StatusOr<Text> operator()(const Text& in) const { return this->operator()(absl::string_view(in)); } absl::StatusOr<Text> operator()(const Text& in, const Text& locale) const { return this->operator()(absl::string_view(in), absl::string_view(locale)); } }; struct ReplaceOp { absl::StatusOr<std::string> operator()(absl::string_view s, absl::string_view old_sub, absl::string_view new_sub, OptionalValue<int32_t> max_subs) const; template <typename StringType> absl::StatusOr<StringType> operator()(const StringType& str, const StringType& old_sub, const StringType& new_sub, OptionalValue<int32_t> max_subs) const { ASSIGN_OR_RETURN( auto result, this->operator()(absl::string_view(str), absl::string_view(old_sub), absl::string_view(new_sub), max_subs)); return StringType(result); } }; struct LStripOp { Bytes operator()(const Bytes& bytes, const OptionalValue<Bytes>& chars) const { auto do_lstrip = [](absl::string_view s, auto strip_test) { const char* b = s.data(); const char* e = s.data() + s.length() - 1; while (b <= e && strip_test(*b)) { ++b; } return absl::string_view(b, e - b + 1); }; if (chars.present) { std::bitset<256> char_set(256); for (char c : absl::string_view(chars.value)) { char_set.set(static_cast<int>(c)); } return Bytes(do_lstrip(bytes, [&](char c) { return char_set.test(c); })); } else { return Bytes( do_lstrip(bytes, [&](char c) { return absl::ascii_isspace(c); })); } } Text operator()(const Text& text, const OptionalValue<Text>& chars) const { auto do_lstrip = [](absl::string_view s, auto strip_test) { int pref = 0; for (int i = 0; i < s.length();) { UChar32 c; U8_NEXT(s.data(), i, s.length(), c); if (!strip_test(c)) { break; } pref = i; } return Text(absl::string_view(s.data() + pref, s.length() - pref)); }; if (!chars.present) { return Text( do_lstrip(text, [](UChar32 c) { return u_isUWhiteSpace(c); })); } absl::string_view chars_bytes = chars.value; absl::flat_hash_set<UChar32> set; for (int i = 0; i < chars_bytes.length();) { UChar32 c; U8_NEXT(chars_bytes.data(), i, chars_bytes.length(), c); set.insert(c); } return Text(do_lstrip(text, [&](UChar32 c) { return set.contains(c); })); } }; struct RStripOp { Bytes operator()(const Bytes& bytes, const OptionalValue<Bytes>& chars) const { auto do_rstrip = [](absl::string_view s, auto strip_test) { const char* b = s.data(); const char* e = s.data() + s.length() - 1; while (b <= e && strip_test(*e)) { --e; } return absl::string_view(b, e - b + 1); }; if (chars.present) { std::bitset<256> char_set(256); for (char c : absl::string_view(chars.value)) { char_set.set(static_cast<int>(c)); } return Bytes(do_rstrip(bytes, [&](char c) { return char_set.test(c); })); } else { return Bytes( do_rstrip(bytes, [&](char c) { return absl::ascii_isspace(c); })); } } Text operator()(const Text& text, const OptionalValue<Text>& chars) const { auto do_rstrip = [](absl::string_view s, auto strip_test) { int len = s.length(); for (int i = s.length(); i > 0;) { UChar32 c; U8_PREV(s.data(), 0, i, c); if (!strip_test(c)) { break; } len = i; } return Text(absl::string_view(s.data(), len)); }; if (!chars.present) { return Text( do_rstrip(text, [](UChar32 c) { return u_isUWhiteSpace(c); })); } absl::string_view chars_bytes = chars.value; absl::flat_hash_set<UChar32> set; for (int i = 0; i < chars_bytes.length();) { UChar32 c; U8_NEXT(chars_bytes.data(), i, chars_bytes.length(), c); set.insert(c); } return Text(do_rstrip(text, [&](UChar32 c) { return set.contains(c); })); } }; struct StripOp { absl::StatusOr<Bytes> operator()(const Bytes& bytes, const OptionalValue<Bytes>& chars) const { return RStripOp()(LStripOp()(bytes, chars), chars); } absl::StatusOr<Text> operator()(const Text& text, const OptionalValue<Text>& chars) const { return RStripOp()(LStripOp()(text, chars), chars); } }; struct BytesLengthOp { int32_t operator()(absl::string_view s) const { return s.length(); } int32_t operator()(const Bytes& bytes) const { return this->operator()(absl::string_view(bytes)); } }; struct TextLengthOp { int32_t operator()(absl::string_view s) const { return icu::UnicodeString::fromUTF8(s).countChar32(); } int32_t operator()(const Text& text) const { return this->operator()(absl::string_view(text)); } }; struct AsTextOp { Text operator()(absl::string_view s) const; Text operator()(const Bytes& x) const; Text operator()(Unit) const; Text operator()(int32_t x) const; Text operator()(int64_t x) const; Text operator()(uint64_t x) const; Text operator()(float x) const; Text operator()(double x) const; Text operator()(bool x) const; }; struct TextAsTextOp { Text operator()(absl::string_view s) const; Text operator()(const Text& s) const; }; struct EncodeOp { Bytes operator()(absl::string_view s) const { return Bytes(s); } Bytes operator()(const Text& text) const { return Bytes(absl::string_view(text)); } }; struct DecodeOp { absl::StatusOr<Text> operator()(absl::string_view s) const; auto operator()(const Bytes& bytes) const { return (*this)(absl::string_view(bytes)); } }; struct CompileRegexOp { absl::StatusOr<Regex> operator()(const Text& pattern) const { return Regex::FromPattern(pattern); } }; struct ContainsRegexOp { OptionalUnit operator()(const Text& text, const Regex& regexp) const; OptionalUnit operator()(const OptionalValue<Text>& text, const Regex& regexp) const { return text.present ? (*this)(text.value, regexp) : kMissing; } }; struct ExtractRegexOp { absl::StatusOr<OptionalValue<Text>> operator()(const Text& text, const Regex& regexp) const; absl::StatusOr<OptionalValue<Text>> operator()( const OptionalValue<Text>& text, const Regex& regexp) const { return text.present ? (*this)(text.value, regexp) : OptionalValue<Text>{}; } }; template <typename FloatT> bool ParseFloatT(absl::string_view str, FloatT& result) { if (!str.empty() && str[0] == '+') { str.remove_prefix(1); if (!str.empty() && str[0] == '-') { return false; } } if (str.size() >= 2 && (str[1] == 'x' || str[1] == 'X')) { return false; if (str.size() >= 3 && (str[2] == 'x' || str[2] == 'X')) { return false; } } auto [ptr, ec] = absl::from_chars(str.data(), str.data() + str.size(), result); if (ptr != str.data() + str.size()) { return false; } if (ec == std::errc::result_out_of_range) { if (result > 1.0) { result = std::numeric_limits<FloatT>::infinity(); } else if (result < -1.0) { result = -std::numeric_limits<FloatT>::infinity(); } return true; } return ec == std::errc(); } template <typename IntT> bool ParseIntT(absl::string_view str, IntT& result) { if (!str.empty() && str[0] == '+') { str.remove_prefix(1); if (!str.empty() && str[0] == '-') { return false; } } auto [ptr, ec] = std::from_chars(str.data(), str.data() + str.size(), result, 10); return ec == std::errc() && ptr == str.data() + str.size(); } struct StringsParseFloat32 { absl::StatusOr<float> operator()(absl::string_view str) const { float result; if (ParseFloatT(str, result)) { return result; } return absl::InvalidArgumentError( absl::StrCat("unable to parse FLOAT32: ", str)); } auto operator()(const ::arolla::Bytes& s) const { return (*this)(absl::string_view(s)); } auto operator()(const ::arolla::Text& s) const { return (*this)(absl::string_view(s)); } }; struct StringsParseFloat64 { absl::StatusOr<double> operator()(absl::string_view str) const { double result; if (ParseFloatT(str, result)) { return result; } return absl::InvalidArgumentError( absl::StrCat("unable to parse FLOAT64: ", str)); } auto operator()(const ::arolla::Bytes& s) const { return (*this)(absl::string_view(s)); } auto operator()(const ::arolla::Text& s) const { return (*this)(absl::string_view(s)); } }; struct StringsParseInt32 { absl::StatusOr<int32_t> operator()(absl::string_view str) const { int32_t result; if (ParseIntT(str, result)) { return result; } return absl::InvalidArgumentError( absl::StrCat("unable to parse INT32: ", str)); } auto operator()(const ::arolla::Bytes& s) const { return (*this)(absl::string_view(s)); } auto operator()(const ::arolla::Text& s) const { return (*this)(absl::string_view(s)); } }; struct StringsParseInt64 { absl::StatusOr<int64_t> operator()(absl::string_view str) const { int64_t result; if (ParseIntT(str, result)) { return result; } return absl::InvalidArgumentError( absl::StrCat("unable to parse INT64: ", str)); } auto operator()(const ::arolla::Bytes& s) const { return (*this)(absl::string_view(s)); } auto operator()(const ::arolla::Text& s) const { return (*this)(absl::string_view(s)); } }; } #endif #include "arolla/qexpr/operators/strings/strings.h" #include <cstddef> #include <cstdint> #include <limits> #include <optional> #include <string> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/escaping.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "icu4c/source/common/unicode/bytestream.h" #include "icu4c/source/common/unicode/casemap.h" #include "icu4c/source/common/unicode/errorcode.h" #include "icu4c/source/common/unicode/stringoptions.h" #include "icu4c/source/common/unicode/umachine.h" #include "icu4c/source/common/unicode/utf8.h" #include "double-conversion/double-to-string.h" #include "double-conversion/utils.h" #include "arolla/memory/optional_value.h" #include "arolla/qtype/strings/regex.h" #include "arolla/util/bytes.h" #include "arolla/util/indestructible.h" #include "arolla/util/text.h" #include "arolla/util/unit.h" #include "re2/re2.h" #include "arolla/util/status_macros_backport.h" namespace arolla { namespace { absl::Status ValidateUtf8(absl::string_view bytes) { if (bytes.size() > size_t{std::numeric_limits<int32_t>::max()}) { return absl::UnimplementedError("string is too long to convert to UTF-8"); } int32_t offset = 0; while (offset < bytes.size()) { UChar32 character; int32_t previous_offset = offset; U8_NEXT(bytes.data(), offset, bytes.size(), character); if (character < 0) { return absl::InvalidArgumentError(absl::StrFormat( "invalid UTF-8 sequence at position %d", previous_offset)); } } return absl::OkStatus(); } } absl::StatusOr<Text> LowerOp::operator()( absl::string_view in, std::optional<absl::string_view> locale) const { std::string result; icu::StringByteSink<std::string> sink(&result); icu::ErrorCode error_code; const char* locale_ptr = locale.has_value() ? locale->data() : nullptr; icu::CaseMap::utf8ToLower(locale_ptr, U_FOLD_CASE_DEFAULT, absl::string_view(in), sink, nullptr, error_code); if (error_code.isFailure()) { return absl::InvalidArgumentError(absl::StrFormat( "utf8ToLower failed with error: %s", error_code.errorName())); } return Text(result); } absl::StatusOr<Text> UpperOp::operator()( absl::string_view in, std::optional<absl::string_view> locale) const { std::string result; icu::StringByteSink<std::string> sink(&result); icu::ErrorCode error_code; const char* locale_ptr = locale.has_value() ? locale->data() : nullptr; icu::CaseMap::utf8ToUpper(locale_ptr, U_FOLD_CASE_DEFAULT, absl::string_view(in), sink, nullptr, error_code); if (error_code.isFailure()) { return absl::InvalidArgumentError(absl::StrFormat( "utf8ToUpper failed with error: %s", error_code.errorName())); } return Text(result); } absl::StatusOr<Text> DecodeOp::operator()(absl::string_view s) const { RETURN_IF_ERROR(ValidateUtf8(s)); return Text(s); } absl::StatusOr<std::string> ReplaceOp::operator()( absl::string_view s, absl::string_view old_sub, absl::string_view new_sub, OptionalValue<int32_t> max_subs) const { size_t count = std::numeric_limits<size_t>::max(); if (max_subs.present && (max_subs.value >= 0)) { count = max_subs.value; } std::string res; if (count == 0) { return res; } size_t offset = 0; if (old_sub.empty()) { absl::StrAppend(&res, new_sub); while ((--count > 0) && (offset < s.length())) { absl::StrAppend(&res, s.substr(offset, 1), new_sub); ++offset; } } else { while (count-- > 0) { const size_t start = s.find(old_sub, offset); if (start == std::string::npos) break; absl::StrAppend(&res, s.substr(offset, start - offset), new_sub); offset = start + old_sub.size(); } } res.append(s.begin() + offset, s.end()); return res; } OptionalUnit ContainsRegexOp::operator()(const Text& text, const Regex& regexp) const { return OptionalUnit{ RE2::PartialMatch(absl::string_view(text), regexp.value())}; } absl::StatusOr<OptionalValue<Text>> ExtractRegexOp::operator()( const Text& text, const Regex& regexp) const { const auto& re = regexp.value(); if (re.NumberOfCapturingGroups() != 1) { return absl::InvalidArgumentError( absl::StrFormat("ExtractRegexOp expected regular expression with " "exactly one capturing group; got `%s` which " "contains %d capturing groups.", re.pattern(), re.NumberOfCapturingGroups())); } std::string match; if (RE2::PartialMatch(text.view(), re, &match)) { return Text(match); } else { return OptionalValue<Text>(); } } template <class T> Text SignedIntegerToText(T x) { return Text(absl::StrFormat("%d", x)); } Text AsTextOp::operator()(absl::string_view s) const { return Text(absl::StrFormat("b'%s'", absl::Utf8SafeCHexEscape(s))); } Text AsTextOp::operator()(const Bytes& x) const { return operator()(absl::string_view(x)); } Text AsTextOp::operator()(Unit) const { return Text("unit"); } Text AsTextOp::operator()(int32_t x) const { return SignedIntegerToText(x); } Text AsTextOp::operator()(int64_t x) const { return SignedIntegerToText(x); } Text AsTextOp::operator()(uint64_t x) const { return Text(absl::StrFormat("%d", x)); } Text AsTextOp::operator()(bool x) const { return x ? Text("true") : Text("false"); } Text AsTextOp::operator()(float x) const { static const Indestructible<double_conversion::DoubleToStringConverter> converter(double_conversion::DoubleToStringConverter::NO_FLAGS, "inf", "nan", 'e', -6, 21, 6, 0); char buf[128]; double_conversion::StringBuilder builder(buf, sizeof(buf)); converter->ToShortestSingle(x, &builder); return Text(builder.Finalize()); } Text AsTextOp::operator()(double x) const { static const Indestructible<double_conversion::DoubleToStringConverter> converter(double_conversion::DoubleToStringConverter::NO_FLAGS, "inf", "nan", 'e', -6, 21, 6, 0); char buf[128]; double_conversion::StringBuilder builder(buf, sizeof(buf)); converter->ToShortest(x, &builder); return Text(builder.Finalize()); } Text TextAsTextOp::operator()(absl::string_view s) const { return Text(s); } Text TextAsTextOp::operator()(const Text& s) const { return s; } }
#include <cstdint> #include <string> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/memory/optional_value.h" #include "arolla/qexpr/operators.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/strings/regex.h" #include "arolla/util/bytes.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/text.h" #include "arolla/util/unit.h" using ::testing::HasSubstr; namespace arolla { using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::testing::ElementsAre; using ::testing::HasSubstr; namespace { class StringsTest : public ::testing::Test { void SetUp() final { ASSERT_OK(InitArolla()); } }; TEST_F(StringsTest, AsText) { EXPECT_THAT(InvokeOperator<Text>("strings.as_text", kUnit), IsOkAndHolds(Text("unit"))); EXPECT_THAT(InvokeOperator<Text>("strings.as_text", Text("text")), IsOkAndHolds(Text("text"))); EXPECT_THAT(InvokeOperator<Text>("strings.as_text", Bytes(std::string({0, 'b', '\'', 'e', 1}))), IsOkAndHolds(Text("b'\\x00\\x62\\'e\\x01'"))); EXPECT_THAT(InvokeOperator<Text>("strings.as_text", false), IsOkAndHolds(Text("false"))); EXPECT_THAT(InvokeOperator<Text>("strings.as_text", int32_t{1}), IsOkAndHolds(Text("1"))); EXPECT_THAT(InvokeOperator<Text>("strings.as_text", int64_t{1}), IsOkAndHolds(Text("1"))); EXPECT_THAT(InvokeOperator<Text>("strings.as_text", 2.3f), IsOkAndHolds(Text("2.3"))); EXPECT_THAT(InvokeOperator<Text>("strings.as_text", 2.3), IsOkAndHolds(Text("2.3"))); EXPECT_THAT(InvokeOperator<Text>("strings.as_text", 14.137167f), IsOkAndHolds(Text("14.137167"))); EXPECT_THAT(InvokeOperator<Text>("strings.as_text", 14.137167), IsOkAndHolds(Text("14.137167"))); EXPECT_THAT( InvokeOperator<DenseArray<Text>>( "strings.as_text", CreateDenseArray<Bytes>( {Bytes(std::string({0, 'b', '\'', 'e', 1}))})), IsOkAndHolds(ElementsAre(Text("b'\\x00\\x62\\'e\\x01'")))); } TEST_F(StringsTest, Decode) { EXPECT_THAT(InvokeOperator<Text>("strings.decode", Bytes("text")), IsOkAndHolds(Text("text"))); EXPECT_THAT(InvokeOperator<Text>("strings.decode", Bytes("te\0xt")), IsOkAndHolds(Text("te\0xt"))); EXPECT_THAT(InvokeOperator<Text>("strings.decode", Bytes("\xEF\xBF\xBD")), IsOkAndHolds(Text("\xEF\xBF\xBD"))); EXPECT_THAT(InvokeOperator<Text>("strings.decode", Bytes("\xA0text")), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("invalid UTF-8 sequence at position 0"))); EXPECT_THAT(InvokeOperator<Text>("strings.decode", Bytes("te\xC0\0xt")), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("invalid UTF-8 sequence at position 2"))); EXPECT_THAT(InvokeOperator<Text>("strings.decode", Bytes("text\x80")), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("invalid UTF-8 sequence at position 4"))); } TEST_F(StringsTest, Lower) { Text input("Hello World."); Text expected_output("hello world."); EXPECT_THAT(InvokeOperator<Text>("strings.lower", input), IsOkAndHolds(expected_output)); } TEST_F(StringsTest, LowerOptional) { OptionalValue<Text> input(Text("Hello World.")); OptionalValue<Text> expected_output(Text("hello world.")); EXPECT_THAT(InvokeOperator<OptionalValue<Text>>("strings.lower", input), IsOkAndHolds(expected_output)); } TEST_F(StringsTest, LowerWithLocale) { Text input("TITLE"); Text locale("TR_tr"); EXPECT_THAT(InvokeOperator<Text>("strings.lower", input, locale), IsOkAndHolds(Text("tıtle"))); } TEST_F(StringsTest, Upper) { Text input("Hello World."); EXPECT_THAT(InvokeOperator<Text>("strings.upper", input), IsOkAndHolds(Text("HELLO WORLD."))); } TEST_F(StringsTest, UpperWithLocale) { Text input("istanbul"); Text locale("TR_tr"); EXPECT_THAT(InvokeOperator<Text>("strings.upper", input, locale), IsOkAndHolds(Text("İSTANBUL"))); } TEST_F(StringsTest, BytesLength) { EXPECT_THAT(InvokeOperator<int32_t>("strings.length", Bytes("古池や蛙飛び込む水の音")), IsOkAndHolds(33)); } TEST_F(StringsTest, TextLength) { EXPECT_THAT( InvokeOperator<int32_t>("strings.length", Text("古池や蛙飛び込む水の音")), IsOkAndHolds(11)); } TEST_F(StringsTest, ContainsRegex) { ASSERT_OK_AND_ASSIGN( Regex regex, InvokeOperator<Regex>("strings._compile_regex", Text("^\\d{1,3} bottles of beer"))); EXPECT_THAT(InvokeOperator<OptionalUnit>("strings._contains_regex", Text("999 bottles of beer"), regex), IsOkAndHolds(kPresent)); EXPECT_THAT(InvokeOperator<OptionalUnit>("strings._contains_regex", Text("1000 bottles of beer"), regex), IsOkAndHolds(kMissing)); } TEST_F(StringsTest, ExtractRegex) { using OT = OptionalValue<Text>; ASSERT_OK_AND_ASSIGN( Regex regex1, InvokeOperator<Regex>("strings._compile_regex", Text("bar:(\\w*)"))); EXPECT_THAT(InvokeOperator<OT>("strings._extract_regex", Text("foo:abc, bar:def, baz:ghi"), regex1), IsOkAndHolds(Text("def"))); EXPECT_THAT(InvokeOperator<OT>("strings._extract_regex", Text("foo:abc, baz:ghi"), regex1), IsOkAndHolds(OT{})); ASSERT_OK_AND_ASSIGN( Regex regex2, InvokeOperator<Regex>("strings._compile_regex", Text("bar:\\w*"))); EXPECT_THAT( InvokeOperator<OT>("strings._extract_regex", Text("foo:abc, bar:def, baz:ghi"), regex2), StatusIs( absl::StatusCode::kInvalidArgument, HasSubstr( "expected regular expression with exactly one capturing group"))); } TEST_F(StringsTest, InvalidRegex) { EXPECT_THAT(InvokeOperator<Regex>("strings._compile_regex", Text("ab\\αcd")), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("Invalid regular expression: \"ab\\αcd\"; "))); } } }
2,375
#ifndef AROLLA_QEXPR_OPERATORS_STRINGS_FORMAT_H_ #define AROLLA_QEXPR_OPERATORS_STRINGS_FORMAT_H_ #include <cstdint> #include <string> #include <type_traits> #include <utility> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/memory/optional_value.h" #include "arolla/qexpr/operators.h" #include "arolla/qtype/qtype.h" #include "arolla/util/bytes.h" namespace arolla { constexpr absl::string_view kFormatOperatorName = "strings.format"; class FormatOperatorFamily : public OperatorFamily { public: using returns_status_or = std::true_type; template <class... Args> auto operator()(const Args&... args) const { if constexpr ((is_optional_v<Args> || ...)) { if ((ArgPresent(args) && ...)) { auto res_or = FormatImpl(ArgValue(args)...); if (res_or.ok()) { return absl::StatusOr<OptionalValue<Bytes>>(res_or.value()); } else { return absl::StatusOr<OptionalValue<Bytes>>(res_or.status()); } } else { return absl::StatusOr<OptionalValue<Bytes>>(OptionalValue<Bytes>()); } } else { return FormatImpl(args...); } } private: template <typename T> bool ArgPresent(const T& arg) const { if constexpr (is_optional_v<T>) { return arg.present; } else { return true; } } template <typename T> const auto& ArgValue(const T& arg) const { if constexpr (is_optional_v<T>) { return arg.value; } else { return arg; } } template <typename T> static constexpr bool IsSupportedArgType() { return std::is_same_v<T, int32_t> || std::is_same_v<T, int64_t> || std::is_same_v<T, float> || std::is_same_v<T, double> || std::is_same_v<T, Bytes> || std::is_same_v<T, bool>; } template <typename... Args> struct FirstUnsupported; template <typename Arg> struct FirstUnsupported<Arg> { using type = Arg; }; template <typename Arg, typename... Args> struct FirstUnsupported<Arg, Args...> { using type = std::conditional_t<IsSupportedArgType<Arg>(), typename FirstUnsupported<Args...>::type, Arg>; }; template <class... Args> absl::StatusOr<Bytes> FormatImpl(const Bytes& format_spec, const Args&... args) const { if constexpr ((IsSupportedArgType<Args>() && ...)) { absl::UntypedFormatSpec fmt(format_spec); std::string out; if (absl::FormatUntyped(&out, fmt, {absl::FormatArg(args)...})) { return Bytes(std::move(out)); } else { return absl::InvalidArgumentError(absl::StrFormat( "format specification '%s' doesn't match format arguments", format_spec)); } } else { return absl::InvalidArgumentError(absl::StrFormat( "%s is not a supported format argument type", GetQType<typename FirstUnsupported<Args...>::type>()->name())); } } absl::StatusOr<OperatorPtr> DoGetOperator( absl::Span<const QTypePtr> input_types, QTypePtr output_type) const final; }; } #endif #include "arolla/qexpr/operators/strings/format.h" #include <cstddef> #include <cstdint> #include <deque> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/memory/frame.h" #include "arolla/memory/optional_value.h" #include "arolla/qexpr/bound_operators.h" #include "arolla/qexpr/eval_context.h" #include "arolla/qexpr/operator_errors.h" #include "arolla/qexpr/operators.h" #include "arolla/qexpr/qexpr_operator_signature.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_ref.h" #include "arolla/qtype/typed_slot.h" #include "arolla/qtype/weak_qtype.h" #include "arolla/util/bytes.h" #include "arolla/util/indestructible.h" #include "arolla/util/status_macros_backport.h" namespace arolla { namespace { template <typename T> using Slot = FrameLayout::Slot<T>; class ValueHolder { public: const absl::string_view& AddValue(absl::string_view value) { return values_.emplace_back(value); } private: std::deque<absl::string_view> values_; }; template <typename T> absl::FormatArg WrapValueImpl(const void* source, ValueHolder*) { const T& value_ref = *(reinterpret_cast<const T*>(source)); return absl::FormatArg(value_ref); } template <> absl::FormatArg WrapValueImpl<Bytes>(const void* source, ValueHolder* value_holder) { const Bytes& value_ref = *(reinterpret_cast<const Bytes*>(source)); return absl::FormatArg(value_holder->AddValue(value_ref)); } using WrapValueFn = absl::FormatArg (*)(const void*, ValueHolder*); absl::StatusOr<WrapValueFn> GetWrapValueFn(QTypePtr qtype) { static const Indestructible<absl::flat_hash_map<QTypePtr, WrapValueFn>> converter_map([](void* self) { new (self) absl::flat_hash_map<QTypePtr, WrapValueFn>{ {GetQType<int32_t>(), &WrapValueImpl<int32_t>}, {GetQType<int64_t>(), &WrapValueImpl<int64_t>}, {GetQType<float>(), &WrapValueImpl<float>}, {GetQType<double>(), &WrapValueImpl<double>}, {GetWeakFloatQType(), &WrapValueImpl<double>}, {GetQType<Bytes>(), &WrapValueImpl<Bytes>}, {GetQType<bool>(), &WrapValueImpl<bool>}}; }); auto iter = converter_map->find(qtype); if (iter == converter_map->end()) { return absl::InvalidArgumentError(absl::StrFormat( "%s is not a supported format argument type", qtype->name())); } return iter->second; } class SlotFormatter { public: static absl::StatusOr<SlotFormatter> Create(TypedSlot slot) { ASSIGN_OR_RETURN(auto wrap_value_fn, GetWrapValueFn(slot.GetType())); return SlotFormatter(slot, wrap_value_fn); } absl::FormatArg Format(FramePtr frame, ValueHolder* value_holder) const { TypedRef ref = TypedRef::FromSlot(slot_, frame); return wrap_value_fn_(ref.GetRawPointer(), value_holder); } private: SlotFormatter(TypedSlot slot, WrapValueFn wrap_value_fn) : slot_(slot), wrap_value_fn_(wrap_value_fn) {} TypedSlot slot_; WrapValueFn wrap_value_fn_; }; class FormatBoundOperator : public BoundOperator { public: FormatBoundOperator(Slot<Bytes> format_spec_slot, std::vector<SlotFormatter> slot_formatters, Slot<Bytes> output_slot) : format_spec_slot_(format_spec_slot), slot_formatters_(std::move(slot_formatters)), output_slot_(output_slot) {} void Run(EvaluationContext* ctx, FramePtr frame) const override { absl::string_view fmt_spec = frame.Get(format_spec_slot_); absl::UntypedFormatSpec fmt(fmt_spec); ValueHolder value_holder; std::vector<absl::FormatArg> fmt_args; fmt_args.reserve(slot_formatters_.size()); for (const auto& slot_formatter : slot_formatters_) { fmt_args.push_back(slot_formatter.Format(frame, &value_holder)); } std::string out; if (absl::FormatUntyped(&out, fmt, fmt_args)) { frame.Set(output_slot_, Bytes(std::move(out))); } else { ctx->set_status(absl::InvalidArgumentError(absl::StrFormat( "format specification '%s' doesn't match format arguments", fmt_spec))); } } private: Slot<Bytes> format_spec_slot_; std::vector<SlotFormatter> slot_formatters_; Slot<Bytes> output_slot_; }; class FormatOperator : public QExprOperator { public: explicit FormatOperator(const QExprOperatorSignature* type) : QExprOperator(std::string(kFormatOperatorName), type) {} private: absl::StatusOr<std::unique_ptr<BoundOperator>> DoBind( absl::Span<const TypedSlot> typed_input_slots, TypedSlot typed_output_slot) const override { std::vector<Slot<bool>> presence_slots; Slot<Bytes> format_spec_slot = Slot<Bytes>::UnsafeSlotFromOffset( 0); if (IsOptionalQType(typed_input_slots[0].GetType())) { DCHECK_EQ(typed_input_slots[0].SubSlotCount(), 2); ASSIGN_OR_RETURN(auto presence_slot, typed_input_slots[0].SubSlot(0).ToSlot<bool>()); presence_slots.push_back(presence_slot); ASSIGN_OR_RETURN(format_spec_slot, typed_input_slots[0].SubSlot(1).ToSlot<Bytes>()); } else { ASSIGN_OR_RETURN(format_spec_slot, typed_input_slots[0].ToSlot<Bytes>()); } auto arg_slots = typed_input_slots.subspan(1); std::vector<SlotFormatter> slot_formatters; slot_formatters.reserve(arg_slots.size()); for (auto arg_slot : arg_slots) { TypedSlot value_slot = arg_slot; if (IsOptionalQType(arg_slot.GetType())) { ASSIGN_OR_RETURN(Slot<bool> presence_slot, GetPresenceSubslotFromOptional(arg_slot)); presence_slots.push_back(presence_slot); ASSIGN_OR_RETURN(value_slot, GetValueSubslotFromOptional(arg_slot)); } ASSIGN_OR_RETURN(auto slot_formatter, SlotFormatter::Create(value_slot)); slot_formatters.push_back(slot_formatter); } if (presence_slots.empty()) { ASSIGN_OR_RETURN(Slot<Bytes> output_slot, typed_output_slot.ToSlot<Bytes>()); return {std::make_unique<FormatBoundOperator>( format_spec_slot, slot_formatters, output_slot)}; } else { ASSIGN_OR_RETURN(Slot<OptionalValue<Bytes>> output_slot, typed_output_slot.ToSlot<OptionalValue<Bytes>>()); FormatBoundOperator format_op(format_spec_slot, slot_formatters, GetValueSubslotFromOptional(output_slot)); return {std::unique_ptr<BoundOperator>(new WhereAllBoundOperator( presence_slots, GetPresenceSubslotFromOptional(output_slot), std::move(format_op)))}; } } }; } absl::StatusOr<OperatorPtr> FormatOperatorFamily::DoGetOperator( absl::Span<const QTypePtr> input_types, QTypePtr output_type) const { if (input_types.empty()) { return OperatorNotDefinedError(kFormatOperatorName, input_types, "expected at least 1 argument"); } if (DecayOptionalQType(input_types[0]) != GetQType<Bytes>()) { return OperatorNotDefinedError(kFormatOperatorName, input_types, "format_spec must have BYTES QType"); } bool has_optional_arg = IsOptionalQType(input_types[0]); for (size_t i = 1; i < input_types.size(); ++i) { QTypePtr value_type = input_types[i]; if (IsOptionalQType(value_type)) { has_optional_arg = true; value_type = DecayOptionalQType(value_type); } RETURN_IF_ERROR(GetWrapValueFn(value_type).status()); } QTypePtr result_type = has_optional_arg ? GetQType<OptionalValue<Bytes>>() : GetQType<Bytes>(); return EnsureOutputQTypeMatches( OperatorPtr(std::make_unique<FormatOperator>( QExprOperatorSignature::Get(input_types, result_type))), input_types, output_type); } }
#include "arolla/qexpr/operators/strings/format.h" #include <cstdint> #include <type_traits> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "arolla/memory/optional_value.h" #include "arolla/qexpr/operators.h" #include "arolla/qtype/base_types.h" #include "arolla/util/bytes.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/text.h" namespace arolla { using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::testing::HasSubstr; namespace { template <typename EvalAsFunctor> class FormatTest : public ::testing::Test { public: template <typename... Args> absl::StatusOr<Bytes> InvokeOperator(const Args&... args) { if constexpr (EvalAsFunctor::value) { auto result = FormatOperatorFamily{}(args...); static_assert(std::is_same_v<decltype(result), absl::StatusOr<Bytes>>); return result; } else { return ::arolla::InvokeOperator<Bytes>("strings._format_bytes", args...); } } template <typename... Args> absl::StatusOr<OptionalValue<Bytes>> InvokeOperatorOptional( const Args&... args) { if constexpr (EvalAsFunctor::value) { auto result = FormatOperatorFamily{}(args...); static_assert(std::is_same_v<decltype(result), absl::StatusOr<OptionalValue<Bytes>>>); return result; } else { return ::arolla::InvokeOperator<OptionalValue<Bytes>>( "strings._format_bytes", args...); } } }; TYPED_TEST_SUITE_P(FormatTest); TYPED_TEST_P(FormatTest, FormatFloats) { Bytes format_spec("a=%0.2f b=%0.3f"); float a = 20.5f; double b = 3.75; EXPECT_THAT(this->InvokeOperator(format_spec, a, b), IsOkAndHolds(Bytes("a=20.50 b=3.750"))); } TYPED_TEST_P(FormatTest, FormatIntegers) { Bytes format_spec("c=%02d, d=%d"); int32_t c = 3; int64_t d = 4; EXPECT_THAT(this->InvokeOperator(format_spec, c, d), IsOkAndHolds(Bytes("c=03, d=4"))); } TYPED_TEST_P(FormatTest, FormatText) { Bytes format_spec("%s is %d years older than %s."); EXPECT_THAT( this->InvokeOperator(format_spec, Bytes("Sophie"), 2, Bytes("Katie")), IsOkAndHolds(Bytes("Sophie is 2 years older than Katie."))); } TYPED_TEST_P(FormatTest, FormatOptional) { Bytes format_spec("The atomic weight of %s is %0.3f"); EXPECT_THAT( this->InvokeOperatorOptional(format_spec, OptionalValue<Bytes>("Iron"), OptionalValue<float>(55.845)), IsOkAndHolds( OptionalValue<Bytes>("The atomic weight of Iron is 55.845"))); EXPECT_THAT(this->InvokeOperatorOptional(OptionalValue<Bytes>(format_spec), OptionalValue<Bytes>("Iron"), OptionalValue<float>(55.845)), IsOkAndHolds( OptionalValue<Bytes>("The atomic weight of Iron is 55.845"))); EXPECT_THAT(this->InvokeOperatorOptional(format_spec, OptionalValue<Bytes>("Unobtainium"), OptionalValue<float>{}), IsOkAndHolds(OptionalValue<Bytes>{})); EXPECT_THAT(this->InvokeOperatorOptional(OptionalValue<Bytes>(), OptionalValue<Bytes>("Unobtainium"), OptionalValue<float>{0}), IsOkAndHolds(OptionalValue<Bytes>{})); } TYPED_TEST_P(FormatTest, FormatMismatchedTypes) { Bytes format_spec("%s's atomic weight is %f"); EXPECT_THAT(this->InvokeOperator(format_spec, 1.0079, Bytes("Hydrogen")), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("doesn't match format arguments"))); } TYPED_TEST_P(FormatTest, FormatUnsupportedType) { Bytes format_spec("Payload is %s."); EXPECT_THAT( this->InvokeOperator(format_spec, Text("abc")), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("TEXT is not a supported format argument type"))); } REGISTER_TYPED_TEST_SUITE_P(FormatTest, FormatFloats, FormatIntegers, FormatText, FormatOptional, FormatMismatchedTypes, FormatUnsupportedType); INSTANTIATE_TYPED_TEST_SUITE_P(Operator, FormatTest, std::bool_constant<false>); INSTANTIATE_TYPED_TEST_SUITE_P(Functor, FormatTest, std::bool_constant<true>); } }
2,376
#ifndef AROLLA_OPERATORS_CORE_LOGIC_OPERATORS_H_ #define AROLLA_OPERATORS_CORE_LOGIC_OPERATORS_H_ #include <type_traits> #include "absl/status/statusor.h" #include "absl/types/span.h" #include "arolla/array/qtype/types.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/memory/optional_value.h" #include "arolla/qexpr/operators.h" #include "arolla/qtype/qtype.h" #include "arolla/util/status.h" #include "arolla/util/unit.h" namespace arolla { struct HasOp { using run_on_missing = std::true_type; template <typename T> std::enable_if_t<is_optional_v<T>, OptionalUnit> operator()( const T& arg) const { return OptionalUnit{arg.present}; } }; struct PresenceOrOp { using run_on_missing = std::true_type; template <typename T> T operator()(const OptionalValue<T>& lhs, const T& rhs) const { return lhs.present ? lhs.value : rhs; } template <typename T> OptionalValue<T> operator()(const OptionalValue<T>& lhs, const OptionalValue<T>& rhs) const { return lhs.present ? lhs : rhs; } template <typename T> T operator()(const T& lhs, const OptionalValue<T>& rhs) const { return lhs; } template <typename T> T operator()(const T& lhs, const T& rhs) const { return lhs; } template <typename T, class Fn> auto operator()(const OptionalValue<T>& lhs, const Fn& rhs) const { using result_t = strip_statusor_t<std::decay_t<decltype(rhs())>>; if constexpr (std::is_same_v<result_t, T>) { return lhs.present ? lhs.value : rhs(); } else { return lhs.present ? lhs : rhs(); } } template <typename T, class Fn> T operator()(const T& lhs, const Fn&) const { return lhs; } }; class PresenceOrVarargsOperatorFamily : public OperatorFamily { absl::StatusOr<OperatorPtr> DoGetOperator( absl::Span<const QTypePtr> input_types, QTypePtr output_type) const final; }; struct PresenceAndOp { using run_on_missing = std::true_type; template <typename T, std::enable_if_t<!std::is_invocable_v<T>, bool> = true> const T& operator()(const T& lhs, Unit) const { return lhs; } template <typename T, std::enable_if_t<!std::is_invocable_v<T>, bool> = true> OptionalValue<T> operator()(const T& lhs, OptionalUnit rhs) const { return rhs ? lhs : OptionalValue<T>{}; } template <typename T> OptionalValue<T> operator()(const OptionalValue<T>& lhs, OptionalUnit rhs) const { return rhs ? lhs : OptionalValue<T>{}; } template <typename Fn, std::enable_if_t<std::is_invocable_v<Fn>, bool> = true> auto operator()(const Fn& lhs, Unit) const { return lhs(); } template <typename Fn, std::enable_if_t<std::is_invocable_v<Fn>, bool> = true> auto operator()(const Fn& lhs, OptionalUnit rhs) const { using T = strip_optional_t<strip_statusor_t<std::decay_t<decltype(lhs())>>>; constexpr bool is_status = IsStatusOrT<std::decay_t<decltype(lhs())>>::value; constexpr bool is_optional = is_optional_v<strip_statusor_t<std::decay_t<decltype(lhs())>>>; if constexpr (is_status) { if constexpr (is_optional) { return rhs ? lhs() : OptionalValue<T>{}; } else { return rhs ? MakeStatusOrOptionalValue(lhs()) : OptionalValue<T>{}; } } else { return rhs ? lhs() : OptionalValue<T>{}; } } }; struct WhereOp { using run_on_missing = std::true_type; template <typename T, std::enable_if_t<!std::is_invocable_v<T>, bool> = true> T operator()(OptionalUnit c, const T& a, const T& b) const { return c.present ? a : b; } template < typename AFn, typename BFn, std::enable_if_t<std::is_invocable_v<AFn> && std::is_invocable_v<BFn>, bool> = true> auto operator()(OptionalUnit c, const AFn& a, const BFn& b) const { return c.present ? a() : b(); } template < typename AFn, typename T, std::enable_if_t<std::is_invocable_v<AFn> && !std::is_invocable_v<T>, bool> = true> auto operator()(OptionalUnit c, const AFn& a, const T& b) const { return c.present ? a() : b; } template < typename BFn, typename T, std::enable_if_t<!std::is_invocable_v<T> && std::is_invocable_v<BFn>, bool> = true> auto operator()(OptionalUnit c, const T& a, const BFn& b) const { return c.present ? a : b(); } }; struct PresenceAndOrOp { using run_on_missing = std::true_type; template <typename T> OptionalValue<T> operator()(const OptionalValue<T>& a, OptionalUnit b, const OptionalValue<T>& c) const { return b && a.present ? a : c; } template <typename T> T operator()(const OptionalValue<T>& a, OptionalUnit b, const T& c) const { return b && a.present ? a.value : c; } template <typename T> OptionalValue<T> operator()(const T& a, OptionalUnit b, const OptionalValue<T>& c) const { return b ? MakeOptionalValue(a) : c; } template <typename T> T operator()(const T& a, OptionalUnit b, const T& c) const { return b ? a : c; } template <typename T, class Fn> auto operator()(const OptionalValue<T>& a, OptionalUnit b, const Fn& c) const { using result_t = strip_statusor_t<std::decay_t<decltype(c())>>; if constexpr (std::is_same_v<result_t, T>) { return b && a.present ? a.value : c(); } else { return b && a.present ? a : c(); } } template <typename T, class Fn> auto operator()(const T& a, OptionalUnit b, const Fn& c) const { using result_t = strip_statusor_t<std::decay_t<decltype(c())>>; if constexpr (std::is_same_v<result_t, T>) { return b ? a : c(); } else { return b ? MakeOptionalValue(a) : c(); } } }; struct PresenceNotOp { using run_on_missing = std::true_type; template <class T> OptionalUnit operator()(const OptionalValue<T>& arg) const { return OptionalUnit{!arg.present}; } }; struct MaskEqualOp { using run_on_missing = std::true_type; template <typename T> OptionalUnit operator()(const T& lhs, const T& rhs) const { return OptionalUnit{lhs == rhs}; } }; struct MaskNotEqualOp { using run_on_missing = std::true_type; template <typename T> OptionalUnit operator()(const T& lhs, const T& rhs) const { return OptionalUnit{lhs != rhs}; } }; struct MaskLessOp { using run_on_missing = std::true_type; template <typename T> OptionalUnit operator()(const T& lhs, const T& rhs) const { return OptionalUnit{lhs < rhs}; } }; struct MaskLessEqualOp { using run_on_missing = std::true_type; template <typename T> OptionalUnit operator()(const T& lhs, const T& rhs) const { return OptionalUnit{(lhs < rhs) || (lhs == rhs)}; } }; class FakeShortCircuitWhereOperatorFamily : public OperatorFamily { absl::StatusOr<OperatorPtr> DoGetOperator( absl::Span<const QTypePtr> input_types, QTypePtr output_type) const final; }; } #endif #include "arolla/qexpr/operators/core/logic_operators.h" #include <algorithm> #include <iterator> #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/memory/frame.h" #include "arolla/memory/optional_value.h" #include "arolla/qexpr/eval_context.h" #include "arolla/qexpr/operator_errors.h" #include "arolla/qexpr/operators.h" #include "arolla/qexpr/qexpr_operator_signature.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/standard_type_properties/common_qtype.h" #include "arolla/util/unit.h" #include "arolla/util/status_macros_backport.h" namespace arolla { template <typename T> using Slot = FrameLayout::Slot<T>; constexpr absl::string_view kPresenceOrVarargsOperatorName = "core._presence_or"; namespace { class PresenceOrVarargsOperator : public QExprOperator { public: explicit PresenceOrVarargsOperator(const QExprOperatorSignature* qtype) : QExprOperator(std::string(kPresenceOrVarargsOperatorName), qtype) {} private: absl::StatusOr<std::unique_ptr<BoundOperator>> DoBind( absl::Span<const TypedSlot> input_slots, TypedSlot output_slot) const override { std::vector<Slot<bool>> presence_in_slots; presence_in_slots.reserve(input_slots.size()); std::vector<TypedSlot> value_in_slots; value_in_slots.reserve(input_slots.size()); for (int i = 0; i < input_slots.size(); ++i) { if (IsOptionalQType(input_slots[i].GetType())) { ASSIGN_OR_RETURN(Slot<bool> presence_in_slot, GetPresenceSubslotFromOptional(input_slots[i])); presence_in_slots.push_back(presence_in_slot); ASSIGN_OR_RETURN(TypedSlot value_in_slot, GetValueSubslotFromOptional(input_slots[i])); value_in_slots.push_back(value_in_slot); } else { DCHECK(i == input_slots.size() - 1); value_in_slots.push_back(input_slots[i]); } } if (IsOptionalQType(output_slot.GetType())) { ASSIGN_OR_RETURN(Slot<bool> presence_out_slot, GetPresenceSubslotFromOptional(output_slot)); ASSIGN_OR_RETURN(TypedSlot value_out_slot, GetValueSubslotFromOptional(output_slot)); return std::make_unique<BoundImpl>(presence_in_slots, value_in_slots, presence_out_slot, value_out_slot); } else { return std::make_unique<BoundImpl>(presence_in_slots, value_in_slots, std::nullopt, output_slot); } } class BoundImpl : public BoundOperator { public: BoundImpl(std::vector<Slot<bool>> presence_in_slots, std::vector<TypedSlot> value_in_slots, std::optional<Slot<bool>> presence_out_slot, TypedSlot value_out_slot) : presence_in_slots_(std::move(presence_in_slots)), value_in_slots_(std::move(value_in_slots)), presence_out_slot_(presence_out_slot), value_out_slot_(value_out_slot) { if (presence_out_slot_.has_value()) { DCHECK_EQ(value_in_slots_.size(), presence_in_slots_.size()); } else { DCHECK_EQ(value_in_slots_.size(), presence_in_slots_.size() + 1); } } void Run(EvaluationContext*, FramePtr frame) const override { auto iter = std::find_if(presence_in_slots_.begin(), presence_in_slots_.end(), [&frame](Slot<bool> slot) { return frame.Get(slot); }); int position = std::distance(presence_in_slots_.begin(), iter); bool has_output = position < value_in_slots_.size(); if (presence_out_slot_.has_value()) { frame.Set(*presence_out_slot_, has_output); } if (has_output) { value_in_slots_[position].CopyTo(frame, value_out_slot_, frame); } } private: std::vector<Slot<bool>> presence_in_slots_; std::vector<TypedSlot> value_in_slots_; std::optional<Slot<bool>> presence_out_slot_; TypedSlot value_out_slot_; }; }; class PresenceOrVarargsUnitOperator : public QExprOperator { public: explicit PresenceOrVarargsUnitOperator(const QExprOperatorSignature* qtype) : QExprOperator(std::string(kPresenceOrVarargsOperatorName), qtype) {} private: absl::StatusOr<std::unique_ptr<BoundOperator>> DoBind( absl::Span<const TypedSlot> input_slots, TypedSlot output_slot) const override { std::vector<Slot<bool>> presence_in_slots; presence_in_slots.reserve(input_slots.size()); for (int i = 0; i < input_slots.size(); ++i) { ASSIGN_OR_RETURN(Slot<bool> presence_in_slot, GetPresenceSubslotFromOptional(input_slots[i])); presence_in_slots.push_back(presence_in_slot); } ASSIGN_OR_RETURN(Slot<bool> presence_out_slot, GetPresenceSubslotFromOptional(output_slot)); return std::make_unique<BoundImpl>(presence_in_slots, presence_out_slot); } class BoundImpl : public BoundOperator { public: BoundImpl(std::vector<Slot<bool>> presence_in_slots, Slot<bool> presence_out_slot) : presence_in_slots_(std::move(presence_in_slots)), presence_out_slot_(presence_out_slot) {} void Run(EvaluationContext*, FramePtr frame) const override { bool any_present = std::any_of(presence_in_slots_.begin(), presence_in_slots_.end(), [&frame](Slot<bool> slot) { return frame.Get(slot); }); frame.Set(presence_out_slot_, any_present); } private: std::vector<Slot<bool>> presence_in_slots_; Slot<bool> presence_out_slot_; }; }; class FakeShortCircuitWhereOperator : public QExprOperator { public: explicit FakeShortCircuitWhereOperator(const QExprOperatorSignature* qtype) : QExprOperator("core._short_circuit_where", qtype) {} private: absl::StatusOr<std::unique_ptr<BoundOperator>> DoBind( absl::Span<const TypedSlot> input_slots, TypedSlot output_slot) const override { return absl::InternalError( "FakeShortCircuitWhereOperator is not supposed to be used"); } }; } absl::StatusOr<OperatorPtr> PresenceOrVarargsOperatorFamily::DoGetOperator( absl::Span<const QTypePtr> input_types, QTypePtr output_type) const { auto not_defined_error = [&](absl::string_view detail) { return OperatorNotDefinedError(kPresenceOrVarargsOperatorName, input_types, detail); }; if (input_types.size() < 2) { return not_defined_error("expected at least two arguments"); } for (int i = 0; i < input_types.size() - 1; ++i) { if (!IsOptionalQType(input_types[i])) { return not_defined_error( "expected all except last argument to be optional"); } } QTypePtr first_value_type = DecayOptionalQType(input_types[0]); for (int i = 1; i < input_types.size(); ++i) { QTypePtr value_type = DecayOptionalQType(input_types[i]); if (value_type != first_value_type) { return not_defined_error( "expected all arguments to have a common value type"); } } bool has_optional_output = IsOptionalQType(input_types.back()); const QExprOperatorSignature* op_qtype = QExprOperatorSignature::Get(input_types, input_types.back()); OperatorPtr op; if (first_value_type == GetQType<Unit>()) { if (has_optional_output) { op = std::make_unique<PresenceOrVarargsUnitOperator>(op_qtype); } else { return not_defined_error( "for Unit value type, expected final argument to be optional"); } } else { op = std::make_unique<PresenceOrVarargsOperator>(op_qtype); } return EnsureOutputQTypeMatches(op, input_types, output_type); } absl::StatusOr<OperatorPtr> FakeShortCircuitWhereOperatorFamily::DoGetOperator( absl::Span<const QTypePtr> input_types, QTypePtr output_type) const { auto not_defined_error = [&](absl::string_view detail) { return OperatorNotDefinedError("core._short_circuit_where", input_types, detail); }; if (input_types.size() < 3) { return not_defined_error("expected 3 arguments"); } if (input_types[0] != GetQType<OptionalUnit>()) { return not_defined_error("first argument must be OPTIONAL_UNIT"); } QTypePtr true_type = input_types[1]; QTypePtr false_type = input_types[2]; const QType* common_type = CommonQType(true_type, false_type, false); if (common_type == nullptr) { return not_defined_error("no common type between operator branches"); } return EnsureOutputQTypeMatches( std::make_unique<FakeShortCircuitWhereOperator>( QExprOperatorSignature::Get( {GetQType<OptionalUnit>(), common_type, common_type}, common_type)), input_types, output_type); } }
#include "arolla/qexpr/operators/core/logic_operators.h" #include <cstdint> #include <string> #include <type_traits> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "arolla/array/qtype/types.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/qtype/types.h" #include "arolla/memory/optional_value.h" #include "arolla/qexpr/operators.h" #include "arolla/qexpr/qexpr_operator_signature.h" #include "arolla/qtype/optional_qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/text.h" #include "arolla/util/unit.h" namespace arolla { namespace { using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::testing::Eq; using ::testing::HasSubstr; using ::testing::Pointee; using ::testing::Property; using Oi64 = OptionalValue<int64_t>; using DAi64 = DenseArray<int64_t>; const int64_t one = 1; const int64_t two = 2; const Oi64 optional_one = 1; const Oi64 optional_two = 2; const Oi64 missing; class LogicOperatorsTest : public ::testing::Test { void SetUp() final { ASSERT_OK(InitArolla()); } }; TEST_F(LogicOperatorsTest, PresenceOr) { EXPECT_THAT( InvokeOperator<OptionalUnit>("core.presence_or", kPresent, kPresent), IsOkAndHolds(kPresent)); EXPECT_THAT( InvokeOperator<OptionalUnit>("core.presence_or", kPresent, kMissing), IsOkAndHolds(kPresent)); EXPECT_THAT( InvokeOperator<OptionalUnit>("core.presence_or", kMissing, kMissing), IsOkAndHolds(kMissing)); EXPECT_THAT(InvokeOperator<int64_t>("core.presence_or", one, one), IsOkAndHolds(one)); EXPECT_THAT(InvokeOperator<int64_t>("core.presence_or", one, optional_two), IsOkAndHolds(one)); EXPECT_THAT(InvokeOperator<int64_t>("core.presence_or", missing, one), IsOkAndHolds(one)); EXPECT_THAT(InvokeOperator<int64_t>("core.presence_or", optional_two, one), IsOkAndHolds(two)); EXPECT_THAT( InvokeOperator<Oi64>("core.presence_or", optional_two, optional_one), IsOkAndHolds(optional_two)); EXPECT_THAT(InvokeOperator<Oi64>("core.presence_or", optional_two, missing), IsOkAndHolds(optional_two)); EXPECT_THAT(InvokeOperator<Oi64>("core.presence_or", missing, optional_two), IsOkAndHolds(optional_two)); EXPECT_THAT(InvokeOperator<Oi64>("core.presence_or", missing, missing), IsOkAndHolds(missing)); } TEST_F(LogicOperatorsTest, LazyPresenceOrFunctor) { auto as_fn = [](auto x) { return [x]() { return x; }; }; auto as_no_call_fn = [](auto x) { return [x]() { ADD_FAILURE() << "function shouldn't be called"; return x; }; }; EXPECT_EQ(PresenceOrOp{}(kPresent, as_no_call_fn(kPresent)), kPresent); EXPECT_EQ(PresenceOrOp{}(kPresent, as_no_call_fn(kMissing)), kPresent); EXPECT_EQ(PresenceOrOp{}(kMissing, as_fn(kMissing)), kMissing); EXPECT_EQ(PresenceOrOp{}(one, as_no_call_fn(one)), one); EXPECT_EQ(PresenceOrOp{}(one, as_no_call_fn(optional_two)), one); EXPECT_EQ(PresenceOrOp{}(missing, as_fn(one)), one); EXPECT_EQ(PresenceOrOp{}(optional_two, as_no_call_fn(one)), two); EXPECT_EQ(PresenceOrOp{}(optional_two, as_no_call_fn(optional_one)), optional_two); EXPECT_EQ(PresenceOrOp{}(optional_two, as_no_call_fn(missing)), optional_two); EXPECT_EQ(PresenceOrOp{}(missing, as_fn(optional_two)), optional_two); EXPECT_EQ(PresenceOrOp{}(missing, as_fn(missing)), missing); } TEST_F(LogicOperatorsTest, WhereOperatorFamily) { EXPECT_THAT(OperatorRegistry::GetInstance()->LookupOperator( "core.where", {GetQType<OptionalUnit>(), GetQType<int32_t>(), GetOptionalQType<int64_t>()}, GetOptionalQType<int64_t>()), IsOkAndHolds(Pointee(Property( &QExprOperator::signature, Eq(QExprOperatorSignature::Get( {GetQType<OptionalUnit>(), GetOptionalQType<int64_t>(), GetOptionalQType<int64_t>()}, GetOptionalQType<int64_t>())))))); EXPECT_THAT(OperatorRegistry::GetInstance()->LookupOperator( "core.where", {GetQType<OptionalUnit>(), GetQType<int32_t>(), GetDenseArrayQType<int64_t>()}, GetDenseArrayQType<int64_t>()), IsOkAndHolds(Pointee(Property( &QExprOperator::signature, Eq(QExprOperatorSignature::Get( {GetQType<OptionalUnit>(), GetDenseArrayQType<int64_t>(), GetDenseArrayQType<int64_t>()}, GetDenseArrayQType<int64_t>())))))); EXPECT_THAT(OperatorRegistry::GetInstance()->LookupOperator( "core.where", {GetQType<OptionalUnit>(), GetQType<int32_t>(), GetArrayQType<int64_t>()}, GetArrayQType<int64_t>()), IsOkAndHolds(Pointee(Property( &QExprOperator::signature, Eq(QExprOperatorSignature::Get( {GetQType<OptionalUnit>(), GetArrayQType<int64_t>(), GetArrayQType<int64_t>()}, GetArrayQType<int64_t>())))))); EXPECT_THAT( OperatorRegistry::GetInstance()->LookupOperator( "core.where", {GetDenseArrayQType<Unit>(), GetQType<int32_t>(), GetQType<int64_t>()}, GetDenseArrayQType<int64_t>()), IsOkAndHolds(Pointee(Property( &QExprOperator::signature, Eq(QExprOperatorSignature::Get( {GetDenseArrayQType<Unit>(), GetDenseArrayQType<int64_t>(), GetDenseArrayQType<int64_t>()}, GetDenseArrayQType<int64_t>())))))); EXPECT_THAT( OperatorRegistry::GetInstance()->LookupOperator( "core.where", {GetArrayQType<Unit>(), GetQType<int32_t>(), GetQType<int64_t>()}, GetArrayQType<int64_t>()), IsOkAndHolds( Pointee(Property(&QExprOperator::signature, Eq(QExprOperatorSignature::Get( {GetArrayQType<Unit>(), GetArrayQType<int64_t>(), GetArrayQType<int64_t>()}, GetArrayQType<int64_t>())))))); } TEST_F(LogicOperatorsTest, LazyWhereFunctor) { auto as_fn = [](auto x) { return [x]() { return x; }; }; auto as_no_call_fn = [](auto x) { return [x]() { ADD_FAILURE() << "function shouldn't be called"; return x; }; }; EXPECT_EQ(WhereOp{}(kPresent, as_fn(kPresent), as_no_call_fn(kPresent)), kPresent); EXPECT_EQ(WhereOp{}(kPresent, as_fn(kMissing), as_no_call_fn(kPresent)), kMissing); EXPECT_EQ(WhereOp{}(kMissing, as_no_call_fn(kPresent), as_fn(kPresent)), kPresent); EXPECT_EQ(WhereOp{}(kMissing, as_no_call_fn(kPresent), as_fn(kMissing)), kMissing); EXPECT_EQ(WhereOp{}(kPresent, kPresent, as_no_call_fn(kPresent)), kPresent); EXPECT_EQ(WhereOp{}(kPresent, kMissing, as_no_call_fn(kPresent)), kMissing); EXPECT_EQ(WhereOp{}(kMissing, as_no_call_fn(kPresent), kPresent), kPresent); EXPECT_EQ(WhereOp{}(kMissing, as_no_call_fn(kPresent), kMissing), kMissing); auto as_status_fn = [](auto x) { return [x]() { return absl::StatusOr<OptionalUnit>(x); }; }; EXPECT_THAT(WhereOp{}(kPresent, as_status_fn(kPresent), kPresent), IsOkAndHolds(kPresent)); EXPECT_THAT(WhereOp{}(kMissing, kPresent, as_status_fn(kPresent)), IsOkAndHolds(kPresent)); EXPECT_THAT( WhereOp{}(kPresent, as_status_fn(kPresent), as_no_call_fn(kPresent)), IsOkAndHolds(kPresent)); EXPECT_THAT( WhereOp{}(kMissing, as_no_call_fn(kPresent), as_status_fn(kPresent)), IsOkAndHolds(kPresent)); EXPECT_THAT( WhereOp{}(kPresent, as_status_fn(kPresent), as_status_fn(kPresent)), IsOkAndHolds(kPresent)); auto as_error_status_fn = []() { return []() { return absl::StatusOr<OptionalUnit>(absl::UnimplementedError("")); }; }; EXPECT_THAT(WhereOp{}(kPresent, as_status_fn(kPresent), as_error_status_fn()), IsOkAndHolds(kPresent)); EXPECT_THAT(WhereOp{}(kPresent, as_error_status_fn(), as_status_fn(kPresent)) .status(), StatusIs(absl::StatusCode::kUnimplemented)); EXPECT_THAT( WhereOp{}(kPresent, as_error_status_fn(), as_fn(kPresent)).status(), StatusIs(absl::StatusCode::kUnimplemented)); EXPECT_THAT(WhereOp{}(kPresent, as_error_status_fn(), kPresent).status(), StatusIs(absl::StatusCode::kUnimplemented)); } TEST_F(LogicOperatorsTest, LazyPresenceOrWithStatusFunctor) { auto as_fn = [](auto x) { return [x]() { return absl::StatusOr<std::decay_t<decltype(x)>>(x); }; }; EXPECT_THAT(PresenceOrOp{}(kPresent, as_fn(kPresent)), IsOkAndHolds(kPresent)); EXPECT_THAT(PresenceOrOp{}(kPresent, as_fn(kMissing)), IsOkAndHolds(kPresent)); EXPECT_THAT(PresenceOrOp{}(kMissing, as_fn(kMissing)), IsOkAndHolds(kMissing)); EXPECT_THAT(PresenceOrOp{}(one, as_fn(one)), Eq(one)); EXPECT_THAT(PresenceOrOp{}(one, as_fn(optional_two)), Eq(one)); EXPECT_THAT(PresenceOrOp{}(missing, as_fn(one)), IsOkAndHolds(one)); EXPECT_THAT(PresenceOrOp{}(optional_two, as_fn(one)), IsOkAndHolds(two)); EXPECT_THAT(PresenceOrOp{}(optional_two, as_fn(optional_one)), IsOkAndHolds(optional_two)); EXPECT_THAT(PresenceOrOp{}(optional_two, as_fn(missing)), IsOkAndHolds(optional_two)); EXPECT_THAT(PresenceOrOp{}(missing, as_fn(optional_two)), IsOkAndHolds(optional_two)); EXPECT_THAT(PresenceOrOp{}(missing, as_fn(missing)), IsOkAndHolds(missing)); auto error_fn = []() { return absl::StatusOr<OptionalUnit>(absl::InternalError("fake")); }; EXPECT_THAT(PresenceOrOp{}(kMissing, error_fn), StatusIs(absl::StatusCode::kInternal, HasSubstr("fake"))); EXPECT_THAT(PresenceOrOp{}(kPresent, error_fn), IsOkAndHolds(kPresent)); } TEST_F(LogicOperatorsTest, PresenceOrVarargs) { EXPECT_THAT( InvokeOperator<OptionalUnit>("core._presence_or", kPresent, kPresent), IsOkAndHolds(kPresent)); EXPECT_THAT( InvokeOperator<OptionalUnit>("core._presence_or", kPresent, kMissing), IsOkAndHolds(kPresent)); EXPECT_THAT( InvokeOperator<OptionalUnit>("core._presence_or", kMissing, kMissing), IsOkAndHolds(kMissing)); EXPECT_THAT(InvokeOperator<OptionalUnit>("core._presence_or", kMissing, kMissing, kMissing, kPresent), IsOkAndHolds(kPresent)); EXPECT_THAT(InvokeOperator<OptionalUnit>("core._presence_or", kMissing, kMissing, kMissing, kMissing), IsOkAndHolds(kMissing)); EXPECT_THAT(InvokeOperator<int64_t>("core._presence_or", missing, one), IsOkAndHolds(one)); EXPECT_THAT(InvokeOperator<int64_t>("core._presence_or", optional_two, one), IsOkAndHolds(two)); EXPECT_THAT(InvokeOperator<int64_t>("core._presence_or", missing, missing, optional_two, one), IsOkAndHolds(two)); EXPECT_THAT(InvokeOperator<int64_t>("core._presence_or", missing, missing, missing, one), IsOkAndHolds(one)); EXPECT_THAT( InvokeOperator<Oi64>("core._presence_or", optional_two, optional_one), IsOkAndHolds(optional_two)); EXPECT_THAT(InvokeOperator<Oi64>("core._presence_or", optional_two, missing), IsOkAndHolds(optional_two)); EXPECT_THAT(InvokeOperator<Oi64>("core._presence_or", missing, optional_two), IsOkAndHolds(optional_two)); EXPECT_THAT(InvokeOperator<Oi64>("core._presence_or", missing, missing), IsOkAndHolds(missing)); EXPECT_THAT(InvokeOperator<Oi64>("core._presence_or", missing, missing, optional_two, missing, optional_one), IsOkAndHolds(optional_two)); EXPECT_THAT(InvokeOperator<Oi64>("core._presence_or", missing, missing, missing, missing, missing), IsOkAndHolds(missing)); EXPECT_THAT(InvokeOperator<OptionalUnit>("core._presence_or", kMissing), StatusIs(absl::StatusCode::kNotFound, HasSubstr("expected at least two arguments"))); EXPECT_THAT( InvokeOperator<int64_t>("core._presence_or", one, two), StatusIs(absl::StatusCode::kNotFound, HasSubstr("expected all except last argument to be optional"))); EXPECT_THAT( InvokeOperator<OptionalUnit>("core._presence_or", kMissing, two), StatusIs( absl::StatusCode::kNotFound, HasSubstr("expected all arguments to have a common value type"))); EXPECT_THAT( InvokeOperator<OptionalUnit>("core._presence_or", kMissing, Unit{}), StatusIs( absl::StatusCode::kNotFound, HasSubstr( "for Unit value type, expected final argument to be optional"))); } TEST_F(LogicOperatorsTest, PresenceAndOr) { EXPECT_THAT( InvokeOperator<int64_t>("core._presence_and_or", one, kPresent, two), IsOkAndHolds(one)); EXPECT_THAT( InvokeOperator<int64_t>("core._presence_and_or", one, kMissing, two), IsOkAndHolds(two)); EXPECT_THAT(InvokeOperator<Oi64>("core._presence_and_or", optional_one, kPresent, optional_two), IsOkAndHolds(optional_one)); EXPECT_THAT(InvokeOperator<Oi64>("core._presence_and_or", optional_one, kMissing, optional_two), IsOkAndHolds(optional_two)); EXPECT_THAT(InvokeOperator<Oi64>("core._presence_and_or", optional_one, kPresent, missing), IsOkAndHolds(optional_one)); EXPECT_THAT(InvokeOperator<Oi64>("core._presence_and_or", missing, kMissing, optional_two), IsOkAndHolds(optional_two)); EXPECT_THAT(InvokeOperator<Oi64>("core._presence_and_or", missing, kPresent, optional_two), IsOkAndHolds(optional_two)); EXPECT_THAT( InvokeOperator<int64_t>("core._presence_and_or", missing, kPresent, two), IsOkAndHolds(two)); EXPECT_THAT(InvokeOperator<Oi64>("core._presence_and_or", optional_one, kMissing, missing), IsOkAndHolds(missing)); } TEST_F(LogicOperatorsTest, LazyPresenceAndOrFunctor) { auto as_fn = [](auto x) { return [x]() { return x; }; }; auto as_no_call_fn = [](auto x) { return [x]() { ADD_FAILURE() << "function shouldn't be called"; return x; }; }; EXPECT_EQ(PresenceAndOrOp{}(one, kPresent, as_no_call_fn(two)), one); EXPECT_EQ(PresenceAndOrOp{}(one, kMissing, as_fn(two)), two); EXPECT_EQ( PresenceAndOrOp{}(optional_one, kPresent, as_no_call_fn(optional_two)), optional_one); EXPECT_EQ(PresenceAndOrOp{}(optional_one, kMissing, as_fn(optional_two)), optional_two); EXPECT_EQ(PresenceAndOrOp{}(optional_one, kPresent, as_no_call_fn(missing)), optional_one); EXPECT_EQ(PresenceAndOrOp{}(missing, kMissing, as_fn(optional_two)), optional_two); EXPECT_EQ(PresenceAndOrOp{}(missing, kPresent, as_fn(optional_two)), optional_two); EXPECT_EQ(PresenceAndOrOp{}(missing, kPresent, as_fn(two)), two); EXPECT_EQ(PresenceAndOrOp{}(optional_one, kMissing, as_fn(missing)), missing); } TEST_F(LogicOperatorsTest, LazyPresenceAndOrWithStatusFunctor) { auto as_fn = [](auto x) { return [x]() { return absl::StatusOr<std::decay_t<decltype(x)>>(x); }; }; EXPECT_THAT(PresenceAndOrOp{}(one, kPresent, as_fn(two)), IsOkAndHolds(one)); EXPECT_THAT(PresenceAndOrOp{}(one, kMissing, as_fn(two)), IsOkAndHolds(two)); EXPECT_THAT(PresenceAndOrOp{}(optional_one, kPresent, as_fn(optional_two)), IsOkAndHolds(optional_one)); EXPECT_THAT(PresenceAndOrOp{}(optional_one, kMissing, as_fn(optional_two)), IsOkAndHolds(optional_two)); EXPECT_THAT(PresenceAndOrOp{}(optional_one, kPresent, as_fn(missing)), IsOkAndHolds(optional_one)); EXPECT_THAT(PresenceAndOrOp{}(missing, kMissing, as_fn(optional_two)), IsOkAndHolds(optional_two)); EXPECT_THAT(PresenceAndOrOp{}(missing, kPresent, as_fn(optional_two)), IsOkAndHolds(optional_two)); EXPECT_THAT(PresenceAndOrOp{}(missing, kPresent, as_fn(two)), IsOkAndHolds(two)); EXPECT_THAT(PresenceAndOrOp{}(optional_one, kMissing, as_fn(missing)), IsOkAndHolds(missing)); auto error_fn = []() { return absl::StatusOr<OptionalUnit>(absl::InternalError("fake")); }; EXPECT_THAT(PresenceAndOrOp{}(kMissing, kMissing, error_fn), StatusIs(absl::StatusCode::kInternal, HasSubstr("fake"))); EXPECT_THAT(PresenceAndOrOp{}(kPresent, kMissing, error_fn), StatusIs(absl::StatusCode::kInternal, HasSubstr("fake"))); EXPECT_THAT(PresenceAndOrOp{}(kPresent, kPresent, error_fn), IsOkAndHolds(kPresent)); } TEST_F(LogicOperatorsTest, PresenceAnd) { EXPECT_THAT(InvokeOperator<int64_t>("core.presence_and", one, kUnit), IsOkAndHolds(one)); EXPECT_THAT( InvokeOperator<OptionalUnit>("core.presence_and", kPresent, kPresent), IsOkAndHolds(kPresent)); EXPECT_THAT( InvokeOperator<OptionalUnit>("core.presence_and", kPresent, kMissing), IsOkAndHolds(kMissing)); EXPECT_THAT(InvokeOperator<Oi64>("core.presence_and", one, kPresent), IsOkAndHolds(optional_one)); EXPECT_THAT(InvokeOperator<Oi64>("core.presence_and", one, kMissing), IsOkAndHolds(missing)); EXPECT_THAT(InvokeOperator<Oi64>("core.presence_and", missing, kPresent), IsOkAndHolds(missing)); EXPECT_THAT(InvokeOperator<Oi64>("core.presence_and", optional_one, kPresent), IsOkAndHolds(optional_one)); EXPECT_THAT(InvokeOperator<Oi64>("core.presence_and", optional_one, kMissing), IsOkAndHolds(missing)); } TEST_F(LogicOperatorsTest, LazyPresenceAndFunctor) { auto as_fn = [](auto x) { return [x]() { return x; }; }; auto as_no_call_fn = [](auto x) { return [x]() { ADD_FAILURE() << "function shouldn't be called"; return x; }; }; EXPECT_EQ(PresenceAndOp{}(as_fn(one), kUnit), one); EXPECT_EQ(PresenceAndOp{}(as_fn(kPresent), kPresent), kPresent); EXPECT_EQ(PresenceAndOp{}(as_no_call_fn(kPresent), kMissing), kMissing); EXPECT_EQ(PresenceAndOp{}(as_fn(one), kPresent), optional_one); EXPECT_EQ(PresenceAndOp{}(as_no_call_fn(one), kMissing), missing); EXPECT_EQ(PresenceAndOp{}(as_fn(missing), kPresent), missing); EXPECT_EQ(PresenceAndOp{}(as_fn(optional_one), kPresent), optional_one); EXPECT_EQ(PresenceAndOp{}(as_no_call_fn(optional_one), kMissing), missing); } TEST_F(LogicOperatorsTest, LazyPresenceAndWithStatusFunctor) { auto as_fn = [](auto x) { return [x]() { return absl::StatusOr<std::decay_t<decltype(x)>>(x); }; }; EXPECT_THAT(PresenceAndOp{}(as_fn(one), kUnit), IsOkAndHolds(one)); EXPECT_THAT(PresenceAndOp{}(as_fn(kPresent), kPresent), IsOkAndHolds(kPresent)); EXPECT_THAT(PresenceAndOp{}(as_fn(kPresent), kMissing), IsOkAndHolds(kMissing)); EXPECT_THAT(PresenceAndOp{}(as_fn(one), kPresent), IsOkAndHolds(optional_one)); EXPECT_THAT(PresenceAndOp{}(as_fn(one), kMissing), IsOkAndHolds(missing)); EXPECT_THAT(PresenceAndOp{}(as_fn(missing), kPresent), IsOkAndHolds(missing)); EXPECT_THAT(PresenceAndOp{}(as_fn(optional_one), kPresent), IsOkAndHolds(optional_one)); EXPECT_THAT(PresenceAndOp{}(as_fn(optional_one), kMissing), IsOkAndHolds(missing)); auto error_fn = []() { return absl::StatusOr<OptionalUnit>(absl::InternalError("fake")); }; EXPECT_THAT(PresenceAndOp{}(error_fn, kPresent), StatusIs(absl::StatusCode::kInternal, HasSubstr("fake"))); EXPECT_THAT(PresenceAndOp{}(error_fn, kMissing), IsOkAndHolds(kMissing)); } TEST_F(LogicOperatorsTest, PresenceNot) { EXPECT_THAT( InvokeOperator<OptionalUnit>("core.presence_not._builtin", kPresent), IsOkAndHolds(kMissing)); EXPECT_THAT(InvokeOperator<OptionalUnit>("core.presence_not._builtin", OptionalValue<float>{0.0f}), IsOkAndHolds(kMissing)); EXPECT_THAT(InvokeOperator<OptionalUnit>("core.presence_not._builtin", OptionalValue<float>{}), IsOkAndHolds(kPresent)); } #define EXPECT_LOGIC_OPERATOR(op_name, lhs, rhs, result) \ EXPECT_THAT(InvokeOperator<OptionalUnit>(op_name, lhs, rhs), \ IsOkAndHolds(result)); TEST_F(LogicOperatorsTest, MaskEqual) { Text foo("foo"); Text bar("bar"); OptionalValue<Text> optional_foo = Text("foo"); OptionalValue<Text> optional_bar = Text("bar"); OptionalValue<Text> missing_text; const std::string op_name = "core.equal"; EXPECT_LOGIC_OPERATOR(op_name, one, one, kPresent); EXPECT_LOGIC_OPERATOR(op_name, one, two, kMissing); EXPECT_LOGIC_OPERATOR(op_name, optional_one, optional_one, kPresent); EXPECT_LOGIC_OPERATOR(op_name, optional_one, optional_two, kMissing); EXPECT_LOGIC_OPERATOR(op_name, optional_one, missing, kMissing); EXPECT_LOGIC_OPERATOR(op_name, missing, missing, kMissing); EXPECT_LOGIC_OPERATOR(op_name, foo, foo, kPresent); EXPECT_LOGIC_OPERATOR(op_name, foo, bar, kMissing); EXPECT_LOGIC_OPERATOR(op_name, optional_foo, optional_foo, kPresent); EXPECT_LOGIC_OPERATOR(op_name, optional_foo, optional_bar, kMissing); EXPECT_LOGIC_OPERATOR(op_name, optional_foo, missing_text, kMissing); } TEST_F(LogicOperatorsTest, MaskNotEqual) { Text foo("foo"); Text bar("bar"); OptionalValue<Text> optional_foo = Text("foo"); OptionalValue<Text> optional_bar = Text("bar"); OptionalValue<Text> missing_text; const std::string op_name = "core.not_equal"; EXPECT_LOGIC_OPERATOR(op_name, one, one, kMissing); EXPECT_LOGIC_OPERATOR(op_name, one, two, kPresent); EXPECT_LOGIC_OPERATOR(op_name, optional_one, optional_one, kMissing); EXPECT_LOGIC_OPERATOR(op_name, optional_one, optional_two, kPresent); EXPECT_LOGIC_OPERATOR(op_name, optional_one, missing, kMissing); EXPECT_LOGIC_OPERATOR(op_name, missing, missing, kMissing); EXPECT_LOGIC_OPERATOR(op_name, foo, foo, kMissing); EXPECT_LOGIC_OPERATOR(op_name, foo, bar, kPresent); EXPECT_LOGIC_OPERATOR(op_name, optional_foo, optional_foo, kMissing); EXPECT_LOGIC_OPERATOR(op_name, optional_foo, optional_bar, kPresent); EXPECT_LOGIC_OPERATOR(op_name, optional_foo, missing_text, kMissing); } TEST_F(LogicOperatorsTest, MaskLess) { Text foo("foo"); Text bar("bar"); OptionalValue<Text> optional_foo = Text("foo"); OptionalValue<Text> optional_bar = Text("bar"); OptionalValue<Text> missing_text; const std::string op_name = "core.less"; EXPECT_LOGIC_OPERATOR(op_name, one, one, kMissing); EXPECT_LOGIC_OPERATOR(op_name, one, two, kPresent); EXPECT_LOGIC_OPERATOR(op_name, two, one, kMissing); EXPECT_LOGIC_OPERATOR(op_name, optional_one, optional_two, kPresent); EXPECT_LOGIC_OPERATOR(op_name, optional_one, optional_one, kMissing); EXPECT_LOGIC_OPERATOR(op_name, optional_two, optional_one, kMissing); EXPECT_LOGIC_OPERATOR(op_name, optional_one, missing, kMissing); EXPECT_LOGIC_OPERATOR(op_name, missing, missing, kMissing); EXPECT_LOGIC_OPERATOR(op_name, foo, foo, kMissing); EXPECT_LOGIC_OPERATOR(op_name, foo, bar, kMissing); EXPECT_LOGIC_OPERATOR(op_name, bar, foo, kPresent); EXPECT_LOGIC_OPERATOR(op_name, optional_foo, optional_foo, kMissing); EXPECT_LOGIC_OPERATOR(op_name, optional_foo, optional_bar, kMissing); EXPECT_LOGIC_OPERATOR(op_name, optional_bar, optional_foo, kPresent); EXPECT_LOGIC_OPERATOR(op_name, optional_foo, missing_text, kMissing); } TEST_F(LogicOperatorsTest, MaskLessEqual) { Text foo("foo"); Text bar("bar"); OptionalValue<Text> optional_foo = Text("foo"); OptionalValue<Text> optional_bar = Text("bar"); OptionalValue<Text> missing_text; const std::string op_name = "core.less_equal"; EXPECT_LOGIC_OPERATOR(op_name, one, one, kPresent); EXPECT_LOGIC_OPERATOR(op_name, one, two, kPresent); EXPECT_LOGIC_OPERATOR(op_name, two, one, kMissing); EXPECT_LOGIC_OPERATOR(op_name, optional_one, optional_two, kPresent); EXPECT_LOGIC_OPERATOR(op_name, optional_one, optional_one, kPresent); EXPECT_LOGIC_OPERATOR(op_name, optional_two, optional_one, kMissing); EXPECT_LOGIC_OPERATOR(op_name, optional_one, missing, kMissing); EXPECT_LOGIC_OPERATOR(op_name, missing, missing, kMissing); EXPECT_LOGIC_OPERATOR(op_name, foo, foo, kPresent); EXPECT_LOGIC_OPERATOR(op_name, foo, bar, kMissing); EXPECT_LOGIC_OPERATOR(op_name, bar, foo, kPresent); EXPECT_LOGIC_OPERATOR(op_name, optional_foo, optional_foo, kPresent); EXPECT_LOGIC_OPERATOR(op_name, optional_foo, optional_bar, kMissing); EXPECT_LOGIC_OPERATOR(op_name, optional_bar, optional_foo, kPresent); EXPECT_LOGIC_OPERATOR(op_name, optional_foo, missing_text, kMissing); } } }
2,377
#ifndef AROLLA_QEXPR_CORE_UTILITY_OPERATORS_H_ #define AROLLA_QEXPR_CORE_UTILITY_OPERATORS_H_ #include "arolla/qexpr/operators.h" #include "arolla/qtype/qtype.h" namespace arolla { OperatorPtr MakeCopyOp(QTypePtr type); } #endif #include "arolla/qexpr/operators/core/utility_operators.h" #include <memory> #include <string> #include "absl/status/statusor.h" #include "absl/types/span.h" #include "arolla/memory/frame.h" #include "arolla/qexpr/bound_operators.h" #include "arolla/qexpr/eval_context.h" #include "arolla/qexpr/operators.h" #include "arolla/qexpr/qexpr_operator_signature.h" #include "arolla/qtype/qtype.h" namespace arolla { namespace { class CopyOperator : public QExprOperator { public: explicit CopyOperator(QTypePtr type) : QExprOperator("core._copy", QExprOperatorSignature::Get({type}, type)) { } private: absl::StatusOr<std::unique_ptr<BoundOperator>> DoBind( absl::Span<const TypedSlot> input_slots, TypedSlot output_slot) const final { return MakeBoundOperator( [input_slot = input_slots[0], output_slot = output_slot]( EvaluationContext*, FramePtr frame) { input_slot.CopyTo(frame, output_slot, frame); }); } }; } OperatorPtr MakeCopyOp(QTypePtr type) { return OperatorPtr(std::make_unique<CopyOperator>(type)); } }
#include "arolla/qexpr/operators/core/utility_operators.h" #include <utility> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "arolla/memory/frame.h" #include "arolla/qexpr/eval_context.h" #include "arolla/qexpr/operators.h" #include "arolla/qexpr/qexpr_operator_signature.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/tuple_qtype.h" #include "arolla/qtype/typed_slot.h" namespace arolla { namespace { using ::testing::Eq; TEST(UtilityOperatorsTest, Identity) { auto i32 = GetQType<int>(); auto copy_op = MakeCopyOp(i32); ASSERT_EQ(copy_op->signature(), QExprOperatorSignature::Get({i32}, i32)); FrameLayout::Builder layout_builder; auto i0_slot = layout_builder.AddSlot<int>(); auto i1_slot = layout_builder.AddSlot<int>(); ASSERT_OK_AND_ASSIGN( auto copy_bound_op0, copy_op->Bind(ToTypedSlots(i0_slot), TypedSlot::FromSlot(i1_slot))); auto memory_layout = std::move(layout_builder).Build(); RootEvaluationContext root_ctx(&memory_layout); EvaluationContext ctx(root_ctx); root_ctx.Set(i0_slot, 7); copy_bound_op0->Run(&ctx, root_ctx.frame()); EXPECT_OK(ctx.status()); EXPECT_THAT(root_ctx.Get(i1_slot), Eq(7)); } TEST(UtilityOperatorsTest, MakeTuple) { auto i32 = GetQType<int>(); auto f64 = GetQType<double>(); auto tuple_qtype = MakeTupleQType({i32, f64}); ASSERT_OK_AND_ASSIGN(auto copy_op, OperatorRegistry::GetInstance()->LookupOperator( "core.make_tuple", {i32, f64}, tuple_qtype)); ASSERT_EQ(copy_op->signature(), QExprOperatorSignature::Get({i32, f64}, tuple_qtype)); FrameLayout::Builder layout_builder; auto tuple0_slot = AddSlot(tuple_qtype, &layout_builder); ASSERT_EQ(tuple0_slot.SubSlotCount(), 2); ASSERT_OK_AND_ASSIGN(auto i0_slot, tuple0_slot.SubSlot(0).ToSlot<int>()); ASSERT_OK_AND_ASSIGN(auto d0_slot, tuple0_slot.SubSlot(1).ToSlot<double>()); auto tuple1_slot = AddSlot(tuple_qtype, &layout_builder); ASSERT_EQ(tuple1_slot.SubSlotCount(), 2); ASSERT_OK_AND_ASSIGN(auto i1_slot, tuple1_slot.SubSlot(0).ToSlot<int>()); ASSERT_OK_AND_ASSIGN(auto d1_slot, tuple1_slot.SubSlot(1).ToSlot<double>()); ASSERT_OK_AND_ASSIGN( auto copy_bound_op, copy_op->Bind(ToTypedSlots(i0_slot, d0_slot), {tuple1_slot})); auto memory_layout = std::move(layout_builder).Build(); RootEvaluationContext root_ctx(&memory_layout); EvaluationContext ctx(root_ctx); root_ctx.Set(i0_slot, 7); root_ctx.Set(d0_slot, 4.5); copy_bound_op->Run(&ctx, root_ctx.frame()); EXPECT_OK(ctx.status()); EXPECT_THAT(root_ctx.Get(i1_slot), Eq(7)); EXPECT_THAT(root_ctx.Get(d1_slot), Eq(4.5)); } } }
2,378
#ifndef AROLLA_QEXPR_EVAL_EXTENSIONS_SEQ_REDUCE_OPERATOR_H_ #define AROLLA_QEXPR_EVAL_EXTENSIONS_SEQ_REDUCE_OPERATOR_H_ #include "absl/status/statusor.h" #include "absl/types/span.h" #include "arolla/expr/basic_expr_operator.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_operator.h" namespace arolla::expr::eval_internal { class PackedSeqReduceOperator final : public BuiltinExprOperatorTag, public ExprOperatorWithFixedSignature { public: explicit PackedSeqReduceOperator(ExprOperatorPtr op); const ExprOperatorPtr& op() const { return op_; } absl::StatusOr<ExprAttributes> InferAttributes( absl::Span<const ExprAttributes> inputs) const final; private: ExprOperatorPtr op_; }; } #endif #include "arolla/qexpr/eval_extensions/seq_reduce_operator.h" #include <cstddef> #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/strings/str_join.h" #include "absl/types/span.h" #include "arolla/expr/basic_expr_operator.h" #include "arolla/expr/eval/dynamic_compiled_expr.h" #include "arolla/expr/eval/eval.h" #include "arolla/expr/eval/executable_builder.h" #include "arolla/expr/eval/extensions.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/registered_expr_operator.h" #include "arolla/expr/seq_reduce_expr_operator.h" #include "arolla/memory/frame.h" #include "arolla/qexpr/bound_operators.h" #include "arolla/qexpr/eval_context.h" #include "arolla/qexpr/evaluation_engine.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_slot.h" #include "arolla/qtype/typed_value.h" #include "arolla/sequence/sequence.h" #include "arolla/sequence/sequence_qtype.h" #include "arolla/util/fingerprint.h" #include "arolla/util/init_arolla.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr::eval_internal { namespace { absl::StatusOr<ExprNodePtr> SeqReduceOperatorTransformation( const DynamicEvaluationEngineOptions&, ExprNodePtr node) { ASSIGN_OR_RETURN(auto seq_reduce_op, DecayRegisteredOperator(node->op())); if (seq_reduce_op == nullptr || typeid(*seq_reduce_op) != typeid(SeqReduceOperator)) { return node; } const auto& node_deps = node->node_deps(); if (node_deps.size() != 3) { return absl::FailedPreconditionError( absl::StrFormat("unexpected number of arguments: expected 3, got %d", node_deps.size())); } const auto& op_node = node_deps[0]; if (op_node->qtype() == nullptr) { return absl::FailedPreconditionError("missing node_deps[0].qtype"); } if (op_node->qtype() != GetQType<ExprOperatorPtr>()) { return absl::FailedPreconditionError(absl::StrFormat( "unexpected node_deps[0].qtype: expected %s, got %s", GetQType<ExprOperatorPtr>()->name(), op_node->qtype()->name())); } const auto& op_qvalue = op_node->qvalue(); if (!op_qvalue.has_value()) { return absl::FailedPreconditionError("missing node_deps[0].literal_value"); } DCHECK(op_qvalue->GetType() == GetQType<ExprOperatorPtr>()); const auto& op = op_qvalue->UnsafeAs<ExprOperatorPtr>(); return MakeOpNode( std::make_shared<PackedSeqReduceOperator>(op), std::vector<ExprNodePtr>(node_deps.begin() + 1, node_deps.end())); } std::optional<absl::Status> CompilePackedSeqReduceOperator( const CompileOperatorFnArgs& args) { const auto* reduce_op = dynamic_cast<const PackedSeqReduceOperator*>(args.op.get()); if (reduce_op == nullptr) { return std::nullopt; } if (args.input_slots.size() != 2) { return absl::FailedPreconditionError( absl::StrFormat("unexpected number of input slots: expected 2, got %d", args.input_slots.size())); } const auto& seq_slot = args.input_slots[0]; const auto& initial_slot = args.input_slots[1]; if (!IsSequenceQType(seq_slot.GetType())) { return absl::FailedPreconditionError( absl::StrFormat("expected a sequence type, got seq_qtype = %s", seq_slot.GetType()->name())); } const auto value_qtype = seq_slot.GetType()->value_qtype(); DCHECK(value_qtype != nullptr); const auto output_qtype = args.output_slot.GetType(); if (initial_slot.GetType() != output_qtype) { return absl::FailedPreconditionError( absl::StrFormat("expected initial_qtype == output_qtype: %s != %s", initial_slot.GetType()->name(), output_qtype->name())); } auto reducer_arg_1_slot = AddSlot(output_qtype, args.executable_builder->layout_builder()); auto reducer_arg_2_slot = AddSlot(value_qtype, args.executable_builder->layout_builder()); DynamicEvaluationEngineOptions subexpression_options(args.options); subexpression_options.enabled_preparation_stages = DynamicEvaluationEngineOptions::PreparationStage::kAll; ASSIGN_OR_RETURN( std::shared_ptr<BoundExpr> reducer_bound_expr, CompileAndBindExprOperator( subexpression_options, args.executable_builder->layout_builder(), reduce_op->op(), {reducer_arg_1_slot, reducer_arg_2_slot}, args.output_slot)); std::string init_op_description; std::string eval_op_description; if (args.options.collect_op_descriptions) { auto dynamic_bound_expr = dynamic_cast<const DynamicBoundExpr*>(reducer_bound_expr.get()); if (dynamic_bound_expr == nullptr) { return absl::InternalError("expected DynamicBoundExpr"); } auto init_op_name = absl::StrFormat( "%s:init{%s}", reduce_op->display_name(), absl::StrJoin(dynamic_bound_expr->init_op_descriptions(), "; ")); init_op_description = FormatOperatorCall(init_op_name, {}, {}); auto eval_op_name = absl::StrFormat( "%s:eval{%s}", reduce_op->display_name(), absl::StrJoin(dynamic_bound_expr->eval_op_descriptions(), "; ")); eval_op_description = FormatOperatorCall(eval_op_name, args.input_slots, {args.output_slot}); } args.executable_builder->AddInitOp( MakeBoundOperator( [reducer_bound_expr](EvaluationContext* ctx, FramePtr frame) { reducer_bound_expr->InitializeLiterals(ctx, frame); }), init_op_description); args.executable_builder->AddEvalOp( MakeBoundOperator( [reducer_bound_expr, initial_slot, seq_slot, output_slot = args.output_slot, reducer_arg_1_slot, reducer_arg_2_slot](EvaluationContext* ctx, FramePtr frame) { const auto& seq = frame.Get(seq_slot.UnsafeToSlot<Sequence>()); const auto* value_qtype = seq.value_qtype(); const size_t seq_size = seq.size(); const size_t value_size = value_qtype->type_layout().AllocSize(); initial_slot.CopyTo(frame, output_slot, frame); for (size_t i = 0; i < seq_size && ctx->status().ok(); ++i) { output_slot.CopyTo(frame, reducer_arg_1_slot, frame); value_qtype->UnsafeCopy( seq.RawAt(i, value_size), frame.GetRawPointer(reducer_arg_2_slot.byte_offset())); reducer_bound_expr->Execute(ctx, frame); } }), eval_op_description, "seq.reduce"); return absl::OkStatus(); } } PackedSeqReduceOperator::PackedSeqReduceOperator(ExprOperatorPtr op) : ExprOperatorWithFixedSignature( absl::StrFormat("packed_seq_reduce[%s]", op->display_name()), ExprOperatorSignature{{"seq"}, {"initial"}}, "(internal operator) packed seq.reduce", FingerprintHasher( "arolla::expr::eval_internal::PackedSeqReduceOperator") .Combine(op->fingerprint()) .Finish()), op_(std::move(op)) {} absl::StatusOr<ExprAttributes> PackedSeqReduceOperator::InferAttributes( absl::Span<const ExprAttributes> inputs) const { std::vector<ExprAttributes> new_inputs; new_inputs.reserve(inputs.size() + 1); new_inputs.emplace_back(GetQType<ExprOperatorPtr>(), TypedValue::FromValue(op_)); new_inputs.insert(new_inputs.end(), inputs.begin(), inputs.end()); return SeqReduceOperator::Make()->InferAttributes(new_inputs); } AROLLA_REGISTER_INITIALIZER( kRegisterQExprOperators, seq_reduce_operator_eval_extensions, [] { ::arolla::expr::eval_internal::CompilerExtensionRegistry::GetInstance() .RegisterNodeTransformationFn(SeqReduceOperatorTransformation); ::arolla::expr::eval_internal::CompilerExtensionRegistry::GetInstance() .RegisterCompileOperatorFn(CompilePackedSeqReduceOperator); }); }
#include "arolla/qexpr/eval_extensions/seq_reduce_operator.h" #include <cstdint> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "arolla/expr/annotation_expr_operators.h" #include "arolla/expr/eval/eval.h" #include "arolla/expr/eval/prepare_expression.h" #include "arolla/expr/eval/test_utils.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/lambda_expr_operator.h" #include "arolla/expr/registered_expr_operator.h" #include "arolla/expr/testing/testing.h" #include "arolla/memory/frame.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_slot.h" #include "arolla/sequence/sequence_qtype.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla::expr::eval_internal { namespace { using ::arolla::testing::EqualsExpr; using ::arolla::testing::IsOkAndHolds; using ::testing::ElementsAre; using ::testing::Eq; using ::testing::NotNull; class SeqReduceOperatorTest : public ::testing::Test { protected: void SetUp() override { ASSERT_OK(InitArolla()); } }; TEST_F(SeqReduceOperatorTest, SeqMapOperatorTransformation) { ASSERT_OK_AND_ASSIGN(ExprOperatorPtr add_operator, LookupOperator("math.add")); ASSERT_OK_AND_ASSIGN(auto expr, CallOp("seq.reduce", {Literal(add_operator), Leaf("xs"), Literal(int32_t{0})})); EXPECT_THAT(expr->qtype(), Eq(GetQType<int32_t>())); QTypePtr seq_i32 = GetSequenceQType(GetQType<int32_t>()); ASSERT_OK_AND_ASSIGN(auto prepared_expr, PrepareExpression(expr, {{"xs", seq_i32}}, DynamicEvaluationEngineOptions{})); EXPECT_THAT(prepared_expr->qtype(), Eq(GetQType<int32_t>())); auto packed_op = dynamic_cast<const PackedSeqReduceOperator*>(prepared_expr->op().get()); ASSERT_THAT(packed_op, NotNull()); EXPECT_THAT(packed_op->op()->display_name(), Eq("math.add")); EXPECT_THAT(packed_op->display_name(), Eq("packed_seq_reduce[math.add]")); EXPECT_THAT(prepared_expr->node_deps(), ElementsAre( EqualsExpr(CallOp(QTypeAnnotation::Make(), {Leaf("xs"), Literal(seq_i32)})), EqualsExpr(Literal(int32_t{0})))); } TEST_F(SeqReduceOperatorTest, CompilePackedSeqReduceOperator) { ASSERT_OK_AND_ASSIGN( ExprOperatorPtr x_plus_y_mul_2, MakeLambdaOperator( "x_plus_y_mul_2", ExprOperatorSignature::Make("x, y"), CallOp("math.multiply", {CallOp("math.add", {Placeholder("x"), Placeholder("y")}), Literal(int32_t{2})}))); ASSERT_OK_AND_ASSIGN( auto expr, CallOp("seq.reduce", {Literal(x_plus_y_mul_2), Leaf("xs"), Literal(int32_t{0})})); QTypePtr seq_i32 = GetSequenceQType(GetQType<int32_t>()); FrameLayout::Builder layout_builder; auto xs_slot = AddSlot(seq_i32, &layout_builder); DynamicEvaluationEngineOptions options{.collect_op_descriptions = true}; EXPECT_THAT( CompileAndBindForDynamicEvaluation(options, &layout_builder, expr, {{"xs", xs_slot}}), IsOkAndHolds(AllOf( InitOperationsAre("packed_seq_reduce[x_plus_y_mul_2]:init{" "INT32 [0x34] = 2" "}()", "INT32 [0x24] = 0"), EvalOperationsAre( "INT32 [0x20] = packed_seq_reduce[x_plus_y_mul_2]:eval{" "INT32 [0x30] = math.add(INT32 [0x28], INT32 [0x2C]); " "INT32 [0x20] = math.multiply(INT32 [0x30], INT32 [0x34])" "}(SEQUENCE[INT32] [0x00], INT32 [0x24])")))); } } }
2,379
#ifndef AROLLA_QEXPR_EVAL_EXTENSIONS_SEQ_MAP_OPERATOR_H_ #define AROLLA_QEXPR_EVAL_EXTENSIONS_SEQ_MAP_OPERATOR_H_ #include "absl/status/statusor.h" #include "absl/types/span.h" #include "arolla/expr/basic_expr_operator.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_operator.h" namespace arolla::expr::eval_internal { class PackedSeqMapOperator final : public BuiltinExprOperatorTag, public ExprOperatorWithFixedSignature { public: explicit PackedSeqMapOperator(ExprOperatorPtr op); const ExprOperatorPtr& op() const { return op_; } absl::StatusOr<ExprAttributes> InferAttributes( absl::Span<const ExprAttributes> inputs) const final; private: ExprOperatorPtr op_; }; } #endif #include "arolla/qexpr/eval_extensions/seq_map_operator.h" #include <cstddef> #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/strings/str_join.h" #include "absl/types/span.h" #include "arolla/expr/basic_expr_operator.h" #include "arolla/expr/eval/dynamic_compiled_expr.h" #include "arolla/expr/eval/eval.h" #include "arolla/expr/eval/executable_builder.h" #include "arolla/expr/eval/extensions.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/registered_expr_operator.h" #include "arolla/expr/seq_map_expr_operator.h" #include "arolla/memory/frame.h" #include "arolla/qexpr/bound_operators.h" #include "arolla/qexpr/eval_context.h" #include "arolla/qexpr/evaluation_engine.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_slot.h" #include "arolla/qtype/typed_value.h" #include "arolla/sequence/mutable_sequence.h" #include "arolla/sequence/sequence.h" #include "arolla/sequence/sequence_qtype.h" #include "arolla/util/fingerprint.h" #include "arolla/util/init_arolla.h" #include "arolla/util/status_macros_backport.h" namespace arolla::expr::eval_internal { namespace { absl::StatusOr<ExprNodePtr> SeqMapOperatorTransformation( const DynamicEvaluationEngineOptions&, ExprNodePtr node) { ASSIGN_OR_RETURN(auto seq_map_op, DecayRegisteredOperator(node->op())); if (seq_map_op == nullptr || typeid(*seq_map_op) != typeid(SeqMapOperator)) { return node; } const auto& node_deps = node->node_deps(); if (node_deps.size() < 2) { return absl::FailedPreconditionError(absl::StrFormat( "unexpected number of arguments: expected at least two, got %d", node_deps.size())); } const auto& op_node = node_deps[0]; if (op_node->qtype() == nullptr) { return absl::FailedPreconditionError("missing node_deps[0].qtype"); } if (op_node->qtype() != GetQType<ExprOperatorPtr>()) { return absl::FailedPreconditionError(absl::StrFormat( "unexpected node_deps[0].qtype: expected %s, got %s", GetQType<ExprOperatorPtr>()->name(), op_node->qtype()->name())); } const auto& op_qvalue = op_node->qvalue(); if (!op_qvalue.has_value()) { return absl::FailedPreconditionError("missing node_deps[0].literal_value"); } DCHECK(op_qvalue->GetType() == GetQType<ExprOperatorPtr>()); const auto& op = op_qvalue->UnsafeAs<ExprOperatorPtr>(); return MakeOpNode( std::make_shared<PackedSeqMapOperator>(op), std::vector<ExprNodePtr>(node_deps.begin() + 1, node_deps.end())); } std::optional<absl::Status> CompilePackedSeqMapOperator( const CompileOperatorFnArgs& args) { const auto* map_op = dynamic_cast<const PackedSeqMapOperator*>(args.op.get()); if (map_op == nullptr) { return std::nullopt; } if (args.input_slots.empty()) { return absl::FailedPreconditionError( absl::StrFormat("expected at least one input slot, got none")); } if (!IsSequenceQType(args.output_slot.GetType())) { return absl::FailedPreconditionError( absl::StrFormat("expected a sequence type, got output_qtype = %s", args.output_slot.GetType()->name())); } std::vector<QTypePtr> value_qtypes; value_qtypes.reserve(args.input_slots.size()); for (size_t i = 0; i < args.input_slots.size(); ++i) { value_qtypes.push_back(args.input_slots[i].GetType()->value_qtype()); DCHECK(value_qtypes.back() != nullptr); } std::vector<TypedSlot> mapper_arg_slots; mapper_arg_slots.reserve(args.input_slots.size()); for (size_t i = 0; i < args.input_slots.size(); ++i) { mapper_arg_slots.push_back( AddSlot(value_qtypes[i], args.executable_builder->layout_builder())); } auto mapper_output_slot = AddSlot(args.output_slot.GetType()->value_qtype(), args.executable_builder->layout_builder()); DynamicEvaluationEngineOptions subexpression_options(args.options); subexpression_options.enabled_preparation_stages = DynamicEvaluationEngineOptions::PreparationStage::kAll; ASSIGN_OR_RETURN( std::shared_ptr<BoundExpr> mapper_bound_expr, CompileAndBindExprOperator( subexpression_options, args.executable_builder->layout_builder(), map_op->op(), mapper_arg_slots, mapper_output_slot)); std::string init_op_description; std::string eval_op_description; if (args.options.collect_op_descriptions) { auto dynamic_bound_expr = dynamic_cast<const DynamicBoundExpr*>(mapper_bound_expr.get()); if (dynamic_bound_expr == nullptr) { return absl::InternalError("expected DynamicBoundExpr"); } auto init_op_name = absl::StrFormat( "%s:init{%s}", map_op->display_name(), absl::StrJoin(dynamic_bound_expr->init_op_descriptions(), "; ")); init_op_description = FormatOperatorCall(init_op_name, {}, {}); auto eval_op_name = absl::StrFormat( "%s:eval{%s}", map_op->display_name(), absl::StrJoin(dynamic_bound_expr->eval_op_descriptions(), "; ")); eval_op_description = FormatOperatorCall(eval_op_name, args.input_slots, {args.output_slot}); } args.executable_builder->AddInitOp( MakeBoundOperator( [mapper_bound_expr](EvaluationContext* ctx, FramePtr frame) { mapper_bound_expr->InitializeLiterals(ctx, frame); }), init_op_description); args.executable_builder->AddEvalOp( MakeBoundOperator([input_slots = std::vector(args.input_slots.begin(), args.input_slots.end()), output_slot = args.output_slot, mapper_bound_expr, mapper_arg_slots, mapper_output_slot]( EvaluationContext* ctx, FramePtr frame) { std::optional<size_t> seq_size = std::nullopt; for (size_t i = 0; i < input_slots.size(); ++i) { const auto& cur_slot = input_slots[i]; const auto& seq = frame.Get(cur_slot.UnsafeToSlot<Sequence>()); if (seq_size.has_value() && *seq_size != seq.size()) { ctx->set_status(absl::InvalidArgumentError(absl::StrFormat( "expected all sequences to have the same length, got %d and %d", *seq_size, seq.size()))); return; } seq_size = seq.size(); } const size_t output_value_size = mapper_output_slot.GetType()->type_layout().AllocSize(); ASSIGN_OR_RETURN( auto mutable_sequence, MutableSequence::Make(mapper_output_slot.GetType(), *seq_size), ctx->set_status(std::move(_))); for (size_t i = 0; i < seq_size && ctx->status().ok(); ++i) { for (size_t arg_id = 0; arg_id < input_slots.size(); ++arg_id) { const auto& cur_slot = input_slots[arg_id]; const auto& seq = frame.Get(cur_slot.UnsafeToSlot<Sequence>()); seq.GetRef(i) .CopyToSlot(mapper_arg_slots[arg_id], frame) .IgnoreError(); } mapper_bound_expr->Execute(ctx, frame); mapper_output_slot.GetType()->UnsafeCopy( frame.GetRawPointer(mapper_output_slot.byte_offset()), mutable_sequence.RawAt(i, output_value_size)); } frame.Set(output_slot.UnsafeToSlot<Sequence>(), std::move(mutable_sequence).Finish()); }), eval_op_description, "seq.map"); return absl::OkStatus(); } } PackedSeqMapOperator::PackedSeqMapOperator(ExprOperatorPtr op) : ExprOperatorWithFixedSignature( absl::StrFormat("packed_seq_map[%s]", op->display_name()), ExprOperatorSignature::MakeVariadicArgs(), "(internal operator) packed seq.map", FingerprintHasher("arolla::expr::eval_internal::PackedSeqMapOperator") .Combine(op->fingerprint()) .Finish()), op_(std::move(op)) {} absl::StatusOr<ExprAttributes> PackedSeqMapOperator::InferAttributes( absl::Span<const ExprAttributes> inputs) const { std::vector<ExprAttributes> new_inputs; new_inputs.reserve(inputs.size() + 1); new_inputs.emplace_back(GetQType<ExprOperatorPtr>(), TypedValue::FromValue(op_)); new_inputs.insert(new_inputs.end(), inputs.begin(), inputs.end()); return SeqMapOperator::Make()->InferAttributes(new_inputs); } AROLLA_REGISTER_INITIALIZER( kRegisterQExprOperators, seq_map_operator_eval_extensions, [] { CompilerExtensionRegistry::GetInstance().RegisterNodeTransformationFn( SeqMapOperatorTransformation); CompilerExtensionRegistry::GetInstance().RegisterCompileOperatorFn( CompilePackedSeqMapOperator); }); }
#include "arolla/qexpr/eval_extensions/seq_map_operator.h" #include <cstdint> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "arolla/expr/annotation_expr_operators.h" #include "arolla/expr/eval/eval.h" #include "arolla/expr/eval/prepare_expression.h" #include "arolla/expr/eval/test_utils.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/lambda_expr_operator.h" #include "arolla/expr/registered_expr_operator.h" #include "arolla/expr/testing/testing.h" #include "arolla/memory/frame.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_slot.h" #include "arolla/sequence/sequence_qtype.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla::expr::eval_internal { namespace { using ::arolla::testing::EqualsExpr; using ::arolla::testing::IsOkAndHolds; using ::testing::ElementsAre; using ::testing::Eq; using ::testing::NotNull; class SeqMapOperatorTest : public ::testing::Test { protected: void SetUp() override { ASSERT_OK(InitArolla()); } }; TEST_F(SeqMapOperatorTest, SeqMapOperatorTransformation) { ASSERT_OK_AND_ASSIGN(ExprOperatorPtr add_operator, LookupOperator("math.add")); ASSERT_OK_AND_ASSIGN(auto expr, CallOp("seq.map", {Literal(add_operator), Leaf("xs"), Leaf("ys")})); EXPECT_THAT(expr->qtype(), Eq(nullptr)); QTypePtr seq_i32 = GetSequenceQType(GetQType<int32_t>()); ASSERT_OK_AND_ASSIGN( auto prepared_expr, PrepareExpression(expr, {{"xs", seq_i32}, {"ys", seq_i32}}, DynamicEvaluationEngineOptions{})); EXPECT_THAT(prepared_expr->qtype(), Eq(seq_i32)); auto packed_op = dynamic_cast<const PackedSeqMapOperator*>(prepared_expr->op().get()); ASSERT_THAT(packed_op, NotNull()); EXPECT_THAT(packed_op->op()->display_name(), Eq("math.add")); EXPECT_THAT(packed_op->display_name(), Eq("packed_seq_map[math.add]")); EXPECT_THAT(prepared_expr->node_deps(), ElementsAre( EqualsExpr(CallOp(QTypeAnnotation::Make(), {Leaf("xs"), Literal(seq_i32)})), EqualsExpr(CallOp(QTypeAnnotation::Make(), {Leaf("ys"), Literal(seq_i32)})))); } TEST_F(SeqMapOperatorTest, CompilePackedSeqMapOperator) { ASSERT_OK_AND_ASSIGN( ExprOperatorPtr x_plus_y_mul_2, MakeLambdaOperator( "x_plus_y_mul_2", ExprOperatorSignature::Make("x, y"), CallOp("math.multiply", {CallOp("math.add", {Placeholder("x"), Placeholder("y")}), Literal(int32_t{2})}))); ASSERT_OK_AND_ASSIGN(auto expr, CallOp("seq.map", {Literal(x_plus_y_mul_2), Leaf("xs"), Leaf("ys")})); QTypePtr seq_i32 = GetSequenceQType(GetQType<int32_t>()); FrameLayout::Builder layout_builder; auto xs_slot = AddSlot(seq_i32, &layout_builder); auto ys_slot = AddSlot(seq_i32, &layout_builder); DynamicEvaluationEngineOptions options{.collect_op_descriptions = true}; EXPECT_THAT( CompileAndBindForDynamicEvaluation(options, &layout_builder, expr, {{"xs", xs_slot}, {"ys", ys_slot}}), IsOkAndHolds(AllOf( InitOperationsAre("packed_seq_map[x_plus_y_mul_2]:init{" "INT32 [0x70] = 2" "}()"), EvalOperationsAre( "SEQUENCE[INT32] [0x40] = packed_seq_map[x_plus_y_mul_2]:eval{" "INT32 [0x6C] = math.add(INT32 [0x60], INT32 [0x64]); " "INT32 [0x68] = math.multiply(INT32 [0x6C], INT32 [0x70])" "}(SEQUENCE[INT32] [0x00], SEQUENCE[INT32] [0x20])")))); } } }
2,380
#ifndef AROLLA_LAZY_LAZY_H_ #define AROLLA_LAZY_LAZY_H_ #include <memory> #include "absl/functional/any_invocable.h" #include "absl/status/statusor.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/fingerprint.h" #include "arolla/util/repr.h" namespace arolla { class Lazy { public: Lazy(const Lazy&) = delete; Lazy& operator=(const Lazy&) = delete; QTypePtr value_qtype() const { return value_qtype_; } const Fingerprint& fingerprint() const { return fingerprint_; } virtual absl::StatusOr<TypedValue> Get() const = 0; virtual ~Lazy() = default; protected: Lazy(QTypePtr value_qtype, const Fingerprint& fingerprint) : value_qtype_(value_qtype), fingerprint_(fingerprint) {} private: QTypePtr value_qtype_; Fingerprint fingerprint_; }; using LazyPtr = std::shared_ptr<const Lazy>; LazyPtr MakeLazyFromQValue(TypedValue value); LazyPtr MakeLazyFromCallable( QTypePtr value_qtype, absl::AnyInvocable<absl::StatusOr<TypedValue>() const> callable); AROLLA_DECLARE_FINGERPRINT_HASHER_TRAITS(LazyPtr); AROLLA_DECLARE_REPR(LazyPtr); } #endif #include "arolla/lazy/lazy.h" #include <memory> #include <utility> #include "absl/functional/any_invocable.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/fingerprint.h" #include "arolla/util/repr.h" namespace arolla { namespace { class LazyValue final : public Lazy { public: explicit LazyValue(TypedValue&& value) : Lazy(value.GetType(), FingerprintHasher("::arolla::LazyValue") .Combine(value.GetFingerprint()) .Finish()), value_(std::move(value)) {} absl::StatusOr<TypedValue> Get() const final { return value_; } private: TypedValue value_; }; class LazyCallable final : public Lazy { public: using Callable = absl::AnyInvocable<absl::StatusOr<TypedValue>() const>; explicit LazyCallable(QTypePtr value_qtype, Callable&& callable) : Lazy(value_qtype, RandomFingerprint()), callable_(std::move(callable)) {} absl::StatusOr<TypedValue> Get() const final { auto result = callable_(); if (result.ok() && result->GetType() != value_qtype()) { return absl::FailedPreconditionError( absl::StrFormat("expected a lazy callable to return %s, got %s", value_qtype()->name(), result->GetType()->name())); } return result; } private: Callable callable_; }; } LazyPtr MakeLazyFromQValue(TypedValue value) { return std::make_shared<LazyValue>(std::move(value)); } LazyPtr MakeLazyFromCallable(QTypePtr value_qtype, LazyCallable::Callable callable) { return std::make_shared<LazyCallable>(value_qtype, std::move(callable)); } void FingerprintHasherTraits<LazyPtr>::operator()(FingerprintHasher* hasher, const LazyPtr& value) const { if (value != nullptr) { hasher->Combine(value->fingerprint()); } } ReprToken ReprTraits<LazyPtr>::operator()(const LazyPtr& value) const { if (value == nullptr) { return ReprToken{"lazy[?]{nullptr}"}; } return ReprToken{absl::StrCat("lazy[", value->value_qtype()->name(), "]")}; } }
#include "arolla/lazy/lazy.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/testing/qtype.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/fingerprint.h" #include "arolla/util/init_arolla.h" #include "arolla/util/repr.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla { namespace { using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::arolla::testing::TypedValueWith; class LazyTest : public ::testing::Test { void SetUp() override { ASSERT_OK(InitArolla()); } }; TEST_F(LazyTest, MakeLazyFromQValue) { auto x = MakeLazyFromQValue(TypedValue::FromValue(GetQTypeQType())); EXPECT_EQ(x->value_qtype(), GetQTypeQType()); EXPECT_EQ(Repr(x), "lazy[QTYPE]"); EXPECT_THAT(x->Get(), IsOkAndHolds(TypedValueWith<QTypePtr>(GetQTypeQType()))); } TEST_F(LazyTest, LazyValueFingerprint) { EXPECT_EQ( MakeLazyFromQValue(TypedValue::FromValue(GetQTypeQType()))->fingerprint(), MakeLazyFromQValue(TypedValue::FromValue(GetQTypeQType())) ->fingerprint()); EXPECT_NE( MakeLazyFromQValue(TypedValue::FromValue(GetQTypeQType()))->fingerprint(), MakeLazyFromQValue(TypedValue::FromValue(GetNothingQType())) ->fingerprint()); } TEST_F(LazyTest, MakeLazyFromCallable) { auto x = MakeLazyFromCallable( GetQTypeQType(), [] { return TypedValue::FromValue(GetNothingQType()); }); EXPECT_EQ(x->value_qtype(), GetQTypeQType()); EXPECT_EQ(Repr(x), "lazy[QTYPE]"); EXPECT_THAT(x->Get(), IsOkAndHolds(TypedValueWith<QTypePtr>(GetNothingQType()))); } TEST_F(LazyTest, LazyCallableFingerprint) { auto x = MakeLazyFromCallable( GetQTypeQType(), [] { return TypedValue::FromValue(GetNothingQType()); }); auto y = MakeLazyFromCallable( GetQTypeQType(), [] { return TypedValue::FromValue(GetNothingQType()); }); EXPECT_EQ(x->fingerprint(), x->fingerprint()); EXPECT_NE(x->fingerprint(), y->fingerprint()); } TEST_F(LazyTest, LazyCallableError) { auto x = MakeLazyFromCallable( GetQTypeQType(), [] { return absl::InvalidArgumentError("error"); }); EXPECT_EQ(x->value_qtype(), GetQTypeQType()); EXPECT_EQ(Repr(x), "lazy[QTYPE]"); EXPECT_THAT(x->Get(), StatusIs(absl::StatusCode::kInvalidArgument, "error")); } TEST_F(LazyTest, Nullptr) { LazyPtr x; EXPECT_EQ(Repr(x), "lazy[?]{nullptr}"); EXPECT_EQ(FingerprintHasher("salt").Combine(x).Finish(), FingerprintHasher("salt").Combine(x).Finish()); } } }
2,381
#ifndef AROLLA_LAZY_LAZY_QTYPE_H_ #define AROLLA_LAZY_LAZY_QTYPE_H_ #include "absl/base/nullability.h" #include "arolla/lazy/lazy.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_value.h" namespace arolla { bool IsLazyQType(absl::Nullable<const QType*> qtype); QTypePtr GetLazyQType(QTypePtr value_qtype); template <typename T> QTypePtr GetLazyQType() { return GetLazyQType(GetQType<T>()); } TypedValue MakeLazyQValue(LazyPtr lazy); } #endif #include "arolla/lazy/lazy_qtype.h" #include <memory> #include <string> #include <utility> #include "absl/base/thread_annotations.h" #include "absl/container/flat_hash_map.h" #include "absl/log/check.h" #include "absl/status/statusor.h" #include "absl/synchronization/mutex.h" #include "arolla/lazy/lazy.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/simple_qtype.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/fast_dynamic_downcast_final.h" #include "arolla/util/indestructible.h" #include "arolla/util/meta.h" namespace arolla { namespace { class LazyQType final : public SimpleQType { public: explicit LazyQType(QTypePtr value_qtype) : SimpleQType(meta::type<LazyPtr>(), "LAZY[" + std::string(value_qtype->name()) + "]", value_qtype, "::arolla::LazyQType") {} }; class LazyQTypeRegistry { public: QTypePtr GetLazyQType(QTypePtr value_qtype) { absl::WriterMutexLock l(&lock_); auto& result = registry_[value_qtype]; if (!result) { result = std::make_unique<LazyQType>(value_qtype); } return result.get(); } private: absl::Mutex lock_; absl::flat_hash_map<QTypePtr, std::unique_ptr<LazyQType>> registry_ ABSL_GUARDED_BY(lock_); }; } bool IsLazyQType(const QType* qtype) { return fast_dynamic_downcast_final<const LazyQType*>(qtype) != nullptr; } QTypePtr GetLazyQType(QTypePtr value_qtype) { static Indestructible<LazyQTypeRegistry> registry; return registry->GetLazyQType(value_qtype); } TypedValue MakeLazyQValue(LazyPtr lazy) { DCHECK_NE(lazy, nullptr); auto result = TypedValue::FromValueWithQType( std::move(lazy), GetLazyQType(lazy->value_qtype())); DCHECK_OK(result.status()); return *std::move(result); } }
#include "arolla/lazy/lazy_qtype.h" #include <cstdint> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "arolla/lazy/lazy.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/qtype.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/testing/qtype.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/repr_token_eq.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla { namespace { using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::ReprTokenEq; using ::arolla::testing::TypedValueWith; class LazyQTypeTest : public ::testing::Test { void SetUp() override { ASSERT_OK(InitArolla()); } }; TEST_F(LazyQTypeTest, Basics) { auto qtype = GetLazyQType<QTypePtr>(); EXPECT_EQ(qtype, GetLazyQType<QTypePtr>()); EXPECT_EQ(qtype->name(), "LAZY[QTYPE]"); EXPECT_EQ(qtype->type_info(), typeid(LazyPtr)); EXPECT_EQ(qtype->type_layout().AllocSize(), sizeof(LazyPtr)); EXPECT_EQ(qtype->type_layout().AllocAlignment().value, alignof(LazyPtr)); EXPECT_TRUE(qtype->type_fields().empty()); EXPECT_EQ(qtype->value_qtype(), GetQTypeQType()); EXPECT_EQ(qtype->qtype_specialization_key(), "::arolla::LazyQType"); } TEST_F(LazyQTypeTest, IsLazyQType) { EXPECT_TRUE(IsLazyQType(GetLazyQType<QTypePtr>())); EXPECT_TRUE(IsLazyQType(GetLazyQType<int32_t>())); EXPECT_TRUE(IsLazyQType(GetLazyQType<float>())); EXPECT_FALSE(IsLazyQType(GetQTypeQType())); EXPECT_FALSE(IsLazyQType(GetQType<int32_t>())); EXPECT_FALSE(IsLazyQType(GetQType<float>())); } TEST_F(LazyQTypeTest, MakeLazyQValue) { auto qvalue = MakeLazyQValue(MakeLazyFromQValue(TypedValue::FromValue(1))); EXPECT_THAT(qvalue.GenReprToken(), ReprTokenEq("lazy[INT32]")); ASSERT_EQ(qvalue.GetType(), GetLazyQType<int>()); EXPECT_THAT(qvalue.UnsafeAs<LazyPtr>()->Get(), IsOkAndHolds(TypedValueWith<int>(1))); EXPECT_EQ(qvalue.GetFingerprint(), MakeLazyQValue(MakeLazyFromQValue(TypedValue::FromValue(1))) .GetFingerprint()); EXPECT_NE(qvalue.GetFingerprint(), MakeLazyQValue(MakeLazyFromQValue(TypedValue::FromValue(2))) .GetFingerprint()); } } }
2,382
#ifndef AROLLA_JAGGED_SHAPE_DENSE_ARRAY_JAGGED_SHAPE_H_ #define AROLLA_JAGGED_SHAPE_DENSE_ARRAY_JAGGED_SHAPE_H_ #include "arolla/dense_array/edge.h" #include "arolla/jagged_shape/jagged_shape.h" #include "arolla/util/repr.h" namespace arolla { using JaggedDenseArrayShape = JaggedShape<DenseArrayEdge>; using JaggedDenseArrayShapePtr = JaggedDenseArrayShape::ShapePtr; AROLLA_DECLARE_REPR(JaggedDenseArrayShape); } #endif #include "arolla/jagged_shape/dense_array/jagged_shape.h" #include <sstream> #include <utility> #include "arolla/jagged_shape/util/repr.h" #include "arolla/util/repr.h" #include "arolla/util/string.h" namespace arolla { ReprToken ReprTraits<JaggedDenseArrayShape>::operator()( const JaggedDenseArrayShape& value) const { std::ostringstream result; result << "JaggedShape("; bool first = true; for (const auto& edge : value.edges()) { result << NonFirstComma(first) << CompactSplitPointsAsSizesRepr(edge.edge_values().values.span(), 3); } result << ")"; return ReprToken{std::move(result).str()}; } }
#include "arolla/jagged_shape/jagged_shape.h" #include <algorithm> #include <cmath> #include <cstdint> #include <optional> #include <string> #include <type_traits> #include <utility> #include <vector> #include "benchmark/benchmark.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/array/array.h" #include "arolla/array/edge.h" #include "arolla/dense_array/dense_array.h" #include "arolla/dense_array/edge.h" #include "arolla/jagged_shape/array/jagged_shape.h" #include "arolla/jagged_shape/dense_array/jagged_shape.h" #include "arolla/memory/buffer.h" #include "arolla/memory/optional_value.h" #include "arolla/memory/raw_buffer_factory.h" #include "arolla/util/fingerprint.h" #include "arolla/util/repr.h" #include "arolla/util/testing/repr_token_eq.h" #include "arolla/util/testing/status_matchers_backport.h" using ::arolla::testing::ReprTokenEq; using ::arolla::testing::StatusIs; using ::testing::ElementsAre; namespace arolla { namespace { class JaggedArrayShapeHelper { public: using Shape = JaggedArrayShape; using ShapePtr = Shape::ShapePtr; using Edge = Shape::Edge; static absl::string_view ReprName() { return "JaggedArrayShape"; } static absl::StatusOr<ArrayEdge> EdgeFromSplitPoints( absl::Span<const OptionalValue<int64_t>> split_points) { return ArrayEdge::FromSplitPoints(CreateArray<int64_t>(split_points)); } static absl::StatusOr<ArrayEdge> EdgeFromMapping( absl::Span<const OptionalValue<int64_t>> mapping, int64_t parent_size) { return ArrayEdge::FromMapping(CreateArray<int64_t>(mapping), parent_size); } static const Buffer<int64_t>& GetSplitPoints(const ArrayEdge& edge) { return edge.edge_values().dense_data().values; } }; class JaggedDenseArrayShapeHelper { public: using Shape = JaggedDenseArrayShape; using ShapePtr = Shape::ShapePtr; using Edge = Shape::Edge; static absl::string_view ReprName() { return "JaggedShape"; } static absl::StatusOr<DenseArrayEdge> EdgeFromSplitPoints( absl::Span<const OptionalValue<int64_t>> split_points) { return DenseArrayEdge::FromSplitPoints( CreateDenseArray<int64_t>(split_points)); } static absl::StatusOr<DenseArrayEdge> EdgeFromMapping( absl::Span<const OptionalValue<int64_t>> mapping, int64_t parent_size) { return DenseArrayEdge::FromMapping(CreateDenseArray<int64_t>(mapping), parent_size); } static const Buffer<int64_t>& GetSplitPoints(const DenseArrayEdge& edge) { return edge.edge_values().values; } }; template <typename JaggedShapeHelper> class JaggedShapeTest : public ::testing::Test { public: using Helper = JaggedShapeHelper; using Shape = typename JaggedShapeHelper::Shape; using ShapePtr = typename JaggedShapeHelper::ShapePtr; }; using JaggedShapeTestTypes = ::testing::Types<JaggedArrayShapeHelper, JaggedDenseArrayShapeHelper>; TYPED_TEST_SUITE(JaggedShapeTest, JaggedShapeTestTypes); TYPED_TEST(JaggedShapeTest, Empty) { auto shape = TestFixture::Shape::Empty(); EXPECT_EQ(shape->rank(), 0); EXPECT_EQ(shape->size(), 1); EXPECT_TRUE(shape->edges().empty()); } TYPED_TEST(JaggedShapeTest, FromEdges) { using Shape = typename TestFixture::Shape; using Helper = typename TestFixture::Helper; { ASSERT_OK_AND_ASSIGN(auto shape, Shape::FromEdges({})); EXPECT_EQ(shape->rank(), 0); EXPECT_EQ(shape->size(), 1); EXPECT_TRUE(shape->edges().empty()); } { ASSERT_OK_AND_ASSIGN(auto edge, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto shape, Shape::FromEdges({std::move(edge)})); EXPECT_EQ(shape->rank(), 1); EXPECT_EQ(shape->size(), 2); auto edges = shape->edges(); EXPECT_EQ(edges.size(), 1); EXPECT_THAT(Helper::GetSplitPoints(edges[0]), ElementsAre(0, 2)); } { ASSERT_OK_AND_ASSIGN(auto edge1, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto edge2, Helper::EdgeFromSplitPoints({0, 1, 3})); ASSERT_OK_AND_ASSIGN(auto edge3, Helper::EdgeFromSplitPoints({0, 1, 2, 4})); ASSERT_OK_AND_ASSIGN(auto shape, Shape::FromEdges({std::move(edge1), std::move(edge2), std::move(edge3)})); EXPECT_EQ(shape->rank(), 3); EXPECT_EQ(shape->size(), 4); auto edges = shape->edges(); EXPECT_EQ(edges.size(), 3); EXPECT_THAT(Helper::GetSplitPoints(edges[0]), ElementsAre(0, 2)); EXPECT_THAT(Helper::GetSplitPoints(edges[1]), ElementsAre(0, 1, 3)); EXPECT_THAT(Helper::GetSplitPoints(edges[2]), ElementsAre(0, 1, 2, 4)); } { ASSERT_OK_AND_ASSIGN(auto edge1, Helper::EdgeFromSplitPoints({0, 8})); ASSERT_OK_AND_ASSIGN(auto edge2, Helper::EdgeFromMapping({0, 0, 1, 1, 3, 5}, 8)); ASSERT_OK_AND_ASSIGN( auto shape, Shape::FromEdges({std::move(edge1), std::move(edge2)})); EXPECT_EQ(shape->rank(), 2); EXPECT_EQ(shape->size(), 6); auto edges = shape->edges(); EXPECT_EQ(edges.size(), 2); EXPECT_THAT(Helper::GetSplitPoints(edges[0]), ElementsAre(0, 8)); EXPECT_THAT(Helper::GetSplitPoints(edges[1]), ElementsAre(0, 2, 4, 4, 5, 5, 6, 6, 6)); } } TYPED_TEST(JaggedShapeTest, FromEdgesErrors) { using Shape = typename TestFixture::Shape; using Helper = typename TestFixture::Helper; { ASSERT_OK_AND_ASSIGN(auto edge, Helper::EdgeFromSplitPoints({0, 2, 3})); EXPECT_THAT(Shape::FromEdges({std::move(edge)}), StatusIs(absl::StatusCode::kInvalidArgument, "incompatible dimensions - edges[0].parent_size " "!= 1 (prior edge's child_size)")); } { ASSERT_OK_AND_ASSIGN(auto edge1, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto edge2, Helper::EdgeFromSplitPoints({0, 1, 3})); ASSERT_OK_AND_ASSIGN(auto edge3, Helper::EdgeFromSplitPoints({0, 1, 4})); EXPECT_THAT(Shape::FromEdges( {std::move(edge1), std::move(edge2), std::move(edge3)}), StatusIs(absl::StatusCode::kInvalidArgument, "incompatible dimensions - edges[2].parent_size " "!= 3 (prior edge's child_size)")); } { ASSERT_OK_AND_ASSIGN(auto edge1, Helper::EdgeFromSplitPoints({0, 1})); ASSERT_OK_AND_ASSIGN(auto edge2, Helper::EdgeFromMapping({0, std::nullopt}, 1)); EXPECT_THAT(Shape::FromEdges({std::move(edge1), std::move(edge2)}), StatusIs(absl::StatusCode::kInvalidArgument, "expected a full mapping")); } { ASSERT_OK_AND_ASSIGN(auto edge1, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto edge2, Helper::EdgeFromMapping({1, 0}, 2)); EXPECT_THAT(Shape::FromEdges({std::move(edge1), std::move(edge2)}), StatusIs(absl::StatusCode::kInvalidArgument, "expected a sorted mapping")); } } TYPED_TEST(JaggedShapeTest, FromEdges_BufferFactory) { using Shape = typename TestFixture::Shape; using Helper = typename TestFixture::Helper; { ASSERT_OK_AND_ASSIGN(auto edge, Helper::EdgeFromMapping({0, 0}, 1)); ASSERT_OK_AND_ASSIGN(auto shape, Shape::FromEdges({std::move(edge)})); EXPECT_TRUE(Helper::GetSplitPoints(shape->edges()[0]).is_owner()); } { ASSERT_OK_AND_ASSIGN(auto edge, Helper::EdgeFromMapping({0, 0}, 1)); UnsafeArenaBufferFactory arena{128}; ASSERT_OK_AND_ASSIGN(auto shape, Shape::FromEdges({std::move(edge)}, arena)); EXPECT_FALSE(Helper::GetSplitPoints(shape->edges()[0]).is_owner()); } } TYPED_TEST(JaggedShapeTest, FlatFromSize) { using Shape = typename TestFixture::Shape; using Helper = typename TestFixture::Helper; { auto shape = Shape::FlatFromSize(3); EXPECT_EQ(shape->rank(), 1); EXPECT_EQ(shape->size(), 3); auto edges = shape->edges(); EXPECT_EQ(edges.size(), 1); EXPECT_THAT(Helper::GetSplitPoints(edges[0]), ElementsAre(0, 3)); } { auto shape = Shape::FlatFromSize(3); EXPECT_TRUE(Helper::GetSplitPoints(shape->edges()[0]).is_owner()); } { UnsafeArenaBufferFactory arena{128}; auto shape = Shape::FlatFromSize(3, arena); EXPECT_FALSE(Helper::GetSplitPoints(shape->edges()[0]).is_owner()); } } TYPED_TEST(JaggedShapeTest, AddDims) { using Shape = typename TestFixture::Shape; using Helper = typename TestFixture::Helper; { ASSERT_OK_AND_ASSIGN(auto edge, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto shape, Shape::FromEdges({std::move(edge)})); ASSERT_OK_AND_ASSIGN(shape, shape->AddDims({})); EXPECT_EQ(shape->rank(), 1); EXPECT_EQ(shape->size(), 2); EXPECT_THAT(Helper::GetSplitPoints(shape->edges()[0]), ElementsAre(0, 2)); } { ASSERT_OK_AND_ASSIGN(auto edge, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto shape, Shape::FromEdges({std::move(edge)})); ASSERT_OK_AND_ASSIGN(auto edge2, Helper::EdgeFromSplitPoints({0, 1, 3})); ASSERT_OK_AND_ASSIGN(auto edge3, Helper::EdgeFromMapping({0, 1, 2, 2}, 3)); ASSERT_OK_AND_ASSIGN(shape, shape->AddDims({edge2, edge3})); EXPECT_EQ(shape->rank(), 3); EXPECT_EQ(shape->size(), 4); auto edges = shape->edges(); EXPECT_THAT(Helper::GetSplitPoints(edges[0]), ElementsAre(0, 2)); EXPECT_THAT(Helper::GetSplitPoints(edges[1]), ElementsAre(0, 1, 3)); EXPECT_THAT(Helper::GetSplitPoints(edges[2]), ElementsAre(0, 1, 2, 4)); } { ASSERT_OK_AND_ASSIGN(auto shape, Shape::FromEdges({})); ASSERT_OK_AND_ASSIGN(auto edge, Helper::EdgeFromMapping({0, 0}, 1)); ASSERT_OK_AND_ASSIGN(shape, shape->AddDims({edge})); EXPECT_TRUE(Helper::GetSplitPoints(shape->edges()[0]).is_owner()); } { ASSERT_OK_AND_ASSIGN(auto shape, Shape::FromEdges({})); ASSERT_OK_AND_ASSIGN(auto edge, Helper::EdgeFromMapping({0, 0}, 1)); UnsafeArenaBufferFactory arena{128}; ASSERT_OK_AND_ASSIGN(shape, shape->AddDims({edge}, arena)); EXPECT_FALSE(Helper::GetSplitPoints(shape->edges()[0]).is_owner()); } { ASSERT_OK_AND_ASSIGN(auto edge, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto shape, Shape::FromEdges({edge})); EXPECT_THAT(shape->AddDims({edge}), StatusIs(absl::StatusCode::kInvalidArgument, "incompatible dimensions - edges[1].parent_size " "!= 2 (prior edge's child_size)")); } } TYPED_TEST(JaggedShapeTest, RemoveDims) { using Shape = typename TestFixture::Shape; using Helper = typename TestFixture::Helper; { ASSERT_OK_AND_ASSIGN(auto shape, Shape::FromEdges({})); shape = shape->RemoveDims(0); EXPECT_EQ(shape->rank(), 0); } { ASSERT_OK_AND_ASSIGN(auto edge, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto shape, Shape::FromEdges({edge})); shape = shape->RemoveDims(1); EXPECT_EQ(shape->rank(), 1); EXPECT_THAT(Helper::GetSplitPoints(shape->edges()[0]), ElementsAre(0, 2)); } { ASSERT_OK_AND_ASSIGN(auto edge, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto edge2, Helper::EdgeFromSplitPoints({0, 1, 2})); ASSERT_OK_AND_ASSIGN(auto shape, Shape::FromEdges({edge, edge2})); shape = shape->RemoveDims(0); EXPECT_EQ(shape->rank(), 0); } { ASSERT_OK_AND_ASSIGN(auto edge, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto edge2, Helper::EdgeFromSplitPoints({0, 1, 3})); ASSERT_OK_AND_ASSIGN(auto edge3, Helper::EdgeFromSplitPoints({0, 1, 2, 4})); ASSERT_OK_AND_ASSIGN(auto shape, Shape::FromEdges({edge, edge2, edge3})); shape = shape->RemoveDims(1); EXPECT_EQ(shape->rank(), 1); EXPECT_THAT(Helper::GetSplitPoints(shape->edges()[0]), ElementsAre(0, 2)); } } TYPED_TEST(JaggedShapeTest, FlattenDims_RankDecrease) { using Shape = typename TestFixture::Shape; using Helper = typename TestFixture::Helper; ASSERT_OK_AND_ASSIGN(auto edge1, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto edge2, Helper::EdgeFromSplitPoints({0, 1, 3})); ASSERT_OK_AND_ASSIGN(auto edge3, Helper::EdgeFromSplitPoints({0, 1, 2, 4})); ASSERT_OK_AND_ASSIGN(auto edge4, Helper::EdgeFromSplitPoints({0, 3, 4, 11, 12})); ASSERT_OK_AND_ASSIGN(auto shape, Shape::FromEdges({edge1, edge2, edge3, edge4})); { auto new_shape = shape->FlattenDims(0, 1); EXPECT_EQ(new_shape->rank(), 4); auto edges = new_shape->edges(); EXPECT_THAT(Helper::GetSplitPoints(edges[0]), ElementsAre(0, 2)); EXPECT_THAT(Helper::GetSplitPoints(edges[1]), ElementsAre(0, 1, 3)); EXPECT_THAT(Helper::GetSplitPoints(edges[2]), ElementsAre(0, 1, 2, 4)); EXPECT_THAT(Helper::GetSplitPoints(edges[3]), ElementsAre(0, 3, 4, 11, 12)); } { auto new_shape = shape->FlattenDims(0, 4); EXPECT_EQ(new_shape->rank(), 1); auto edges = new_shape->edges(); EXPECT_THAT(Helper::GetSplitPoints(edges[0]), ElementsAre(0, 12)); } { auto new_shape = shape->FlattenDims(1, 3); EXPECT_EQ(new_shape->rank(), 3); auto edges = new_shape->edges(); EXPECT_THAT(Helper::GetSplitPoints(edges[0]), ElementsAre(0, 2)); EXPECT_THAT(Helper::GetSplitPoints(edges[1]), ElementsAre(0, 1, 4)); EXPECT_THAT(Helper::GetSplitPoints(edges[2]), ElementsAre(0, 3, 4, 11, 12)); } { auto new_shape = shape->FlattenDims(0, 4); EXPECT_TRUE(Helper::GetSplitPoints(new_shape->edges()[0]).is_owner()); } { UnsafeArenaBufferFactory arena{128}; auto new_shape = shape->FlattenDims(0, 4, arena); EXPECT_FALSE(Helper::GetSplitPoints(new_shape->edges()[0]).is_owner()); } } TYPED_TEST(JaggedShapeTest, FlattenDims_RankIncrease) { using Shape = typename TestFixture::Shape; using Helper = typename TestFixture::Helper; ASSERT_OK_AND_ASSIGN(auto edge1, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto edge2, Helper::EdgeFromSplitPoints({0, 1, 3})); ASSERT_OK_AND_ASSIGN(auto edge3, Helper::EdgeFromSplitPoints({0, 1, 2, 4})); ASSERT_OK_AND_ASSIGN(auto edge4, Helper::EdgeFromSplitPoints({0, 3, 4, 11, 12})); ASSERT_OK_AND_ASSIGN(auto shape, Shape::FromEdges({edge1, edge2, edge3, edge4})); { auto new_shape = shape->FlattenDims(0, 0); EXPECT_EQ(new_shape->rank(), 5); auto edges = new_shape->edges(); EXPECT_THAT(Helper::GetSplitPoints(edges[0]), ElementsAre(0, 1)); EXPECT_THAT(Helper::GetSplitPoints(edges[1]), ElementsAre(0, 2)); EXPECT_THAT(Helper::GetSplitPoints(edges[2]), ElementsAre(0, 1, 3)); EXPECT_THAT(Helper::GetSplitPoints(edges[3]), ElementsAre(0, 1, 2, 4)); EXPECT_THAT(Helper::GetSplitPoints(edges[4]), ElementsAre(0, 3, 4, 11, 12)); } { auto new_shape = shape->FlattenDims(2, 2); EXPECT_EQ(new_shape->rank(), 5); auto edges = new_shape->edges(); EXPECT_THAT(Helper::GetSplitPoints(edges[0]), ElementsAre(0, 2)); EXPECT_THAT(Helper::GetSplitPoints(edges[1]), ElementsAre(0, 1, 3)); EXPECT_THAT(Helper::GetSplitPoints(edges[2]), ElementsAre(0, 1, 2, 3)); EXPECT_THAT(Helper::GetSplitPoints(edges[3]), ElementsAre(0, 1, 2, 4)); EXPECT_THAT(Helper::GetSplitPoints(edges[4]), ElementsAre(0, 3, 4, 11, 12)); } { auto new_shape = shape->FlattenDims(4, 4); EXPECT_EQ(new_shape->rank(), 5); auto edges = new_shape->edges(); EXPECT_THAT(Helper::GetSplitPoints(edges[0]), ElementsAre(0, 2)); EXPECT_THAT(Helper::GetSplitPoints(edges[1]), ElementsAre(0, 1, 3)); EXPECT_THAT(Helper::GetSplitPoints(edges[2]), ElementsAre(0, 1, 2, 4)); EXPECT_THAT(Helper::GetSplitPoints(edges[3]), ElementsAre(0, 3, 4, 11, 12)); EXPECT_THAT(Helper::GetSplitPoints(edges[4]), ElementsAre(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)); } { auto empty_shape = Shape::Empty(); auto new_shape = empty_shape->FlattenDims(0, 0); EXPECT_EQ(new_shape->rank(), 1); auto edges = new_shape->edges(); EXPECT_THAT(Helper::GetSplitPoints(edges[0]), ElementsAre(0, 1)); } { auto new_shape = shape->FlattenDims(0, 0); EXPECT_TRUE(Helper::GetSplitPoints(new_shape->edges()[0]).is_owner()); } { UnsafeArenaBufferFactory arena{128}; auto new_shape = shape->FlattenDims(0, 0, arena); EXPECT_FALSE(Helper::GetSplitPoints(new_shape->edges()[0]).is_owner()); } } TYPED_TEST(JaggedShapeTest, NotMovableAndCopyableClass) { using Shape = typename TestFixture::Shape; static_assert(!std::is_copy_constructible_v<Shape> && !std::is_copy_assignable_v<Shape>); static_assert(!std::is_move_constructible_v<Shape> && !std::is_move_assignable_v<Shape>); } TYPED_TEST(JaggedShapeTest, MovableAndCopyablePtr) { using Shape = typename TestFixture::Shape; using ShapePtr = typename TestFixture::ShapePtr; using Helper = typename TestFixture::Helper; { ASSERT_OK_AND_ASSIGN(auto edge, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto shape, Shape::FromEdges({std::move(edge)})); ShapePtr shape_cpy = shape; EXPECT_EQ(shape_cpy->rank(), 1); EXPECT_EQ(shape_cpy->size(), 2); auto edges = shape_cpy->edges(); EXPECT_EQ(edges.size(), 1); EXPECT_THAT(Helper::GetSplitPoints(edges[0]), ElementsAre(0, 2)); } { ASSERT_OK_AND_ASSIGN(auto edge, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto shape, Shape::FromEdges({std::move(edge)})); ShapePtr shape_move = std::move(shape); EXPECT_EQ(shape_move->rank(), 1); EXPECT_EQ(shape_move->size(), 2); auto edges = shape_move->edges(); EXPECT_EQ(edges.size(), 1); EXPECT_THAT(Helper::GetSplitPoints(edges[0]), ElementsAre(0, 2)); } } TYPED_TEST(JaggedShapeTest, Fingerprint) { using Shape = typename TestFixture::Shape; using Helper = typename TestFixture::Helper; ASSERT_OK_AND_ASSIGN(auto edge1, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto edge2, Helper::EdgeFromSplitPoints({0, 1, 2})); ASSERT_OK_AND_ASSIGN(auto shape1, Shape::FromEdges({edge1, edge2})); ASSERT_OK_AND_ASSIGN(auto shape2, Shape::FromEdges({edge1, edge2})); EXPECT_EQ(FingerprintHasher("salt").Combine(*shape1).Finish(), FingerprintHasher("salt").Combine(*shape2).Finish()); ASSERT_OK_AND_ASSIGN(auto edge3, Helper::EdgeFromSplitPoints({0, 2, 4})); ASSERT_OK_AND_ASSIGN(auto shape3, Shape::FromEdges({edge1, edge3})); EXPECT_NE(FingerprintHasher("salt").Combine(*shape1).Finish(), FingerprintHasher("salt").Combine(*shape3).Finish()); ASSERT_OK_AND_ASSIGN(auto shape4, Shape::FromEdges({edge1, edge2, edge3})); EXPECT_NE(FingerprintHasher("salt").Combine(*shape1).Finish(), FingerprintHasher("salt").Combine(*shape4).Finish()); } TYPED_TEST(JaggedShapeTest, FastEquivalenceCheck) { using Shape = typename TestFixture::Shape; using Helper = typename TestFixture::Helper; JaggedShapeFastEquivalenceResult kEqSizes( JaggedShapeFastEquivalenceResult::kSizesEq); JaggedShapeFastEquivalenceResult kNotEq( JaggedShapeFastEquivalenceResult::kNotEq); JaggedShapeFastEquivalenceResult kEq( JaggedShapeFastEquivalenceResult::kEq); { SCOPED_TRACE("Empty is fully equal."); auto shape = Shape::Empty(); EXPECT_EQ(shape->FastEquivalenceCheck(*shape), kEq); } { SCOPED_TRACE("Rank 1 is fully equal."); ASSERT_OK_AND_ASSIGN(auto edge1, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto shape, Shape::FromEdges({edge1})); EXPECT_EQ(shape->FastEquivalenceCheck(*shape), kEq); ASSERT_OK_AND_ASSIGN(auto shape2, Shape::FromEdges({edge1})); EXPECT_EQ(shape->FastEquivalenceCheck(*shape2), kEq); EXPECT_EQ(shape2->FastEquivalenceCheck(*shape), kEq); ASSERT_OK_AND_ASSIGN(auto edge1_new, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto shape2_new, Shape::FromEdges({edge1_new})); EXPECT_EQ(shape->FastEquivalenceCheck(*shape2_new), kEq); EXPECT_EQ(shape2_new->FastEquivalenceCheck(*shape), kEq); } { SCOPED_TRACE("Equal shapes."); ASSERT_OK_AND_ASSIGN(auto edge1, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto edge2, Helper::EdgeFromSplitPoints({0, 1, 3})); ASSERT_OK_AND_ASSIGN(auto edge3, Helper::EdgeFromSplitPoints({0, 1, 2, 4})); ASSERT_OK_AND_ASSIGN(auto shape1, Shape::FromEdges({edge1, edge2, edge3})); ASSERT_OK_AND_ASSIGN(auto shape2, Shape::FromEdges({edge1, edge2, edge3})); EXPECT_EQ(shape1->FastEquivalenceCheck(*shape1), kEq) << "the same pointer must be exact equal"; EXPECT_EQ(shape1->FastEquivalenceCheck(*shape2), kEqSizes); EXPECT_EQ(shape2->FastEquivalenceCheck(*shape1), kEqSizes); } { SCOPED_TRACE("Different shapes."); ASSERT_OK_AND_ASSIGN(auto edge1, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto shape1, Shape::FromEdges({edge1})); ASSERT_OK_AND_ASSIGN(auto edge2, Helper::EdgeFromSplitPoints({0, 3})); ASSERT_OK_AND_ASSIGN(auto shape2, Shape::FromEdges({edge2})); EXPECT_EQ(shape1->FastEquivalenceCheck(*shape2), kNotEq); EXPECT_EQ(shape2->FastEquivalenceCheck(*shape1), kNotEq); } { SCOPED_TRACE("Different ranks."); ASSERT_OK_AND_ASSIGN(auto edge1, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto edge2, Helper::EdgeFromSplitPoints({0, 1, 3})); ASSERT_OK_AND_ASSIGN(auto shape1, Shape::FromEdges({edge1, edge2})); ASSERT_OK_AND_ASSIGN(auto shape2, Shape::FromEdges({edge1})); EXPECT_EQ(shape1->FastEquivalenceCheck(*shape2), kNotEq); EXPECT_EQ(shape2->FastEquivalenceCheck(*shape1), kNotEq); } { SCOPED_TRACE("False negative."); ASSERT_OK_AND_ASSIGN(auto edge1, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto edge2, Helper::EdgeFromSplitPoints({0, 1, 3})); ASSERT_OK_AND_ASSIGN(auto shape1, Shape::FromEdges({edge1, edge2})); ASSERT_OK_AND_ASSIGN(auto edge3, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto edge4, Helper::EdgeFromSplitPoints({0, 2, 3})); ASSERT_OK_AND_ASSIGN(auto shape2, Shape::FromEdges({edge3, edge4})); EXPECT_EQ(shape1->FastEquivalenceCheck(*shape2), kEqSizes); EXPECT_EQ(shape2->FastEquivalenceCheck(*shape1), kEqSizes); } } TYPED_TEST(JaggedShapeTest, EqOp) { using Shape = typename TestFixture::Shape; using Helper = typename TestFixture::Helper; { ASSERT_OK_AND_ASSIGN(auto edge1, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto edge2, Helper::EdgeFromSplitPoints({0, 1, 3})); ASSERT_OK_AND_ASSIGN(auto edge3, Helper::EdgeFromSplitPoints({0, 1, 2, 4})); ASSERT_OK_AND_ASSIGN(auto shape1, Shape::FromEdges({edge1, edge2, edge3})); ASSERT_OK_AND_ASSIGN(auto shape2, Shape::FromEdges({edge1, edge2, edge3})); EXPECT_TRUE(shape1->IsEquivalentTo(*shape2)); EXPECT_TRUE(shape2->IsEquivalentTo(*shape1)); EXPECT_TRUE(shape1->IsEquivalentTo(*shape1)); } { ASSERT_OK_AND_ASSIGN(auto edge1, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto shape1, Shape::FromEdges({edge1})); ASSERT_OK_AND_ASSIGN(auto edge2, Helper::EdgeFromSplitPoints({0, 3})); ASSERT_OK_AND_ASSIGN(auto shape2, Shape::FromEdges({edge2})); EXPECT_FALSE(shape1->IsEquivalentTo(*shape2)); EXPECT_FALSE(shape2->IsEquivalentTo(*shape1)); } { ASSERT_OK_AND_ASSIGN(auto edge1, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto edge2, Helper::EdgeFromSplitPoints({0, 1, 3})); ASSERT_OK_AND_ASSIGN(auto shape1, Shape::FromEdges({edge1, edge2})); ASSERT_OK_AND_ASSIGN(auto shape2, Shape::FromEdges({edge1})); EXPECT_FALSE(shape1->IsEquivalentTo(*shape2)); EXPECT_FALSE(shape2->IsEquivalentTo(*shape1)); } { ASSERT_OK_AND_ASSIGN(auto edge1, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto edge2, Helper::EdgeFromSplitPoints({0, 1, 3})); ASSERT_OK_AND_ASSIGN(auto shape1, Shape::FromEdges({edge1, edge2})); ASSERT_OK_AND_ASSIGN(auto edge3, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto edge4, Helper::EdgeFromSplitPoints({0, 2, 3})); ASSERT_OK_AND_ASSIGN(auto shape2, Shape::FromEdges({edge3, edge4})); EXPECT_FALSE(shape1->IsEquivalentTo(*shape2)); EXPECT_FALSE(shape2->IsEquivalentTo(*shape1)); } } TYPED_TEST(JaggedShapeTest, IsBroadcastableTo) { using Shape = typename TestFixture::Shape; using Helper = typename TestFixture::Helper; { ASSERT_OK_AND_ASSIGN(auto edge1, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto edge2, Helper::EdgeFromSplitPoints({0, 1, 3})); ASSERT_OK_AND_ASSIGN(auto edge3, Helper::EdgeFromSplitPoints({0, 1, 2, 4})); ASSERT_OK_AND_ASSIGN(auto shape1, Shape::FromEdges({edge1, edge2, edge3})); ASSERT_OK_AND_ASSIGN(auto shape2, Shape::FromEdges({edge1, edge2, edge3})); EXPECT_TRUE(shape1->IsBroadcastableTo(*shape2)); EXPECT_TRUE(shape2->IsBroadcastableTo(*shape1)); EXPECT_TRUE(shape1->IsBroadcastableTo(*shape1)); } { ASSERT_OK_AND_ASSIGN(auto edge1, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto shape1, Shape::FromEdges({edge1})); ASSERT_OK_AND_ASSIGN(auto edge2, Helper::EdgeFromSplitPoints({0, 3})); ASSERT_OK_AND_ASSIGN(auto shape2, Shape::FromEdges({edge2})); EXPECT_FALSE(shape1->IsBroadcastableTo(*shape2)); EXPECT_FALSE(shape2->IsBroadcastableTo(*shape1)); } { ASSERT_OK_AND_ASSIGN(auto edge1, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto edge2, Helper::EdgeFromSplitPoints({0, 2, 3})); ASSERT_OK_AND_ASSIGN(auto edge3, Helper::EdgeFromSplitPoints({0, 2, 4, 6})); ASSERT_OK_AND_ASSIGN(auto shape1, Shape::FromEdges({edge1, edge2})); ASSERT_OK_AND_ASSIGN(auto shape2, Shape::FromEdges({edge1, edge2, edge3})); EXPECT_TRUE(shape1->IsBroadcastableTo(*shape2)); EXPECT_FALSE(shape2->IsBroadcastableTo(*shape1)); } { ASSERT_OK_AND_ASSIGN(auto edge1, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto edge2_1, Helper::EdgeFromSplitPoints({0, 2, 3})); ASSERT_OK_AND_ASSIGN(auto edge2_2, Helper::EdgeFromSplitPoints({0, 1, 3})); ASSERT_OK_AND_ASSIGN(auto edge3, Helper::EdgeFromSplitPoints({0, 2, 4, 6})); ASSERT_OK_AND_ASSIGN(auto shape1, Shape::FromEdges({edge1, edge2_1})); ASSERT_OK_AND_ASSIGN(auto shape2, Shape::FromEdges({edge1, edge2_2, edge3})); EXPECT_FALSE(shape1->IsBroadcastableTo(*shape2)); EXPECT_FALSE(shape2->IsBroadcastableTo(*shape1)); } } TYPED_TEST(JaggedShapeTest, GetBroadcastEdge) { using Shape = typename TestFixture::Shape; using Helper = typename TestFixture::Helper; { ASSERT_OK_AND_ASSIGN(auto edge1, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto edge2, Helper::EdgeFromSplitPoints({0, 1, 3})); ASSERT_OK_AND_ASSIGN(auto edge3, Helper::EdgeFromSplitPoints({0, 1, 2, 4})); ASSERT_OK_AND_ASSIGN(auto shape1, Shape::FromEdges({edge1})); ASSERT_OK_AND_ASSIGN(auto shape2, Shape::FromEdges({edge1, edge2, edge3})); auto edge = shape1->GetBroadcastEdge(*shape2); EXPECT_TRUE(edge.IsEquivalentTo(*Helper::EdgeFromSplitPoints({0, 1, 4}))); } { ASSERT_OK_AND_ASSIGN(auto edge1, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto edge2, Helper::EdgeFromSplitPoints({0, 1, 3})); ASSERT_OK_AND_ASSIGN(auto edge3, Helper::EdgeFromSplitPoints({0, 1, 2, 4})); ASSERT_OK_AND_ASSIGN(auto shape1, Shape::FromEdges({edge1, edge2, edge3})); ASSERT_OK_AND_ASSIGN(auto shape2, Shape::FromEdges({edge1, edge2, edge3})); auto edge = shape1->GetBroadcastEdge(*shape2); EXPECT_TRUE( edge.IsEquivalentTo(*Helper::EdgeFromSplitPoints({0, 1, 2, 3, 4}))); } { ASSERT_OK_AND_ASSIGN(auto edge1, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto edge2, Helper::EdgeFromSplitPoints({0, 1, 3})); ASSERT_OK_AND_ASSIGN(auto edge3, Helper::EdgeFromSplitPoints({0, 1, 2, 4})); ASSERT_OK_AND_ASSIGN(auto shape1, Shape::FromEdges({edge1})); ASSERT_OK_AND_ASSIGN(auto shape2, Shape::FromEdges({edge1, edge2, edge3})); auto edge = shape1->GetBroadcastEdge(*shape2); EXPECT_TRUE(Helper::GetSplitPoints(edge).is_owner()); } { ASSERT_OK_AND_ASSIGN(auto edge1, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto edge2, Helper::EdgeFromSplitPoints({0, 1, 3})); ASSERT_OK_AND_ASSIGN(auto edge3, Helper::EdgeFromSplitPoints({0, 1, 2, 4})); ASSERT_OK_AND_ASSIGN(auto shape1, Shape::FromEdges({edge1})); ASSERT_OK_AND_ASSIGN(auto shape2, Shape::FromEdges({edge1, edge2, edge3})); UnsafeArenaBufferFactory arena{128}; auto edge = shape1->GetBroadcastEdge(*shape2, arena); EXPECT_FALSE(Helper::GetSplitPoints(edge).is_owner()); } { ASSERT_OK_AND_ASSIGN(auto edge1, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto edge2, Helper::EdgeFromSplitPoints({0, 1, 3})); ASSERT_OK_AND_ASSIGN(auto edge3, Helper::EdgeFromSplitPoints({0, 1, 2, 4})); ASSERT_OK_AND_ASSIGN(auto shape1, Shape::FromEdges({edge1, edge2, edge3})); ASSERT_OK_AND_ASSIGN(auto shape2, Shape::FromEdges({edge1, edge2, edge3})); auto edge = shape1->GetBroadcastEdge(*shape2); EXPECT_TRUE(Helper::GetSplitPoints(edge).is_owner()); } { ASSERT_OK_AND_ASSIGN(auto edge1, Helper::EdgeFromSplitPoints({0, 2})); ASSERT_OK_AND_ASSIGN(auto edge2, Helper::EdgeFromSplitPoints({0, 1, 3})); ASSERT_OK_AND_ASSIGN(auto edge3, Helper::EdgeFromSplitPoints({0, 1, 2, 4})); ASSERT_OK_AND_ASSIGN(auto shape1, Shape::FromEdges({edge1, edge2, edge3})); ASSERT_OK_AND_ASSIGN(auto shape2, Shape::FromEdges({edge1, edge2, edge3})); UnsafeArenaBufferFactory arena{128}; auto edge = shape1->GetBroadcastEdge(*shape2, arena); EXPECT_FALSE(Helper::GetSplitPoints(edge).is_owner()); } } TYPED_TEST(JaggedShapeTest, EdgeT) { using Edge = typename TestFixture::Shape::Edge; using TestEdge = typename TestFixture::Helper::Edge; static_assert(std::is_same_v<Edge, TestEdge>); } TYPED_TEST(JaggedShapeTest, PtrT) { using ShapePtr = typename TestFixture::Shape::ShapePtr; using TestShapePtr = typename TestFixture::Helper::ShapePtr; static_assert(std::is_same_v<S
2,383
#ifndef AROLLA_SERIALIZATION_BASE_DECODER_H_ #define AROLLA_SERIALIZATION_BASE_DECODER_H_ #include <cstdint> #include <deque> #include <functional> #include <string> #include <vector> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/expr/expr_node.h" #include "arolla/qtype/typed_value.h" #include "arolla/serialization_base/base.pb.h" #include "arolla/serialization_base/container.h" namespace arolla::serialization_base { struct NoExtensionFound {}; using ValueDecoderResult = std::variant<TypedValue, NoExtensionFound>; using ValueDecoder = std::function<absl::StatusOr<ValueDecoderResult>( const ValueProto& value_proto, absl::Span<const TypedValue> input_values, absl::Span<const arolla::expr::ExprNodePtr> input_exprs)>; using ValueDecoderProvider = std::function<absl::StatusOr<ValueDecoder>(absl::string_view codec_name)>; class Decoder final : public ContainerProcessor { public: struct Options { bool infer_attributes_for_operator_nodes = true; }; struct Result { std::vector<TypedValue> values; std::vector<arolla::expr::ExprNodePtr> exprs; }; Decoder(ValueDecoderProvider value_decoder_provider, const Options& options); absl::Status OnDecodingStep( uint64_t decoding_step_index, const DecodingStepProto& decoding_step_proto) final; Result Finish() &&; private: struct Codec { std::string codec_name; ValueDecoder value_decoder; }; struct DecodingStepResult { const TypedValue* value = nullptr; const arolla::expr::ExprNode* expr = nullptr; const Codec* codec = nullptr; }; absl::StatusOr<arolla::expr::ExprNodePtr> DecodeLiteralNode( const LiteralNodeProto& literal_node_proto) const; absl::StatusOr<arolla::expr::ExprNodePtr> DecodeLeafNode( const LeafNodeProto& leaf_node_proto) const; absl::StatusOr<arolla::expr::ExprNodePtr> DecodePlaceholderNode( const PlaceholderNodeProto& placeholder_node_proto) const; absl::StatusOr<arolla::expr::ExprNodePtr> DecodeOperatorNode( const OperatorNodeProto& operator_node_proto) const; absl::StatusOr<TypedValue> DecodeValue(const ValueProto& value_proto) const; absl::StatusOr<TypedValue> DecodeValueWithKnownCodec( const ValueProto& value_proto, uint64_t codec_index, absl::Span<const TypedValue> input_values, absl::Span<const arolla::expr::ExprNodePtr> input_exprs) const; absl::StatusOr<TypedValue> DecodeValueWithUnknownCodec( const ValueProto& value_proto, absl::Span<const TypedValue> input_values, absl::Span<const arolla::expr::ExprNodePtr> input_exprs) const; absl::StatusOr<Codec> DecodeCodec(const CodecProto& codec_proto) const; absl::Status StoreDecodedValue(uint64_t value_index, TypedValue&& value); absl::Status StoreDecodedExpr(uint64_t expr_index, arolla::expr::ExprNodePtr&& expr); absl::Status StoreDecodedCodec(uint64_t codec_index, Codec&& codec); absl::StatusOr<TypedValue> LoadDecodedValue(uint64_t value_index) const; absl::StatusOr<arolla::expr::ExprNodePtr> LoadDecodedExpr( uint64_t expr_index) const; ValueDecoderProvider value_decoder_provider_; Options options_; std::deque<TypedValue> know_values_; std::deque<arolla::expr::ExprNodePtr> know_exprs_; std::deque<Codec> know_codecs_; std::vector<DecodingStepResult> decoding_step_results_; Result result_; }; } #endif #include "arolla/serialization_base/decoder.h" #include <cstddef> #include <cstdint> #include <utility> #include <variant> #include <vector> #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/types/span.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/qtype/qtype_traits.h" #include "arolla/qtype/typed_value.h" #include "arolla/serialization_base/base.pb.h" #include "arolla/util/status_macros_backport.h" namespace arolla::serialization_base { using ::arolla::expr::ExprNode; using ::arolla::expr::ExprNodePtr; using ::arolla::expr::ExprOperatorPtr; using ::arolla::expr::Leaf; using ::arolla::expr::Literal; using ::arolla::expr::MakeOpNode; using ::arolla::expr::Placeholder; Decoder::Decoder(ValueDecoderProvider value_decoder_provider, const Options& options) : value_decoder_provider_(std::move(value_decoder_provider)), options_(options) {} absl::Status Decoder::OnDecodingStep( uint64_t decoding_step_index, const DecodingStepProto& decoding_step_proto) { if (decoding_step_index > decoding_step_results_.size()) { return absl::InvalidArgumentError( absl::StrFormat("encountered unexpected decoding_step_index=%d, " "indicating missing step %d", decoding_step_index, decoding_step_results_.size())); } if (decoding_step_index == decoding_step_results_.size()) { decoding_step_results_.emplace_back(); } switch (decoding_step_proto.type_case()) { case DecodingStepProto::kLiteralNode: { ASSIGN_OR_RETURN(auto expr, DecodeLiteralNode(decoding_step_proto.literal_node()), _ << "decoding_step.type=LITERAL_NODE"); return StoreDecodedExpr(decoding_step_index, std::move(expr)); } case DecodingStepProto::kLeafNode: { ASSIGN_OR_RETURN(auto expr, DecodeLeafNode(decoding_step_proto.leaf_node()), _ << "decoding_step.type=LEAF_NODE"); return StoreDecodedExpr(decoding_step_index, std::move(expr)); } case DecodingStepProto::kPlaceholderNode: { ASSIGN_OR_RETURN( auto expr, DecodePlaceholderNode(decoding_step_proto.placeholder_node()), _ << "decoding_step.type=PLACEHOLDER_NODE"); return StoreDecodedExpr(decoding_step_index, std::move(expr)); } case DecodingStepProto::kOperatorNode: { ASSIGN_OR_RETURN(auto expr, DecodeOperatorNode(decoding_step_proto.operator_node()), _ << "decoding_step.type=OPERATOR_NODE"); return StoreDecodedExpr(decoding_step_index, std::move(expr)); } case DecodingStepProto::kValue: { ASSIGN_OR_RETURN(auto value, DecodeValue(decoding_step_proto.value()), _ << "decoding_step.type=VALUE"); return StoreDecodedValue(decoding_step_index, std::move(value)); } case DecodingStepProto::kCodec: { ASSIGN_OR_RETURN(auto codec, DecodeCodec(decoding_step_proto.codec()), _ << "decoding_step.type=CODEC"); return StoreDecodedCodec(decoding_step_index, std::move(codec)); } case DecodingStepProto::kOutputValueIndex: { ASSIGN_OR_RETURN( auto value, LoadDecodedValue(decoding_step_proto.output_value_index()), _ << "decoding_step.type=OUTPUT_VALUE_INDEX"); result_.values.push_back(std::move(value)); return absl::OkStatus(); } case DecodingStepProto::kOutputExprIndex: { ASSIGN_OR_RETURN(auto expr, LoadDecodedExpr(decoding_step_proto.output_expr_index()), _ << "decoding_step.type=OUTPUT_EXPR_INDEX"); result_.exprs.push_back(std::move(expr)); return absl::OkStatus(); } case DecodingStepProto::TYPE_NOT_SET: return absl::InvalidArgumentError("missing decoding_step.type"); } return absl::InvalidArgumentError( absl::StrFormat("unexpected decoding_step.type=%d", static_cast<int>(decoding_step_proto.type_case()))); } Decoder::Result Decoder::Finish() && { return std::move(result_); } absl::StatusOr<ExprNodePtr> Decoder::DecodeLiteralNode( const LiteralNodeProto& literal_node_proto) const { if (!literal_node_proto.has_literal_value_index()) { return absl::InvalidArgumentError( "missing literal_node.literal_value_index"); } ASSIGN_OR_RETURN(auto value, LoadDecodedValue(literal_node_proto.literal_value_index())); return Literal(std::move(value)); } absl::StatusOr<ExprNodePtr> Decoder::DecodeLeafNode( const LeafNodeProto& leaf_node_proto) const { if (!leaf_node_proto.has_leaf_key()) { return absl::InvalidArgumentError("missing leaf_node.leaf_key"); } return Leaf(leaf_node_proto.leaf_key()); } absl::StatusOr<ExprNodePtr> Decoder::DecodePlaceholderNode( const PlaceholderNodeProto& placeholder_node_proto) const { if (!placeholder_node_proto.has_placeholder_key()) { return absl::InvalidArgumentError( "missing placeholder_node.placeholder_key"); } return Placeholder(placeholder_node_proto.placeholder_key()); } absl::StatusOr<ExprNodePtr> Decoder::DecodeOperatorNode( const OperatorNodeProto& operator_node_proto) const { if (!operator_node_proto.has_operator_value_index()) { return absl::InvalidArgumentError( "missing operator_node.operator_value_index"); } ASSIGN_OR_RETURN( auto value, LoadDecodedValue(operator_node_proto.operator_value_index())); if (value.GetType() != GetQType<ExprOperatorPtr>()) { return absl::InvalidArgumentError(absl::StrFormat( "expected an operator in decoding_step_results[%d], got %s", operator_node_proto.operator_value_index(), value.GetType()->name())); } const auto& op = value.UnsafeAs<ExprOperatorPtr>(); std::vector<ExprNodePtr> exprs(operator_node_proto.input_expr_indices_size()); for (size_t i = 0; i < exprs.size(); ++i) { ASSIGN_OR_RETURN( exprs[i], LoadDecodedExpr(operator_node_proto.input_expr_indices(i))); } if (options_.infer_attributes_for_operator_nodes) { return MakeOpNode(op, std::move(exprs)); } else { return ExprNode::UnsafeMakeOperatorNode(ExprOperatorPtr(op), std::move(exprs), {}); } } absl::StatusOr<TypedValue> Decoder::DecodeValue( const ValueProto& value_proto) const { std::vector<TypedValue> input_values; input_values.reserve(value_proto.input_value_indices_size()); for (auto value_index : value_proto.input_value_indices()) { ASSIGN_OR_RETURN(auto value, LoadDecodedValue(value_index)); input_values.push_back(std::move(value)); } std::vector<ExprNodePtr> input_exprs(value_proto.input_expr_indices_size()); for (size_t i = 0; i < input_exprs.size(); ++i) { ASSIGN_OR_RETURN(input_exprs[i], LoadDecodedExpr(value_proto.input_expr_indices(i))); } if (value_proto.has_codec_index()) { return DecodeValueWithKnownCodec(value_proto, value_proto.codec_index(), input_values, input_exprs); } return DecodeValueWithUnknownCodec(value_proto, input_values, input_exprs); } absl::StatusOr<TypedValue> Decoder::DecodeValueWithKnownCodec( const ValueProto& value_proto, uint64_t codec_index, absl::Span<const TypedValue> input_values, absl::Span<const ExprNodePtr> input_exprs) const { if (static_cast<size_t>(codec_index) >= decoding_step_results_.size()) { return absl::InvalidArgumentError( absl::StrFormat("codec_index is out of range: %d", codec_index)); } auto* codec = decoding_step_results_[codec_index].codec; if (codec == nullptr) { return absl::InvalidArgumentError(absl::StrFormat( "found no codec in decoding_step_results[%d]", codec_index)); } ASSIGN_OR_RETURN(auto value_decoder_result, codec->value_decoder(value_proto, input_values, input_exprs), _ << "codecs[" << codec_index << "]=" << codec->codec_name); if (auto* value = std::get_if<TypedValue>(&value_decoder_result)) { return std::move(*value); } return absl::NotFoundError(absl::StrFormat( "no extension found; codecs[%d]=%s", codec_index, codec->codec_name)); } absl::StatusOr<TypedValue> Decoder::DecodeValueWithUnknownCodec( const ValueProto& value_proto, absl::Span<const TypedValue> input_values, absl::Span<const ExprNodePtr> input_exprs) const { for (const auto& codec : know_codecs_) { ASSIGN_OR_RETURN( auto value_decoder_result, codec.value_decoder(value_proto, input_values, input_exprs), _ << "detected_codec=" << codec.codec_name); if (auto* value = std::get_if<TypedValue>(&value_decoder_result)) { return *value; } } return absl::InvalidArgumentError("unable to detect codec"); } absl::StatusOr<Decoder::Codec> Decoder::DecodeCodec( const CodecProto& codec_proto) const { ASSIGN_OR_RETURN(auto value_decoder, value_decoder_provider_(codec_proto.name())); DCHECK(value_decoder != nullptr); return Codec{codec_proto.name(), std::move(value_decoder)}; } absl::Status Decoder::StoreDecodedValue(uint64_t value_index, TypedValue&& value) { DCHECK_LT(value_index, decoding_step_results_.size()); if (decoding_step_results_[value_index].value != nullptr) { return absl::InvalidArgumentError("value_index collision"); } decoding_step_results_[value_index].value = &know_values_.emplace_back(std::move(value)); return absl::OkStatus(); } absl::Status Decoder::StoreDecodedExpr(uint64_t expr_index, ExprNodePtr&& expr) { DCHECK_LT(expr_index, decoding_step_results_.size()); if (decoding_step_results_[expr_index].expr != nullptr) { return absl::InvalidArgumentError("expr_index collision"); } decoding_step_results_[expr_index].expr = know_exprs_.emplace_back(std::move(expr)).get(); return absl::OkStatus(); } absl::Status Decoder::StoreDecodedCodec(uint64_t codec_index, Codec&& codec) { DCHECK_LT(codec_index, decoding_step_results_.size()); if (decoding_step_results_[codec_index].codec != nullptr) { return absl::InvalidArgumentError("codec_index collision"); } decoding_step_results_[codec_index].codec = &know_codecs_.emplace_back(std::move(codec)); return absl::OkStatus(); } absl::StatusOr<TypedValue> Decoder::LoadDecodedValue( uint64_t value_index) const { if (static_cast<size_t>(value_index) >= decoding_step_results_.size()) { return absl::InvalidArgumentError( absl::StrFormat("value_index is out of range: %d", value_index)); } if (decoding_step_results_[value_index].value == nullptr) { return absl::InvalidArgumentError(absl::StrFormat( "found no value in decoding_step_results[%d]", value_index)); } return *decoding_step_results_[value_index].value; } absl::StatusOr<ExprNodePtr> Decoder::LoadDecodedExpr( uint64_t expr_index) const { if (static_cast<size_t>(expr_index) >= decoding_step_results_.size()) { return absl::InvalidArgumentError( absl::StrFormat("expr_index is out of range: %d", expr_index)); } if (decoding_step_results_[expr_index].expr == nullptr) { return absl::InvalidArgumentError(absl::StrFormat( "found no expression in decoding_step_results[%d]", expr_index)); } return ExprNodePtr::NewRef(decoding_step_results_[expr_index].expr); } }
#include "arolla/serialization_base/decoder.h" #include <memory> #include <string> #include <utility> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_attributes.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/lambda_expr_operator.h" #include "arolla/expr/testing/testing.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/testing/qtype.h" #include "arolla/qtype/typed_value.h" #include "arolla/serialization_base/base.pb.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla::serialization_base { namespace { using ::arolla::expr::ExprAttributes; using ::arolla::expr::ExprNode; using ::arolla::expr::ExprNodePtr; using ::arolla::expr::ExprOperatorPtr; using ::arolla::expr::LambdaOperator; using ::arolla::expr::Leaf; using ::arolla::expr::Literal; using ::arolla::expr::Placeholder; using ::arolla::testing::EqualsExpr; using ::arolla::testing::StatusIs; using ::arolla::testing::TypedValueWith; using ::testing::ElementsAre; using ::testing::InSequence; using ::testing::IsEmpty; using ::testing::MockFunction; using ::testing::Ref; using ::testing::Return; using MockValueDecoderProvider = MockFunction<absl::StatusOr<ValueDecoder>(absl::string_view codec_name)>; using MockValueDecoder = MockFunction<absl::StatusOr<ValueDecoderResult>( const ValueProto& value_proto, absl::Span<const TypedValue> input_values, absl::Span<const ExprNodePtr> input_exprs)>; class DecodeTest : public ::testing::Test { protected: void SetUp() override { ASSERT_OK(InitArolla()); } }; TEST_F(DecodeTest, EmptyMessage) { MockValueDecoderProvider mock_value_decoder_provider; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); auto output = std::move(decoder).Finish(); EXPECT_THAT(output.values, IsEmpty()); EXPECT_THAT(output.exprs, IsEmpty()); } TEST_F(DecodeTest, LiteralNode) { MockValueDecoderProvider mock_value_decoder_provider; MockValueDecoder mock_value_decoder; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); DecodingStepProto decoding_step_proto; { decoding_step_proto.mutable_codec()->set_name("mock_codec"); EXPECT_CALL(mock_value_decoder_provider, Call("mock_codec")) .WillOnce(Return(mock_value_decoder.AsStdFunction())); EXPECT_OK(decoder.OnDecodingStep(0, decoding_step_proto)); } { decoding_step_proto.mutable_value(); EXPECT_CALL(mock_value_decoder, Call(Ref(decoding_step_proto.value()), IsEmpty(), IsEmpty())) .WillOnce(Return(TypedValue::FromValue(1.0f))); EXPECT_OK(decoder.OnDecodingStep(1, decoding_step_proto)); } { decoding_step_proto.mutable_literal_node()->set_literal_value_index(1); EXPECT_OK(decoder.OnDecodingStep(2, decoding_step_proto)); } { decoding_step_proto.set_output_expr_index(2); EXPECT_OK(decoder.OnDecodingStep(3, decoding_step_proto)); } auto output = std::move(decoder).Finish(); EXPECT_THAT(output.values, IsEmpty()); EXPECT_THAT(output.exprs, ElementsAre(EqualsExpr(Literal(1.0f)))); } TEST_F(DecodeTest, LeafNode) { MockValueDecoderProvider mock_value_decoder_provider; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); DecodingStepProto decoding_step_proto; { decoding_step_proto.mutable_leaf_node()->set_leaf_key("leaf_key"); EXPECT_OK(decoder.OnDecodingStep(0, decoding_step_proto)); } { decoding_step_proto.set_output_expr_index(0); EXPECT_OK(decoder.OnDecodingStep(1, decoding_step_proto)); } auto output = std::move(decoder).Finish(); EXPECT_THAT(output.values, IsEmpty()); EXPECT_THAT(output.exprs, ElementsAre(EqualsExpr(Leaf("leaf_key")))); } TEST_F(DecodeTest, PlaceholderNode) { MockValueDecoderProvider mock_value_decoder_provider; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); DecodingStepProto decoding_step_proto; { decoding_step_proto.mutable_placeholder_node()->set_placeholder_key( "placeholder_key"); EXPECT_OK(decoder.OnDecodingStep(0, decoding_step_proto)); } { decoding_step_proto.set_output_expr_index(0); EXPECT_OK(decoder.OnDecodingStep(1, decoding_step_proto)); } auto output = std::move(decoder).Finish(); EXPECT_THAT(output.values, IsEmpty()); EXPECT_THAT(output.exprs, ElementsAre(EqualsExpr(Placeholder("placeholder_key")))); } TEST_F(DecodeTest, OperatorNode) { MockValueDecoderProvider mock_value_decoder_provider; MockValueDecoder mock_value_decoder; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); DecodingStepProto decoding_step_proto; ASSERT_OK_AND_ASSIGN(ExprOperatorPtr dummy_op, LambdaOperator::Make("dummy_op", Placeholder("x"))); { decoding_step_proto.mutable_codec()->set_name("mock_codec"); EXPECT_CALL(mock_value_decoder_provider, Call("mock_codec")) .WillOnce(Return(mock_value_decoder.AsStdFunction())); EXPECT_OK(decoder.OnDecodingStep(0, decoding_step_proto)); } { decoding_step_proto.mutable_value()->set_codec_index(0); EXPECT_CALL(mock_value_decoder, Call(Ref(decoding_step_proto.value()), IsEmpty(), IsEmpty())) .WillOnce(Return(TypedValue::FromValue(dummy_op))); EXPECT_OK(decoder.OnDecodingStep(1, decoding_step_proto)); } { decoding_step_proto.mutable_value()->set_codec_index(0); EXPECT_CALL(mock_value_decoder, Call(Ref(decoding_step_proto.value()), IsEmpty(), IsEmpty())) .WillOnce(Return(TypedValue::FromValue(1.0f))); EXPECT_OK(decoder.OnDecodingStep(2, decoding_step_proto)); } { decoding_step_proto.mutable_literal_node()->set_literal_value_index(2); EXPECT_OK(decoder.OnDecodingStep(3, decoding_step_proto)); } { auto* operator_node_proto = decoding_step_proto.mutable_operator_node(); operator_node_proto->set_operator_value_index(1); operator_node_proto->add_input_expr_indices(3); EXPECT_OK(decoder.OnDecodingStep(4, decoding_step_proto)); } { decoding_step_proto.set_output_expr_index(4); EXPECT_OK(decoder.OnDecodingStep(5, decoding_step_proto)); } auto output = std::move(decoder).Finish(); EXPECT_THAT(output.values, IsEmpty()); EXPECT_THAT(output.exprs, ElementsAre(EqualsExpr(ExprNode::UnsafeMakeOperatorNode( ExprOperatorPtr(dummy_op), {Literal(1.0f)}, ExprAttributes{TypedValue::FromValue(1.0f)})))); } TEST_F(DecodeTest, OperatorNode_NoMetadata) { MockValueDecoderProvider mock_value_decoder_provider; MockValueDecoder mock_value_decoder; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {.infer_attributes_for_operator_nodes = false}); DecodingStepProto decoding_step_proto; ASSERT_OK_AND_ASSIGN(ExprOperatorPtr dummy_op, LambdaOperator::Make("dummy_op", Placeholder("x"))); { decoding_step_proto.mutable_codec()->set_name("mock_codec"); EXPECT_CALL(mock_value_decoder_provider, Call("mock_codec")) .WillOnce(Return(mock_value_decoder.AsStdFunction())); EXPECT_OK(decoder.OnDecodingStep(0, decoding_step_proto)); } { decoding_step_proto.mutable_value()->set_codec_index(0); EXPECT_CALL(mock_value_decoder, Call(Ref(decoding_step_proto.value()), IsEmpty(), IsEmpty())) .WillOnce(Return(TypedValue::FromValue(dummy_op))); EXPECT_OK(decoder.OnDecodingStep(1, decoding_step_proto)); } { decoding_step_proto.mutable_value()->set_codec_index(0); EXPECT_CALL(mock_value_decoder, Call(Ref(decoding_step_proto.value()), IsEmpty(), IsEmpty())) .WillOnce(Return(TypedValue::FromValue(1.0f))); EXPECT_OK(decoder.OnDecodingStep(2, decoding_step_proto)); } { decoding_step_proto.mutable_literal_node()->set_literal_value_index(2); EXPECT_OK(decoder.OnDecodingStep(3, decoding_step_proto)); } { auto* operator_node_proto = decoding_step_proto.mutable_operator_node(); operator_node_proto->set_operator_value_index(1); operator_node_proto->add_input_expr_indices(3); EXPECT_OK(decoder.OnDecodingStep(4, decoding_step_proto)); } { decoding_step_proto.set_output_expr_index(4); EXPECT_OK(decoder.OnDecodingStep(5, decoding_step_proto)); } auto output = std::move(decoder).Finish(); EXPECT_THAT(output.values, IsEmpty()); EXPECT_THAT( output.exprs, ElementsAre(EqualsExpr(ExprNode::UnsafeMakeOperatorNode( ExprOperatorPtr(dummy_op), {Literal(1.0f)}, ExprAttributes{})))); } TEST_F(DecodeTest, Value) { MockValueDecoderProvider mock_value_decoder_provider; MockValueDecoder mock_value_decoder_1; MockValueDecoder mock_value_decoder_2; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); DecodingStepProto decoding_step_proto; { decoding_step_proto.mutable_codec()->set_name("mock_codec_1"); EXPECT_CALL(mock_value_decoder_provider, Call("mock_codec_1")) .WillOnce(Return(mock_value_decoder_1.AsStdFunction())); EXPECT_OK(decoder.OnDecodingStep(0, decoding_step_proto)); } { decoding_step_proto.mutable_codec()->set_name("mock_codec_2"); EXPECT_CALL(mock_value_decoder_provider, Call("mock_codec_2")) .WillOnce(Return(mock_value_decoder_2.AsStdFunction())); EXPECT_OK(decoder.OnDecodingStep(1, decoding_step_proto)); } { decoding_step_proto.mutable_value()->set_codec_index(0); EXPECT_CALL(mock_value_decoder_1, Call(Ref(decoding_step_proto.value()), IsEmpty(), IsEmpty())) .WillOnce(Return(TypedValue::FromValue(1.0f))); EXPECT_OK(decoder.OnDecodingStep(2, decoding_step_proto)); } { decoding_step_proto.mutable_value()->set_codec_index(0); EXPECT_CALL(mock_value_decoder_1, Call(Ref(decoding_step_proto.value()), IsEmpty(), IsEmpty())) .WillOnce(Return(TypedValue::FromValue(2.0f))); EXPECT_OK(decoder.OnDecodingStep(3, decoding_step_proto)); } { decoding_step_proto.mutable_leaf_node()->set_leaf_key("leaf_key"); EXPECT_OK(decoder.OnDecodingStep(4, decoding_step_proto)); } { decoding_step_proto.mutable_placeholder_node()->set_placeholder_key( "placeholder_key"); EXPECT_OK(decoder.OnDecodingStep(5, decoding_step_proto)); } { decoding_step_proto.mutable_value()->add_input_value_indices(2); decoding_step_proto.mutable_value()->add_input_value_indices(3); decoding_step_proto.mutable_value()->add_input_value_indices(2); decoding_step_proto.mutable_value()->add_input_expr_indices(5); decoding_step_proto.mutable_value()->add_input_expr_indices(4); decoding_step_proto.mutable_value()->add_input_expr_indices(5); decoding_step_proto.mutable_value()->add_input_expr_indices(4); decoding_step_proto.mutable_value()->set_codec_index(1); EXPECT_CALL(mock_value_decoder_2, Call(Ref(decoding_step_proto.value()), ElementsAre(TypedValueWith<float>(1.0f), TypedValueWith<float>(2.0f), TypedValueWith<float>(1.0f)), ElementsAre(EqualsExpr(Placeholder("placeholder_key")), EqualsExpr(Leaf("leaf_key")), EqualsExpr(Placeholder("placeholder_key")), EqualsExpr(Leaf("leaf_key"))))) .WillOnce(Return(TypedValue::FromValue(3.0f))); EXPECT_OK(decoder.OnDecodingStep(6, decoding_step_proto)); } { decoding_step_proto.set_output_value_index(6); EXPECT_OK(decoder.OnDecodingStep(7, decoding_step_proto)); } auto output = std::move(decoder).Finish(); EXPECT_THAT(output.values, ElementsAre(TypedValueWith<float>(3.0f))); EXPECT_THAT(output.exprs, IsEmpty()); } TEST_F(DecodeTest, ValueWithUnknownCodec) { MockValueDecoderProvider mock_value_decoder_provider; MockValueDecoder mock_value_decoder_1; MockValueDecoder mock_value_decoder_2; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); DecodingStepProto decoding_step_proto; { decoding_step_proto.mutable_codec()->set_name("mock_codec_1"); EXPECT_CALL(mock_value_decoder_provider, Call("mock_codec_1")) .WillOnce(Return(mock_value_decoder_1.AsStdFunction())); EXPECT_OK(decoder.OnDecodingStep(0, decoding_step_proto)); } { decoding_step_proto.mutable_codec()->set_name("mock_codec_2"); EXPECT_CALL(mock_value_decoder_provider, Call("mock_codec_2")) .WillOnce(Return(mock_value_decoder_2.AsStdFunction())); EXPECT_OK(decoder.OnDecodingStep(1, decoding_step_proto)); } { InSequence seq; decoding_step_proto.mutable_value(); EXPECT_CALL(mock_value_decoder_1, Call(Ref(decoding_step_proto.value()), IsEmpty(), IsEmpty())) .WillOnce(Return(NoExtensionFound{})); EXPECT_CALL(mock_value_decoder_2, Call(Ref(decoding_step_proto.value()), IsEmpty(), IsEmpty())) .WillOnce(Return(TypedValue::FromValue(1.0f))); EXPECT_OK(decoder.OnDecodingStep(2, decoding_step_proto)); } { decoding_step_proto.set_output_value_index(2); EXPECT_OK(decoder.OnDecodingStep(3, decoding_step_proto)); } auto output = std::move(decoder).Finish(); EXPECT_THAT(output.values, ElementsAre(TypedValueWith<float>(1.0f))); EXPECT_THAT(output.exprs, IsEmpty()); } TEST_F(DecodeTest, Error_UnexpectedDecodingStepIndex) { MockValueDecoderProvider mock_value_decoder_provider; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); EXPECT_THAT(decoder.OnDecodingStep(2, DecodingStepProto()), StatusIs(absl::StatusCode::kInvalidArgument, "encountered unexpected decoding_step_index=2, " "indicating missing step 0")); } TEST_F(DecodeTest, Error_EmptyDecodingStep) { MockValueDecoderProvider mock_value_decoder_provider; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); EXPECT_THAT(decoder.OnDecodingStep(0, DecodingStepProto()), StatusIs(absl::StatusCode::kInvalidArgument, "missing decoding_step.type")); } TEST_F(DecodeTest, Error_Codec_CodecNotFound) { MockValueDecoderProvider mock_value_decoder_provider; MockValueDecoder mock_value_decoder; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); DecodingStepProto decoding_step_proto; { decoding_step_proto.mutable_codec()->set_name("foo"); EXPECT_CALL(mock_value_decoder_provider, Call("foo")) .WillOnce(Return(mock_value_decoder.AsStdFunction())); EXPECT_OK(decoder.OnDecodingStep(0, decoding_step_proto)); } { decoding_step_proto.mutable_codec()->set_name("foo"); EXPECT_CALL(mock_value_decoder_provider, Call("foo")) .WillOnce(Return(absl::InvalidArgumentError("unknown codec: bar"))); EXPECT_THAT(decoder.OnDecodingStep(1, decoding_step_proto), StatusIs(absl::StatusCode::kInvalidArgument, "unknown codec: bar; decoding_step.type=CODEC")); } } TEST_F(DecodeTest, Error_CodecIndexCollision) { MockValueDecoderProvider mock_value_decoder_provider; MockValueDecoder mock_value_decoder; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); DecodingStepProto decoding_step_proto; { decoding_step_proto.mutable_codec()->set_name("foo"); EXPECT_CALL(mock_value_decoder_provider, Call("foo")) .WillOnce(Return(mock_value_decoder.AsStdFunction())); EXPECT_OK(decoder.OnDecodingStep(0, decoding_step_proto)); } { decoding_step_proto.mutable_codec()->set_name("bar"); EXPECT_CALL(mock_value_decoder_provider, Call("bar")) .WillOnce(Return(mock_value_decoder.AsStdFunction())); EXPECT_THAT( decoder.OnDecodingStep(0, decoding_step_proto), StatusIs(absl::StatusCode::kInvalidArgument, "codec_index collision")); } } TEST_F(DecodeTest, Error_ExprIndexCollision) { MockValueDecoderProvider mock_value_decoder_provider; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); DecodingStepProto decoding_step_proto; { decoding_step_proto.mutable_leaf_node()->set_leaf_key("leaf_key"); EXPECT_OK(decoder.OnDecodingStep(0, decoding_step_proto)); } { decoding_step_proto.mutable_leaf_node()->set_leaf_key("leaf_key"); EXPECT_THAT( decoder.OnDecodingStep(0, decoding_step_proto), StatusIs(absl::StatusCode::kInvalidArgument, "expr_index collision")); } } TEST_F(DecodeTest, Error_ValueIndexCollision) { MockValueDecoderProvider mock_value_decoder_provider; MockValueDecoder mock_value_decoder; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); DecodingStepProto decoding_step_proto; { decoding_step_proto.mutable_codec()->set_name("mock_codec"); EXPECT_CALL(mock_value_decoder_provider, Call("mock_codec")) .WillOnce(Return(mock_value_decoder.AsStdFunction())); EXPECT_OK(decoder.OnDecodingStep(0, decoding_step_proto)); } { decoding_step_proto.mutable_value(); EXPECT_CALL(mock_value_decoder, Call(Ref(decoding_step_proto.value()), IsEmpty(), IsEmpty())) .WillOnce(Return(TypedValue::FromValue(1.0f))); EXPECT_OK(decoder.OnDecodingStep(1, decoding_step_proto)); } { decoding_step_proto.mutable_value(); EXPECT_CALL(mock_value_decoder, Call(Ref(decoding_step_proto.value()), IsEmpty(), IsEmpty())) .WillOnce(Return(TypedValue::FromValue(1.0f))); EXPECT_THAT( decoder.OnDecodingStep(1, decoding_step_proto), StatusIs(absl::StatusCode::kInvalidArgument, "value_index collision")); } } TEST_F(DecodeTest, Error_LiteralNode_MissingLiteralValueIndex) { MockValueDecoderProvider mock_value_decoder_provider; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); DecodingStepProto decoding_step_proto; decoding_step_proto.mutable_literal_node(); EXPECT_THAT(decoder.OnDecodingStep(0, decoding_step_proto), StatusIs(absl::StatusCode::kInvalidArgument, "missing literal_node.literal_value_index; " "decoding_step.type=LITERAL_NODE")); } TEST_F(DecodeTest, Error_LiteralNode_IllegalLiteralValueIndex) { MockValueDecoderProvider mock_value_decoder_provider; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); DecodingStepProto decoding_step_proto; decoding_step_proto.mutable_literal_node()->set_literal_value_index(100); EXPECT_THAT(decoder.OnDecodingStep(0, decoding_step_proto), StatusIs(absl::StatusCode::kInvalidArgument, "value_index is out of range: 100; " "decoding_step.type=LITERAL_NODE")); } TEST_F(DecodeTest, Error_LiteralNode_LiteralValueIndexPointsToExpr) { MockValueDecoderProvider mock_value_decoder_provider; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); DecodingStepProto decoding_step_proto; { decoding_step_proto.mutable_leaf_node()->set_leaf_key("leaf_key"); EXPECT_OK(decoder.OnDecodingStep(0, decoding_step_proto)); } { decoding_step_proto.mutable_literal_node()->set_literal_value_index(1); EXPECT_THAT(decoder.OnDecodingStep(1, decoding_step_proto), StatusIs(absl::StatusCode::kInvalidArgument, "found no value in decoding_step_results[1]; " "decoding_step.type=LITERAL_NODE")); } } TEST_F(DecodeTest, Error_LeafNode_MissingLeafKey) { MockValueDecoderProvider mock_value_decoder_provider; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); DecodingStepProto decoding_step_proto; decoding_step_proto.mutable_leaf_node(); EXPECT_THAT(decoder.OnDecodingStep(0, decoding_step_proto), StatusIs(absl::StatusCode::kInvalidArgument, "missing leaf_node.leaf_key; " "decoding_step.type=LEAF_NODE")); } TEST_F(DecodeTest, Error_PlaceholderNode_MissingPlaceholderKey) { MockValueDecoderProvider mock_value_decoder_provider; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); DecodingStepProto decoding_step_proto; decoding_step_proto.mutable_placeholder_node(); EXPECT_THAT(decoder.OnDecodingStep(0, decoding_step_proto), StatusIs(absl::StatusCode::kInvalidArgument, "missing placeholder_node.placeholder_key; " "decoding_step.type=PLACEHOLDER_NODE")); } TEST_F(DecodeTest, Error_OperatorNode_MissingOperatorValueIndex) { MockValueDecoderProvider mock_value_decoder_provider; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); DecodingStepProto decoding_step_proto; decoding_step_proto.mutable_operator_node(); EXPECT_THAT(decoder.OnDecodingStep(0, decoding_step_proto), StatusIs(absl::StatusCode::kInvalidArgument, "missing operator_node.operator_value_index; " "decoding_step.type=OPERATOR_NODE")); } TEST_F(DecodeTest, Error_OperatorNode_IllegalOperatorValueIndex) { MockValueDecoderProvider mock_value_decoder_provider; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); DecodingStepProto decoding_step_proto; decoding_step_proto.mutable_operator_node()->set_operator_value_index(100); EXPECT_THAT(decoder.OnDecodingStep(0, decoding_step_proto), StatusIs(absl::StatusCode::kInvalidArgument, "value_index is out of range: 100; " "decoding_step.type=OPERATOR_NODE")); } TEST_F(DecodeTest, Error_OperatorNode_OperatorValueIndexPointsToFloat32) { MockValueDecoderProvider mock_value_decoder_provider; MockValueDecoder mock_value_decoder; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); DecodingStepProto decoding_step_proto; { decoding_step_proto.mutable_codec()->set_name("mock_codec"); EXPECT_CALL(mock_value_decoder_provider, Call("mock_codec")) .WillOnce(Return(mock_value_decoder.AsStdFunction())); EXPECT_OK(decoder.OnDecodingStep(0, decoding_step_proto)); } { decoding_step_proto.mutable_value()->set_codec_index(0); EXPECT_CALL(mock_value_decoder, Call(Ref(decoding_step_proto.value()), IsEmpty(), IsEmpty())) .WillOnce(Return(TypedValue::FromValue(1.0f))); EXPECT_OK(decoder.OnDecodingStep(1, decoding_step_proto)); } { decoding_step_proto.mutable_operator_node()->set_operator_value_index(1); EXPECT_THAT( decoder.OnDecodingStep(2, decoding_step_proto), StatusIs( absl::StatusCode::kInvalidArgument, "expected an operator in decoding_step_results[1], got FLOAT32; " "decoding_step.type=OPERATOR_NODE")); } } TEST_F(DecodeTest, Error_OperatorNode_IllegalInputExprIndex) { MockValueDecoderProvider mock_value_decoder_provider; MockValueDecoder mock_value_decoder; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); DecodingStepProto decoding_step_proto; ASSERT_OK_AND_ASSIGN(ExprOperatorPtr dummy_op, LambdaOperator::Make("dummy_op", Placeholder("x"))); { decoding_step_proto.mutable_codec()->set_name("mock_codec"); EXPECT_CALL(mock_value_decoder_provider, Call("mock_codec")) .WillOnce(Return(mock_value_decoder.AsStdFunction())); EXPECT_OK(decoder.OnDecodingStep(0, decoding_step_proto)); } { decoding_step_proto.mutable_value()->set_codec_index(0); EXPECT_CALL(mock_value_decoder, Call(Ref(decoding_step_proto.value()), IsEmpty(), IsEmpty())) .WillOnce(Return(TypedValue::FromValue(dummy_op))); EXPECT_OK(decoder.OnDecodingStep(1, decoding_step_proto)); } { auto* operator_node_proto = decoding_step_proto.mutable_operator_node(); operator_node_proto->set_operator_value_index(1); operator_node_proto->add_input_expr_indices(100); EXPECT_THAT(decoder.OnDecodingStep(2, decoding_step_proto), StatusIs(absl::StatusCode::kInvalidArgument, "expr_index is out of range: 100; " "decoding_step.type=OPERATOR_NODE")); } } TEST_F(DecodeTest, Error_OperatorNode_InvalidDepCount) { MockValueDecoderProvider mock_value_decoder_provider; MockValueDecoder mock_value_decoder; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); DecodingStepProto decoding_step_proto; ASSERT_OK_AND_ASSIGN(ExprOperatorPtr dummy_op, LambdaOperator::Make("dummy_op", Placeholder("x"))); { decoding_step_proto.mutable_codec()->set_name("mock_codec"); EXPECT_CALL(mock_value_decoder_provider, Call("mock_codec")) .WillOnce(Return(mock_value_decoder.AsStdFunction())); EXPECT_OK(decoder.OnDecodingStep(0, decoding_step_proto)); } { decoding_step_proto.mutable_value()->set_codec_index(0); EXPECT_CALL(mock_value_decoder, Call(Ref(decoding_step_proto.value()), IsEmpty(), IsEmpty())) .WillOnce(Return(TypedValue::FromValue(dummy_op))); EXPECT_OK(decoder.OnDecodingStep(1, decoding_step_proto)); } { decoding_step_proto.mutable_leaf_node()->set_leaf_key("leaf_key"); EXPECT_OK(decoder.OnDecodingStep(2, decoding_step_proto)); } { auto* operator_node_proto = decoding_step_proto.mutable_operator_node(); operator_node_proto->set_operator_value_index(1); operator_node_proto->add_input_expr_indices(2); operator_node_proto->add_input_expr_indices(2); EXPECT_THAT( decoder.OnDecodingStep(2, decoding_step_proto), StatusIs(absl::StatusCode::kInvalidArgument, "incorrect number of dependencies passed to an " "operator node: expected 1 but got 2; " "while calling dummy_op with args {L.leaf_key, L.leaf_key}; " "decoding_step.type=OPERATOR_NODE")); } } TEST_F(DecodeTest, Error_Value_IllegalInputValueIndex) { MockValueDecoderProvider mock_value_decoder_provider; MockValueDecoder mock_value_decoder; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); DecodingStepProto decoding_step_proto; { decoding_step_proto.mutable_codec()->set_name("mock_codec"); EXPECT_CALL(mock_value_decoder_provider, Call("mock_codec")) .WillOnce(Return(mock_value_decoder.AsStdFunction())); EXPECT_OK(decoder.OnDecodingStep(0, decoding_step_proto)); } { auto* value_proto = decoding_step_proto.mutable_value(); value_proto->set_codec_index(0); value_proto->add_input_value_indices(100); EXPECT_THAT(decoder.OnDecodingStep(1, decoding_step_proto), StatusIs(absl::StatusCode::kInvalidArgument, "value_index is out of range: 100; " "decoding_step.type=VALUE")); } } TEST_F(DecodeTest, Error_Value_IllegalInputExprIndex) { MockValueDecoderProvider mock_value_decoder_provider; MockValueDecoder mock_value_decoder; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); DecodingStepProto decoding_step_proto; { decoding_step_proto.mutable_codec()->set_name("mock_codec"); EXPECT_CALL(mock_value_decoder_provider, Call("mock_codec")) .WillOnce(Return(mock_value_decoder.AsStdFunction())); EXPECT_OK(decoder.OnDecodingStep(0, decoding_step_proto)); } { auto* value_proto = decoding_step_proto.mutable_value(); value_proto->set_codec_index(0); value_proto->add_input_expr_indices(100); EXPECT_THAT(decoder.OnDecodingStep(1, decoding_step_proto), StatusIs(absl::StatusCode::kInvalidArgument, "expr_index is out of range: 100; " "decoding_step.type=VALUE")); } } TEST_F(DecodeTest, Error_Value_IllegalCodecIndex) { MockValueDecoderProvider mock_value_decoder_provider; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); DecodingStepProto decoding_step_proto; decoding_step_proto.mutable_value()->set_codec_index(100); EXPECT_THAT(decoder.OnDecodingStep(0, decoding_step_proto), StatusIs(absl::StatusCode::kInvalidArgument, "codec_index is out of range: 100; " "decoding_step.type=VALUE")); } TEST_F(DecodeTest, Error_Value_InvalidCodecIndex) { MockValueDecoderProvider mock_value_decoder_provider; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); DecodingStepProto decoding_step_proto; { decoding_step_proto.mutable_leaf_node()->set_leaf_key("leaf_key"); EXPECT_OK(decoder.OnDecodingStep(0, decoding_step_proto)); } { decoding_step_proto.mutable_value()->set_codec_index(0); EXPECT_THAT(decoder.OnDecodingStep(0, decoding_step_proto), StatusIs(absl::StatusCode::kInvalidArgument, "found no codec in decoding_step_results[0]; " "decoding_step.type=VALUE")); } } TEST_F(DecodeTest, Error_Value_CodecFailed) { MockValueDecoderProvider mock_value_decoder_provider; MockValueDecoder mock_value_decoder; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); DecodingStepProto decoding_step_proto; { decoding_step_proto.mutable_codec()->set_name("mock_codec"); EXPECT_CALL(mock_value_decoder_provider, Call("mock_codec")) .WillOnce(Return(mock_value_decoder.AsStdFunction())); EXPECT_OK(decoder.OnDecodingStep(0, decoding_step_proto)); } { decoding_step_proto.mutable_value()->set_codec_index(0); EXPECT_CALL(mock_value_decoder, Call(Ref(decoding_step_proto.value()), IsEmpty(), IsEmpty())) .WillOnce(Return(absl::UnimplementedError("codec error"))); EXPECT_THAT(decoder.OnDecodingStep(1, decoding_step_proto), StatusIs(absl::StatusCode::kUnimplemented, "codec error; codecs[0]=mock_codec; " "decoding_step.type=VALUE")); } } TEST_F(DecodeTest, Error_Value_NoExtensionFound) { MockValueDecoderProvider mock_value_decoder_provider; MockValueDecoder mock_value_decoder; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); DecodingStepProto decoding_step_proto; { decoding_step_proto.mutable_codec()->set_name("mock_codec"); EXPECT_CALL(mock_value_decoder_provider, Call("mock_codec")) .WillOnce(Return(mock_value_decoder.AsStdFunction())); EXPECT_OK(decoder.OnDecodingStep(0, decoding_step_proto)); } { decoding_step_proto.mutable_value()->set_codec_index(0); EXPECT_CALL(mock_value_decoder, Call(Ref(decoding_step_proto.value()), IsEmpty(), IsEmpty())) .WillOnce(Return(NoExtensionFound{})); EXPECT_THAT(decoder.OnDecodingStep(1, decoding_step_proto), StatusIs(absl::StatusCode::kNotFound, "no extension found; codecs[0]=mock_codec; " "decoding_step.type=VALUE")); } } TEST_F(DecodeTest, Error_ValueWithUnknownCodec_CodecFailed) { MockValueDecoderProvider mock_value_decoder_provider; MockValueDecoder mock_value_decoder; Decoder decoder(mock_value_decoder_provider.AsStdFunction(), {}); DecodingStepProto decoding_step_proto; { decoding_step_proto.mutable_codec()->set_name("mock_codec"); EXPECT_CALL(mock_value_decoder_provider, Call("mock_codec")) .WillOnce(Return(mock_value_decoder.AsStdFunction())); EXPECT_OK(decoder.OnDecodingStep(0, decoding_step_proto)); } { decoding_step_proto.mutable_value(); EXPECT_CALL(mock_value_decoder, Call(Ref(decoding_step_proto.value()), IsEmpty(), IsEmpty())) .WillOnce(Return(absl::UnimplementedError("codec error"))); EXPECT_THAT(decoder.OnDecodingStep(1, decoding_step_proto), StatusIs(absl::StatusCode::kUnimplemented, "codec error; detected_codec=mock_codec; " "
2,384
#ifndef AROLLA_SERIALIZATION_BASE_ENCODER_H_ #define AROLLA_SERIALIZATION_BASE_ENCODER_H_ #include <cstdint> #include <functional> #include <string> #include "absl/container/flat_hash_map.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "arolla/expr/expr_node.h" #include "arolla/qtype/typed_ref.h" #include "arolla/qtype/typed_value.h" #include "arolla/serialization_base/base.pb.h" #include "arolla/serialization_base/container.h" #include "arolla/util/fingerprint.h" namespace arolla::serialization_base { class Encoder; using ValueEncoder = std::function<absl::StatusOr<ValueProto>(TypedRef value, Encoder& encoder)>; class Encoder { public: explicit Encoder(ValueEncoder value_encoder, ContainerBuilder& container_builder); virtual ~Encoder() = default; Encoder(const Encoder&) = delete; Encoder& operator=(const Encoder&) = delete; absl::StatusOr<uint64_t> EncodeCodec(absl::string_view codec); absl::StatusOr<uint64_t> EncodeValue(const TypedValue& value); absl::StatusOr<uint64_t> EncodeExpr(const arolla::expr::ExprNodePtr& expr); private: absl::Status EncodeExprNode(const arolla::expr::ExprNode& expr_node); absl::Status EncodeLiteralNode(const arolla::expr::ExprNode& expr_node); absl::Status EncodeLeafNode(const arolla::expr::ExprNode& expr_node); absl::Status EncodePlaceholderNode(const arolla::expr::ExprNode& expr_node); absl::Status EncodeOperatorNode(const arolla::expr::ExprNode& expr_node); ValueEncoder value_encoder_; ContainerBuilder& container_builder_; uint64_t nesting_ = 0; absl::flat_hash_map<std::string, uint64_t> known_codecs_; absl::flat_hash_map<Fingerprint, uint64_t> known_values_; absl::flat_hash_map<Fingerprint, uint64_t> known_exprs_; }; } #endif #include "arolla/serialization_base/encoder.h" #include <cstdint> #include <utility> #include "absl/cleanup/cleanup.h" #include "absl/container/flat_hash_map.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "arolla/expr/expr_node.h" #include "arolla/expr/expr_visitor.h" #include "arolla/qtype/typed_value.h" #include "arolla/serialization_base/base.pb.h" #include "arolla/serialization_base/container.h" #include "arolla/util/fingerprint.h" #include "arolla/util/status_macros_backport.h" namespace arolla::serialization_base { using ::arolla::expr::ExprNode; using ::arolla::expr::ExprNodePtr; using ::arolla::expr::ExprNodeType; using ::arolla::expr::VisitorOrder; Encoder::Encoder(ValueEncoder value_encoder, ContainerBuilder& container_builder) : value_encoder_(std::move(value_encoder)), container_builder_(container_builder) {} absl::StatusOr<uint64_t> Encoder::EncodeValue(const TypedValue& value) { uint64_t value_index; const auto fingerprint = value.GetFingerprint(); if (auto it = known_values_.find(fingerprint); it != known_values_.end()) { value_index = it->second; } else { nesting_ += 1; absl::Cleanup guard = [&] { nesting_ -= 1; }; DecodingStepProto decoding_step_proto; ASSIGN_OR_RETURN(*decoding_step_proto.mutable_value(), value_encoder_(value.AsRef(), *this)); ASSIGN_OR_RETURN(value_index, container_builder_.Add(std::move(decoding_step_proto))); known_values_[fingerprint] = value_index; } if (nesting_ == 0) { DecodingStepProto decoding_step_proto; decoding_step_proto.set_output_value_index(value_index); RETURN_IF_ERROR( container_builder_.Add(std::move(decoding_step_proto)).status()); } return value_index; } absl::StatusOr<uint64_t> Encoder::EncodeCodec(absl::string_view codec) { if (auto it = known_codecs_.find(codec); it != known_codecs_.end()) { return it->second; } DecodingStepProto decoding_step_proto; decoding_step_proto.mutable_codec()->set_name(codec.data(), codec.size()); ASSIGN_OR_RETURN(auto codec_index, container_builder_.Add(std::move(decoding_step_proto))); known_codecs_[codec] = codec_index; return codec_index; } absl::StatusOr<uint64_t> Encoder::EncodeExpr(const ExprNodePtr& expr) { if (expr == nullptr) { return absl::InvalidArgumentError("expr is nullptr"); } uint64_t expr_index; const auto fingerprint = expr->fingerprint(); if (auto it = known_exprs_.find(fingerprint); it != known_exprs_.end()) { expr_index = it->second; } else { nesting_ += 1; absl::Cleanup guard = [&] { nesting_ -= 1; }; for (const auto& expr_node : VisitorOrder(expr)) { RETURN_IF_ERROR(EncodeExprNode(*expr_node)); } expr_index = known_exprs_.at(fingerprint); } if (nesting_ == 0) { DecodingStepProto decoding_step_proto; decoding_step_proto.set_output_expr_index(expr_index); RETURN_IF_ERROR( container_builder_.Add(std::move(decoding_step_proto)).status()); } return expr_index; } absl::Status Encoder::EncodeExprNode(const ExprNode& expr_node) { if (known_exprs_.contains(expr_node.fingerprint())) { return absl::OkStatus(); } switch (expr_node.type()) { case ExprNodeType::kLiteral: return EncodeLiteralNode(expr_node); case ExprNodeType::kLeaf: return EncodeLeafNode(expr_node); case ExprNodeType::kPlaceholder: return EncodePlaceholderNode(expr_node); case ExprNodeType::kOperator: return EncodeOperatorNode(expr_node); } return absl::FailedPreconditionError(absl::StrFormat( "unexpected ExprNodeType(%d)", static_cast<int>(expr_node.type()))); } absl::Status Encoder::EncodeLiteralNode(const ExprNode& expr_node) { ASSIGN_OR_RETURN(auto value_index, EncodeValue(*expr_node.qvalue())); DecodingStepProto decoding_step_proto; decoding_step_proto.mutable_literal_node()->set_literal_value_index( value_index); ASSIGN_OR_RETURN(known_exprs_[expr_node.fingerprint()], container_builder_.Add(std::move(decoding_step_proto))); return absl::OkStatus(); } absl::Status Encoder::EncodeLeafNode(const ExprNode& expr_node) { DecodingStepProto decoding_step_proto; decoding_step_proto.mutable_leaf_node()->set_leaf_key(expr_node.leaf_key()); ASSIGN_OR_RETURN(known_exprs_[expr_node.fingerprint()], container_builder_.Add(std::move(decoding_step_proto))); return absl::OkStatus(); } absl::Status Encoder::EncodePlaceholderNode(const ExprNode& expr_node) { DecodingStepProto decoding_step_proto; decoding_step_proto.mutable_placeholder_node()->set_placeholder_key( expr_node.placeholder_key()); ASSIGN_OR_RETURN(known_exprs_[expr_node.fingerprint()], container_builder_.Add(std::move(decoding_step_proto))); return absl::OkStatus(); } absl::Status Encoder::EncodeOperatorNode(const ExprNode& expr_node) { DecodingStepProto decoding_step_proto; auto* operator_node_proto = decoding_step_proto.mutable_operator_node(); ASSIGN_OR_RETURN(auto operator_value_index, EncodeValue(TypedValue::FromValue(expr_node.op()))); operator_node_proto->set_operator_value_index(operator_value_index); for (const auto& node_dep : expr_node.node_deps()) { auto it = known_exprs_.find(node_dep->fingerprint()); if (it == known_exprs_.end()) { return absl::FailedPreconditionError( "node dependencies must to be pre-serialized"); } operator_node_proto->add_input_expr_indices(it->second); } ASSIGN_OR_RETURN(known_exprs_[expr_node.fingerprint()], container_builder_.Add(std::move(decoding_step_proto))); return absl::OkStatus(); } }
#include "arolla/serialization_base/encoder.h" #include <cstdint> #include <memory> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "arolla/expr/expr.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/testing/test_operators.h" #include "arolla/qtype/base_types.h" #include "arolla/qtype/typed_ref.h" #include "arolla/qtype/typed_value.h" #include "arolla/serialization_base/base.pb.h" #include "arolla/serialization_base/container.h" #include "arolla/util/init_arolla.h" #include "arolla/util/testing/equals_proto.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla::serialization_base { namespace { using ::arolla::expr::ExprOperatorPtr; using ::arolla::expr::ExprOperatorSignature; using ::arolla::expr::Leaf; using ::arolla::expr::Literal; using ::arolla::expr::Placeholder; using ::arolla::expr::testing::DummyOp; using ::arolla::testing::EqualsProto; using ::arolla::testing::IsOkAndHolds; using ::arolla::testing::StatusIs; using ::testing::InSequence; using ::testing::MockFunction; using ::testing::Ref; using ::testing::Return; using ::testing::Truly; auto EqualsTypedRef(TypedRef expected_value) { return Truly([expected_value](TypedRef actual_value) { return expected_value.GetRawPointer() == actual_value.GetRawPointer() && expected_value.GetType() == actual_value.GetType(); }); } template <typename T> auto EqualsTypedRefAsT(const T& expected_value) { return Truly([expected_value](TypedRef actual_value) { auto status_or_value = actual_value.As<T>(); return status_or_value.ok() && status_or_value.value().get() == expected_value; }); } class MockContainerBuilder : public ContainerBuilder { public: MOCK_METHOD(absl::StatusOr<uint64_t>, Add, (DecodingStepProto && decoding_step_proto), (override)); }; class EncoderTest : public ::testing::Test { protected: void SetUp() override { ASSERT_OK(InitArolla()); } MockContainerBuilder mock_container_builder_; MockFunction<absl::StatusOr<ValueProto>(TypedRef value, Encoder& encoder)> mock_value_encoder_; Encoder encoder_{mock_value_encoder_.AsStdFunction(), mock_container_builder_}; }; TEST_F(EncoderTest, EncodeExpr_nullptr) { EXPECT_THAT(encoder_.EncodeExpr(nullptr), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST_F(EncoderTest, Codecs) { { EXPECT_CALL(mock_container_builder_, Add(EqualsProto(R"pb(codec: { name: "a" })pb"))) .WillOnce(Return(0)); EXPECT_THAT(encoder_.EncodeCodec("a"), IsOkAndHolds(0)); EXPECT_THAT(encoder_.EncodeCodec("a"), IsOkAndHolds(0)); } { EXPECT_CALL(mock_container_builder_, Add(EqualsProto(R"pb(codec: { name: "b" })pb"))) .WillOnce(Return(1)); EXPECT_THAT(encoder_.EncodeCodec("b"), IsOkAndHolds(1)); EXPECT_THAT(encoder_.EncodeCodec("a"), IsOkAndHolds(0)); } } TEST_F(EncoderTest, EncodeExpr_LiteralNode) { auto literal = Literal(1.0f); InSequence seq; EXPECT_CALL(mock_value_encoder_, Call(EqualsTypedRef(literal->qvalue()->AsRef()), Ref(encoder_))) .WillOnce(Return(ValueProto())); EXPECT_CALL(mock_container_builder_, Add(EqualsProto(R"pb(value: {})pb"))) .WillOnce(Return(0)); EXPECT_CALL( mock_container_builder_, Add(EqualsProto(R"pb(literal_node: { literal_value_index: 0 })pb"))) .WillOnce(Return(1)); EXPECT_CALL(mock_container_builder_, Add(EqualsProto(R"pb(output_expr_index: 1)pb"))) .WillOnce(Return(2)); EXPECT_THAT(encoder_.EncodeExpr(literal), IsOkAndHolds(1)); } TEST_F(EncoderTest, EncodeExpr_LeafNode) { auto leaf = Leaf("key"); InSequence seq; EXPECT_CALL(mock_container_builder_, Add(EqualsProto(R"pb(leaf_node: { leaf_key: "key" })pb"))) .WillOnce(Return(0)); EXPECT_CALL(mock_container_builder_, Add(EqualsProto(R"pb(output_expr_index: 0)pb"))) .WillOnce(Return(1)); EXPECT_THAT(encoder_.EncodeExpr(leaf), IsOkAndHolds(0)); } TEST_F(EncoderTest, EncodeExpr_PlaceholderNode) { auto placeholder = Placeholder("key"); InSequence seq; EXPECT_CALL( mock_container_builder_, Add(EqualsProto(R"pb(placeholder_node: { placeholder_key: "key" })pb"))) .WillOnce(Return(0)); EXPECT_CALL(mock_container_builder_, Add(EqualsProto(R"pb(output_expr_index: 0)pb"))) .WillOnce(Return(1)); EXPECT_THAT(encoder_.EncodeExpr(placeholder), IsOkAndHolds(0)); } TEST_F(EncoderTest, EncodeExpr_OperatorNode) { ExprOperatorPtr dummy_op = std::make_shared<DummyOp>( "dummy_op", ExprOperatorSignature::MakeVariadicArgs()); auto leaf = Leaf("leaf"); auto literal = Literal(1.0f); ASSERT_OK_AND_ASSIGN(auto expr, BindOp(dummy_op, {leaf, literal, leaf, literal}, {})); InSequence seq; EXPECT_CALL(mock_container_builder_, Add(EqualsProto(R"pb(leaf_node: { leaf_key: "leaf" })pb"))) .WillOnce(Return(0)); EXPECT_CALL(mock_value_encoder_, Call(EqualsTypedRef(literal->qvalue()->AsRef()), Ref(encoder_))) .WillOnce(Return(ValueProto())); EXPECT_CALL(mock_container_builder_, Add(EqualsProto(R"pb(value: {})pb"))) .WillOnce(Return(1)); EXPECT_CALL( mock_container_builder_, Add(EqualsProto(R"pb(literal_node: { literal_value_index: 1 })pb"))) .WillOnce(Return(2)); EXPECT_CALL(mock_value_encoder_, Call(EqualsTypedRefAsT(dummy_op), Ref(encoder_))) .WillOnce(Return(ValueProto())); EXPECT_CALL(mock_container_builder_, Add(EqualsProto(R"pb(value: {})pb"))) .WillOnce(Return(3)); EXPECT_CALL(mock_container_builder_, Add(EqualsProto(R"pb(operator_node: { operator_value_index: 3 input_expr_indices: [ 0, 2, 0, 2 ] })pb"))) .WillOnce(Return(4)); EXPECT_CALL(mock_container_builder_, Add(EqualsProto(R"pb(output_expr_index: 4)pb"))) .WillOnce(Return(5)); EXPECT_THAT(encoder_.EncodeExpr(expr), IsOkAndHolds(4)); } TEST_F(EncoderTest, EncodeExpr_SubExprDeduplication) { ExprOperatorPtr dummy_op = std::make_shared<DummyOp>( "dummy_op", ExprOperatorSignature::MakeVariadicArgs()); auto leaf = Leaf("leaf"); ASSERT_OK_AND_ASSIGN(auto expr, BindOp(dummy_op, {leaf}, {})); InSequence seq; EXPECT_CALL(mock_container_builder_, Add(EqualsProto(R"pb(leaf_node { leaf_key: "leaf" })pb"))) .WillOnce(Return(0)); EXPECT_CALL(mock_value_encoder_, Call(EqualsTypedRefAsT(dummy_op), Ref(encoder_))) .WillOnce(Return(ValueProto())); EXPECT_CALL(mock_container_builder_, Add(EqualsProto(R"pb(value {})pb"))) .WillOnce(Return(1)); EXPECT_CALL(mock_container_builder_, Add(EqualsProto(R"pb(operator_node { operator_value_index: 1 input_expr_indices: [ 0 ] })pb"))) .WillOnce(Return(2)); EXPECT_CALL(mock_container_builder_, Add(EqualsProto(R"pb(output_expr_index: 2)pb"))) .WillOnce(Return(3)); EXPECT_CALL(mock_container_builder_, Add(EqualsProto(R"pb(output_expr_index: 0)pb"))) .WillOnce(Return(4)); EXPECT_THAT(encoder_.EncodeExpr(expr), IsOkAndHolds(2)); EXPECT_THAT(encoder_.EncodeExpr(leaf), IsOkAndHolds(0)); } TEST_F(EncoderTest, EncodeValue) { auto value = TypedValue::FromValue(1.0f); auto value_proto = ValueProto(); value_proto.add_input_value_indices(1); value_proto.add_input_value_indices(2); value_proto.add_input_expr_indices(3); value_proto.add_input_expr_indices(4); value_proto.add_input_expr_indices(5); value_proto.set_codec_index(123); InSequence seq; EXPECT_CALL(mock_value_encoder_, Call(EqualsTypedRef(value.AsRef()), Ref(encoder_))) .WillOnce(Return(value_proto)); EXPECT_CALL(mock_container_builder_, Add(EqualsProto(R"pb(value { input_value_indices: [ 1, 2 ] input_expr_indices: [ 3, 4, 5 ] codec_index: 123 })pb"))) .WillOnce(Return(0)); EXPECT_CALL(mock_container_builder_, Add(EqualsProto(R"pb(output_value_index: 0)pb"))) .WillOnce(Return(1)); EXPECT_THAT(encoder_.EncodeValue(value), IsOkAndHolds(0)); EXPECT_CALL( mock_container_builder_, Add(EqualsProto(R"pb(literal_node: { literal_value_index: 0 })pb"))) .WillOnce(Return(2)); EXPECT_CALL(mock_container_builder_, Add(EqualsProto(R"pb(output_expr_index: 2)pb"))) .WillOnce(Return(3)); EXPECT_THAT(encoder_.EncodeExpr(Literal(value)), IsOkAndHolds(2)); } } }
2,385
#ifndef AROLLA_UTIL_REPR_H_ #define AROLLA_UTIL_REPR_H_ #include <cstdint> #include <string> #include <type_traits> #include <vector> #include "arolla/util/fingerprint.h" namespace arolla { struct ReprToken { struct Precedence { int8_t left = -1; int8_t right = -1; }; static constexpr Precedence kHighest{-1, -1}; static constexpr Precedence kSafeForSubscription = kHighest; static constexpr Precedence kSafeForNegation{0, 0}; static constexpr Precedence kSafeForArithmetic{1, 1}; static constexpr Precedence kOpSubscription{0, -1}; std::string str; Precedence precedence = kHighest; }; AROLLA_DECLARE_FINGERPRINT_HASHER_TRAITS(ReprToken::Precedence); AROLLA_DECLARE_FINGERPRINT_HASHER_TRAITS(ReprToken); template <typename T, typename Enabled = void> struct ReprTraits {}; template <typename T> struct ReprTraits<T, std::void_t<decltype(static_cast<ReprToken (T::*)() const>( &T::ArollaReprToken))>> { ReprToken operator()(const T& value) const { return value.ArollaReprToken(); } }; template <typename T> auto GenReprToken(const T& value) -> decltype(ReprTraits<T>()(value)) { return ReprTraits<T>()(value); } template <typename T> auto Repr(const T& value) -> decltype(GenReprToken(value).str) { return std::move(GenReprToken(value).str); } ReprToken GenReprTokenWeakFloat(double value); #define AROLLA_DECLARE_REPR(CPP_TYPE) \ template <> \ struct ReprTraits<CPP_TYPE> { \ ReprToken operator()(const CPP_TYPE& value) const; \ } AROLLA_DECLARE_REPR(bool); AROLLA_DECLARE_REPR(int32_t); AROLLA_DECLARE_REPR(int64_t); AROLLA_DECLARE_REPR(uint64_t); AROLLA_DECLARE_REPR(float); AROLLA_DECLARE_REPR(double); namespace repr_traits_vector_bool_ref_impl { struct FakeStdVectorBoolConstRef; using StdVectorBoolConstRef = std::conditional_t< std::is_same_v<bool, std::decay_t<std::vector<bool>::const_reference>>, repr_traits_vector_bool_ref_impl::FakeStdVectorBoolConstRef, std::decay_t<std::vector<bool>::const_reference>>; } template <> struct ReprTraits<repr_traits_vector_bool_ref_impl::StdVectorBoolConstRef> : ReprTraits<bool> {}; } #endif #include "arolla/util/repr.h" #include <cstdint> #include <string> #include "absl/strings/str_cat.h" #include "double-conversion/double-to-string.h" #include "double-conversion/utils.h" #include "arolla/util/fingerprint.h" namespace arolla { ReprToken ReprTraits<bool>::operator()(const bool& value) const { return ReprToken{value ? "true" : "false"}; } ReprToken ReprTraits<int32_t>::operator()(const int32_t& value) const { ReprToken result{absl::StrCat(value)}; if (result.str[0] == '-') { result.precedence = ReprToken::kSafeForArithmetic; } else { result.precedence = ReprToken::kSafeForNegation; } return result; } ReprToken ReprTraits<int64_t>::operator()(const int64_t& value) const { return ReprToken{absl::StrCat("int64{", value, "}")}; } ReprToken ReprTraits<uint64_t>::operator()(const uint64_t& value) const { return ReprToken{absl::StrCat("uint64{", value, "}")}; } using double_conversion::DoubleToStringConverter; ReprToken ReprTraits<float>::operator()(const float& value) const { static const DoubleToStringConverter converter( DoubleToStringConverter::EMIT_TRAILING_DECIMAL_POINT, "inf", "nan", 'e', -6, 21, 6, 0); char buf[128]; double_conversion::StringBuilder builder(buf, sizeof(buf)); converter.ToShortestSingle(value, &builder); ReprToken result{builder.Finalize()}; if (result.str[0] == '-') { result.precedence = ReprToken::kSafeForArithmetic; } else { result.precedence = ReprToken::kSafeForNegation; } return result; } ReprToken ReprTraits<double>::operator()(const double& value) const { static const DoubleToStringConverter converter( DoubleToStringConverter::NO_FLAGS, "inf", "nan", 'e', -6, 21, 6, 0); char buf[128]; double_conversion::StringBuilder builder(buf, sizeof(buf)); builder.AddString("float64{"); converter.ToShortest(value, &builder); builder.AddString("}"); return ReprToken{builder.Finalize()}; } ReprToken GenReprTokenWeakFloat(double value) { static const DoubleToStringConverter converter( DoubleToStringConverter::NO_FLAGS, "inf", "nan", 'e', -6, 21, 6, 0); char buf[128]; double_conversion::StringBuilder builder(buf, sizeof(buf)); builder.AddString("weak_float{"); converter.ToShortest(value, &builder); builder.AddString("}"); return ReprToken{builder.Finalize()}; } void FingerprintHasherTraits<ReprToken::Precedence>::operator()( FingerprintHasher* hasher, const ReprToken::Precedence& value) const { hasher->Combine(value.left, value.right); } void FingerprintHasherTraits<ReprToken>::operator()( FingerprintHasher* hasher, const ReprToken& value) const { hasher->Combine(value.str, value.precedence); } }
#include "arolla/util/repr.h" #include <cstdint> #include <limits> #include <string> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "arolla/util/fingerprint.h" #include "arolla/util/testing/repr_token_eq.h" namespace arolla { namespace { using ::arolla::testing::ReprTokenEq; TEST(ReprTest, Bool) { EXPECT_THAT(GenReprToken(true), ReprTokenEq("true")); EXPECT_THAT(GenReprToken(false), ReprTokenEq("false")); } TEST(ReprTest, VectorBoolConstReference) { const std::vector<bool> vector = {true}; EXPECT_THAT(GenReprToken(vector[0]), ReprTokenEq("true")); } TEST(ReprTest, int32_t) { EXPECT_THAT(GenReprToken(int32_t{-1}), ReprTokenEq("-1", ReprToken::kSafeForArithmetic)); EXPECT_THAT(GenReprToken(int32_t{0}), ReprTokenEq("0", ReprToken::kSafeForNegation)); EXPECT_THAT(GenReprToken(int32_t{1}), ReprTokenEq("1", ReprToken::kSafeForNegation)); } TEST(ReprTest, int64_t) { EXPECT_THAT(GenReprToken(int64_t{-1}), ReprTokenEq("int64{-1}")); EXPECT_THAT(GenReprToken(int64_t{0}), ReprTokenEq("int64{0}")); EXPECT_THAT(GenReprToken(int64_t{1}), ReprTokenEq("int64{1}")); } TEST(ReprTest, float32) { EXPECT_THAT(GenReprToken(float{-1.}), ReprTokenEq("-1.", ReprToken::kSafeForArithmetic)); EXPECT_THAT(GenReprToken(float{-0.}), ReprTokenEq("-0.", ReprToken::kSafeForArithmetic)); EXPECT_THAT(GenReprToken(float{0.}), ReprTokenEq("0.", ReprToken::kSafeForNegation)); EXPECT_THAT(GenReprToken(float{1}), ReprTokenEq("1.", ReprToken::kSafeForNegation)); EXPECT_THAT(GenReprToken(float{0.2}), ReprTokenEq("0.2", ReprToken::kSafeForNegation)); EXPECT_THAT(GenReprToken(float{1e30}), ReprTokenEq("1e30", ReprToken::kSafeForNegation)); EXPECT_THAT(GenReprToken(float{1e-30}), ReprTokenEq("1e-30", ReprToken::kSafeForNegation)); EXPECT_THAT(GenReprToken(std::numeric_limits<float>::infinity()), ReprTokenEq("inf", ReprToken::kSafeForNegation)); EXPECT_THAT(GenReprToken(-std::numeric_limits<float>::infinity()), ReprTokenEq("-inf", ReprToken::kSafeForArithmetic)); EXPECT_THAT(GenReprToken(std::numeric_limits<float>::quiet_NaN()), ReprTokenEq("nan", ReprToken::kSafeForNegation)); EXPECT_THAT(GenReprToken(-std::numeric_limits<float>::quiet_NaN()), ReprTokenEq("nan", ReprToken::kSafeForNegation)); EXPECT_THAT(GenReprToken(std::numeric_limits<float>::signaling_NaN()), ReprTokenEq("nan", ReprToken::kSafeForNegation)); EXPECT_THAT(GenReprToken(-std::numeric_limits<float>::signaling_NaN()), ReprTokenEq("nan", ReprToken::kSafeForNegation)); } TEST(ReprTest, float64) { EXPECT_THAT(GenReprToken(double{-1.}), ReprTokenEq("float64{-1}")); EXPECT_THAT(GenReprToken(double{-0.}), ReprTokenEq("float64{-0}")); EXPECT_THAT(GenReprToken(double{0.}), ReprTokenEq("float64{0}")); EXPECT_THAT(GenReprToken(double{1}), ReprTokenEq("float64{1}")); EXPECT_THAT(GenReprToken(double{0.2}), ReprTokenEq("float64{0.2}")); EXPECT_THAT(GenReprToken(double{1e30}), ReprTokenEq("float64{1e30}")); EXPECT_THAT(GenReprToken(double{1e-30}), ReprTokenEq("float64{1e-30}")); EXPECT_THAT(GenReprToken(std::numeric_limits<double>::infinity()), ReprTokenEq("float64{inf}")); EXPECT_THAT(GenReprToken(-std::numeric_limits<double>::infinity()), ReprTokenEq("float64{-inf}")); EXPECT_THAT(GenReprToken(std::numeric_limits<double>::quiet_NaN()), ReprTokenEq("float64{nan}")); EXPECT_THAT(GenReprToken(-std::numeric_limits<double>::quiet_NaN()), ReprTokenEq("float64{nan}")); EXPECT_THAT(GenReprToken(double{0.2f}), ReprTokenEq("float64{0.20000000298023224}")); } TEST(ReprTest, weak_float) { EXPECT_THAT(GenReprTokenWeakFloat(double{-1.}), ReprTokenEq("weak_float{-1}")); EXPECT_THAT(GenReprTokenWeakFloat(double{-0.}), ReprTokenEq("weak_float{-0}")); EXPECT_THAT(GenReprTokenWeakFloat(double{0.}), ReprTokenEq("weak_float{0}")); EXPECT_THAT(GenReprTokenWeakFloat(double{1}), ReprTokenEq("weak_float{1}")); EXPECT_THAT(GenReprTokenWeakFloat(double{0.2}), ReprTokenEq("weak_float{0.2}")); EXPECT_THAT(GenReprTokenWeakFloat(double{1e30}), ReprTokenEq("weak_float{1e30}")); EXPECT_THAT(GenReprTokenWeakFloat(double{1e-30}), ReprTokenEq("weak_float{1e-30}")); EXPECT_THAT(GenReprTokenWeakFloat(std::numeric_limits<double>::infinity()), ReprTokenEq("weak_float{inf}")); EXPECT_THAT(GenReprTokenWeakFloat(-std::numeric_limits<double>::infinity()), ReprTokenEq("weak_float{-inf}")); EXPECT_THAT(GenReprTokenWeakFloat(std::numeric_limits<double>::quiet_NaN()), ReprTokenEq("weak_float{nan}")); EXPECT_THAT(GenReprTokenWeakFloat(-std::numeric_limits<double>::quiet_NaN()), ReprTokenEq("weak_float{nan}")); EXPECT_THAT(GenReprTokenWeakFloat(double{0.2f}), ReprTokenEq("weak_float{0.20000000298023224}")); } TEST(ReprTest, fingerprint) { auto fp = [](const auto& value) { return FingerprintHasher("").Combine(value).Finish(); }; ReprToken::Precedence p01{0, 1}; { auto p01_hash = fp(p01); EXPECT_EQ(p01_hash, fp(p01)); EXPECT_NE(p01_hash, fp(ReprToken::Precedence{0, 0})); EXPECT_NE(p01_hash, fp(ReprToken::Precedence{1, 1})); } { ReprToken abc{.str = "abc"}; auto abc_hash = fp(abc); EXPECT_EQ(abc_hash, fp(abc)); EXPECT_NE(abc_hash, fp(ReprToken{.str = "foo"})); auto abc_p01_hash = fp(ReprToken{.str = "abc", .precedence = p01}); EXPECT_EQ(abc_p01_hash, fp(ReprToken{.str = "abc", .precedence = p01})); EXPECT_NE( abc_p01_hash, fp(ReprToken{.str = "abc", .precedence = ReprToken::Precedence{0, 0}})); } } struct ClassWithArollaReprToken { std::string v; ReprToken ArollaReprToken() const { return {v}; } }; TEST(ReprTest, ClassWithArollaReprToken) { ReprTraits<ClassWithArollaReprToken> traits; EXPECT_EQ(traits(ClassWithArollaReprToken{"x"}).str, "x"); EXPECT_EQ(GenReprToken(ClassWithArollaReprToken{"x"}).str, "x"); EXPECT_EQ(Repr(ClassWithArollaReprToken{"x"}), "x"); } } }
2,386