ID
int64 0
2.65k
| Language
stringclasses 1
value | Repository Name
stringclasses 14
values | File Name
stringlengths 2
48
| File Path in Repository
stringlengths 11
111
⌀ | File Path for Unit Test
stringlengths 16
116
⌀ | Code
stringlengths 411
31.4k
| Unit Test - (Ground Truth)
stringlengths 40
32.1k
|
---|---|---|---|---|---|---|---|
0 | cpp | google/cel-cpp | kind | common/kind.cc | common/kind_test.cc | #ifndef THIRD_PARTY_CEL_CPP_BASE_KIND_H_
#define THIRD_PARTY_CEL_CPP_BASE_KIND_H_
#include "common/kind.h"
#include "common/type_kind.h"
#include "common/value_kind.h"
#endif
#include "common/kind.h"
#include "absl/strings/string_view.h"
namespace cel {
absl::string_view KindToString(Kind kind) {
switch (kind) {
case Kind::kNullType:
return "null_type";
case Kind::kDyn:
return "dyn";
case Kind::kAny:
return "any";
case Kind::kType:
return "type";
case Kind::kTypeParam:
return "type_param";
case Kind::kFunction:
return "function";
case Kind::kBool:
return "bool";
case Kind::kInt:
return "int";
case Kind::kUint:
return "uint";
case Kind::kDouble:
return "double";
case Kind::kString:
return "string";
case Kind::kBytes:
return "bytes";
case Kind::kDuration:
return "duration";
case Kind::kTimestamp:
return "timestamp";
case Kind::kList:
return "list";
case Kind::kMap:
return "map";
case Kind::kStruct:
return "struct";
case Kind::kUnknown:
return "*unknown*";
case Kind::kOpaque:
return "*opaque*";
case Kind::kBoolWrapper:
return "google.protobuf.BoolValue";
case Kind::kIntWrapper:
return "google.protobuf.Int64Value";
case Kind::kUintWrapper:
return "google.protobuf.UInt64Value";
case Kind::kDoubleWrapper:
return "google.protobuf.DoubleValue";
case Kind::kStringWrapper:
return "google.protobuf.StringValue";
case Kind::kBytesWrapper:
return "google.protobuf.BytesValue";
default:
return "*error*";
}
}
} | #include "common/kind.h"
#include <limits>
#include <type_traits>
#include "common/type_kind.h"
#include "common/value_kind.h"
#include "internal/testing.h"
namespace cel {
namespace {
static_assert(std::is_same_v<std::underlying_type_t<TypeKind>,
std::underlying_type_t<ValueKind>>,
"TypeKind and ValueKind must have the same underlying type");
TEST(Kind, ToString) {
EXPECT_EQ(KindToString(Kind::kError), "*error*");
EXPECT_EQ(KindToString(Kind::kNullType), "null_type");
EXPECT_EQ(KindToString(Kind::kDyn), "dyn");
EXPECT_EQ(KindToString(Kind::kAny), "any");
EXPECT_EQ(KindToString(Kind::kType), "type");
EXPECT_EQ(KindToString(Kind::kBool), "bool");
EXPECT_EQ(KindToString(Kind::kInt), "int");
EXPECT_EQ(KindToString(Kind::kUint), "uint");
EXPECT_EQ(KindToString(Kind::kDouble), "double");
EXPECT_EQ(KindToString(Kind::kString), "string");
EXPECT_EQ(KindToString(Kind::kBytes), "bytes");
EXPECT_EQ(KindToString(Kind::kDuration), "duration");
EXPECT_EQ(KindToString(Kind::kTimestamp), "timestamp");
EXPECT_EQ(KindToString(Kind::kList), "list");
EXPECT_EQ(KindToString(Kind::kMap), "map");
EXPECT_EQ(KindToString(Kind::kStruct), "struct");
EXPECT_EQ(KindToString(Kind::kUnknown), "*unknown*");
EXPECT_EQ(KindToString(Kind::kOpaque), "*opaque*");
EXPECT_EQ(KindToString(Kind::kBoolWrapper), "google.protobuf.BoolValue");
EXPECT_EQ(KindToString(Kind::kIntWrapper), "google.protobuf.Int64Value");
EXPECT_EQ(KindToString(Kind::kUintWrapper), "google.protobuf.UInt64Value");
EXPECT_EQ(KindToString(Kind::kDoubleWrapper), "google.protobuf.DoubleValue");
EXPECT_EQ(KindToString(Kind::kStringWrapper), "google.protobuf.StringValue");
EXPECT_EQ(KindToString(Kind::kBytesWrapper), "google.protobuf.BytesValue");
EXPECT_EQ(KindToString(static_cast<Kind>(std::numeric_limits<int>::max())),
"*error*");
}
TEST(Kind, TypeKindRoundtrip) {
EXPECT_EQ(TypeKindToKind(KindToTypeKind(Kind::kBool)), Kind::kBool);
}
TEST(Kind, ValueKindRoundtrip) {
EXPECT_EQ(ValueKindToKind(KindToValueKind(Kind::kBool)), Kind::kBool);
}
TEST(Kind, IsTypeKind) {
EXPECT_TRUE(KindIsTypeKind(Kind::kBool));
EXPECT_TRUE(KindIsTypeKind(Kind::kAny));
EXPECT_TRUE(KindIsTypeKind(Kind::kDyn));
}
TEST(Kind, IsValueKind) {
EXPECT_TRUE(KindIsValueKind(Kind::kBool));
EXPECT_FALSE(KindIsValueKind(Kind::kAny));
EXPECT_FALSE(KindIsValueKind(Kind::kDyn));
}
TEST(Kind, Equality) {
EXPECT_EQ(Kind::kBool, TypeKind::kBool);
EXPECT_EQ(TypeKind::kBool, Kind::kBool);
EXPECT_EQ(Kind::kBool, ValueKind::kBool);
EXPECT_EQ(ValueKind::kBool, Kind::kBool);
EXPECT_NE(Kind::kBool, TypeKind::kInt);
EXPECT_NE(TypeKind::kInt, Kind::kBool);
EXPECT_NE(Kind::kBool, ValueKind::kInt);
EXPECT_NE(ValueKind::kInt, Kind::kBool);
}
TEST(TypeKind, ToString) {
EXPECT_EQ(TypeKindToString(TypeKind::kBool), KindToString(Kind::kBool));
}
TEST(ValueKind, ToString) {
EXPECT_EQ(ValueKindToString(ValueKind::kBool), KindToString(Kind::kBool));
}
}
} |
1 | cpp | google/cel-cpp | value_factory | common/value_factory.cc | common/value_factory_test.cc | #ifndef THIRD_PARTY_CEL_CPP_COMMON_VALUE_FACTORY_H_
#define THIRD_PARTY_CEL_CPP_COMMON_VALUE_FACTORY_H_
#include <cstdint>
#include <string>
#include <utility>
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/cord.h"
#include "absl/strings/string_view.h"
#include "absl/time/time.h"
#include "common/json.h"
#include "common/type.h"
#include "common/type_factory.h"
#include "common/unknown.h"
#include "common/value.h"
namespace cel {
namespace common_internal {
class PiecewiseValueManager;
}
class ValueFactory : public virtual TypeFactory {
public:
Value CreateValueFromJson(Json json);
ListValue CreateListValueFromJsonArray(JsonArray json);
MapValue CreateMapValueFromJsonObject(JsonObject json);
ListValue CreateZeroListValue(ListTypeView type);
MapValue CreateZeroMapValue(MapTypeView type);
OptionalValue CreateZeroOptionalValue(OptionalTypeView type);
ListValueView GetZeroDynListValue();
MapValueView GetZeroDynDynMapValue();
MapValueView GetZeroStringDynMapValue();
OptionalValueView GetZeroDynOptionalValue();
NullValue GetNullValue() { return NullValue{}; }
ErrorValue CreateErrorValue(absl::Status status) {
return ErrorValue{std::move(status)};
}
BoolValue CreateBoolValue(bool value) { return BoolValue{value}; }
IntValue CreateIntValue(int64_t value) { return IntValue{value}; }
UintValue CreateUintValue(uint64_t value) { return UintValue{value}; }
DoubleValue CreateDoubleValue(double value) { return DoubleValue{value}; }
BytesValue GetBytesValue() { return BytesValue(); }
absl::StatusOr<BytesValue> CreateBytesValue(const char* value) {
return CreateBytesValue(absl::string_view(value));
}
absl::StatusOr<BytesValue> CreateBytesValue(absl::string_view value) {
return CreateBytesValue(std::string(value));
}
absl::StatusOr<BytesValue> CreateBytesValue(std::string value);
absl::StatusOr<BytesValue> CreateBytesValue(absl::Cord value) {
return BytesValue(std::move(value));
}
template <typename Releaser>
absl::StatusOr<BytesValue> CreateBytesValue(absl::string_view value,
Releaser&& releaser) {
return BytesValue(
absl::MakeCordFromExternal(value, std::forward<Releaser>(releaser)));
}
StringValue GetStringValue() { return StringValue(); }
absl::StatusOr<StringValue> CreateStringValue(const char* value) {
return CreateStringValue(absl::string_view(value));
}
absl::StatusOr<StringValue> CreateStringValue(absl::string_view value) {
return CreateStringValue(std::string(value));
}
absl::StatusOr<StringValue> CreateStringValue(std::string value);
absl::StatusOr<StringValue> CreateStringValue(absl::Cord value);
template <typename Releaser>
absl::StatusOr<StringValue> CreateStringValue(absl::string_view value,
Releaser&& releaser) {
return StringValue(
absl::MakeCordFromExternal(value, std::forward<Releaser>(releaser)));
}
StringValue CreateUncheckedStringValue(const char* value) {
return CreateUncheckedStringValue(absl::string_view(value));
}
StringValue CreateUncheckedStringValue(absl::string_view value) {
return CreateUncheckedStringValue(std::string(value));
}
StringValue CreateUncheckedStringValue(std::string value);
StringValue CreateUncheckedStringValue(absl::Cord value) {
return StringValue(std::move(value));
}
template <typename Releaser>
StringValue CreateUncheckedStringValue(absl::string_view value,
Releaser&& releaser) {
return StringValue(
absl::MakeCordFromExternal(value, std::forward<Releaser>(releaser)));
}
absl::StatusOr<DurationValue> CreateDurationValue(absl::Duration value);
DurationValue CreateUncheckedDurationValue(absl::Duration value) {
return DurationValue{value};
}
absl::StatusOr<TimestampValue> CreateTimestampValue(absl::Time value);
TimestampValue CreateUncheckedTimestampValue(absl::Time value) {
return TimestampValue{value};
}
TypeValue CreateTypeValue(TypeView type) { return TypeValue{Type(type)}; }
UnknownValue CreateUnknownValue() {
return CreateUnknownValue(AttributeSet(), FunctionResultSet());
}
UnknownValue CreateUnknownValue(AttributeSet attribute_set) {
return CreateUnknownValue(std::move(attribute_set), FunctionResultSet());
}
UnknownValue CreateUnknownValue(FunctionResultSet function_result_set) {
return CreateUnknownValue(AttributeSet(), std::move(function_result_set));
}
UnknownValue CreateUnknownValue(AttributeSet attribute_set,
FunctionResultSet function_result_set) {
return UnknownValue{
Unknown{std::move(attribute_set), std::move(function_result_set)}};
}
protected:
friend class common_internal::PiecewiseValueManager;
virtual ListValue CreateZeroListValueImpl(ListTypeView type) = 0;
virtual MapValue CreateZeroMapValueImpl(MapTypeView type) = 0;
virtual OptionalValue CreateZeroOptionalValueImpl(OptionalTypeView type) = 0;
};
}
#endif
#include "common/value_factory.h"
#include <algorithm>
#include <cstddef>
#include <memory>
#include <new>
#include <string>
#include <utility>
#include <vector>
#include "absl/base/attributes.h"
#include "absl/base/nullability.h"
#include "absl/base/optimization.h"
#include "absl/functional/overload.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/cord.h"
#include "absl/strings/string_view.h"
#include "absl/time/time.h"
#include "absl/types/optional.h"
#include "absl/types/variant.h"
#include "common/casting.h"
#include "common/internal/arena_string.h"
#include "common/internal/reference_count.h"
#include "common/json.h"
#include "common/memory.h"
#include "common/native_type.h"
#include "common/type.h"
#include "common/value.h"
#include "common/value_manager.h"
#include "common/values/value_cache.h"
#include "internal/status_macros.h"
#include "internal/time.h"
#include "internal/utf8.h"
namespace cel {
namespace {
using common_internal::ProcessLocalValueCache;
void JsonToValue(const Json& json, ValueFactory& value_factory, Value& result) {
absl::visit(
absl::Overload(
[&result](JsonNull) { result = NullValue(); },
[&result](JsonBool value) { result = BoolValue(value); },
[&result](JsonNumber value) { result = DoubleValue(value); },
[&result](const JsonString& value) { result = StringValue(value); },
[&value_factory, &result](const JsonArray& value) {
result = value_factory.CreateListValueFromJsonArray(value);
},
[&value_factory, &result](const JsonObject& value) {
result = value_factory.CreateMapValueFromJsonObject(value);
}),
json);
}
void JsonDebugString(const Json& json, std::string& out);
void JsonArrayDebugString(const JsonArray& json, std::string& out) {
out.push_back('[');
auto element = json.begin();
if (element != json.end()) {
JsonDebugString(*element, out);
++element;
for (; element != json.end(); ++element) {
out.append(", ");
JsonDebugString(*element, out);
}
}
out.push_back(']');
}
void JsonObjectEntryDebugString(const JsonString& key, const Json& value,
std::string& out) {
out.append(StringValueView(key).DebugString());
out.append(": ");
JsonDebugString(value, out);
}
void JsonObjectDebugString(const JsonObject& json, std::string& out) {
std::vector<JsonString> keys;
keys.reserve(json.size());
for (const auto& entry : json) {
keys.push_back(entry.first);
}
std::stable_sort(keys.begin(), keys.end());
out.push_back('{');
auto key = keys.begin();
if (key != keys.end()) {
JsonObjectEntryDebugString(*key, json.find(*key)->second, out);
++key;
for (; key != keys.end(); ++key) {
out.append(", ");
JsonObjectEntryDebugString(*key, json.find(*key)->second, out);
}
}
out.push_back('}');
}
void JsonDebugString(const Json& json, std::string& out) {
absl::visit(absl::Overload(
[&out](JsonNull) -> void {
out.append(NullValueView().DebugString());
},
[&out](JsonBool value) -> void {
out.append(BoolValueView(value).DebugString());
},
[&out](JsonNumber value) -> void {
out.append(DoubleValueView(value).DebugString());
},
[&out](const JsonString& value) -> void {
out.append(StringValueView(value).DebugString());
},
[&out](const JsonArray& value) -> void {
JsonArrayDebugString(value, out);
},
[&out](const JsonObject& value) -> void {
JsonObjectDebugString(value, out);
}),
json);
}
class JsonListValue final : public ParsedListValueInterface {
public:
explicit JsonListValue(JsonArray array) : array_(std::move(array)) {}
std::string DebugString() const override {
std::string out;
JsonArrayDebugString(array_, out);
return out;
}
bool IsEmpty() const override { return array_.empty(); }
size_t Size() const override { return array_.size(); }
absl::StatusOr<JsonArray> ConvertToJsonArray(
AnyToJsonConverter&) const override {
return array_;
}
private:
Type GetTypeImpl(TypeManager& type_manager) const override {
return ListType(type_manager.GetDynListType());
}
absl::Status GetImpl(ValueManager& value_manager, size_t index,
Value& result) const override {
JsonToValue(array_[index], value_manager, result);
return absl::OkStatus();
}
NativeTypeId GetNativeTypeId() const noexcept override {
return NativeTypeId::For<JsonListValue>();
}
const JsonArray array_;
};
class JsonMapValueKeyIterator final : public ValueIterator {
public:
explicit JsonMapValueKeyIterator(
const JsonObject& object ABSL_ATTRIBUTE_LIFETIME_BOUND)
: begin_(object.begin()), end_(object.end()) {}
bool HasNext() override { return begin_ != end_; }
absl::Status Next(ValueManager&, Value& result) override {
if (ABSL_PREDICT_FALSE(begin_ == end_)) {
return absl::FailedPreconditionError(
"ValueIterator::Next() called when "
"ValueIterator::HasNext() returns false");
}
const auto& key = begin_->first;
++begin_;
result = StringValue(key);
return absl::OkStatus();
}
private:
typename JsonObject::const_iterator begin_;
typename JsonObject::const_iterator end_;
};
class JsonMapValue final : public ParsedMapValueInterface {
public:
explicit JsonMapValue(JsonObject object) : object_(std::move(object)) {}
std::string DebugString() const override {
std::string out;
JsonObjectDebugString(object_, out);
return out;
}
bool IsEmpty() const override { return object_.empty(); }
size_t Size() const override { return object_.size(); }
absl::Status ListKeys(ValueManager& value_manager,
ListValue& result) const override {
JsonArrayBuilder keys;
keys.reserve(object_.size());
for (const auto& entry : object_) {
keys.push_back(entry.first);
}
result = ParsedListValue(
value_manager.GetMemoryManager().MakeShared<JsonListValue>(
std::move(keys).Build()));
return absl::OkStatus();
}
absl::StatusOr<absl::Nonnull<ValueIteratorPtr>> NewIterator(
ValueManager&) const override {
return std::make_unique<JsonMapValueKeyIterator>(object_);
}
absl::StatusOr<JsonObject> ConvertToJsonObject(
AnyToJsonConverter&) const override {
return object_;
}
private:
absl::StatusOr<bool> FindImpl(ValueManager& value_manager, ValueView key,
Value& result) const override {
return Cast<StringValueView>(key).NativeValue(absl::Overload(
[this, &value_manager, &result](absl::string_view value) -> bool {
if (auto entry = object_.find(value); entry != object_.end()) {
JsonToValue(entry->second, value_manager, result);
return true;
}
return false;
},
[this, &value_manager, &result](const absl::Cord& value) -> bool {
if (auto entry = object_.find(value); entry != object_.end()) {
JsonToValue(entry->second, value_manager, result);
return true;
}
return false;
}));
}
absl::StatusOr<bool> HasImpl(ValueManager&, ValueView key) const override {
return Cast<StringValueView>(key).NativeValue(absl::Overload(
[this](absl::string_view value) -> bool {
return object_.contains(value);
},
[this](const absl::Cord& value) -> bool {
return object_.contains(value);
}));
}
Type GetTypeImpl(TypeManager& type_manager) const override {
return MapType(type_manager.GetStringDynMapType());
}
NativeTypeId GetNativeTypeId() const noexcept override {
return NativeTypeId::For<JsonMapValue>();
}
const JsonObject object_;
};
}
Value ValueFactory::CreateValueFromJson(Json json) {
return absl::visit(
absl::Overload(
[](JsonNull) -> Value { return NullValue(); },
[](JsonBool value) -> Value { return BoolValue(value); },
[](JsonNumber value) -> Value { return DoubleValue(value); },
[](const JsonString& value) -> Value { return StringValue(value); },
[this](JsonArray value) -> Value {
return CreateListValueFromJsonArray(std::move(value));
},
[this](JsonObject value) -> Value {
return CreateMapValueFromJsonObject(std::move(value));
}),
std::move(json));
}
ListValue ValueFactory::CreateListValueFromJsonArray(JsonArray json) {
if (json.empty()) {
return ListValue(GetZeroDynListValue());
}
return ParsedListValue(
GetMemoryManager().MakeShared<JsonListValue>(std::move(json)));
}
MapValue ValueFactory::CreateMapValueFromJsonObject(JsonObject json) {
if (json.empty()) {
return MapValue(GetZeroStringDynMapValue());
}
return ParsedMapValue(
GetMemoryManager().MakeShared<JsonMapValue>(std::move(json)));
}
ListValue ValueFactory::CreateZeroListValue(ListTypeView type) {
if (auto list_value = ProcessLocalValueCache::Get()->GetEmptyListValue(type);
list_value.has_value()) {
return ListValue(*list_value);
}
return CreateZeroListValueImpl(type);
}
MapValue ValueFactory::CreateZeroMapValue(MapTypeView type) {
if (auto map_value = ProcessLocalValueCache::Get()->GetEmptyMapValue(type);
map_value.has_value()) {
return MapValue(*map_value);
}
return CreateZeroMapValueImpl(type);
}
OptionalValue ValueFactory::CreateZeroOptionalValue(OptionalTypeView type) {
if (auto optional_value =
ProcessLocalValueCache::Get()->GetEmptyOptionalValue(type);
optional_value.has_value()) {
return OptionalValue(*optional_value);
}
return CreateZeroOptionalValueImpl(type);
}
ListValueView ValueFactory::GetZeroDynListValue() {
return ProcessLocalValueCache::Get()->GetEmptyDynListValue();
}
MapValueView ValueFactory::GetZeroDynDynMapValue() {
return ProcessLocalValueCache::Get()->GetEmptyDynDynMapValue();
}
MapValueView ValueFactory::GetZeroStringDynMapValue() {
return ProcessLocalValueCache::Get()->GetEmptyStringDynMapValue();
}
OptionalValueView ValueFactory::GetZeroDynOptionalValue() {
return ProcessLocalValueCache::Get()->GetEmptyDynOptionalValue();
}
namespace {
class ReferenceCountedString final : public common_internal::ReferenceCounted {
public:
static const ReferenceCountedString* New(std::string&& string) {
return new ReferenceCountedString(std::move(string));
}
const char* data() const {
return std::launder(reinterpret_cast<const std::string*>(&string_[0]))
->data();
}
size_t size() const {
return std::launder(reinterpret_cast<const std::string*>(&string_[0]))
->size();
}
private:
explicit ReferenceCountedString(std::string&& robbed) : ReferenceCounted() {
::new (static_cast<void*>(&string_[0])) std::string(std::move(robbed));
}
void Finalize() noexcept override {
std::launder(reinterpret_cast<const std::string*>(&string_[0]))
->~basic_string();
}
alignas(std::string) char string_[sizeof(std::string)];
};
}
static void StringDestructor(void* string) {
static_cast<std::string*>(string)->~basic_string();
}
absl::StatusOr<BytesValue> ValueFactory::CreateBytesValue(std::string value) {
auto memory_manager = GetMemoryManager();
switch (memory_manager.memory_management()) {
case MemoryManagement::kPooling: {
auto* string = ::new (
memory_manager.Allocate(sizeof(std::string), alignof(std::string)))
std::string(std::move(value));
memory_manager.OwnCustomDestructor(string, &StringDestructor);
return BytesValue{common_internal::ArenaString(*string)};
}
case MemoryManagement::kReferenceCounting: {
auto* refcount = ReferenceCountedString::New(std::move(value));
auto bytes_value = BytesValue{common_internal::SharedByteString(
refcount, absl::string_view(refcount->data(), refcount->size()))};
common_internal::StrongUnref(*refcount);
return bytes_value;
}
}
}
StringValue ValueFactory::CreateUncheckedStringValue(std::string value) {
auto memory_manager = GetMemoryManager();
switch (memory_manager.memory_management()) {
case MemoryManagement::kPooling: {
auto* string = ::new (
memory_manager.Allocate(sizeof(std::string), alignof(std::string)))
std::string(std::move(value));
memory_manager.OwnCustomDestructor(string, &StringDestructor);
return StringValue{common_internal::ArenaString(*string)};
}
case MemoryManagement::kReferenceCounting: {
auto* refcount = ReferenceCountedString::New(std::move(value));
auto string_value = StringValue{common_internal::SharedByteString(
refcount, absl::string_view(refcount->data(), refcount->size()))};
common_internal::StrongUnref(*refcount);
return string_value;
}
}
}
absl::StatusOr<StringValue> ValueFactory::CreateStringValue(std::string value) {
auto [count, ok] = internal::Utf8Validate(value);
if (ABSL_PREDICT_FALSE(!ok)) {
return absl::InvalidArgumentError(
"Illegal byte sequence in UTF-8 encoded string");
}
return CreateUncheckedStringValue(std::move(value));
}
absl::StatusOr<StringValue> ValueFactory::CreateStringValue(absl::Cord value) {
auto [count, ok] = internal::Utf8Validate(value);
if (ABSL_PREDICT_FALSE(!ok)) {
return absl::InvalidArgumentError(
"Illegal byte sequence in UTF-8 encoded string");
}
return StringValue(std::move(value));
}
absl::StatusOr<DurationValue> ValueFactory::CreateDurationValue(
absl::Duration value) {
CEL_RETURN_IF_ERROR(internal::ValidateDuration(value));
return DurationValue{value};
}
absl::StatusOr<TimestampValue> ValueFactory::CreateTimestampValue(
absl::Time value) {
CEL_RETURN_IF_ERROR(internal::ValidateTimestamp(value));
return TimestampValue{value};
}
} | #include "common/value_factory.h"
#include <ostream>
#include <sstream>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#include "absl/strings/cord.h"
#include "absl/types/optional.h"
#include "common/casting.h"
#include "common/json.h"
#include "common/memory.h"
#include "common/memory_testing.h"
#include "common/type.h"
#include "common/type_factory.h"
#include "common/type_reflector.h"
#include "common/types/type_cache.h"
#include "common/value.h"
#include "common/value_manager.h"
#include "internal/testing.h"
namespace cel {
namespace {
using common_internal::ProcessLocalTypeCache;
using testing::TestParamInfo;
using testing::TestWithParam;
using testing::UnorderedElementsAreArray;
using cel::internal::IsOkAndHolds;
enum class ThreadSafety {
kCompatible,
kSafe,
};
std::ostream& operator<<(std::ostream& out, ThreadSafety thread_safety) {
switch (thread_safety) {
case ThreadSafety::kCompatible:
return out << "THREAD_SAFE";
case ThreadSafety::kSafe:
return out << "THREAD_COMPATIBLE";
}
}
class ValueFactoryTest
: public common_internal::ThreadCompatibleMemoryTest<ThreadSafety> {
public:
void SetUp() override {
switch (thread_safety()) {
case ThreadSafety::kCompatible:
value_manager_ = NewThreadCompatibleValueManager(
memory_manager(),
NewThreadCompatibleTypeReflector(memory_manager()));
break;
case ThreadSafety::kSafe:
value_manager_ = NewThreadSafeValueManager(
memory_manager(), NewThreadSafeTypeReflector(memory_manager()));
break;
}
}
void TearDown() override { Finish(); }
void Finish() {
value_manager_.reset();
ThreadCompatibleMemoryTest::Finish();
}
TypeFactory& type_factory() const { return value_manager(); }
TypeManager& type_manager() const { return value_manager(); }
ValueFactory& value_factory() const { return value_manager(); }
ValueManager& value_manager() const { return **value_manager_; }
ThreadSafety thread_safety() const { return std::get<1>(GetParam()); }
static std::string ToString(
TestParamInfo<std::tuple<MemoryManagement, ThreadSafety>> param) {
std::ostringstream out;
out << std::get<0>(param.param) << "_" << std::get<1>(param.param);
return out.str();
}
private:
absl::optional<Shared<ValueManager>> value_manager_;
};
TEST_P(ValueFactoryTest, JsonValueNull) {
auto value = value_factory().CreateValueFromJson(kJsonNull);
EXPECT_TRUE(InstanceOf<NullValue>(value));
}
TEST_P(ValueFactoryTest, JsonValueBool) {
auto value = value_factory().CreateValueFromJson(true);
ASSERT_TRUE(InstanceOf<BoolValue>(value));
EXPECT_TRUE(Cast<BoolValue>(value).NativeValue());
}
TEST_P(ValueFactoryTest, JsonValueNumber) {
auto value = value_factory().CreateValueFromJson(1.0);
ASSERT_TRUE(InstanceOf<DoubleValue>(value));
EXPECT_EQ(Cast<DoubleValue>(value).NativeValue(), 1.0);
}
TEST_P(ValueFactoryTest, JsonValueString) {
auto value = value_factory().CreateValueFromJson(absl::Cord("foo"));
ASSERT_TRUE(InstanceOf<StringValue>(value));
EXPECT_EQ(Cast<StringValue>(value).NativeString(), "foo");
}
JsonObject NewJsonObjectForTesting(bool with_array = true,
bool with_nested_object = true);
JsonArray NewJsonArrayForTesting(bool with_nested_array = true,
bool with_object = true) {
JsonArrayBuilder builder;
builder.push_back(kJsonNull);
builder.push_back(true);
builder.push_back(1.0);
builder.push_back(absl::Cord("foo"));
if (with_nested_array) {
builder.push_back(NewJsonArrayForTesting(false, false));
}
if (with_object) {
builder.push_back(NewJsonObjectForTesting(false, false));
}
return std::move(builder).Build();
}
JsonObject NewJsonObjectForTesting(bool with_array, bool with_nested_object) {
JsonObjectBuilder builder;
builder.insert_or_assign(absl::Cord("a"), kJsonNull);
builder.insert_or_assign(absl::Cord("b"), true);
builder.insert_or_assign(absl::Cord("c"), 1.0);
builder.insert_or_assign(absl::Cord("d"), absl::Cord("foo"));
if (with_array) {
builder.insert_or_assign(absl::Cord("e"),
NewJsonArrayForTesting(false, false));
}
if (with_nested_object) {
builder.insert_or_assign(absl::Cord("f"),
NewJsonObjectForTesting(false, false));
}
return std::move(builder).Build();
}
TEST_P(ValueFactoryTest, JsonValueArray) {
auto value = value_factory().CreateValueFromJson(NewJsonArrayForTesting());
ASSERT_TRUE(InstanceOf<ListValue>(value));
EXPECT_EQ(TypeView(value.GetType(type_manager())),
type_factory().GetDynListType());
auto list_value = Cast<ListValue>(value);
EXPECT_THAT(list_value.IsEmpty(), IsOkAndHolds(false));
EXPECT_THAT(list_value.Size(), IsOkAndHolds(6));
EXPECT_EQ(list_value.DebugString(),
"[null, true, 1.0, \"foo\", [null, true, 1.0, \"foo\"], {\"a\": "
"null, \"b\": true, \"c\": 1.0, \"d\": \"foo\"}]");
ASSERT_OK_AND_ASSIGN(auto element, list_value.Get(value_manager(), 0));
EXPECT_TRUE(InstanceOf<NullValue>(element));
}
TEST_P(ValueFactoryTest, JsonValueObject) {
auto value = value_factory().CreateValueFromJson(NewJsonObjectForTesting());
ASSERT_TRUE(InstanceOf<MapValue>(value));
EXPECT_EQ(TypeView(value.GetType(type_manager())),
type_factory().GetStringDynMapType());
auto map_value = Cast<MapValue>(value);
EXPECT_THAT(map_value.IsEmpty(), IsOkAndHolds(false));
EXPECT_THAT(map_value.Size(), IsOkAndHolds(6));
EXPECT_EQ(map_value.DebugString(),
"{\"a\": null, \"b\": true, \"c\": 1.0, \"d\": \"foo\", \"e\": "
"[null, true, 1.0, \"foo\"], \"f\": {\"a\": null, \"b\": true, "
"\"c\": 1.0, \"d\": \"foo\"}}");
ASSERT_OK_AND_ASSIGN(auto keys, map_value.ListKeys(value_manager()));
EXPECT_THAT(keys.Size(), IsOkAndHolds(6));
ASSERT_OK_AND_ASSIGN(auto keys_iterator,
map_value.NewIterator(value_manager()));
std::vector<StringValue> string_keys;
while (keys_iterator->HasNext()) {
ASSERT_OK_AND_ASSIGN(auto key, keys_iterator->Next(value_manager()));
string_keys.push_back(StringValue(Cast<StringValue>(key)));
}
EXPECT_THAT(string_keys, UnorderedElementsAreArray(
{StringValueView("a"), StringValueView("b"),
StringValueView("c"), StringValueView("d"),
StringValueView("e"), StringValueView("f")}));
ASSERT_OK_AND_ASSIGN(auto has,
map_value.Has(value_manager(), StringValueView("a")));
ASSERT_TRUE(InstanceOf<BoolValue>(has));
EXPECT_TRUE(Cast<BoolValue>(has).NativeValue());
ASSERT_OK_AND_ASSIGN(
has, map_value.Has(value_manager(), StringValueView(absl::Cord("a"))));
ASSERT_TRUE(InstanceOf<BoolValue>(has));
EXPECT_TRUE(Cast<BoolValue>(has).NativeValue());
ASSERT_OK_AND_ASSIGN(auto get,
map_value.Get(value_manager(), StringValueView("a")));
ASSERT_TRUE(InstanceOf<NullValue>(get));
ASSERT_OK_AND_ASSIGN(
get, map_value.Get(value_manager(), StringValueView(absl::Cord("a"))));
ASSERT_TRUE(InstanceOf<NullValue>(get));
}
TEST_P(ValueFactoryTest, ListValue) {
auto list_value1 = value_factory().CreateZeroListValue(
type_factory().CreateListType(StringTypeView()));
EXPECT_TRUE(
Is(list_value1, value_factory().CreateZeroListValue(
type_factory().CreateListType(StringTypeView()))));
EXPECT_FALSE(
Is(list_value1, value_factory().CreateZeroListValue(
type_factory().CreateListType(BoolTypeView()))));
auto struct_type1 = type_factory().CreateStructType("test.Struct1");
auto struct_type2 = type_factory().CreateStructType("test.Struct2");
auto list_value2 = value_factory().CreateZeroListValue(
type_factory().CreateListType(struct_type1));
EXPECT_TRUE(
Is(list_value2, value_factory().CreateZeroListValue(
type_factory().CreateListType(struct_type1))));
EXPECT_FALSE(
Is(list_value2, value_factory().CreateZeroListValue(
type_factory().CreateListType(struct_type2))));
auto zero_list_value = value_factory().GetZeroDynListValue();
EXPECT_THAT(zero_list_value.IsEmpty(), IsOkAndHolds(true));
EXPECT_THAT(zero_list_value.Size(), IsOkAndHolds(0));
EXPECT_EQ(zero_list_value.GetType(type_manager()),
ProcessLocalTypeCache::Get()->GetDynListType());
}
TEST_P(ValueFactoryTest, MapValue) {
auto map_value1 = value_factory().CreateZeroMapValue(
type_factory().CreateMapType(StringTypeView(), IntTypeView()));
EXPECT_TRUE(Is(map_value1, value_factory().CreateZeroMapValue(
type_factory().CreateMapType(StringTypeView(),
IntTypeView()))));
EXPECT_FALSE(Is(map_value1, value_factory().CreateZeroMapValue(
type_factory().CreateMapType(
StringTypeView(), BoolTypeView()))));
auto struct_type1 = type_factory().CreateStructType("test.Struct1");
auto struct_type2 = type_factory().CreateStructType("test.Struct2");
auto map_value2 = value_factory().CreateZeroMapValue(
type_factory().CreateMapType(StringTypeView(), struct_type1));
EXPECT_TRUE(Is(map_value2, value_factory().CreateZeroMapValue(
type_factory().CreateMapType(StringTypeView(),
struct_type1))));
EXPECT_FALSE(Is(map_value2, value_factory().CreateZeroMapValue(
type_factory().CreateMapType(StringTypeView(),
struct_type2))));
auto zero_map_value = value_factory().GetZeroDynDynMapValue();
EXPECT_THAT(zero_map_value.IsEmpty(), IsOkAndHolds(true));
EXPECT_THAT(zero_map_value.Size(), IsOkAndHolds(0));
EXPECT_EQ(zero_map_value.GetType(type_manager()),
ProcessLocalTypeCache::Get()->GetDynDynMapType());
zero_map_value = value_factory().GetZeroStringDynMapValue();
EXPECT_THAT(zero_map_value.IsEmpty(), IsOkAndHolds(true));
EXPECT_THAT(zero_map_value.Size(), IsOkAndHolds(0));
EXPECT_EQ(zero_map_value.GetType(type_manager()),
ProcessLocalTypeCache::Get()->GetStringDynMapType());
}
TEST_P(ValueFactoryTest, OptionalType) {
auto optional_value1 = value_factory().CreateZeroOptionalValue(
type_factory().CreateOptionalType(StringTypeView()));
EXPECT_TRUE(Is(optional_value1,
value_factory().CreateZeroOptionalValue(
type_factory().CreateOptionalType(StringTypeView()))));
EXPECT_FALSE(Is(optional_value1,
value_factory().CreateZeroOptionalValue(
type_factory().CreateOptionalType(BoolTypeView()))));
auto struct_type1 = type_factory().CreateStructType("test.Struct1");
auto struct_type2 = type_factory().CreateStructType("test.Struct2");
auto optional_value2 = value_factory().CreateZeroOptionalValue(
type_factory().CreateOptionalType(struct_type1));
EXPECT_TRUE(Is(optional_value2,
value_factory().CreateZeroOptionalValue(
type_factory().CreateOptionalType(struct_type1))));
EXPECT_FALSE(Is(optional_value2,
value_factory().CreateZeroOptionalValue(
type_factory().CreateOptionalType(struct_type2))));
auto zero_optional_value = value_factory().GetZeroDynOptionalValue();
EXPECT_FALSE(zero_optional_value.HasValue());
EXPECT_EQ(zero_optional_value.GetType(type_manager()),
ProcessLocalTypeCache::Get()->GetDynOptionalType());
}
INSTANTIATE_TEST_SUITE_P(
ValueFactoryTest, ValueFactoryTest,
::testing::Combine(::testing::Values(MemoryManagement::kPooling,
MemoryManagement::kReferenceCounting),
::testing::Values(ThreadSafety::kCompatible,
ThreadSafety::kSafe)),
ValueFactoryTest::ToString);
}
} |
2 | cpp | google/cel-cpp | value_testing | common/value_testing.cc | extensions/protobuf/value_testing_test.cc | #ifndef THIRD_PARTY_CEL_CPP_EXTENSIONS_PROTOBUF_VALUE_TESTING_H_
#define THIRD_PARTY_CEL_CPP_EXTENSIONS_PROTOBUF_VALUE_TESTING_H_
#include <ostream>
#include "absl/status/status.h"
#include "common/value.h"
#include "extensions/protobuf/internal/message.h"
#include "extensions/protobuf/value.h"
#include "internal/testing.h"
namespace cel::extensions::test {
template <typename MessageType>
class StructValueAsProtoMatcher {
public:
using is_gtest_matcher = void;
explicit StructValueAsProtoMatcher(testing::Matcher<MessageType>&& m)
: m_(std::move(m)) {}
bool MatchAndExplain(cel::Value v,
testing::MatchResultListener* result_listener) const {
MessageType msg;
absl::Status s = ProtoMessageFromValue(v, msg);
if (!s.ok()) {
*result_listener << "cannot convert to "
<< MessageType::descriptor()->full_name() << ": " << s;
return false;
}
return m_.MatchAndExplain(msg, result_listener);
}
void DescribeTo(std::ostream* os) const {
*os << "matches proto message " << m_;
}
void DescribeNegationTo(std::ostream* os) const {
*os << "does not match proto message " << m_;
}
private:
testing::Matcher<MessageType> m_;
};
template <typename MessageType>
inline StructValueAsProtoMatcher<MessageType> StructValueAsProto(
testing::Matcher<MessageType>&& m) {
static_assert(
cel::extensions::protobuf_internal::IsProtoMessage<MessageType>);
return StructValueAsProtoMatcher<MessageType>(std::move(m));
}
}
#endif
#include "common/value_testing.h"
#include <cstdint>
#include <ostream>
#include <string>
#include <utility>
#include "gtest/gtest.h"
#include "absl/status/status.h"
#include "absl/time/time.h"
#include "common/casting.h"
#include "common/value.h"
#include "common/value_kind.h"
#include "internal/testing.h"
namespace cel {
void PrintTo(const Value& value, std::ostream* os) { *os << value << "\n"; }
namespace test {
namespace {
using testing::Matcher;
template <typename Type>
constexpr ValueKind ToValueKind() {
if constexpr (std::is_same_v<Type, BoolValue>) {
return ValueKind::kBool;
} else if constexpr (std::is_same_v<Type, IntValue>) {
return ValueKind::kInt;
} else if constexpr (std::is_same_v<Type, UintValue>) {
return ValueKind::kUint;
} else if constexpr (std::is_same_v<Type, DoubleValue>) {
return ValueKind::kDouble;
} else if constexpr (std::is_same_v<Type, StringValue>) {
return ValueKind::kString;
} else if constexpr (std::is_same_v<Type, BytesValue>) {
return ValueKind::kBytes;
} else if constexpr (std::is_same_v<Type, DurationValue>) {
return ValueKind::kDuration;
} else if constexpr (std::is_same_v<Type, TimestampValue>) {
return ValueKind::kTimestamp;
} else if constexpr (std::is_same_v<Type, ErrorValue>) {
return ValueKind::kError;
} else if constexpr (std::is_same_v<Type, MapValue>) {
return ValueKind::kMap;
} else if constexpr (std::is_same_v<Type, ListValue>) {
return ValueKind::kList;
} else if constexpr (std::is_same_v<Type, StructValue>) {
return ValueKind::kStruct;
} else if constexpr (std::is_same_v<Type, OpaqueValue>) {
return ValueKind::kOpaque;
} else {
return ValueKind::kError;
}
}
template <typename Type, typename NativeType>
class SimpleTypeMatcherImpl : public testing::MatcherInterface<const Value&> {
public:
using MatcherType = Matcher<NativeType>;
explicit SimpleTypeMatcherImpl(MatcherType&& matcher)
: matcher_(std::forward<MatcherType>(matcher)) {}
bool MatchAndExplain(const Value& v,
testing::MatchResultListener* listener) const override {
return InstanceOf<Type>(v) &&
matcher_.MatchAndExplain(Cast<Type>(v).NativeValue(), listener);
}
void DescribeTo(std::ostream* os) const override {
*os << absl::StrCat("kind is ", ValueKindToString(ToValueKind<Type>()),
" and ");
matcher_.DescribeTo(os);
}
private:
MatcherType matcher_;
};
template <typename Type>
class StringTypeMatcherImpl : public testing::MatcherInterface<const Value&> {
public:
using MatcherType = Matcher<std::string>;
explicit StringTypeMatcherImpl(MatcherType matcher)
: matcher_((std::move(matcher))) {}
bool MatchAndExplain(const Value& v,
testing::MatchResultListener* listener) const override {
return InstanceOf<Type>(v) && matcher_.Matches(Cast<Type>(v).ToString());
}
void DescribeTo(std::ostream* os) const override {
*os << absl::StrCat("kind is ", ValueKindToString(ToValueKind<Type>()),
" and ");
matcher_.DescribeTo(os);
}
private:
MatcherType matcher_;
};
template <typename Type>
class AbstractTypeMatcherImpl : public testing::MatcherInterface<const Value&> {
public:
using MatcherType = Matcher<Type>;
explicit AbstractTypeMatcherImpl(MatcherType&& matcher)
: matcher_(std::forward<MatcherType>(matcher)) {}
bool MatchAndExplain(const Value& v,
testing::MatchResultListener* listener) const override {
return InstanceOf<Type>(v) && matcher_.Matches(Cast<Type>(v));
}
void DescribeTo(std::ostream* os) const override {
*os << absl::StrCat("kind is ", ValueKindToString(ToValueKind<Type>()),
" and ");
matcher_.DescribeTo(os);
}
private:
MatcherType matcher_;
};
class OptionalValueMatcherImpl
: public testing::MatcherInterface<const Value&> {
public:
explicit OptionalValueMatcherImpl(ValueMatcher matcher)
: matcher_(std::move(matcher)) {}
bool MatchAndExplain(const Value& v,
testing::MatchResultListener* listener) const override {
if (!InstanceOf<OptionalValue>(v)) {
*listener << "wanted OptionalValue, got " << ValueKindToString(v.kind());
return false;
}
const auto& optional_value = Cast<OptionalValue>(v);
if (!optional_value->HasValue()) {
*listener << "OptionalValue is not engaged";
return false;
}
return matcher_.MatchAndExplain(optional_value->Value(), listener);
}
void DescribeTo(std::ostream* os) const override {
*os << "is OptionalValue that is engaged with value whose ";
matcher_.DescribeTo(os);
}
private:
ValueMatcher matcher_;
};
MATCHER(OptionalValueIsEmptyImpl, "is empty OptionalValue") {
const Value& v = arg;
if (!InstanceOf<OptionalValue>(v)) {
*result_listener << "wanted OptionalValue, got "
<< ValueKindToString(v.kind());
return false;
}
const auto& optional_value = Cast<OptionalValue>(v);
*result_listener << (optional_value.HasValue() ? "is not empty" : "is empty");
return !optional_value->HasValue();
}
}
ValueMatcher BoolValueIs(Matcher<bool> m) {
return ValueMatcher(new SimpleTypeMatcherImpl<BoolValue, bool>(std::move(m)));
}
ValueMatcher IntValueIs(Matcher<int64_t> m) {
return ValueMatcher(
new SimpleTypeMatcherImpl<IntValue, int64_t>(std::move(m)));
}
ValueMatcher UintValueIs(Matcher<uint64_t> m) {
return ValueMatcher(
new SimpleTypeMatcherImpl<UintValue, uint64_t>(std::move(m)));
}
ValueMatcher DoubleValueIs(Matcher<double> m) {
return ValueMatcher(
new SimpleTypeMatcherImpl<DoubleValue, double>(std::move(m)));
}
ValueMatcher TimestampValueIs(Matcher<absl::Time> m) {
return ValueMatcher(
new SimpleTypeMatcherImpl<TimestampValue, absl::Time>(std::move(m)));
}
ValueMatcher DurationValueIs(Matcher<absl::Duration> m) {
return ValueMatcher(
new SimpleTypeMatcherImpl<DurationValue, absl::Duration>(std::move(m)));
}
ValueMatcher ErrorValueIs(Matcher<absl::Status> m) {
return ValueMatcher(
new SimpleTypeMatcherImpl<ErrorValue, absl::Status>(std::move(m)));
}
ValueMatcher StringValueIs(Matcher<std::string> m) {
return ValueMatcher(new StringTypeMatcherImpl<StringValue>(std::move(m)));
}
ValueMatcher BytesValueIs(Matcher<std::string> m) {
return ValueMatcher(new StringTypeMatcherImpl<BytesValue>(std::move(m)));
}
ValueMatcher MapValueIs(Matcher<MapValue> m) {
return ValueMatcher(new AbstractTypeMatcherImpl<MapValue>(std::move(m)));
}
ValueMatcher ListValueIs(Matcher<ListValue> m) {
return ValueMatcher(new AbstractTypeMatcherImpl<ListValue>(std::move(m)));
}
ValueMatcher StructValueIs(Matcher<StructValue> m) {
return ValueMatcher(new AbstractTypeMatcherImpl<StructValue>(std::move(m)));
}
ValueMatcher OptionalValueIs(ValueMatcher m) {
return ValueMatcher(new OptionalValueMatcherImpl(std::move(m)));
}
ValueMatcher OptionalValueIsEmpty() { return OptionalValueIsEmptyImpl(); }
}
} | #include "extensions/protobuf/value_testing.h"
#include "common/memory.h"
#include "common/value.h"
#include "common/value_testing.h"
#include "extensions/protobuf/memory_manager.h"
#include "extensions/protobuf/value.h"
#include "internal/proto_matchers.h"
#include "internal/testing.h"
#include "proto/test/v1/proto2/test_all_types.pb.h"
#include "google/protobuf/arena.h"
namespace cel::extensions::test {
namespace {
using ::cel::extensions::ProtoMessageToValue;
using ::cel::internal::test::EqualsProto;
using ::google::api::expr::test::v1::proto2::TestAllTypes;
class ProtoValueTesting : public common_internal::ThreadCompatibleValueTest<> {
protected:
MemoryManager NewThreadCompatiblePoolingMemoryManager() override {
return cel::extensions::ProtoMemoryManager(&arena_);
}
private:
google::protobuf::Arena arena_;
};
class ProtoValueTestingTest : public ProtoValueTesting {};
TEST_P(ProtoValueTestingTest, StructValueAsProtoSimple) {
TestAllTypes test_proto;
test_proto.set_single_int32(42);
test_proto.set_single_string("foo");
ASSERT_OK_AND_ASSIGN(cel::Value v,
ProtoMessageToValue(value_manager(), test_proto));
EXPECT_THAT(v, StructValueAsProto<TestAllTypes>(EqualsProto(R"pb(
single_int32: 42
single_string: "foo"
)pb")));
}
INSTANTIATE_TEST_SUITE_P(ProtoValueTesting, ProtoValueTestingTest,
testing::Values(MemoryManagement::kPooling,
MemoryManagement::kReferenceCounting),
ProtoValueTestingTest::ToString);
}
} |
3 | cpp | google/cel-cpp | type_introspector | extensions/protobuf/type_introspector.cc | extensions/protobuf/type_introspector_test.cc | #ifndef THIRD_PARTY_CEL_CPP_EXTENSIONS_PROTOBUF_TYPE_INTROSPECTOR_H_
#define THIRD_PARTY_CEL_CPP_EXTENSIONS_PROTOBUF_TYPE_INTROSPECTOR_H_
#include "absl/base/nullability.h"
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "common/type.h"
#include "common/type_factory.h"
#include "common/type_introspector.h"
#include "google/protobuf/descriptor.h"
namespace cel::extensions {
class ProtoTypeIntrospector : public virtual TypeIntrospector {
public:
ProtoTypeIntrospector()
: ProtoTypeIntrospector(google::protobuf::DescriptorPool::generated_pool()) {}
explicit ProtoTypeIntrospector(
absl::Nonnull<const google::protobuf::DescriptorPool*> descriptor_pool)
: descriptor_pool_(descriptor_pool) {}
absl::Nonnull<const google::protobuf::DescriptorPool*> descriptor_pool() const {
return descriptor_pool_;
}
protected:
absl::StatusOr<absl::optional<TypeView>> FindTypeImpl(
TypeFactory& type_factory, absl::string_view name,
Type& scratch) const final;
absl::StatusOr<absl::optional<StructTypeFieldView>>
FindStructTypeFieldByNameImpl(TypeFactory& type_factory,
absl::string_view type, absl::string_view name,
StructTypeField& scratch) const final;
private:
absl::Nonnull<const google::protobuf::DescriptorPool*> const descriptor_pool_;
};
}
#endif
#include "extensions/protobuf/type_introspector.h"
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "common/type.h"
#include "common/type_factory.h"
#include "common/type_introspector.h"
#include "extensions/protobuf/type.h"
#include "internal/status_macros.h"
namespace cel::extensions {
absl::StatusOr<absl::optional<TypeView>> ProtoTypeIntrospector::FindTypeImpl(
TypeFactory& type_factory, absl::string_view name, Type& scratch) const {
const auto* desc = descriptor_pool()->FindMessageTypeByName(name);
if (desc == nullptr) {
return absl::nullopt;
}
scratch = type_factory.CreateStructType(desc->full_name());
return scratch;
}
absl::StatusOr<absl::optional<StructTypeFieldView>>
ProtoTypeIntrospector::FindStructTypeFieldByNameImpl(
TypeFactory& type_factory, absl::string_view type, absl::string_view name,
StructTypeField& scratch) const {
const auto* desc = descriptor_pool()->FindMessageTypeByName(type);
if (desc == nullptr) {
return absl::nullopt;
}
const auto* field_desc = desc->FindFieldByName(name);
if (field_desc == nullptr) {
field_desc = descriptor_pool()->FindExtensionByPrintableName(desc, name);
if (field_desc == nullptr) {
return absl::nullopt;
}
}
StructTypeFieldView result;
CEL_ASSIGN_OR_RETURN(
result.type,
ProtoFieldTypeToType(type_factory, field_desc, scratch.type));
result.name = field_desc->name();
result.number = field_desc->number();
return result;
}
} | #include "extensions/protobuf/type_introspector.h"
#include "absl/types/optional.h"
#include "common/type.h"
#include "common/type_testing.h"
#include "internal/testing.h"
#include "proto/test/v1/proto2/test_all_types.pb.h"
#include "google/protobuf/descriptor.h"
namespace cel::extensions {
namespace {
using ::google::api::expr::test::v1::proto2::TestAllTypes;
using testing::Eq;
using testing::Optional;
using cel::internal::IsOkAndHolds;
class ProtoTypeIntrospectorTest
: public common_internal::ThreadCompatibleTypeTest<> {
private:
Shared<TypeIntrospector> NewTypeIntrospector(
MemoryManagerRef memory_manager) override {
return memory_manager.MakeShared<ProtoTypeIntrospector>();
}
};
TEST_P(ProtoTypeIntrospectorTest, FindType) {
EXPECT_THAT(
type_manager().FindType(TestAllTypes::descriptor()->full_name()),
IsOkAndHolds(Optional(Eq(StructType(
memory_manager(), TestAllTypes::GetDescriptor()->full_name())))));
EXPECT_THAT(type_manager().FindType("type.that.does.not.Exist"),
IsOkAndHolds(Eq(absl::nullopt)));
}
TEST_P(ProtoTypeIntrospectorTest, FindStructTypeFieldByName) {
ASSERT_OK_AND_ASSIGN(
auto field, type_manager().FindStructTypeFieldByName(
TestAllTypes::descriptor()->full_name(), "single_int32"));
ASSERT_TRUE(field.has_value());
EXPECT_THAT(field->name, Eq("single_int32"));
EXPECT_THAT(field->number, Eq(1));
EXPECT_THAT(field->type, Eq(IntType{}));
EXPECT_THAT(
type_manager().FindStructTypeFieldByName(
TestAllTypes::descriptor()->full_name(), "field_that_does_not_exist"),
IsOkAndHolds(Eq(absl::nullopt)));
EXPECT_THAT(type_manager().FindStructTypeFieldByName(
"type.that.does.not.Exist", "does_not_matter"),
IsOkAndHolds(Eq(absl::nullopt)));
}
INSTANTIATE_TEST_SUITE_P(
ProtoTypeIntrospectorTest, ProtoTypeIntrospectorTest,
::testing::Values(MemoryManagement::kPooling,
MemoryManagement::kReferenceCounting),
ProtoTypeIntrospectorTest::ToString);
}
} |
4 | cpp | google/cel-cpp | constant | extensions/protobuf/internal/constant.cc | common/constant_test.cc | #ifndef THIRD_PARTY_CEL_CPP_EXTENSIONS_PROTOBUF_INTERNAL_CONSTANT_H_
#define THIRD_PARTY_CEL_CPP_EXTENSIONS_PROTOBUF_INTERNAL_CONSTANT_H_
#include "google/api/expr/v1alpha1/syntax.pb.h"
#include "absl/base/nullability.h"
#include "absl/status/status.h"
#include "common/constant.h"
namespace cel::extensions::protobuf_internal {
absl::Status ConstantToProto(const Constant& constant,
absl::Nonnull<google::api::expr::v1alpha1::Constant*> proto);
absl::Status ConstantFromProto(const google::api::expr::v1alpha1::Constant& proto,
Constant& constant);
}
#endif
#include "extensions/protobuf/internal/constant.h"
#include <cstddef>
#include <cstdint>
#include "google/api/expr/v1alpha1/syntax.pb.h"
#include "google/protobuf/struct.pb.h"
#include "absl/base/nullability.h"
#include "absl/functional/overload.h"
#include "absl/status/status.h"
#include "absl/strings/str_cat.h"
#include "absl/time/time.h"
#include "absl/types/variant.h"
#include "common/constant.h"
#include "internal/proto_time_encoding.h"
namespace cel::extensions::protobuf_internal {
using ConstantProto = google::api::expr::v1alpha1::Constant;
absl::Status ConstantToProto(const Constant& constant,
absl::Nonnull<ConstantProto*> proto) {
return absl::visit(absl::Overload(
[proto](absl::monostate) -> absl::Status {
proto->clear_constant_kind();
return absl::OkStatus();
},
[proto](std::nullptr_t) -> absl::Status {
proto->set_null_value(google::protobuf::NULL_VALUE);
return absl::OkStatus();
},
[proto](bool value) -> absl::Status {
proto->set_bool_value(value);
return absl::OkStatus();
},
[proto](int64_t value) -> absl::Status {
proto->set_int64_value(value);
return absl::OkStatus();
},
[proto](uint64_t value) -> absl::Status {
proto->set_uint64_value(value);
return absl::OkStatus();
},
[proto](double value) -> absl::Status {
proto->set_double_value(value);
return absl::OkStatus();
},
[proto](const BytesConstant& value) -> absl::Status {
proto->set_bytes_value(value);
return absl::OkStatus();
},
[proto](const StringConstant& value) -> absl::Status {
proto->set_string_value(value);
return absl::OkStatus();
},
[proto](absl::Duration value) -> absl::Status {
return internal::EncodeDuration(
value, proto->mutable_duration_value());
},
[proto](absl::Time value) -> absl::Status {
return internal::EncodeTime(
value, proto->mutable_timestamp_value());
}),
constant.kind());
}
absl::Status ConstantFromProto(const ConstantProto& proto, Constant& constant) {
switch (proto.constant_kind_case()) {
case ConstantProto::CONSTANT_KIND_NOT_SET:
constant = Constant{};
break;
case ConstantProto::kNullValue:
constant.set_null_value();
break;
case ConstantProto::kBoolValue:
constant.set_bool_value(proto.bool_value());
break;
case ConstantProto::kInt64Value:
constant.set_int_value(proto.int64_value());
break;
case ConstantProto::kUint64Value:
constant.set_uint_value(proto.uint64_value());
break;
case ConstantProto::kDoubleValue:
constant.set_double_value(proto.double_value());
break;
case ConstantProto::kStringValue:
constant.set_string_value(proto.string_value());
break;
case ConstantProto::kBytesValue:
constant.set_bytes_value(proto.bytes_value());
break;
case ConstantProto::kDurationValue:
constant.set_duration_value(
internal::DecodeDuration(proto.duration_value()));
break;
case ConstantProto::kTimestampValue:
constant.set_timestamp_value(
internal::DecodeTime(proto.timestamp_value()));
break;
default:
return absl::InvalidArgumentError(
absl::StrCat("unexpected ConstantKindCase: ",
static_cast<int>(proto.constant_kind_case())));
}
return absl::OkStatus();
}
} | #include "common/constant.h"
#include <cmath>
#include <string>
#include "absl/strings/has_absl_stringify.h"
#include "absl/strings/str_format.h"
#include "absl/time/time.h"
#include "internal/testing.h"
namespace cel {
namespace {
using testing::IsEmpty;
using testing::IsFalse;
using testing::IsTrue;
TEST(Constant, NullValue) {
Constant const_expr;
EXPECT_THAT(const_expr.has_null_value(), IsFalse());
const_expr.set_null_value();
EXPECT_THAT(const_expr.has_null_value(), IsTrue());
}
TEST(Constant, BoolValue) {
Constant const_expr;
EXPECT_THAT(const_expr.has_bool_value(), IsFalse());
EXPECT_EQ(const_expr.bool_value(), false);
const_expr.set_bool_value(false);
EXPECT_THAT(const_expr.has_bool_value(), IsTrue());
EXPECT_EQ(const_expr.bool_value(), false);
}
TEST(Constant, IntValue) {
Constant const_expr;
EXPECT_THAT(const_expr.has_int_value(), IsFalse());
EXPECT_EQ(const_expr.int_value(), 0);
const_expr.set_int_value(0);
EXPECT_THAT(const_expr.has_int_value(), IsTrue());
EXPECT_EQ(const_expr.int_value(), 0);
}
TEST(Constant, UintValue) {
Constant const_expr;
EXPECT_THAT(const_expr.has_uint_value(), IsFalse());
EXPECT_EQ(const_expr.uint_value(), 0);
const_expr.set_uint_value(0);
EXPECT_THAT(const_expr.has_uint_value(), IsTrue());
EXPECT_EQ(const_expr.uint_value(), 0);
}
TEST(Constant, DoubleValue) {
Constant const_expr;
EXPECT_THAT(const_expr.has_double_value(), IsFalse());
EXPECT_EQ(const_expr.double_value(), 0);
const_expr.set_double_value(0);
EXPECT_THAT(const_expr.has_double_value(), IsTrue());
EXPECT_EQ(const_expr.double_value(), 0);
}
TEST(Constant, BytesValue) {
Constant const_expr;
EXPECT_THAT(const_expr.has_bytes_value(), IsFalse());
EXPECT_THAT(const_expr.bytes_value(), IsEmpty());
const_expr.set_bytes_value("foo");
EXPECT_THAT(const_expr.has_bytes_value(), IsTrue());
EXPECT_EQ(const_expr.bytes_value(), "foo");
}
TEST(Constant, StringValue) {
Constant const_expr;
EXPECT_THAT(const_expr.has_string_value(), IsFalse());
EXPECT_THAT(const_expr.string_value(), IsEmpty());
const_expr.set_string_value("foo");
EXPECT_THAT(const_expr.has_string_value(), IsTrue());
EXPECT_EQ(const_expr.string_value(), "foo");
}
TEST(Constant, DurationValue) {
Constant const_expr;
EXPECT_THAT(const_expr.has_duration_value(), IsFalse());
EXPECT_EQ(const_expr.duration_value(), absl::ZeroDuration());
const_expr.set_duration_value(absl::ZeroDuration());
EXPECT_THAT(const_expr.has_duration_value(), IsTrue());
EXPECT_EQ(const_expr.duration_value(), absl::ZeroDuration());
}
TEST(Constant, TimestampValue) {
Constant const_expr;
EXPECT_THAT(const_expr.has_timestamp_value(), IsFalse());
EXPECT_EQ(const_expr.timestamp_value(), absl::UnixEpoch());
const_expr.set_timestamp_value(absl::UnixEpoch());
EXPECT_THAT(const_expr.has_timestamp_value(), IsTrue());
EXPECT_EQ(const_expr.timestamp_value(), absl::UnixEpoch());
}
TEST(Constant, Equality) {
EXPECT_EQ(Constant{}, Constant{});
Constant lhs_const_expr;
Constant rhs_const_expr;
lhs_const_expr.set_null_value();
rhs_const_expr.set_null_value();
EXPECT_EQ(lhs_const_expr, rhs_const_expr);
EXPECT_EQ(rhs_const_expr, lhs_const_expr);
EXPECT_NE(lhs_const_expr, Constant{});
EXPECT_NE(Constant{}, rhs_const_expr);
lhs_const_expr.set_bool_value(false);
rhs_const_expr.set_null_value();
EXPECT_NE(lhs_const_expr, rhs_const_expr);
EXPECT_NE(rhs_const_expr, lhs_const_expr);
EXPECT_NE(lhs_const_expr, Constant{});
EXPECT_NE(Constant{}, rhs_const_expr);
rhs_const_expr.set_bool_value(false);
EXPECT_EQ(lhs_const_expr, rhs_const_expr);
EXPECT_EQ(rhs_const_expr, lhs_const_expr);
EXPECT_NE(lhs_const_expr, Constant{});
EXPECT_NE(Constant{}, rhs_const_expr);
lhs_const_expr.set_int_value(0);
rhs_const_expr.set_null_value();
EXPECT_NE(lhs_const_expr, rhs_const_expr);
EXPECT_NE(rhs_const_expr, lhs_const_expr);
EXPECT_NE(lhs_const_expr, Constant{});
EXPECT_NE(Constant{}, rhs_const_expr);
rhs_const_expr.set_int_value(0);
EXPECT_EQ(lhs_const_expr, rhs_const_expr);
EXPECT_EQ(rhs_const_expr, lhs_const_expr);
EXPECT_NE(lhs_const_expr, Constant{});
EXPECT_NE(Constant{}, rhs_const_expr);
lhs_const_expr.set_uint_value(0);
rhs_const_expr.set_null_value();
EXPECT_NE(lhs_const_expr, rhs_const_expr);
EXPECT_NE(rhs_const_expr, lhs_const_expr);
EXPECT_NE(lhs_const_expr, Constant{});
EXPECT_NE(Constant{}, rhs_const_expr);
rhs_const_expr.set_uint_value(0);
EXPECT_EQ(lhs_const_expr, rhs_const_expr);
EXPECT_EQ(rhs_const_expr, lhs_const_expr);
EXPECT_NE(lhs_const_expr, Constant{});
EXPECT_NE(Constant{}, rhs_const_expr);
lhs_const_expr.set_double_value(0);
rhs_const_expr.set_null_value();
EXPECT_NE(lhs_const_expr, rhs_const_expr);
EXPECT_NE(rhs_const_expr, lhs_const_expr);
EXPECT_NE(lhs_const_expr, Constant{});
EXPECT_NE(Constant{}, rhs_const_expr);
rhs_const_expr.set_double_value(0);
EXPECT_EQ(lhs_const_expr, rhs_const_expr);
EXPECT_EQ(rhs_const_expr, lhs_const_expr);
EXPECT_NE(lhs_const_expr, Constant{});
EXPECT_NE(Constant{}, rhs_const_expr);
lhs_const_expr.set_bytes_value("foo");
rhs_const_expr.set_null_value();
EXPECT_NE(lhs_const_expr, rhs_const_expr);
EXPECT_NE(rhs_const_expr, lhs_const_expr);
EXPECT_NE(lhs_const_expr, Constant{});
EXPECT_NE(Constant{}, rhs_const_expr);
rhs_const_expr.set_bytes_value("foo");
EXPECT_EQ(lhs_const_expr, rhs_const_expr);
EXPECT_EQ(rhs_const_expr, lhs_const_expr);
EXPECT_NE(lhs_const_expr, Constant{});
EXPECT_NE(Constant{}, rhs_const_expr);
lhs_const_expr.set_string_value("foo");
rhs_const_expr.set_null_value();
EXPECT_NE(lhs_const_expr, rhs_const_expr);
EXPECT_NE(rhs_const_expr, lhs_const_expr);
EXPECT_NE(lhs_const_expr, Constant{});
EXPECT_NE(Constant{}, rhs_const_expr);
rhs_const_expr.set_string_value("foo");
EXPECT_EQ(lhs_const_expr, rhs_const_expr);
EXPECT_EQ(rhs_const_expr, lhs_const_expr);
EXPECT_NE(lhs_const_expr, Constant{});
EXPECT_NE(Constant{}, rhs_const_expr);
lhs_const_expr.set_duration_value(absl::ZeroDuration());
rhs_const_expr.set_null_value();
EXPECT_NE(lhs_const_expr, rhs_const_expr);
EXPECT_NE(rhs_const_expr, lhs_const_expr);
EXPECT_NE(lhs_const_expr, Constant{});
EXPECT_NE(Constant{}, rhs_const_expr);
rhs_const_expr.set_duration_value(absl::ZeroDuration());
EXPECT_EQ(lhs_const_expr, rhs_const_expr);
EXPECT_EQ(rhs_const_expr, lhs_const_expr);
EXPECT_NE(lhs_const_expr, Constant{});
EXPECT_NE(Constant{}, rhs_const_expr);
lhs_const_expr.set_timestamp_value(absl::UnixEpoch());
rhs_const_expr.set_null_value();
EXPECT_NE(lhs_const_expr, rhs_const_expr);
EXPECT_NE(rhs_const_expr, lhs_const_expr);
EXPECT_NE(lhs_const_expr, Constant{});
EXPECT_NE(Constant{}, rhs_const_expr);
rhs_const_expr.set_timestamp_value(absl::UnixEpoch());
EXPECT_EQ(lhs_const_expr, rhs_const_expr);
EXPECT_EQ(rhs_const_expr, lhs_const_expr);
EXPECT_NE(lhs_const_expr, Constant{});
EXPECT_NE(Constant{}, rhs_const_expr);
}
std::string Stringify(const Constant& constant) {
return absl::StrFormat("%v", constant);
}
TEST(Constant, HasAbslStringify) {
EXPECT_TRUE(absl::HasAbslStringify<Constant>::value);
}
TEST(Constant, AbslStringify) {
Constant constant;
EXPECT_EQ(Stringify(constant), "<unspecified>");
constant.set_null_value();
EXPECT_EQ(Stringify(constant), "null");
constant.set_bool_value(true);
EXPECT_EQ(Stringify(constant), "true");
constant.set_int_value(1);
EXPECT_EQ(Stringify(constant), "1");
constant.set_uint_value(1);
EXPECT_EQ(Stringify(constant), "1u");
constant.set_double_value(1);
EXPECT_EQ(Stringify(constant), "1.0");
constant.set_double_value(1.1);
EXPECT_EQ(Stringify(constant), "1.1");
constant.set_double_value(NAN);
EXPECT_EQ(Stringify(constant), "nan");
constant.set_double_value(INFINITY);
EXPECT_EQ(Stringify(constant), "+infinity");
constant.set_double_value(-INFINITY);
EXPECT_EQ(Stringify(constant), "-infinity");
constant.set_bytes_value("foo");
EXPECT_EQ(Stringify(constant), "b\"foo\"");
constant.set_string_value("foo");
EXPECT_EQ(Stringify(constant), "\"foo\"");
constant.set_duration_value(absl::Seconds(1));
EXPECT_EQ(Stringify(constant), "duration(\"1s\")");
constant.set_timestamp_value(absl::UnixEpoch() + absl::Seconds(1));
EXPECT_EQ(Stringify(constant), "timestamp(\"1970-01-01T00:00:01Z\")");
}
}
} |
5 | cpp | google/cel-cpp | expr | common/expr.cc | common/expr_test.cc | #ifndef THIRD_PARTY_CEL_CPP_BASE_AST_INTERNAL_EXPR_H_
#define THIRD_PARTY_CEL_CPP_BASE_AST_INTERNAL_EXPR_H_
#include <cstddef>
#include <cstdint>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "absl/types/optional.h"
#include "absl/types/variant.h"
#include "common/ast.h"
#include "common/constant.h"
#include "common/expr.h"
namespace cel::ast_internal {
using NullValue = std::nullptr_t;
using Bytes = cel::BytesConstant;
using Constant = cel::Constant;
using ConstantKind = cel::ConstantKind;
using Ident = cel::IdentExpr;
using Expr = cel::Expr;
using ExprKind = cel::ExprKind;
using Select = cel::SelectExpr;
using Call = cel::CallExpr;
using CreateList = cel::ListExpr;
using CreateStruct = cel::StructExpr;
using Comprehension = cel::ComprehensionExpr;
class Extension {
public:
class Version {
public:
Version() : major_(0), minor_(0) {}
Version(int64_t major, int64_t minor) : major_(major), minor_(minor) {}
Version(const Version& other) = default;
Version(Version&& other) = default;
Version& operator=(const Version& other) = default;
Version& operator=(Version&& other) = default;
static const Version& DefaultInstance();
int64_t major() const { return major_; }
void set_major(int64_t val) { major_ = val; }
int64_t minor() const { return minor_; }
void set_minor(int64_t val) { minor_ = val; }
bool operator==(const Version& other) const {
return major_ == other.major_ && minor_ == other.minor_;
}
bool operator!=(const Version& other) const { return !operator==(other); }
private:
int64_t major_;
int64_t minor_;
};
enum class Component {
kUnspecified,
kParser,
kTypeChecker,
kRuntime
};
static const Extension& DefaultInstance();
Extension() = default;
Extension(std::string id, std::unique_ptr<Version> version,
std::vector<Component> affected_components)
: id_(std::move(id)),
affected_components_(std::move(affected_components)),
version_(std::move(version)) {}
Extension(const Extension& other);
Extension(Extension&& other) = default;
Extension& operator=(const Extension& other);
Extension& operator=(Extension&& other) = default;
const std::string& id() const { return id_; }
void set_id(std::string id) { id_ = std::move(id); }
const std::vector<Component>& affected_components() const {
return affected_components_;
}
std::vector<Component>& mutable_affected_components() {
return affected_components_;
}
const Version& version() const {
if (version_ == nullptr) {
return Version::DefaultInstance();
}
return *version_;
}
Version& mutable_version() {
if (version_ == nullptr) {
version_ = std::make_unique<Version>();
}
return *version_;
}
void set_version(std::unique_ptr<Version> version) {
version_ = std::move(version);
}
bool operator==(const Extension& other) const {
return id_ == other.id_ &&
affected_components_ == other.affected_components_ &&
version() == other.version();
}
bool operator!=(const Extension& other) const { return !operator==(other); }
private:
std::string id_;
std::vector<Component> affected_components_;
std::unique_ptr<Version> version_;
};
class SourceInfo {
public:
SourceInfo() = default;
SourceInfo(std::string syntax_version, std::string location,
std::vector<int32_t> line_offsets,
absl::flat_hash_map<int64_t, int32_t> positions,
absl::flat_hash_map<int64_t, Expr> macro_calls,
std::vector<Extension> extensions)
: syntax_version_(std::move(syntax_version)),
location_(std::move(location)),
line_offsets_(std::move(line_offsets)),
positions_(std::move(positions)),
macro_calls_(std::move(macro_calls)),
extensions_(std::move(extensions)) {}
void set_syntax_version(std::string syntax_version) {
syntax_version_ = std::move(syntax_version);
}
void set_location(std::string location) { location_ = std::move(location); }
void set_line_offsets(std::vector<int32_t> line_offsets) {
line_offsets_ = std::move(line_offsets);
}
void set_positions(absl::flat_hash_map<int64_t, int32_t> positions) {
positions_ = std::move(positions);
}
void set_macro_calls(absl::flat_hash_map<int64_t, Expr> macro_calls) {
macro_calls_ = std::move(macro_calls);
}
const std::string& syntax_version() const { return syntax_version_; }
const std::string& location() const { return location_; }
const std::vector<int32_t>& line_offsets() const { return line_offsets_; }
std::vector<int32_t>& mutable_line_offsets() { return line_offsets_; }
const absl::flat_hash_map<int64_t, int32_t>& positions() const {
return positions_;
}
absl::flat_hash_map<int64_t, int32_t>& mutable_positions() {
return positions_;
}
const absl::flat_hash_map<int64_t, Expr>& macro_calls() const {
return macro_calls_;
}
absl::flat_hash_map<int64_t, Expr>& mutable_macro_calls() {
return macro_calls_;
}
bool operator==(const SourceInfo& other) const {
return syntax_version_ == other.syntax_version_ &&
location_ == other.location_ &&
line_offsets_ == other.line_offsets_ &&
positions_ == other.positions_ &&
macro_calls_ == other.macro_calls_ &&
extensions_ == other.extensions_;
}
bool operator!=(const SourceInfo& other) const { return !operator==(other); }
const std::vector<Extension>& extensions() const { return extensions_; }
std::vector<Extension>& mutable_extensions() { return extensions_; }
private:
std::string syntax_version_;
std::string location_;
std::vector<int32_t> line_offsets_;
absl::flat_hash_map<int64_t, int32_t> positions_;
absl::flat_hash_map<int64_t, Expr> macro_calls_;
std::vector<Extension> extensions_;
};
class ParsedExpr {
public:
ParsedExpr() = default;
ParsedExpr(Expr expr, SourceInfo source_info)
: expr_(std::move(expr)), source_info_(std::move(source_info)) {}
ParsedExpr(ParsedExpr&& rhs) = default;
ParsedExpr& operator=(ParsedExpr&& rhs) = default;
void set_expr(Expr expr) { expr_ = std::move(expr); }
void set_source_info(SourceInfo source_info) {
source_info_ = std::move(source_info);
}
const Expr& expr() const { return expr_; }
Expr& mutable_expr() { return expr_; }
const SourceInfo& source_info() const { return source_info_; }
SourceInfo& mutable_source_info() { return source_info_; }
private:
Expr expr_;
SourceInfo source_info_;
};
enum class PrimitiveType {
kPrimitiveTypeUnspecified = 0,
kBool = 1,
kInt64 = 2,
kUint64 = 3,
kDouble = 4,
kString = 5,
kBytes = 6,
};
enum class WellKnownType {
kWellKnownTypeUnspecified = 0,
kAny = 1,
kTimestamp = 2,
kDuration = 3,
};
class Type;
class ListType {
public:
ListType() = default;
ListType(const ListType& rhs)
: elem_type_(std::make_unique<Type>(rhs.elem_type())) {}
ListType& operator=(const ListType& rhs) {
elem_type_ = std::make_unique<Type>(rhs.elem_type());
return *this;
}
ListType(ListType&& rhs) = default;
ListType& operator=(ListType&& rhs) = default;
explicit ListType(std::unique_ptr<Type> elem_type)
: elem_type_(std::move(elem_type)) {}
void set_elem_type(std::unique_ptr<Type> elem_type) {
elem_type_ = std::move(elem_type);
}
bool has_elem_type() const { return elem_type_ != nullptr; }
const Type& elem_type() const;
Type& mutable_elem_type() {
if (elem_type_ == nullptr) {
elem_type_ = std::make_unique<Type>();
}
return *elem_type_;
}
bool operator==(const ListType& other) const;
private:
std::unique_ptr<Type> elem_type_;
};
class MapType {
public:
MapType() = default;
MapType(std::unique_ptr<Type> key_type, std::unique_ptr<Type> value_type)
: key_type_(std::move(key_type)), value_type_(std::move(value_type)) {}
MapType(const MapType& rhs)
: key_type_(std::make_unique<Type>(rhs.key_type())),
value_type_(std::make_unique<Type>(rhs.value_type())) {}
MapType& operator=(const MapType& rhs) {
key_type_ = std::make_unique<Type>(rhs.key_type());
value_type_ = std::make_unique<Type>(rhs.value_type());
return *this;
}
MapType(MapType&& rhs) = default;
MapType& operator=(MapType&& rhs) = default;
void set_key_type(std::unique_ptr<Type> key_type) {
key_type_ = std::move(key_type);
}
void set_value_type(std::unique_ptr<Type> value_type) {
value_type_ = std::move(value_type);
}
bool has_key_type() const { return key_type_ != nullptr; }
bool has_value_type() const { return value_type_ != nullptr; }
const Type& key_type() const;
const Type& value_type() const;
bool operator==(const MapType& other) const;
Type& mutable_key_type() {
if (key_type_ == nullptr) {
key_type_ = std::make_unique<Type>();
}
return *key_type_;
}
Type& mutable_value_type() {
if (value_type_ == nullptr) {
value_type_ = std::make_unique<Type>();
}
return *value_type_;
}
private:
std::unique_ptr<Type> key_type_;
std::unique_ptr<Type> value_type_;
};
class FunctionType {
public:
FunctionType() = default;
FunctionType(std::unique_ptr<Type> result_type, std::vector<Type> arg_types);
FunctionType(const FunctionType& other);
FunctionType& operator=(const FunctionType& other);
FunctionType(FunctionType&&) = default;
FunctionType& operator=(FunctionType&&) = default;
void set_result_type(std::unique_ptr<Type> result_type) {
result_type_ = std::move(result_type);
}
void set_arg_types(std::vector<Type> arg_types);
bool has_result_type() const { return result_type_ != nullptr; }
const Type& result_type() const;
Type& mutable_result_type() {
if (result_type_ == nullptr) {
result_type_ = std::make_unique<Type>();
}
return *result_type_;
}
const std::vector<Type>& arg_types() const { return arg_types_; }
std::vector<Type>& mutable_arg_types() { return arg_types_; }
bool operator==(const FunctionType& other) const;
private:
std::unique_ptr<Type> result_type_;
std::vector<Type> arg_types_;
};
class AbstractType {
public:
AbstractType() = default;
AbstractType(std::string name, std::vector<Type> parameter_types);
void set_name(std::string name) { name_ = std::move(name); }
void set_parameter_types(std::vector<Type> parameter_types);
const std::string& name() const { return name_; }
const std::vector<Type>& parameter_types() const { return parameter_types_; }
std::vector<Type>& mutable_parameter_types() { return parameter_types_; }
bool operator==(const AbstractType& other) const;
private:
std::string name_;
std::vector<Type> parameter_types_;
};
class PrimitiveTypeWrapper {
public:
explicit PrimitiveTypeWrapper(PrimitiveType type) : type_(std::move(type)) {}
void set_type(PrimitiveType type) { type_ = std::move(type); }
const PrimitiveType& type() const { return type_; }
PrimitiveType& mutable_type() { return type_; }
bool operator==(const PrimitiveTypeWrapper& other) const {
return type_ == other.type_;
}
private:
PrimitiveType type_;
};
class MessageType {
public:
MessageType() = default;
explicit MessageType(std::string type) : type_(std::move(type)) {}
void set_type(std::string type) { type_ = std::move(type); }
const std::string& type() const { return type_; }
bool operator==(const MessageType& other) const {
return type_ == other.type_;
}
private:
std::string type_;
};
class ParamType {
public:
ParamType() = default;
explicit ParamType(std::string type) : type_(std::move(type)) {}
void set_type(std::string type) { type_ = std::move(type); }
const std::string& type() const { return type_; }
bool operator==(const ParamType& other) const { return type_ == other.type_; }
private:
std::string type_;
};
enum class ErrorType { kErrorTypeValue = 0 };
using DynamicType = absl::monostate;
using TypeKind =
absl::variant<DynamicType, NullValue, PrimitiveType, PrimitiveTypeWrapper,
WellKnownType, ListType, MapType, FunctionType, MessageType,
ParamType, std::unique_ptr<Type>, ErrorType, AbstractType>;
class Type {
public:
Type() = default;
explicit Type(TypeKind type_kind) : type_kind_(std::move(type_kind)) {}
Type(const Type& other);
Type& operator=(const Type& other);
Type(Type&&) = default;
Type& operator=(Type&&) = default;
void set_type_kind(TypeKind type_kind) { type_kind_ = std::move(type_kind); }
const TypeKind& type_kind() const { return type_kind_; }
TypeKind& mutable_type_kind() { return type_kind_; }
bool has_dyn() const {
return absl::holds_alternative<DynamicType>(type_kind_);
}
bool has_null() const {
return absl::holds_alternative<NullValue>(type_kind_);
}
bool has_primitive() const {
return absl::holds_alternative<PrimitiveType>(type_kind_);
}
bool has_wrapper() const {
return absl::holds_alternative<PrimitiveTypeWrapper>(type_kind_);
}
bool has_well_known() const {
return absl::holds_alternative<WellKnownType>(type_kind_);
}
bool has_list_type() const {
return absl::holds_alternative<ListType>(type_kind_);
}
bool has_map_type() const {
return absl::holds_alternative<MapType>(type_kind_);
}
bool has_function() const {
return absl::holds_alternative<FunctionType>(type_kind_);
}
bool has_message_type() const {
return absl::holds_alternative<MessageType>(type_kind_);
}
bool has_type_param() const {
return absl::holds_alternative<ParamType>(type_kind_);
}
bool has_type() const {
return absl::holds_alternative<std::unique_ptr<Type>>(type_kind_);
}
bool has_error() const {
return absl::holds_alternative<ErrorType>(type_kind_);
}
bool has_abstract_type() const {
return absl::holds_alternative<AbstractType>(type_kind_);
}
NullValue null() const {
auto* value = absl::get_if<NullValue>(&type_kind_);
if (value != nullptr) {
return *value;
}
return nullptr;
}
PrimitiveType primitive() const {
auto* value = absl::get_if<PrimitiveType>(&type_kind_);
if (value != nullptr) {
return *value;
}
return PrimitiveType::kPrimitiveTypeUnspecified;
}
PrimitiveType wrapper() const {
auto* value = absl::get_if<PrimitiveTypeWrapper>(&type_kind_);
if (value != nullptr) {
return value->type();
}
return PrimitiveType::kPrimitiveTypeUnspecified;
}
WellKnownType well_known() const {
auto* value = absl::get_if<WellKnownType>(&type_kind_);
if (value != nullptr) {
return *value;
}
return WellKnownType::kWellKnownTypeUnspecified;
}
const ListType& list_type() const {
auto* value = absl::get_if<ListType>(&type_kind_);
if (value != nullptr) {
return *value;
}
static const ListType* default_list_type = new ListType();
return *default_list_type;
}
const MapType& map_type() const {
auto* value = absl::get_if<MapType>(&type_kind_);
if (value != nullptr) {
return *value;
}
static const MapType* default_map_type = new MapType();
return *default_map_type;
}
const FunctionType& function() const {
auto* value = absl::get_if<FunctionType>(&type_kind_);
if (value != nullptr) {
return *value;
}
static const FunctionType* default_function_type = new FunctionType();
return *default_function_type;
}
const MessageType& message_type() const {
auto* value = absl::get_if<MessageType>(&type_kind_);
if (value != nullptr) {
return *value;
}
static const MessageType* default_message_type = new MessageType();
return *default_message_type;
}
const ParamType& type_param() const {
auto* value = absl::get_if<ParamType>(&type_kind_);
if (value != nullptr) {
return *value;
}
static const ParamType* default_param_type = new ParamType();
return *default_param_type;
}
const Type& type() const;
ErrorType error_type() const {
auto* value = absl::get_if<ErrorType>(&type_kind_);
if (value != nullptr) {
return *value;
}
return ErrorType::kErrorTypeValue;
}
const AbstractType& abstract_type() const {
auto* value = absl::get_if<AbstractType>(&type_kind_);
if (value != nullptr) {
return *value;
}
static const AbstractType* default_abstract_type = new AbstractType();
return *default_abstract_type;
}
bool operator==(const Type& other) const {
return type_kind_ == other.type_kind_;
}
private:
TypeKind type_kind_;
};
class Reference {
public:
Reference() = default;
Reference(std::string name, std::vector<std::string> overload_id,
Constant value)
: name_(std::move(name)),
overload_id_(std::move(overload_id)),
value_(std::move(value)) {}
void set_name(std::string name) { name_ = std::move(name); }
void set_overload_id(std::vector<std::string> overload_id) {
overload_id_ = std::move(overload_id);
}
void set_value(Constant value) { value_ = std::move(value); }
const std::string& name() const { return name_; }
const std::vector<std::string>& overload_id() const { return overload_id_; }
const Constant& value() const {
if (value_.has_value()) {
return value_.value();
}
static const Constant* default_constant = new Constant;
return *default_constant;
}
std::vector<std::string>& mutable_overload_id() { return overload_id_; }
Constant& mutable_value() {
if (!value_.has_value()) {
value_.emplace();
}
return *value_;
}
bool has_value() const { return value_.has_value(); }
bool operator==(const Reference& other) const {
return name_ == other.name_ && overload_id_ == other.overload_id_ &&
value() == other.value();
}
private:
std::string name_;
std::vector<std::string> overload_id_;
absl::optional<Constant> value_;
};
class CheckedExpr {
public:
CheckedExpr() = default;
CheckedExpr(absl::flat_hash_map<int64_t, Reference> reference_map,
absl::flat_hash_map<int64_t, Type> type_map,
SourceInfo source_info, std::string expr_version, Expr expr)
: reference_map_(std::move(reference_map)),
type_map_(std::move(type_map)),
source_info_(std::move(source_info)),
expr_version_(std::move(expr_version)),
expr_(std::move(expr)) {}
CheckedExpr(CheckedExpr&& rhs) = default;
CheckedExpr& operator=(CheckedExpr&& rhs) = default;
void set_reference_map(
absl::flat_hash_map<int64_t, Reference> reference_map) {
reference_map_ = std::move(reference_map);
}
void set_type_map(absl::flat_hash_map<int64_t, Type> type_map) {
type_map_ = std::move(type_map);
}
void set_source_info(SourceInfo source_info) {
source_info_ = std::move(source_info);
}
void set_expr_version(std::string expr_version) {
expr_version_ = std::move(expr_version);
}
void set_expr(Expr expr) { expr_ = std::move(expr); }
const absl::flat_hash_map<int64_t, Reference>& reference_map() const {
return reference_map_;
}
absl::flat_hash_map<int64_t, Reference>& mutable_reference_map() {
return reference_map_;
}
const absl::flat_hash_map<int64_t, Type>& type_map() const {
return type_map_;
}
absl::flat_hash_map<int64_t, Type>& mutable_type_map() { return type_map_; }
const SourceInfo& source_info() const { return source_info_; }
SourceInfo& mutable_source_info() { return source_info_; }
const std::string& expr_version() const { return expr_version_; }
std::string& mutable_expr_version() { return expr_version_; }
const Expr& expr() const { return expr_; }
Expr& mutable_expr() { return expr_; }
private:
absl::flat_hash_map<int64_t, Reference> reference_map_;
absl::flat_hash_map<int64_t, Type> type_map_;
SourceInfo source_info_;
std::string expr_version_;
Expr expr_;
};
inline FunctionType::FunctionType(std::unique_ptr<Type> result_type,
std::vector<Type> arg_types)
: result_type_(std::move(result_type)), arg_types_(std::move(arg_types)) {}
inline void FunctionType::set_arg_types(std::vector<Type> arg_types) {
arg_types_ = std::move(arg_types);
}
inline AbstractType::AbstractType(std::string name,
std::vector<Type> parameter_types)
: name_(std::move(name)), parameter_types_(std::move(parameter_types)) {}
inline void AbstractType::set_parameter_types(
std::vector<Type> parameter_types) {
parameter_types_ = std::move(parameter_types);
}
inline bool AbstractType::operator==(const AbstractType& other) const {
return name_ == other.name_ && parameter_types_ == other.parameter_types_;
}
}
#endif
#include "base/ast_internal/expr.h"
#include <memory>
#include <vector>
#include "absl/base/no_destructor.h"
#include "absl/functional/overload.h"
#include "absl/types/variant.h"
namespace cel::ast_internal {
namespace {
const Type& default_type() {
static absl::NoDestructor<Type> type;
return *type;
}
TypeKind CopyImpl(const TypeKind& other) {
return absl::visit(absl::Overload(
[](const std::unique_ptr<Type>& other) -> TypeKind {
return std::make_unique<Type>(*other);
},
[](const auto& other) -> TypeKind {
return other;
}),
other);
}
}
const Extension::Version& Extension::Version::DefaultInstance() {
static absl::NoDestructor<Version> instance;
return *instance;
}
const Extension& Extension::DefaultInstance() {
static absl::NoDestructor<Extension> instance;
return *instance;
}
Extension::Extension(const Extension& other)
: id_(other.id_),
affected_components_(other.affected_components_),
version_(std::make_unique<Version>(*other.version_)) {}
Extension& Extension::operator=(const Extension& other) {
id_ = other.id_;
affected_components_ = other.affected_components_;
version_ = std::make_unique<Version>(*other.version_);
return *this;
}
const Type& ListType::elem_type() const {
if (elem_type_ != nullptr) {
return *elem_type_;
}
return default_type();
}
bool ListType::operator==(const ListType& other) const {
return elem_type() == other.elem_type();
}
const Type& MapType::key_type() const {
if (key_type_ != nullptr) {
return *key_type_;
}
return default_type();
}
const Type& MapType::value_type() const {
if (value_type_ != nullptr) {
return *value_type_;
}
return default_type();
}
bool MapType::operator==(const MapType& other) const {
return key_type() == other.key_type() && value_type() == other.value_type();
}
const Type& FunctionType::result_type() const {
if (result_type_ != nullptr) {
return *result_type_;
}
return default_type();
}
bool FunctionType::operator==(const FunctionType& other) const {
return result_type() == other.result_type() && arg_types_ == other.arg_types_;
}
const Type& Type::type() const {
auto* v | #include "base/ast_internal/expr.h"
#include <memory>
#include <string>
#include <utility>
#include "absl/types/variant.h"
#include "common/ast.h"
#include "internal/testing.h"
namespace cel {
namespace ast_internal {
namespace {
TEST(AstTest, ParsedExpr) {
ParsedExpr parsed_expr;
auto& expr = parsed_expr.mutable_expr();
expr.set_id(1);
expr.mutable_ident_expr().set_name("name");
auto& source_info = parsed_expr.mutable_source_info();
source_info.set_syntax_version("syntax_version");
source_info.set_location("location");
source_info.set_line_offsets({1, 2, 3});
source_info.set_positions({{1, 1}, {2, 2}});
ASSERT_TRUE(absl::holds_alternative<Ident>(parsed_expr.expr().kind()));
ASSERT_EQ(absl::get<Ident>(parsed_expr.expr().kind()).name(), "name");
ASSERT_EQ(parsed_expr.source_info().syntax_version(), "syntax_version");
ASSERT_EQ(parsed_expr.source_info().location(), "location");
EXPECT_THAT(parsed_expr.source_info().line_offsets(),
testing::UnorderedElementsAre(1, 2, 3));
EXPECT_THAT(
parsed_expr.source_info().positions(),
testing::UnorderedElementsAre(testing::Pair(1, 1), testing::Pair(2, 2)));
}
TEST(AstTest, ListTypeMutableConstruction) {
ListType type;
type.mutable_elem_type() = Type(PrimitiveType::kBool);
EXPECT_EQ(absl::get<PrimitiveType>(type.elem_type().type_kind()),
PrimitiveType::kBool);
}
TEST(AstTest, MapTypeMutableConstruction) {
MapType type;
type.mutable_key_type() = Type(PrimitiveType::kBool);
type.mutable_value_type() = Type(PrimitiveType::kBool);
EXPECT_EQ(absl::get<PrimitiveType>(type.key_type().type_kind()),
PrimitiveType::kBool);
EXPECT_EQ(absl::get<PrimitiveType>(type.value_type().type_kind()),
PrimitiveType::kBool);
}
TEST(AstTest, MapTypeComparatorKeyType) {
MapType type;
type.mutable_key_type() = Type(PrimitiveType::kBool);
EXPECT_FALSE(type == MapType());
}
TEST(AstTest, MapTypeComparatorValueType) {
MapType type;
type.mutable_value_type() = Type(PrimitiveType::kBool);
EXPECT_FALSE(type == MapType());
}
TEST(AstTest, FunctionTypeMutableConstruction) {
FunctionType type;
type.mutable_result_type() = Type(PrimitiveType::kBool);
EXPECT_EQ(absl::get<PrimitiveType>(type.result_type().type_kind()),
PrimitiveType::kBool);
}
TEST(AstTest, FunctionTypeComparatorArgTypes) {
FunctionType type;
type.mutable_arg_types().emplace_back(Type());
EXPECT_FALSE(type == FunctionType());
}
TEST(AstTest, CheckedExpr) {
CheckedExpr checked_expr;
auto& expr = checked_expr.mutable_expr();
expr.set_id(1);
expr.mutable_ident_expr().set_name("name");
auto& source_info = checked_expr.mutable_source_info();
source_info.set_syntax_version("syntax_version");
source_info.set_location("location");
source_info.set_line_offsets({1, 2, 3});
source_info.set_positions({{1, 1}, {2, 2}});
checked_expr.set_expr_version("expr_version");
checked_expr.mutable_type_map().insert(
{1, Type(PrimitiveType(PrimitiveType::kBool))});
ASSERT_TRUE(absl::holds_alternative<Ident>(checked_expr.expr().kind()));
ASSERT_EQ(absl::get<Ident>(checked_expr.expr().kind()).name(), "name");
ASSERT_EQ(checked_expr.source_info().syntax_version(), "syntax_version");
ASSERT_EQ(checked_expr.source_info().location(), "location");
EXPECT_THAT(checked_expr.source_info().line_offsets(),
testing::UnorderedElementsAre(1, 2, 3));
EXPECT_THAT(
checked_expr.source_info().positions(),
testing::UnorderedElementsAre(testing::Pair(1, 1), testing::Pair(2, 2)));
EXPECT_EQ(checked_expr.expr_version(), "expr_version");
}
TEST(AstTest, ListTypeDefaults) { EXPECT_EQ(ListType().elem_type(), Type()); }
TEST(AstTest, MapTypeDefaults) {
EXPECT_EQ(MapType().key_type(), Type());
EXPECT_EQ(MapType().value_type(), Type());
}
TEST(AstTest, FunctionTypeDefaults) {
EXPECT_EQ(FunctionType().result_type(), Type());
}
TEST(AstTest, TypeDefaults) {
EXPECT_EQ(Type().null(), nullptr);
EXPECT_EQ(Type().primitive(), PrimitiveType::kPrimitiveTypeUnspecified);
EXPECT_EQ(Type().wrapper(), PrimitiveType::kPrimitiveTypeUnspecified);
EXPECT_EQ(Type().well_known(), WellKnownType::kWellKnownTypeUnspecified);
EXPECT_EQ(Type().list_type(), ListType());
EXPECT_EQ(Type().map_type(), MapType());
EXPECT_EQ(Type().function(), FunctionType());
EXPECT_EQ(Type().message_type(), MessageType());
EXPECT_EQ(Type().type_param(), ParamType());
EXPECT_EQ(Type().type(), Type());
EXPECT_EQ(Type().error_type(), ErrorType());
EXPECT_EQ(Type().abstract_type(), AbstractType());
}
TEST(AstTest, TypeComparatorTest) {
Type type;
type.set_type_kind(std::make_unique<Type>(PrimitiveType::kBool));
EXPECT_FALSE(type.type() == Type());
}
TEST(AstTest, ExprMutableConstruction) {
Expr expr;
expr.mutable_const_expr().set_bool_value(true);
ASSERT_TRUE(expr.has_const_expr());
EXPECT_TRUE(expr.const_expr().bool_value());
expr.mutable_ident_expr().set_name("expr");
ASSERT_TRUE(expr.has_ident_expr());
EXPECT_FALSE(expr.has_const_expr());
EXPECT_EQ(expr.ident_expr().name(), "expr");
expr.mutable_select_expr().set_field("field");
ASSERT_TRUE(expr.has_select_expr());
EXPECT_FALSE(expr.has_ident_expr());
EXPECT_EQ(expr.select_expr().field(), "field");
expr.mutable_call_expr().set_function("function");
ASSERT_TRUE(expr.has_call_expr());
EXPECT_FALSE(expr.has_select_expr());
EXPECT_EQ(expr.call_expr().function(), "function");
expr.mutable_list_expr();
EXPECT_TRUE(expr.has_list_expr());
EXPECT_FALSE(expr.has_call_expr());
expr.mutable_struct_expr().set_name("name");
ASSERT_TRUE(expr.has_struct_expr());
EXPECT_EQ(expr.struct_expr().name(), "name");
EXPECT_FALSE(expr.has_list_expr());
expr.mutable_comprehension_expr().set_accu_var("accu_var");
ASSERT_TRUE(expr.has_comprehension_expr());
EXPECT_FALSE(expr.has_list_expr());
EXPECT_EQ(expr.comprehension_expr().accu_var(), "accu_var");
}
TEST(AstTest, ReferenceConstantDefaultValue) {
Reference reference;
EXPECT_EQ(reference.value(), Constant());
}
TEST(AstTest, TypeCopyable) {
Type type = Type(PrimitiveType::kBool);
Type type2 = type;
EXPECT_TRUE(type2.has_primitive());
EXPECT_EQ(type2, type);
type = Type(ListType(std::make_unique<Type>(PrimitiveType::kBool)));
type2 = type;
EXPECT_TRUE(type2.has_list_type());
EXPECT_EQ(type2, type);
type = Type(MapType(std::make_unique<Type>(PrimitiveType::kBool),
std::make_unique<Type>(PrimitiveType::kBool)));
type2 = type;
EXPECT_TRUE(type2.has_map_type());
EXPECT_EQ(type2, type);
type = Type(FunctionType(std::make_unique<Type>(PrimitiveType::kBool), {}));
type2 = type;
EXPECT_TRUE(type2.has_function());
EXPECT_EQ(type2, type);
type = Type(AbstractType("optional", {Type(PrimitiveType::kBool)}));
type2 = type;
EXPECT_TRUE(type2.has_abstract_type());
EXPECT_EQ(type2, type);
}
TEST(AstTest, TypeMoveable) {
Type type = Type(PrimitiveType::kBool);
Type type2 = type;
Type type3 = std::move(type);
EXPECT_TRUE(type2.has_primitive());
EXPECT_EQ(type2, type3);
type = Type(ListType(std::make_unique<Type>(PrimitiveType::kBool)));
type2 = type;
type3 = std::move(type);
EXPECT_TRUE(type2.has_list_type());
EXPECT_EQ(type2, type3);
type = Type(MapType(std::make_unique<Type>(PrimitiveType::kBool),
std::make_unique<Type>(PrimitiveType::kBool)));
type2 = type;
type3 = std::move(type);
EXPECT_TRUE(type2.has_map_type());
EXPECT_EQ(type2, type3);
type = Type(FunctionType(std::make_unique<Type>(PrimitiveType::kBool), {}));
type2 = type;
type3 = std::move(type);
EXPECT_TRUE(type2.has_function());
EXPECT_EQ(type2, type3);
type = Type(AbstractType("optional", {Type(PrimitiveType::kBool)}));
type2 = type;
type3 = std::move(type);
EXPECT_TRUE(type2.has_abstract_type());
EXPECT_EQ(type2, type3);
}
TEST(AstTest, NestedTypeKindCopyAssignable) {
ListType list_type(std::make_unique<Type>(PrimitiveType::kBool));
ListType list_type2;
list_type2 = list_type;
EXPECT_EQ(list_type2, list_type);
MapType map_type(std::make_unique<Type>(PrimitiveType::kBool),
std::make_unique<Type>(PrimitiveType::kBool));
MapType map_type2;
map_type2 = map_type;
AbstractType abstract_type(
"abstract", {Type(PrimitiveType::kBool), Type(PrimitiveType::kBool)});
AbstractType abstract_type2;
abstract_type2 = abstract_type;
EXPECT_EQ(abstract_type2, abstract_type);
FunctionType function_type(
std::make_unique<Type>(PrimitiveType::kBool),
{Type(PrimitiveType::kBool), Type(PrimitiveType::kBool)});
FunctionType function_type2;
function_type2 = function_type;
EXPECT_EQ(function_type2, function_type);
}
TEST(AstTest, ExtensionSupported) {
SourceInfo source_info;
source_info.mutable_extensions().push_back(
Extension("constant_folding", nullptr, {}));
EXPECT_EQ(source_info.extensions()[0],
Extension("constant_folding", nullptr, {}));
}
TEST(AstTest, ExtensionEquality) {
Extension extension1("constant_folding", nullptr, {});
EXPECT_EQ(extension1, Extension("constant_folding", nullptr, {}));
EXPECT_NE(extension1,
Extension("constant_folding",
std::make_unique<Extension::Version>(1, 0), {}));
EXPECT_NE(extension1, Extension("constant_folding", nullptr,
{Extension::Component::kRuntime}));
EXPECT_EQ(extension1,
Extension("constant_folding",
std::make_unique<Extension::Version>(0, 0), {}));
}
}
}
} |
6 | cpp | google/cel-cpp | decl | common/decl.cc | common/decl_test.cc | #ifndef THIRD_PARTY_CEL_CPP_COMMON_DECL_H_
#define THIRD_PARTY_CEL_CPP_COMMON_DECL_H_
#include <cstddef>
#include <string>
#include <utility>
#include <vector>
#include "absl/algorithm/container.h"
#include "absl/base/attributes.h"
#include "absl/container/flat_hash_set.h"
#include "absl/hash/hash.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "common/constant.h"
#include "common/type.h"
#include "internal/status_macros.h"
namespace cel {
class VariableDecl;
class OverloadDecl;
class FunctionDecl;
class VariableDecl final {
public:
VariableDecl() = default;
VariableDecl(const VariableDecl&) = default;
VariableDecl(VariableDecl&&) = default;
VariableDecl& operator=(const VariableDecl&) = default;
VariableDecl& operator=(VariableDecl&&) = default;
ABSL_MUST_USE_RESULT const std::string& name() const
ABSL_ATTRIBUTE_LIFETIME_BOUND {
return name_;
}
void set_name(std::string name) { name_ = std::move(name); }
void set_name(absl::string_view name) {
name_.assign(name.data(), name.size());
}
void set_name(const char* name) { set_name(absl::NullSafeStringView(name)); }
ABSL_MUST_USE_RESULT std::string release_name() {
std::string released;
released.swap(name_);
return released;
}
ABSL_MUST_USE_RESULT const Type& type() const ABSL_ATTRIBUTE_LIFETIME_BOUND {
return type_;
}
ABSL_MUST_USE_RESULT Type& mutable_type() ABSL_ATTRIBUTE_LIFETIME_BOUND {
return type_;
}
void set_type(Type type) { mutable_type() = std::move(type); }
ABSL_MUST_USE_RESULT bool has_value() const { return value_.has_value(); }
ABSL_MUST_USE_RESULT const Constant& value() const
ABSL_ATTRIBUTE_LIFETIME_BOUND {
return has_value() ? *value_ : Constant::default_instance();
}
Constant& mutable_value() ABSL_ATTRIBUTE_LIFETIME_BOUND {
if (!has_value()) {
value_.emplace();
}
return *value_;
}
void set_value(absl::optional<Constant> value) { value_ = std::move(value); }
void set_value(Constant value) { mutable_value() = std::move(value); }
ABSL_MUST_USE_RESULT Constant release_value() {
absl::optional<Constant> released;
released.swap(value_);
return std::move(released).value_or(Constant{});
}
private:
std::string name_;
Type type_ = DynType{};
absl::optional<Constant> value_;
};
inline VariableDecl MakeVariableDecl(std::string name, Type type) {
VariableDecl variable_decl;
variable_decl.set_name(std::move(name));
variable_decl.set_type(std::move(type));
return variable_decl;
}
inline VariableDecl MakeConstantVariableDecl(std::string name, Type type,
Constant value) {
VariableDecl variable_decl;
variable_decl.set_name(std::move(name));
variable_decl.set_type(std::move(type));
variable_decl.set_value(std::move(value));
return variable_decl;
}
inline bool operator==(const VariableDecl& lhs, const VariableDecl& rhs) {
return lhs.name() == rhs.name() && lhs.type() == rhs.type() &&
lhs.has_value() == rhs.has_value() && lhs.value() == rhs.value();
}
inline bool operator!=(const VariableDecl& lhs, const VariableDecl& rhs) {
return !operator==(lhs, rhs);
}
class OverloadDecl final {
public:
OverloadDecl() = default;
OverloadDecl(const OverloadDecl&) = default;
OverloadDecl(OverloadDecl&&) = default;
OverloadDecl& operator=(const OverloadDecl&) = default;
OverloadDecl& operator=(OverloadDecl&&) = default;
ABSL_MUST_USE_RESULT const std::string& id() const
ABSL_ATTRIBUTE_LIFETIME_BOUND {
return id_;
}
void set_id(std::string id) { id_ = std::move(id); }
void set_id(absl::string_view id) { id_.assign(id.data(), id.size()); }
void set_id(const char* id) { set_id(absl::NullSafeStringView(id)); }
ABSL_MUST_USE_RESULT std::string release_id() {
std::string released;
released.swap(id_);
return released;
}
ABSL_MUST_USE_RESULT const std::vector<Type>& args() const
ABSL_ATTRIBUTE_LIFETIME_BOUND {
return args_;
}
ABSL_MUST_USE_RESULT std::vector<Type>& mutable_args()
ABSL_ATTRIBUTE_LIFETIME_BOUND {
return args_;
}
ABSL_MUST_USE_RESULT std::vector<Type> release_args() {
std::vector<Type> released;
released.swap(mutable_args());
return released;
}
ABSL_MUST_USE_RESULT const Type& result() const
ABSL_ATTRIBUTE_LIFETIME_BOUND {
return result_;
}
ABSL_MUST_USE_RESULT Type& mutable_result() ABSL_ATTRIBUTE_LIFETIME_BOUND {
return result_;
}
void set_result(Type result) { mutable_result() = std::move(result); }
ABSL_MUST_USE_RESULT bool member() const { return member_; }
void set_member(bool member) { member_ = member; }
absl::flat_hash_set<std::string> GetTypeParams() const;
private:
std::string id_;
std::vector<Type> args_;
Type result_ = DynType{};
bool member_ = false;
};
inline bool operator==(const OverloadDecl& lhs, const OverloadDecl& rhs) {
return lhs.id() == rhs.id() && absl::c_equal(lhs.args(), rhs.args()) &&
lhs.result() == rhs.result() && lhs.member() == rhs.member();
}
inline bool operator!=(const OverloadDecl& lhs, const OverloadDecl& rhs) {
return !operator==(lhs, rhs);
}
template <typename... Args>
OverloadDecl MakeOverloadDecl(std::string id, Type result, Args&&... args) {
OverloadDecl overload_decl;
overload_decl.set_id(std::move(id));
overload_decl.set_result(std::move(result));
overload_decl.set_member(false);
auto& mutable_args = overload_decl.mutable_args();
mutable_args.reserve(sizeof...(Args));
(mutable_args.push_back(std::forward<Args>(args)), ...);
return overload_decl;
}
template <typename... Args>
OverloadDecl MakeMemberOverloadDecl(std::string id, Type result,
Args&&... args) {
OverloadDecl overload_decl;
overload_decl.set_id(std::move(id));
overload_decl.set_result(std::move(result));
overload_decl.set_member(true);
auto& mutable_args = overload_decl.mutable_args();
mutable_args.reserve(sizeof...(Args));
(mutable_args.push_back(std::forward<Args>(args)), ...);
return overload_decl;
}
struct OverloadDeclHash {
using is_transparent = void;
size_t operator()(const OverloadDecl& overload_decl) const {
return (*this)(overload_decl.id());
}
size_t operator()(absl::string_view id) const { return absl::HashOf(id); }
};
struct OverloadDeclEqualTo {
using is_transparent = void;
bool operator()(const OverloadDecl& lhs, const OverloadDecl& rhs) const {
return (*this)(lhs.id(), rhs.id());
}
bool operator()(const OverloadDecl& lhs, absl::string_view rhs) const {
return (*this)(lhs.id(), rhs);
}
bool operator()(absl::string_view lhs, const OverloadDecl& rhs) const {
return (*this)(lhs, rhs.id());
}
bool operator()(absl::string_view lhs, absl::string_view rhs) const {
return lhs == rhs;
}
};
using OverloadDeclHashSet =
absl::flat_hash_set<OverloadDecl, OverloadDeclHash, OverloadDeclEqualTo>;
template <typename... Overloads>
absl::StatusOr<FunctionDecl> MakeFunctionDecl(std::string name,
Overloads&&... overloads);
class FunctionDecl final {
public:
FunctionDecl() = default;
FunctionDecl(const FunctionDecl&) = default;
FunctionDecl(FunctionDecl&&) = default;
FunctionDecl& operator=(const FunctionDecl&) = default;
FunctionDecl& operator=(FunctionDecl&&) = default;
ABSL_MUST_USE_RESULT const std::string& name() const
ABSL_ATTRIBUTE_LIFETIME_BOUND {
return name_;
}
void set_name(std::string name) { name_ = std::move(name); }
void set_name(absl::string_view name) {
name_.assign(name.data(), name.size());
}
void set_name(const char* name) { set_name(absl::NullSafeStringView(name)); }
ABSL_MUST_USE_RESULT std::string release_name() {
std::string released;
released.swap(name_);
return released;
}
absl::Status AddOverload(const OverloadDecl& overload) {
absl::Status status;
AddOverloadImpl(overload, status);
return status;
}
absl::Status AddOverload(OverloadDecl&& overload) {
absl::Status status;
AddOverloadImpl(std::move(overload), status);
return status;
}
ABSL_MUST_USE_RESULT const OverloadDeclHashSet& overloads() const
ABSL_ATTRIBUTE_LIFETIME_BOUND {
return overloads_;
}
ABSL_MUST_USE_RESULT OverloadDeclHashSet release_overloads() {
OverloadDeclHashSet released;
released.swap(overloads_);
return released;
}
private:
template <typename... Overloads>
friend absl::StatusOr<FunctionDecl> MakeFunctionDecl(
std::string name, Overloads&&... overloads);
void AddOverloadImpl(const OverloadDecl& overload, absl::Status& status);
void AddOverloadImpl(OverloadDecl&& overload, absl::Status& status);
std::string name_;
OverloadDeclHashSet overloads_;
};
inline bool operator==(const FunctionDecl& lhs, const FunctionDecl& rhs) {
return lhs.name() == rhs.name() &&
absl::c_equal(lhs.overloads(), rhs.overloads());
}
inline bool operator!=(const FunctionDecl& lhs, const FunctionDecl& rhs) {
return !operator==(lhs, rhs);
}
template <typename... Overloads>
absl::StatusOr<FunctionDecl> MakeFunctionDecl(std::string name,
Overloads&&... overloads) {
FunctionDecl function_decl;
function_decl.set_name(std::move(name));
function_decl.overloads_.reserve(sizeof...(Overloads));
absl::Status status;
(function_decl.AddOverloadImpl(std::forward<Overloads>(overloads), status),
...);
CEL_RETURN_IF_ERROR(status);
return function_decl;
}
namespace common_internal {
bool TypeIsAssignable(TypeView to, TypeView from);
}
}
#endif
#include "common/decl.h"
#include <cstddef>
#include <string>
#include <utility>
#include "absl/container/flat_hash_set.h"
#include "absl/log/absl_check.h"
#include "absl/status/status.h"
#include "absl/strings/str_cat.h"
#include "common/casting.h"
#include "common/type.h"
#include "common/type_kind.h"
namespace cel {
namespace common_internal {
bool TypeIsAssignable(TypeView to, TypeView from) {
if (to == from) {
return true;
}
const auto to_kind = to.kind();
if (to_kind == TypeKind::kDyn) {
return true;
}
switch (to_kind) {
case TypeKind::kBoolWrapper:
return TypeIsAssignable(NullTypeView{}, from) ||
TypeIsAssignable(BoolTypeView{}, from);
case TypeKind::kIntWrapper:
return TypeIsAssignable(NullTypeView{}, from) ||
TypeIsAssignable(IntTypeView{}, from);
case TypeKind::kUintWrapper:
return TypeIsAssignable(NullTypeView{}, from) ||
TypeIsAssignable(UintTypeView{}, from);
case TypeKind::kDoubleWrapper:
return TypeIsAssignable(NullTypeView{}, from) ||
TypeIsAssignable(DoubleTypeView{}, from);
case TypeKind::kBytesWrapper:
return TypeIsAssignable(NullTypeView{}, from) ||
TypeIsAssignable(BytesTypeView{}, from);
case TypeKind::kStringWrapper:
return TypeIsAssignable(NullTypeView{}, from) ||
TypeIsAssignable(StringTypeView{}, from);
default:
break;
}
const auto from_kind = from.kind();
if (to_kind != from_kind || to.name() != from.name()) {
return false;
}
const auto& to_params = to.parameters();
const auto& from_params = from.parameters();
const auto params_size = to_params.size();
if (params_size != from_params.size()) {
return false;
}
for (size_t i = 0; i < params_size; ++i) {
if (!TypeIsAssignable(to_params[i], from_params[i])) {
return false;
}
}
return true;
}
}
namespace {
bool SignaturesOverlap(const OverloadDecl& lhs, const OverloadDecl& rhs) {
if (lhs.member() != rhs.member()) {
return false;
}
const auto& lhs_args = lhs.args();
const auto& rhs_args = rhs.args();
const auto args_size = lhs_args.size();
if (args_size != rhs_args.size()) {
return false;
}
bool args_overlap = true;
for (size_t i = 0; i < args_size; ++i) {
args_overlap =
args_overlap &&
(common_internal::TypeIsAssignable(lhs_args[i], rhs_args[i]) ||
common_internal::TypeIsAssignable(rhs_args[i], lhs_args[i]));
}
return args_overlap;
}
template <typename Overload>
void AddOverloadInternal(OverloadDeclHashSet& overloads, Overload&& overload,
absl::Status& status) {
if (!status.ok()) {
return;
}
if (auto it = overloads.find(overload.id()); it != overloads.end()) {
status = absl::AlreadyExistsError(
absl::StrCat("overload already exists: ", overload.id()));
return;
}
for (const auto& existing : overloads) {
if (SignaturesOverlap(overload, existing)) {
status = absl::InvalidArgumentError(
absl::StrCat("overload signature collision: ", existing.id(),
" collides with ", overload.id()));
return;
}
}
const auto inserted =
overloads.insert(std::forward<Overload>(overload)).second;
ABSL_DCHECK(inserted);
}
void CollectTypeParams(absl::flat_hash_set<std::string>& type_params,
TypeView type) {
const auto kind = type.kind();
switch (kind) {
case TypeKind::kList: {
const auto& list_type = cel::Cast<ListTypeView>(type);
CollectTypeParams(type_params, list_type.element());
} break;
case TypeKind::kMap: {
const auto& map_type = cel::Cast<MapTypeView>(type);
CollectTypeParams(type_params, map_type.key());
CollectTypeParams(type_params, map_type.value());
} break;
case TypeKind::kOpaque: {
const auto& opaque_type = cel::Cast<OpaqueTypeView>(type);
for (const auto& param : opaque_type.parameters()) {
CollectTypeParams(type_params, param);
}
} break;
case TypeKind::kFunction: {
const auto& function_type = cel::Cast<FunctionTypeView>(type);
CollectTypeParams(type_params, function_type.result());
for (const auto& arg : function_type.args()) {
CollectTypeParams(type_params, arg);
}
} break;
case TypeKind::kTypeParam:
type_params.emplace(cel::Cast<TypeParamTypeView>(type).name());
break;
default:
break;
}
}
}
absl::flat_hash_set<std::string> OverloadDecl::GetTypeParams() const {
absl::flat_hash_set<std::string> type_params;
CollectTypeParams(type_params, result());
for (const auto& arg : args()) {
CollectTypeParams(type_params, arg);
}
return type_params;
}
void FunctionDecl::AddOverloadImpl(const OverloadDecl& overload,
absl::Status& status) {
AddOverloadInternal(overloads_, overload, status);
}
void FunctionDecl::AddOverloadImpl(OverloadDecl&& overload,
absl::Status& status) {
AddOverloadInternal(overloads_, std::move(overload), status);
}
} | #include "common/decl.h"
#include "absl/status/status.h"
#include "common/constant.h"
#include "common/memory.h"
#include "common/type.h"
#include "internal/testing.h"
namespace cel {
namespace {
using testing::ElementsAre;
using testing::IsEmpty;
using testing::UnorderedElementsAre;
using cel::internal::StatusIs;
TEST(VariableDecl, Name) {
VariableDecl variable_decl;
EXPECT_THAT(variable_decl.name(), IsEmpty());
variable_decl.set_name("foo");
EXPECT_EQ(variable_decl.name(), "foo");
EXPECT_EQ(variable_decl.release_name(), "foo");
EXPECT_THAT(variable_decl.name(), IsEmpty());
}
TEST(VariableDecl, Type) {
VariableDecl variable_decl;
EXPECT_EQ(variable_decl.type(), DynType{});
variable_decl.set_type(StringType{});
EXPECT_EQ(variable_decl.type(), StringType{});
}
TEST(VariableDecl, Value) {
VariableDecl variable_decl;
EXPECT_FALSE(variable_decl.has_value());
EXPECT_EQ(variable_decl.value(), Constant{});
Constant value;
value.set_bool_value(true);
variable_decl.set_value(value);
EXPECT_TRUE(variable_decl.has_value());
EXPECT_EQ(variable_decl.value(), value);
EXPECT_EQ(variable_decl.release_value(), value);
EXPECT_EQ(variable_decl.value(), Constant{});
}
Constant MakeBoolConstant(bool value) {
Constant constant;
constant.set_bool_value(value);
return constant;
}
TEST(VariableDecl, Equality) {
VariableDecl variable_decl;
EXPECT_EQ(variable_decl, VariableDecl{});
variable_decl.mutable_value().set_bool_value(true);
EXPECT_NE(variable_decl, VariableDecl{});
EXPECT_EQ(MakeVariableDecl("foo", StringType{}),
MakeVariableDecl("foo", StringType{}));
EXPECT_EQ(MakeVariableDecl("foo", StringType{}),
MakeVariableDecl("foo", StringType{}));
EXPECT_EQ(
MakeConstantVariableDecl("foo", StringType{}, MakeBoolConstant(true)),
MakeConstantVariableDecl("foo", StringType{}, MakeBoolConstant(true)));
EXPECT_EQ(
MakeConstantVariableDecl("foo", StringType{}, MakeBoolConstant(true)),
MakeConstantVariableDecl("foo", StringType{}, MakeBoolConstant(true)));
}
TEST(OverloadDecl, Id) {
OverloadDecl overload_decl;
EXPECT_THAT(overload_decl.id(), IsEmpty());
overload_decl.set_id("foo");
EXPECT_EQ(overload_decl.id(), "foo");
EXPECT_EQ(overload_decl.release_id(), "foo");
EXPECT_THAT(overload_decl.id(), IsEmpty());
}
TEST(OverloadDecl, Result) {
OverloadDecl overload_decl;
EXPECT_EQ(overload_decl.result(), DynType{});
overload_decl.set_result(StringType{});
EXPECT_EQ(overload_decl.result(), StringType{});
}
TEST(OverloadDecl, Args) {
OverloadDecl overload_decl;
EXPECT_THAT(overload_decl.args(), IsEmpty());
overload_decl.mutable_args().push_back(StringType{});
EXPECT_THAT(overload_decl.args(), ElementsAre(StringType{}));
EXPECT_THAT(overload_decl.release_args(), ElementsAre(StringType{}));
EXPECT_THAT(overload_decl.args(), IsEmpty());
}
TEST(OverloadDecl, Member) {
OverloadDecl overload_decl;
EXPECT_FALSE(overload_decl.member());
overload_decl.set_member(true);
EXPECT_TRUE(overload_decl.member());
}
TEST(OverloadDecl, Equality) {
OverloadDecl overload_decl;
EXPECT_EQ(overload_decl, OverloadDecl{});
overload_decl.set_member(true);
EXPECT_NE(overload_decl, OverloadDecl{});
}
TEST(OverloadDecl, GetTypeParams) {
auto memory_manager = MemoryManagerRef::ReferenceCounting();
auto overload_decl = MakeOverloadDecl(
"foo", ListType(memory_manager, TypeParamType(memory_manager, "A")),
MapType(memory_manager, TypeParamType(memory_manager, "B"),
TypeParamType(memory_manager, "C")),
OpaqueType(memory_manager, "bar",
{FunctionType(memory_manager,
TypeParamType(memory_manager, "D"), {})}));
EXPECT_THAT(overload_decl.GetTypeParams(),
UnorderedElementsAre("A", "B", "C", "D"));
}
TEST(FunctionDecl, Name) {
FunctionDecl function_decl;
EXPECT_THAT(function_decl.name(), IsEmpty());
function_decl.set_name("foo");
EXPECT_EQ(function_decl.name(), "foo");
EXPECT_EQ(function_decl.release_name(), "foo");
EXPECT_THAT(function_decl.name(), IsEmpty());
}
TEST(FunctionDecl, Overloads) {
ASSERT_OK_AND_ASSIGN(
auto function_decl,
MakeFunctionDecl(
"hello", MakeOverloadDecl("foo", StringType{}, StringType{}),
MakeMemberOverloadDecl("bar", StringType{}, StringType{})));
EXPECT_THAT(function_decl.AddOverload(
MakeOverloadDecl("baz", DynType{}, StringType{})),
StatusIs(absl::StatusCode::kInvalidArgument));
}
using common_internal::TypeIsAssignable;
TEST(TypeIsAssignable, BoolWrapper) {
EXPECT_TRUE(TypeIsAssignable(BoolWrapperTypeView{}, BoolWrapperTypeView{}));
EXPECT_TRUE(TypeIsAssignable(BoolWrapperTypeView{}, NullTypeView{}));
EXPECT_TRUE(TypeIsAssignable(BoolWrapperTypeView{}, BoolTypeView{}));
EXPECT_FALSE(TypeIsAssignable(BoolWrapperTypeView{}, DurationTypeView{}));
}
TEST(TypeIsAssignable, IntWrapper) {
EXPECT_TRUE(TypeIsAssignable(IntWrapperTypeView{}, IntWrapperTypeView{}));
EXPECT_TRUE(TypeIsAssignable(IntWrapperTypeView{}, NullTypeView{}));
EXPECT_TRUE(TypeIsAssignable(IntWrapperTypeView{}, IntTypeView{}));
EXPECT_FALSE(TypeIsAssignable(IntWrapperTypeView{}, DurationTypeView{}));
}
TEST(TypeIsAssignable, UintWrapper) {
EXPECT_TRUE(TypeIsAssignable(UintWrapperTypeView{}, UintWrapperTypeView{}));
EXPECT_TRUE(TypeIsAssignable(UintWrapperTypeView{}, NullTypeView{}));
EXPECT_TRUE(TypeIsAssignable(UintWrapperTypeView{}, UintTypeView{}));
EXPECT_FALSE(TypeIsAssignable(UintWrapperTypeView{}, DurationTypeView{}));
}
TEST(TypeIsAssignable, DoubleWrapper) {
EXPECT_TRUE(
TypeIsAssignable(DoubleWrapperTypeView{}, DoubleWrapperTypeView{}));
EXPECT_TRUE(TypeIsAssignable(DoubleWrapperTypeView{}, NullTypeView{}));
EXPECT_TRUE(TypeIsAssignable(DoubleWrapperTypeView{}, DoubleTypeView{}));
EXPECT_FALSE(TypeIsAssignable(DoubleWrapperTypeView{}, DurationTypeView{}));
}
TEST(TypeIsAssignable, BytesWrapper) {
EXPECT_TRUE(TypeIsAssignable(BytesWrapperTypeView{}, BytesWrapperTypeView{}));
EXPECT_TRUE(TypeIsAssignable(BytesWrapperTypeView{}, NullTypeView{}));
EXPECT_TRUE(TypeIsAssignable(BytesWrapperTypeView{}, BytesTypeView{}));
EXPECT_FALSE(TypeIsAssignable(BytesWrapperTypeView{}, DurationTypeView{}));
}
TEST(TypeIsAssignable, StringWrapper) {
EXPECT_TRUE(
TypeIsAssignable(StringWrapperTypeView{}, StringWrapperTypeView{}));
EXPECT_TRUE(TypeIsAssignable(StringWrapperTypeView{}, NullTypeView{}));
EXPECT_TRUE(TypeIsAssignable(StringWrapperTypeView{}, StringTypeView{}));
EXPECT_FALSE(TypeIsAssignable(StringWrapperTypeView{}, DurationTypeView{}));
}
TEST(TypeIsAssignable, Complex) {
auto memory_manager = MemoryManagerRef::ReferenceCounting();
EXPECT_TRUE(TypeIsAssignable(OptionalType(memory_manager, DynTypeView{}),
OptionalType(memory_manager, StringTypeView{})));
EXPECT_FALSE(
TypeIsAssignable(OptionalType(memory_manager, BoolTypeView{}),
OptionalType(memory_manager, StringTypeView{})));
}
}
} |
7 | cpp | google/cel-cpp | type_factory | null | null | #ifndef THIRD_PARTY_CEL_CPP_COMMON_TYPE_FACTORY_H_
#define THIRD_PARTY_CEL_CPP_COMMON_TYPE_FACTORY_H_
#include "absl/strings/string_view.h"
#include "common/memory.h"
#include "common/sized_input_view.h"
#include "common/type.h"
namespace cel {
namespace common_internal {
class PiecewiseValueManager;
}
class TypeFactory {
public:
virtual ~TypeFactory() = default;
virtual MemoryManagerRef GetMemoryManager() const = 0;
ListType CreateListType(TypeView element);
MapType CreateMapType(TypeView key, TypeView value);
StructType CreateStructType(absl::string_view name);
OpaqueType CreateOpaqueType(absl::string_view name,
const SizedInputView<TypeView>& parameters);
OptionalType CreateOptionalType(TypeView parameter);
ListTypeView GetDynListType();
MapTypeView GetDynDynMapType();
MapTypeView GetStringDynMapType();
OptionalTypeView GetDynOptionalType();
NullType GetNullType() { return NullType{}; }
ErrorType GetErrorType() { return ErrorType{}; }
DynType GetDynType() { return DynType{}; }
AnyType GetAnyType() { return AnyType{}; }
BoolType GetBoolType() { return BoolType{}; }
IntType GetIntType() { return IntType{}; }
UintType GetUintType() { return UintType{}; }
DoubleType GetDoubleType() { return DoubleType{}; }
StringType GetStringType() { return StringType{}; }
BytesType GetBytesType() { return BytesType{}; }
DurationType GetDurationType() { return DurationType{}; }
TimestampType GetTimestampType() { return TimestampType{}; }
TypeType GetTypeType() { return TypeType{}; }
UnknownType GetUnknownType() { return UnknownType{}; }
BoolWrapperType GetBoolWrapperType() { return BoolWrapperType{}; }
BytesWrapperType GetBytesWrapperType() { return BytesWrapperType{}; }
DoubleWrapperType GetDoubleWrapperType() { return DoubleWrapperType{}; }
IntWrapperType GetIntWrapperType() { return IntWrapperType{}; }
StringWrapperType GetStringWrapperType() { return StringWrapperType{}; }
UintWrapperType GetUintWrapperType() { return UintWrapperType{}; }
Type GetJsonValueType() { return DynType{}; }
ListType GetJsonListType() { return ListType(GetDynListType()); }
MapType GetJsonMapType() { return MapType(GetStringDynMapType()); }
protected:
friend class common_internal::PiecewiseValueManager;
virtual ListType CreateListTypeImpl(TypeView element) = 0;
virtual MapType CreateMapTypeImpl(TypeView key, TypeView value) = 0;
virtual StructType CreateStructTypeImpl(absl::string_view name) = 0;
virtual OpaqueType CreateOpaqueTypeImpl(
absl::string_view name, const SizedInputView<TypeView>& parameters) = 0;
};
}
#endif
#include "common/type_factory.h"
#include "absl/base/attributes.h"
#include "absl/log/absl_check.h"
#include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "common/casting.h"
#include "common/sized_input_view.h"
#include "common/type.h"
#include "common/type_kind.h"
#include "common/types/type_cache.h"
#include "internal/names.h"
namespace cel {
namespace {
using common_internal::ListTypeCacheMap;
using common_internal::MapTypeCacheMap;
using common_internal::OpaqueTypeCacheMap;
using common_internal::ProcessLocalTypeCache;
using common_internal::StructTypeCacheMap;
bool IsValidMapKeyType(TypeView type) {
switch (type.kind()) {
case TypeKind::kDyn:
ABSL_FALLTHROUGH_INTENDED;
case TypeKind::kError:
ABSL_FALLTHROUGH_INTENDED;
case TypeKind::kBool:
ABSL_FALLTHROUGH_INTENDED;
case TypeKind::kInt:
ABSL_FALLTHROUGH_INTENDED;
case TypeKind::kUint:
ABSL_FALLTHROUGH_INTENDED;
case TypeKind::kString:
return true;
default:
return false;
}
}
}
ListType TypeFactory::CreateListType(TypeView element) {
if (auto list_type = ProcessLocalTypeCache::Get()->FindListType(element);
list_type.has_value()) {
return ListType(*list_type);
}
return CreateListTypeImpl(element);
}
MapType TypeFactory::CreateMapType(TypeView key, TypeView value) {
ABSL_DCHECK(IsValidMapKeyType(key)) << key;
if (auto map_type = ProcessLocalTypeCache::Get()->FindMapType(key, value);
map_type.has_value()) {
return MapType(*map_type);
}
return CreateMapTypeImpl(key, value);
}
StructType TypeFactory::CreateStructType(absl::string_view name) {
ABSL_DCHECK(internal::IsValidRelativeName(name)) << name;
return CreateStructTypeImpl(name);
}
OpaqueType TypeFactory::CreateOpaqueType(
absl::string_view name, const SizedInputView<TypeView>& parameters) {
ABSL_DCHECK(internal::IsValidRelativeName(name)) << name;
if (auto opaque_type =
ProcessLocalTypeCache::Get()->FindOpaqueType(name, parameters);
opaque_type.has_value()) {
return OpaqueType(*opaque_type);
}
return CreateOpaqueTypeImpl(name, parameters);
}
OptionalType TypeFactory::CreateOptionalType(TypeView parameter) {
return Cast<OptionalType>(CreateOpaqueType(OptionalType::kName, {parameter}));
}
ListTypeView TypeFactory::GetDynListType() {
return ProcessLocalTypeCache::Get()->GetDynListType();
}
MapTypeView TypeFactory::GetDynDynMapType() {
return ProcessLocalTypeCache::Get()->GetDynDynMapType();
}
MapTypeView TypeFactory::GetStringDynMapType() {
return ProcessLocalTypeCache::Get()->GetStringDynMapType();
}
OptionalTypeView TypeFactory::GetDynOptionalType() {
return ProcessLocalTypeCache::Get()->GetDynOptionalType();
}
} | #include "common/type_factory.h"
#include <ostream>
#include <sstream>
#include <string>
#include <tuple>
#include "absl/types/optional.h"
#include "common/memory.h"
#include "common/memory_testing.h"
#include "common/type.h"
#include "common/type_introspector.h"
#include "common/type_manager.h"
#include "common/types/type_cache.h"
#include "internal/testing.h"
namespace cel {
namespace {
using common_internal::ProcessLocalTypeCache;
using testing::_;
using testing::Eq;
using testing::Ne;
using testing::TestParamInfo;
using testing::TestWithParam;
enum class ThreadSafety {
kCompatible,
kSafe,
};
std::ostream& operator<<(std::ostream& out, ThreadSafety thread_safety) {
switch (thread_safety) {
case ThreadSafety::kCompatible:
return out << "THREAD_SAFE";
case ThreadSafety::kSafe:
return out << "THREAD_COMPATIBLE";
}
}
class TypeFactoryTest
: public common_internal::ThreadCompatibleMemoryTest<ThreadSafety> {
public:
void SetUp() override {
ThreadCompatibleMemoryTest::SetUp();
switch (thread_safety()) {
case ThreadSafety::kCompatible:
type_manager_ = NewThreadCompatibleTypeManager(
memory_manager(),
NewThreadCompatibleTypeIntrospector(memory_manager()));
break;
case ThreadSafety::kSafe:
type_manager_ = NewThreadSafeTypeManager(
memory_manager(), NewThreadSafeTypeIntrospector(memory_manager()));
break;
}
}
void TearDown() override { Finish(); }
void Finish() {
type_manager_.reset();
ThreadCompatibleMemoryTest::Finish();
}
TypeFactory& type_factory() const { return **type_manager_; }
ThreadSafety thread_safety() const { return std::get<1>(GetParam()); }
static std::string ToString(
TestParamInfo<std::tuple<MemoryManagement, ThreadSafety>> param) {
std::ostringstream out;
out << std::get<0>(param.param) << "_" << std::get<1>(param.param);
return out.str();
}
private:
absl::optional<Shared<TypeManager>> type_manager_;
};
TEST_P(TypeFactoryTest, ListType) {
auto list_type1 = type_factory().CreateListType(StringType());
EXPECT_THAT(type_factory().CreateListType(StringType()), Eq(list_type1));
EXPECT_THAT(type_factory().CreateListType(BytesType()), Ne(list_type1));
auto struct_type1 = type_factory().CreateStructType("test.Struct1");
auto struct_type2 = type_factory().CreateStructType("test.Struct2");
auto list_type2 = type_factory().CreateListType(struct_type1);
EXPECT_THAT(type_factory().CreateListType(struct_type1), Eq(list_type2));
EXPECT_THAT(type_factory().CreateListType(struct_type2), Ne(list_type2));
EXPECT_EQ(type_factory().GetDynListType(),
ProcessLocalTypeCache::Get()->GetDynListType());
}
TEST_P(TypeFactoryTest, MapType) {
auto map_type1 = type_factory().CreateMapType(StringType(), BytesType());
EXPECT_THAT(type_factory().CreateMapType(StringType(), BytesType()),
Eq(map_type1));
EXPECT_THAT(type_factory().CreateMapType(StringType(), StringType()),
Ne(map_type1));
auto struct_type1 = type_factory().CreateStructType("test.Struct1");
auto struct_type2 = type_factory().CreateStructType("test.Struct2");
auto map_type2 = type_factory().CreateMapType(StringType(), struct_type1);
EXPECT_THAT(type_factory().CreateMapType(StringType(), struct_type1),
Eq(map_type2));
EXPECT_THAT(type_factory().CreateMapType(StringType(), struct_type2),
Ne(map_type2));
EXPECT_EQ(type_factory().GetDynDynMapType(),
ProcessLocalTypeCache::Get()->GetDynDynMapType());
EXPECT_EQ(type_factory().GetStringDynMapType(),
ProcessLocalTypeCache::Get()->GetStringDynMapType());
}
TEST_P(TypeFactoryTest, MapTypeInvalidKeyType) {
EXPECT_DEBUG_DEATH(type_factory().CreateMapType(DoubleType(), BytesType()),
_);
}
TEST_P(TypeFactoryTest, StructType) {
auto struct_type1 = type_factory().CreateStructType("test.Struct1");
EXPECT_THAT(type_factory().CreateStructType("test.Struct1"),
Eq(struct_type1));
EXPECT_THAT(type_factory().CreateStructType("test.Struct2"),
Ne(struct_type1));
}
TEST_P(TypeFactoryTest, StructTypeBadName) {
EXPECT_DEBUG_DEATH(type_factory().CreateStructType("test.~"), _);
}
TEST_P(TypeFactoryTest, OpaqueType) {
auto opaque_type1 =
type_factory().CreateOpaqueType("test.Struct1", {BytesType()});
EXPECT_THAT(type_factory().CreateOpaqueType("test.Struct1", {BytesType()}),
Eq(opaque_type1));
EXPECT_THAT(type_factory().CreateOpaqueType("test.Struct2", {}),
Ne(opaque_type1));
}
TEST_P(TypeFactoryTest, OpaqueTypeBadName) {
EXPECT_DEBUG_DEATH(type_factory().CreateOpaqueType("test.~", {}), _);
}
TEST_P(TypeFactoryTest, OptionalType) {
auto optional_type1 = type_factory().CreateOptionalType(StringType());
EXPECT_THAT(type_factory().CreateOptionalType(StringType()),
Eq(optional_type1));
EXPECT_THAT(type_factory().CreateOptionalType(BytesType()),
Ne(optional_type1));
auto struct_type1 = type_factory().CreateStructType("test.Struct1");
auto struct_type2 = type_factory().CreateStructType("test.Struct2");
auto optional_type2 = type_factory().CreateOptionalType(struct_type1);
EXPECT_THAT(type_factory().CreateOptionalType(struct_type1),
Eq(optional_type2));
EXPECT_THAT(type_factory().CreateOptionalType(struct_type2),
Ne(optional_type2));
EXPECT_EQ(type_factory().GetDynOptionalType(),
ProcessLocalTypeCache::Get()->GetDynOptionalType());
}
INSTANTIATE_TEST_SUITE_P(
TypeFactoryTest, TypeFactoryTest,
::testing::Combine(::testing::Values(MemoryManagement::kPooling,
MemoryManagement::kReferenceCounting),
::testing::Values(ThreadSafety::kCompatible,
ThreadSafety::kSafe)),
TypeFactoryTest::ToString);
}
} |
8 | cpp | google/cel-cpp | ast_traverse | eval/public/ast_traverse.cc | eval/public/ast_traverse_test.cc | #ifndef THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_AST_TRAVERSE_H_
#define THIRD_PARTY_CEL_CPP_EVAL_PUBLIC_AST_TRAVERSE_H_
#include "google/api/expr/v1alpha1/syntax.pb.h"
#include "eval/public/ast_visitor.h"
namespace google::api::expr::runtime {
struct TraversalOptions {
bool use_comprehension_callbacks;
TraversalOptions() : use_comprehension_callbacks(false) {}
};
void AstTraverse(const google::api::expr::v1alpha1::Expr* expr,
const google::api::expr::v1alpha1::SourceInfo* source_info,
AstVisitor* visitor,
TraversalOptions options = TraversalOptions());
}
#endif
#include "eval/public/ast_traverse.h"
#include <stack>
#include "google/api/expr/v1alpha1/syntax.pb.h"
#include "absl/log/absl_log.h"
#include "absl/types/variant.h"
#include "eval/public/ast_visitor.h"
#include "eval/public/source_position.h"
namespace google::api::expr::runtime {
using google::api::expr::v1alpha1::Expr;
using google::api::expr::v1alpha1::SourceInfo;
using Ident = google::api::expr::v1alpha1::Expr::Ident;
using Select = google::api::expr::v1alpha1::Expr::Select;
using Call = google::api::expr::v1alpha1::Expr::Call;
using CreateList = google::api::expr::v1alpha1::Expr::CreateList;
using CreateStruct = google::api::expr::v1alpha1::Expr::CreateStruct;
using Comprehension = google::api::expr::v1alpha1::Expr::Comprehension;
namespace {
struct ArgRecord {
const Expr* expr;
const SourceInfo* source_info;
const Expr* calling_expr;
int call_arg;
};
struct ComprehensionRecord {
const Expr* expr;
const SourceInfo* source_info;
const Comprehension* comprehension;
const Expr* comprehension_expr;
ComprehensionArg comprehension_arg;
bool use_comprehension_callbacks;
};
struct ExprRecord {
const Expr* expr;
const SourceInfo* source_info;
};
using StackRecordKind =
absl::variant<ExprRecord, ArgRecord, ComprehensionRecord>;
struct StackRecord {
public:
ABSL_ATTRIBUTE_UNUSED static constexpr int kNotCallArg = -1;
static constexpr int kTarget = -2;
StackRecord(const Expr* e, const SourceInfo* info) {
ExprRecord record;
record.expr = e;
record.source_info = info;
record_variant = record;
}
StackRecord(const Expr* e, const SourceInfo* info,
const Comprehension* comprehension,
const Expr* comprehension_expr,
ComprehensionArg comprehension_arg,
bool use_comprehension_callbacks) {
if (use_comprehension_callbacks) {
ComprehensionRecord record;
record.expr = e;
record.source_info = info;
record.comprehension = comprehension;
record.comprehension_expr = comprehension_expr;
record.comprehension_arg = comprehension_arg;
record.use_comprehension_callbacks = use_comprehension_callbacks;
record_variant = record;
return;
}
ArgRecord record;
record.expr = e;
record.source_info = info;
record.calling_expr = comprehension_expr;
record.call_arg = comprehension_arg;
record_variant = record;
}
StackRecord(const Expr* e, const SourceInfo* info, const Expr* call,
int argnum) {
ArgRecord record;
record.expr = e;
record.source_info = info;
record.calling_expr = call;
record.call_arg = argnum;
record_variant = record;
}
StackRecordKind record_variant;
bool visited = false;
};
struct PreVisitor {
void operator()(const ExprRecord& record) {
const Expr* expr = record.expr;
const SourcePosition position(expr->id(), record.source_info);
visitor->PreVisitExpr(expr, &position);
switch (expr->expr_kind_case()) {
case Expr::kConstExpr:
visitor->PreVisitConst(&expr->const_expr(), expr, &position);
break;
case Expr::kIdentExpr:
visitor->PreVisitIdent(&expr->ident_expr(), expr, &position);
break;
case Expr::kSelectExpr:
visitor->PreVisitSelect(&expr->select_expr(), expr, &position);
break;
case Expr::kCallExpr:
visitor->PreVisitCall(&expr->call_expr(), expr, &position);
break;
case Expr::kListExpr:
visitor->PreVisitCreateList(&expr->list_expr(), expr, &position);
break;
case Expr::kStructExpr:
visitor->PreVisitCreateStruct(&expr->struct_expr(), expr, &position);
break;
case Expr::kComprehensionExpr:
visitor->PreVisitComprehension(&expr->comprehension_expr(), expr,
&position);
break;
default:
break;
}
}
void operator()(const ArgRecord&) {}
void operator()(const ComprehensionRecord& record) {
const Expr* expr = record.expr;
const SourcePosition position(expr->id(), record.source_info);
visitor->PreVisitComprehensionSubexpression(
expr, record.comprehension, record.comprehension_arg, &position);
}
AstVisitor* visitor;
};
void PreVisit(const StackRecord& record, AstVisitor* visitor) {
absl::visit(PreVisitor{visitor}, record.record_variant);
}
struct PostVisitor {
void operator()(const ExprRecord& record) {
const Expr* expr = record.expr;
const SourcePosition position(expr->id(), record.source_info);
switch (expr->expr_kind_case()) {
case Expr::kConstExpr:
visitor->PostVisitConst(&expr->const_expr(), expr, &position);
break;
case Expr::kIdentExpr:
visitor->PostVisitIdent(&expr->ident_expr(), expr, &position);
break;
case Expr::kSelectExpr:
visitor->PostVisitSelect(&expr->select_expr(), expr, &position);
break;
case Expr::kCallExpr:
visitor->PostVisitCall(&expr->call_expr(), expr, &position);
break;
case Expr::kListExpr:
visitor->PostVisitCreateList(&expr->list_expr(), expr, &position);
break;
case Expr::kStructExpr:
visitor->PostVisitCreateStruct(&expr->struct_expr(), expr, &position);
break;
case Expr::kComprehensionExpr:
visitor->PostVisitComprehension(&expr->comprehension_expr(), expr,
&position);
break;
default:
ABSL_LOG(ERROR) << "Unsupported Expr kind: " << expr->expr_kind_case();
}
visitor->PostVisitExpr(expr, &position);
}
void operator()(const ArgRecord& record) {
const Expr* expr = record.expr;
const SourcePosition position(expr->id(), record.source_info);
if (record.call_arg == StackRecord::kTarget) {
visitor->PostVisitTarget(record.calling_expr, &position);
} else {
visitor->PostVisitArg(record.call_arg, record.calling_expr, &position);
}
}
void operator()(const ComprehensionRecord& record) {
const Expr* expr = record.expr;
const SourcePosition position(expr->id(), record.source_info);
visitor->PostVisitComprehensionSubexpression(
expr, record.comprehension, record.comprehension_arg, &position);
}
AstVisitor* visitor;
};
void PostVisit(const StackRecord& record, AstVisitor* visitor) {
absl::visit(PostVisitor{visitor}, record.record_variant);
}
void PushSelectDeps(const Select* select_expr, const SourceInfo* source_info,
std::stack<StackRecord>* stack) {
if (select_expr->has_operand()) {
stack->push(StackRecord(&select_expr->operand(), source_info));
}
}
void PushCallDeps(const Call* call_expr, const Expr* expr,
const SourceInfo* source_info,
std::stack<StackRecord>* stack) {
const int arg_size = call_expr->args_size();
for (int i = arg_size - 1; i >= 0; --i) {
stack->push(StackRecord(&call_expr->args(i), source_info, expr, i));
}
if (call_expr->has_target()) {
stack->push(StackRecord(&call_expr->target(), source_info, expr,
StackRecord::kTarget));
}
}
void PushListDeps(const CreateList* list_expr, const SourceInfo* source_info,
std::stack<StackRecord>* stack) {
const auto& elements = list_expr->elements();
for (auto it = elements.rbegin(); it != elements.rend(); ++it) {
const auto& element = *it;
stack->push(StackRecord(&element, source_info));
}
}
void PushStructDeps(const CreateStruct* struct_expr,
const SourceInfo* source_info,
std::stack<StackRecord>* stack) {
const auto& entries = struct_expr->entries();
for (auto it = entries.rbegin(); it != entries.rend(); ++it) {
const auto& entry = *it;
if (entry.has_value()) {
stack->push(StackRecord(&entry.value(), source_info));
}
if (entry.has_map_key()) {
stack->push(StackRecord(&entry.map_key(), source_info));
}
}
}
void PushComprehensionDeps(const Comprehension* c, const Expr* expr,
const SourceInfo* source_info,
std::stack<StackRecord>* stack,
bool use_comprehension_callbacks) {
StackRecord iter_range(&c->iter_range(), source_info, c, expr, ITER_RANGE,
use_comprehension_callbacks);
StackRecord accu_init(&c->accu_init(), source_info, c, expr, ACCU_INIT,
use_comprehension_callbacks);
StackRecord loop_condition(&c->loop_condition(), source_info, c, expr,
LOOP_CONDITION, use_comprehension_callbacks);
StackRecord loop_step(&c->loop_step(), source_info, c, expr, LOOP_STEP,
use_comprehension_callbacks);
StackRecord result(&c->result(), source_info, c, expr, RESULT,
use_comprehension_callbacks);
stack->push(result);
stack->push(loop_step);
stack->push(loop_condition);
stack->push(accu_init);
stack->push(iter_range);
}
struct PushDepsVisitor {
void operator()(const ExprRecord& record) {
const Expr* expr = record.expr;
switch (expr->expr_kind_case()) {
case Expr::kSelectExpr:
PushSelectDeps(&expr->select_expr(), record.source_info, &stack);
break;
case Expr::kCallExpr:
PushCallDeps(&expr->call_expr(), expr, record.source_info, &stack);
break;
case Expr::kListExpr:
PushListDeps(&expr->list_expr(), record.source_info, &stack);
break;
case Expr::kStructExpr:
PushStructDeps(&expr->struct_expr(), record.source_info, &stack);
break;
case Expr::kComprehensionExpr:
PushComprehensionDeps(&expr->comprehension_expr(), expr,
record.source_info, &stack,
options.use_comprehension_callbacks);
break;
default:
break;
}
}
void operator()(const ArgRecord& record) {
stack.push(StackRecord(record.expr, record.source_info));
}
void operator()(const ComprehensionRecord& record) {
stack.push(StackRecord(record.expr, record.source_info));
}
std::stack<StackRecord>& stack;
const TraversalOptions& options;
};
void PushDependencies(const StackRecord& record, std::stack<StackRecord>& stack,
const TraversalOptions& options) {
absl::visit(PushDepsVisitor{stack, options}, record.record_variant);
}
}
void AstTraverse(const Expr* expr, const SourceInfo* source_info,
AstVisitor* visitor, TraversalOptions options) {
std::stack<StackRecord> stack;
stack.push(StackRecord(expr, source_info));
while (!stack.empty()) {
StackRecord& record = stack.top();
if (!record.visited) {
PreVisit(record, visitor);
PushDependencies(record, stack, options);
record.visited = true;
} else {
PostVisit(record, visitor);
stack.pop();
}
}
}
} | #include "eval/public/ast_traverse.h"
#include "eval/public/ast_visitor.h"
#include "internal/testing.h"
namespace google::api::expr::runtime {
namespace {
using google::api::expr::v1alpha1::Constant;
using google::api::expr::v1alpha1::Expr;
using google::api::expr::v1alpha1::SourceInfo;
using testing::_;
using Ident = google::api::expr::v1alpha1::Expr::Ident;
using Select = google::api::expr::v1alpha1::Expr::Select;
using Call = google::api::expr::v1alpha1::Expr::Call;
using CreateList = google::api::expr::v1alpha1::Expr::CreateList;
using CreateStruct = google::api::expr::v1alpha1::Expr::CreateStruct;
using Comprehension = google::api::expr::v1alpha1::Expr::Comprehension;
class MockAstVisitor : public AstVisitor {
public:
MOCK_METHOD(void, PreVisitExpr,
(const Expr* expr, const SourcePosition* position), (override));
MOCK_METHOD(void, PostVisitExpr,
(const Expr* expr, const SourcePosition* position), (override));
MOCK_METHOD(void, PreVisitConst,
(const Constant* const_expr, const Expr* expr,
const SourcePosition* position),
(override));
MOCK_METHOD(void, PostVisitConst,
(const Constant* const_expr, const Expr* expr,
const SourcePosition* position),
(override));
MOCK_METHOD(void, PreVisitIdent,
(const Ident* ident_expr, const Expr* expr,
const SourcePosition* position),
(override));
MOCK_METHOD(void, PostVisitIdent,
(const Ident* ident_expr, const Expr* expr,
const SourcePosition* position),
(override));
MOCK_METHOD(void, PreVisitSelect,
(const Select* select_expr, const Expr* expr,
const SourcePosition* position),
(override));
MOCK_METHOD(void, PostVisitSelect,
(const Select* select_expr, const Expr* expr,
const SourcePosition* position),
(override));
MOCK_METHOD(void, PreVisitCall,
(const Call* call_expr, const Expr* expr,
const SourcePosition* position),
(override));
MOCK_METHOD(void, PostVisitCall,
(const Call* call_expr, const Expr* expr,
const SourcePosition* position),
(override));
MOCK_METHOD(void, PreVisitComprehension,
(const Comprehension* comprehension_expr, const Expr* expr,
const SourcePosition* position),
(override));
MOCK_METHOD(void, PostVisitComprehension,
(const Comprehension* comprehension_expr, const Expr* expr,
const SourcePosition* position),
(override));
MOCK_METHOD(void, PreVisitComprehensionSubexpression,
(const Expr* expr, const Comprehension* comprehension_expr,
ComprehensionArg comprehension_arg,
const SourcePosition* position),
(override));
MOCK_METHOD(void, PostVisitComprehensionSubexpression,
(const Expr* expr, const Comprehension* comprehension_expr,
ComprehensionArg comprehension_arg,
const SourcePosition* position),
(override));
MOCK_METHOD(void, PostVisitTarget,
(const Expr* expr, const SourcePosition* position), (override));
MOCK_METHOD(void, PostVisitArg,
(int arg_num, const Expr* expr, const SourcePosition* position),
(override));
MOCK_METHOD(void, PreVisitCreateList,
(const CreateList* list_expr, const Expr* expr,
const SourcePosition* position),
(override));
MOCK_METHOD(void, PostVisitCreateList,
(const CreateList* list_expr, const Expr* expr,
const SourcePosition* position),
(override));
MOCK_METHOD(void, PreVisitCreateStruct,
(const CreateStruct* struct_expr, const Expr* expr,
const SourcePosition* position),
(override));
MOCK_METHOD(void, PostVisitCreateStruct,
(const CreateStruct* struct_expr, const Expr* expr,
const SourcePosition* position),
(override));
};
TEST(AstCrawlerTest, CheckCrawlConstant) {
SourceInfo source_info;
MockAstVisitor handler;
Expr expr;
auto const_expr = expr.mutable_const_expr();
EXPECT_CALL(handler, PreVisitConst(const_expr, &expr, _)).Times(1);
EXPECT_CALL(handler, PostVisitConst(const_expr, &expr, _)).Times(1);
AstTraverse(&expr, &source_info, &handler);
}
TEST(AstCrawlerTest, CheckCrawlIdent) {
SourceInfo source_info;
MockAstVisitor handler;
Expr expr;
auto ident_expr = expr.mutable_ident_expr();
EXPECT_CALL(handler, PreVisitIdent(ident_expr, &expr, _)).Times(1);
EXPECT_CALL(handler, PostVisitIdent(ident_expr, &expr, _)).Times(1);
AstTraverse(&expr, &source_info, &handler);
}
TEST(AstCrawlerTest, CheckCrawlSelectNotCrashingPostVisitAbsentOperand) {
SourceInfo source_info;
MockAstVisitor handler;
Expr expr;
auto select_expr = expr.mutable_select_expr();
EXPECT_CALL(handler, PostVisitSelect(select_expr, &expr, _)).Times(1);
AstTraverse(&expr, &source_info, &handler);
}
TEST(AstCrawlerTest, CheckCrawlSelect) {
SourceInfo source_info;
MockAstVisitor handler;
Expr expr;
auto select_expr = expr.mutable_select_expr();
auto operand = select_expr->mutable_operand();
auto ident_expr = operand->mutable_ident_expr();
testing::InSequence seq;
EXPECT_CALL(handler, PostVisitIdent(ident_expr, operand, _)).Times(1);
EXPECT_CALL(handler, PostVisitSelect(select_expr, &expr, _)).Times(1);
AstTraverse(&expr, &source_info, &handler);
}
TEST(AstCrawlerTest, CheckCrawlCallNoReceiver) {
SourceInfo source_info;
MockAstVisitor handler;
Expr expr;
auto* call_expr = expr.mutable_call_expr();
Expr* arg0 = call_expr->add_args();
auto* const_expr = arg0->mutable_const_expr();
Expr* arg1 = call_expr->add_args();
auto* ident_expr = arg1->mutable_ident_expr();
testing::InSequence seq;
EXPECT_CALL(handler, PreVisitCall(call_expr, &expr, _)).Times(1);
EXPECT_CALL(handler, PostVisitTarget(_, _)).Times(0);
EXPECT_CALL(handler, PostVisitConst(const_expr, arg0, _)).Times(1);
EXPECT_CALL(handler, PostVisitExpr(arg0, _)).Times(1);
EXPECT_CALL(handler, PostVisitArg(0, &expr, _)).Times(1);
EXPECT_CALL(handler, PostVisitIdent(ident_expr, arg1, _)).Times(1);
EXPECT_CALL(handler, PostVisitExpr(arg1, _)).Times(1);
EXPECT_CALL(handler, PostVisitArg(1, &expr, _)).Times(1);
EXPECT_CALL(handler, PostVisitCall(call_expr, &expr, _)).Times(1);
EXPECT_CALL(handler, PostVisitExpr(&expr, _)).Times(1);
AstTraverse(&expr, &source_info, &handler);
}
TEST(AstCrawlerTest, CheckCrawlCallReceiver) {
SourceInfo source_info;
MockAstVisitor handler;
Expr expr;
auto* call_expr = expr.mutable_call_expr();
Expr* target = call_expr->mutable_target();
auto* target_ident = target->mutable_ident_expr();
Expr* arg0 = call_expr->add_args();
auto* const_expr = arg0->mutable_const_expr();
Expr* arg1 = call_expr->add_args();
auto* ident_expr = arg1->mutable_ident_expr();
testing::InSequence seq;
EXPECT_CALL(handler, PreVisitCall(call_expr, &expr, _)).Times(1);
EXPECT_CALL(handler, PostVisitIdent(target_ident, target, _)).Times(1);
EXPECT_CALL(handler, PostVisitExpr(target, _)).Times(1);
EXPECT_CALL(handler, PostVisitTarget(&expr, _)).Times(1);
EXPECT_CALL(handler, PostVisitConst(const_expr, arg0, _)).Times(1);
EXPECT_CALL(handler, PostVisitExpr(arg0, _)).Times(1);
EXPECT_CALL(handler, PostVisitArg(0, &expr, _)).Times(1);
EXPECT_CALL(handler, PostVisitIdent(ident_expr, arg1, _)).Times(1);
EXPECT_CALL(handler, PostVisitExpr(arg1, _)).Times(1);
EXPECT_CALL(handler, PostVisitArg(1, &expr, _)).Times(1);
EXPECT_CALL(handler, PostVisitCall(call_expr, &expr, _)).Times(1);
EXPECT_CALL(handler, PostVisitExpr(&expr, _)).Times(1);
AstTraverse(&expr, &source_info, &handler);
}
TEST(AstCrawlerTest, CheckCrawlComprehension) {
SourceInfo source_info;
MockAstVisitor handler;
Expr expr;
auto c = expr.mutable_comprehension_expr();
auto iter_range = c->mutable_iter_range();
auto iter_range_expr = iter_range->mutable_const_expr();
auto accu_init = c->mutable_accu_init();
auto accu_init_expr = accu_init->mutable_ident_expr();
auto loop_condition = c->mutable_loop_condition();
auto loop_condition_expr = loop_condition->mutable_const_expr();
auto loop_step = c->mutable_loop_step();
auto loop_step_expr = loop_step->mutable_ident_expr();
auto result = c->mutable_result();
auto result_expr = result->mutable_const_expr();
testing::InSequence seq;
EXPECT_CALL(handler, PreVisitComprehension(c, &expr, _)).Times(1);
EXPECT_CALL(handler,
PreVisitComprehensionSubexpression(iter_range, c, ITER_RANGE, _))
.Times(1);
EXPECT_CALL(handler, PostVisitConst(iter_range_expr, iter_range, _)).Times(1);
EXPECT_CALL(handler,
PostVisitComprehensionSubexpression(iter_range, c, ITER_RANGE, _))
.Times(1);
EXPECT_CALL(handler,
PreVisitComprehensionSubexpression(accu_init, c, ACCU_INIT, _))
.Times(1);
EXPECT_CALL(handler, PostVisitIdent(accu_init_expr, accu_init, _)).Times(1);
EXPECT_CALL(handler,
PostVisitComprehensionSubexpression(accu_init, c, ACCU_INIT, _))
.Times(1);
EXPECT_CALL(handler, PreVisitComprehensionSubexpression(loop_condition, c,
LOOP_CONDITION, _))
.Times(1);
EXPECT_CALL(handler, PostVisitConst(loop_condition_expr, loop_condition, _))
.Times(1);
EXPECT_CALL(handler, PostVisitComprehensionSubexpression(loop_condition, c,
LOOP_CONDITION, _))
.Times(1);
EXPECT_CALL(handler,
PreVisitComprehensionSubexpression(loop_step, c, LOOP_STEP, _))
.Times(1);
EXPECT_CALL(handler, PostVisitIdent(loop_step_expr, loop_step, _)).Times(1);
EXPECT_CALL(handler,
PostVisitComprehensionSubexpression(loop_step, c, LOOP_STEP, _))
.Times(1);
EXPECT_CALL(handler, PreVisitComprehensionSubexpression(result, c, RESULT, _))
.Times(1);
EXPECT_CALL(handler, PostVisitConst(result_expr, result, _)).Times(1);
EXPECT_CALL(handler,
PostVisitComprehensionSubexpression(result, c, RESULT, _))
.Times(1);
EXPECT_CALL(handler, PostVisitComprehension(c, &expr, _)).Times(1);
TraversalOptions opts;
opts.use_comprehension_callbacks = true;
AstTraverse(&expr, &source_info, &handler, opts);
}
TEST(AstCrawlerTest, CheckCrawlComprehensionLegacyCallbacks) {
SourceInfo source_info;
MockAstVisitor handler;
Expr expr;
auto c = expr.mutable_comprehension_expr();
auto iter_range = c->mutable_iter_range();
auto iter_range_expr = iter_range->mutable_const_expr();
auto accu_init = c->mutable_accu_init();
auto accu_init_expr = accu_init->mutable_ident_expr();
auto loop_condition = c->mutable_loop_condition();
auto loop_condition_expr = loop_condition->mutable_const_expr();
auto loop_step = c->mutable_loop_step();
auto loop_step_expr = loop_step->mutable_ident_expr();
auto result = c->mutable_result();
auto result_expr = result->mutable_const_expr();
testing::InSequence seq;
EXPECT_CALL(handler, PreVisitComprehension(c, &expr, _)).Times(1);
EXPECT_CALL(handler, PostVisitConst(iter_range_expr, iter_range, _)).Times(1);
EXPECT_CALL(handler, PostVisitArg(ITER_RANGE, &expr, _)).Times(1);
EXPECT_CALL(handler, PostVisitIdent(accu_init_expr, accu_init, _)).Times(1);
EXPECT_CALL(handler, PostVisitArg(ACCU_INIT, &expr, _)).Times(1);
EXPECT_CALL(handler, PostVisitConst(loop_condition_expr, loop_condition, _))
.Times(1);
EXPECT_CALL(handler, PostVisitArg(LOOP_CONDITION, &expr, _)).Times(1);
EXPECT_CALL(handler, PostVisitIdent(loop_step_expr, loop_step, _)).Times(1);
EXPECT_CALL(handler, PostVisitArg(LOOP_STEP, &expr, _)).Times(1);
EXPECT_CALL(handler, PostVisitConst(result_expr, result, _)).Times(1);
EXPECT_CALL(handler, PostVisitArg(RESULT, &expr, _)).Times(1);
EXPECT_CALL(handler, PostVisitComprehension(c, &expr, _)).Times(1);
AstTraverse(&expr, &source_info, &handler);
}
TEST(AstCrawlerTest, CheckCreateList) {
SourceInfo source_info;
MockAstVisitor handler;
Expr expr;
auto list_expr = expr.mutable_list_expr();
auto arg0 = list_expr->add_elements();
auto const_expr = arg0->mutable_const_expr();
auto arg1 = list_expr->add_elements();
auto ident_expr = arg1->mutable_ident_expr();
testing::InSequence seq;
EXPECT_CALL(handler, PreVisitCreateList(list_expr, &expr, _)).Times(1);
EXPECT_CALL(handler, PostVisitConst(const_expr, arg0, _)).Times(1);
EXPECT_CALL(handler, PostVisitIdent(ident_expr, arg1, _)).Times(1);
EXPECT_CALL(handler, PostVisitCreateList(list_expr, &expr, _)).Times(1);
AstTraverse(&expr, &source_info, &handler);
}
TEST(AstCrawlerTest, CheckCreateStruct) {
SourceInfo source_info;
MockAstVisitor handler;
Expr expr;
auto struct_expr = expr.mutable_struct_expr();
auto entry0 = struct_expr->add_entries();
auto key = entry0->mutable_map_key()->mutable_const_expr();
auto value = entry0->mutable_value()->mutable_ident_expr();
testing::InSequence seq;
EXPECT_CALL(handler, PreVisitCreateStruct(struct_expr, &expr, _)).Times(1);
EXPECT_CALL(handler, PostVisitConst(key, &entry0->map_key(), _)).Times(1);
EXPECT_CALL(handler, PostVisitIdent(value, &entry0->value(), _)).Times(1);
EXPECT_CALL(handler, PostVisitCreateStruct(struct_expr, &expr, _)).Times(1);
AstTraverse(&expr, &source_info, &handler);
}
TEST(AstCrawlerTest, CheckExprHandlers) {
SourceInfo source_info;
MockAstVisitor handler;
Expr expr;
auto struct_expr = expr.mutable_struct_expr();
auto entry0 = struct_expr->add_entries();
entry0->mutable_map_key()->mutable_const_expr();
entry0->mutable_value()->mutable_ident_expr();
EXPECT_CALL(handler, PreVisitExpr(_, _)).Times(3);
EXPECT_CALL(handler, PostVisitExpr(_, _)).Times(3);
AstTraverse(&expr, &source_info, &handler);
}
}
} |
9 | cpp | google/cel-cpp | source | common/source.cc | common/source_test.cc | #ifndef THIRD_PARTY_CEL_CPP_COMMON_SOURCE_H_
#define THIRD_PARTY_CEL_CPP_COMMON_SOURCE_H_
#include <cstdint>
#include <memory>
#include <string>
#include <utility>
#include "absl/base/attributes.h"
#include "absl/base/nullability.h"
#include "absl/status/statusor.h"
#include "absl/strings/cord.h"
#include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "absl/types/span.h"
#include "absl/types/variant.h"
namespace cel {
namespace common_internal {
class SourceImpl;
}
class Source;
using SourcePosition = int32_t;
struct SourceRange final {
SourcePosition begin = -1;
SourcePosition end = -1;
};
inline bool operator==(const SourceRange& lhs, const SourceRange& rhs) {
return lhs.begin == rhs.begin && lhs.end == rhs.end;
}
inline bool operator!=(const SourceRange& lhs, const SourceRange& rhs) {
return !operator==(lhs, rhs);
}
struct SourceLocation final {
int32_t line = -1;
int32_t column = -1;
};
inline bool operator==(const SourceLocation& lhs, const SourceLocation& rhs) {
return lhs.line == rhs.line && lhs.column == rhs.column;
}
inline bool operator!=(const SourceLocation& lhs, const SourceLocation& rhs) {
return !operator==(lhs, rhs);
}
class SourceContentView final {
public:
SourceContentView(const SourceContentView&) = default;
SourceContentView(SourceContentView&&) = default;
SourceContentView& operator=(const SourceContentView&) = default;
SourceContentView& operator=(SourceContentView&&) = default;
SourcePosition size() const;
bool empty() const;
char32_t at(SourcePosition position) const;
std::string ToString(SourcePosition begin, SourcePosition end) const;
std::string ToString(SourcePosition begin) const {
return ToString(begin, size());
}
std::string ToString() const { return ToString(0); }
void AppendToString(std::string& dest) const;
private:
friend class Source;
constexpr SourceContentView() = default;
constexpr explicit SourceContentView(absl::Span<const char> view)
: view_(view) {}
constexpr explicit SourceContentView(absl::Span<const uint8_t> view)
: view_(view) {}
constexpr explicit SourceContentView(absl::Span<const char16_t> view)
: view_(view) {}
constexpr explicit SourceContentView(absl::Span<const char32_t> view)
: view_(view) {}
absl::variant<absl::Span<const char>, absl::Span<const uint8_t>,
absl::Span<const char16_t>, absl::Span<const char32_t>>
view_;
};
class Source {
public:
using ContentView = SourceContentView;
Source(const Source&) = delete;
Source(Source&&) = delete;
virtual ~Source() = default;
Source& operator=(const Source&) = delete;
Source& operator=(Source&&) = delete;
virtual absl::string_view description() const
ABSL_ATTRIBUTE_LIFETIME_BOUND = 0;
absl::optional<SourceLocation> GetLocation(SourcePosition position) const;
absl::optional<SourcePosition> GetPosition(
const SourceLocation& location) const;
absl::optional<std::string> Snippet(int32_t line) const;
std::string DisplayErrorLocation(SourceLocation location) const;
virtual ContentView content() const ABSL_ATTRIBUTE_LIFETIME_BOUND = 0;
virtual absl::Span<const SourcePosition> line_offsets() const
ABSL_ATTRIBUTE_LIFETIME_BOUND = 0;
protected:
static constexpr ContentView EmptyContentView() { return ContentView(); }
static constexpr ContentView MakeContentView(absl::Span<const char> view) {
return ContentView(view);
}
static constexpr ContentView MakeContentView(absl::Span<const uint8_t> view) {
return ContentView(view);
}
static constexpr ContentView MakeContentView(
absl::Span<const char16_t> view) {
return ContentView(view);
}
static constexpr ContentView MakeContentView(
absl::Span<const char32_t> view) {
return ContentView(view);
}
private:
friend class common_internal::SourceImpl;
Source() = default;
absl::optional<SourcePosition> FindLinePosition(int32_t line) const;
absl::optional<std::pair<int32_t, SourcePosition>> FindLine(
SourcePosition position) const;
};
using SourcePtr = std::unique_ptr<Source>;
absl::StatusOr<absl::Nonnull<SourcePtr>> NewSource(
absl::string_view content, std::string description = "<input>");
absl::StatusOr<absl::Nonnull<SourcePtr>> NewSource(
const absl::Cord& content, std::string description = "<input>");
}
#endif
#include "common/source.h"
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <limits>
#include <memory>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#include "absl/base/nullability.h"
#include "absl/base/optimization.h"
#include "absl/container/inlined_vector.h"
#include "absl/functional/overload.h"
#include "absl/log/absl_check.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/cord.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_replace.h"
#include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "absl/types/span.h"
#include "absl/types/variant.h"
#include "internal/unicode.h"
#include "internal/utf8.h"
namespace cel {
SourcePosition SourceContentView::size() const {
return static_cast<SourcePosition>(absl::visit(
absl::Overload(
[](absl::Span<const char> view) { return view.size(); },
[](absl::Span<const uint8_t> view) { return view.size(); },
[](absl::Span<const char16_t> view) { return view.size(); },
[](absl::Span<const char32_t> view) { return view.size(); }),
view_));
}
bool SourceContentView::empty() const {
return absl::visit(
absl::Overload(
[](absl::Span<const char> view) { return view.empty(); },
[](absl::Span<const uint8_t> view) { return view.empty(); },
[](absl::Span<const char16_t> view) { return view.empty(); },
[](absl::Span<const char32_t> view) { return view.empty(); }),
view_);
}
char32_t SourceContentView::at(SourcePosition position) const {
ABSL_DCHECK_GE(position, 0);
ABSL_DCHECK_LT(position, size());
return absl::visit(
absl::Overload(
[position =
static_cast<size_t>(position)](absl::Span<const char> view) {
return static_cast<char32_t>(static_cast<uint8_t>(view[position]));
},
[position =
static_cast<size_t>(position)](absl::Span<const uint8_t> view) {
return static_cast<char32_t>(view[position]);
},
[position =
static_cast<size_t>(position)](absl::Span<const char16_t> view) {
return static_cast<char32_t>(view[position]);
},
[position =
static_cast<size_t>(position)](absl::Span<const char32_t> view) {
return static_cast<char32_t>(view[position]);
}),
view_);
}
std::string SourceContentView::ToString(SourcePosition begin,
SourcePosition end) const {
ABSL_DCHECK_GE(begin, 0);
ABSL_DCHECK_LE(end, size());
ABSL_DCHECK_LE(begin, end);
return absl::visit(
absl::Overload(
[begin = static_cast<size_t>(begin),
end = static_cast<size_t>(end)](absl::Span<const char> view) {
view = view.subspan(begin, end - begin);
return std::string(view.data(), view.size());
},
[begin = static_cast<size_t>(begin),
end = static_cast<size_t>(end)](absl::Span<const uint8_t> view) {
view = view.subspan(begin, end - begin);
std::string result;
result.reserve(view.size() * 2);
for (const auto& code_point : view) {
internal::Utf8Encode(result, code_point);
}
result.shrink_to_fit();
return result;
},
[begin = static_cast<size_t>(begin),
end = static_cast<size_t>(end)](absl::Span<const char16_t> view) {
view = view.subspan(begin, end - begin);
std::string result;
result.reserve(view.size() * 3);
for (const auto& code_point : view) {
internal::Utf8Encode(result, code_point);
}
result.shrink_to_fit();
return result;
},
[begin = static_cast<size_t>(begin),
end = static_cast<size_t>(end)](absl::Span<const char32_t> view) {
view = view.subspan(begin, end - begin);
std::string result;
result.reserve(view.size() * 4);
for (const auto& code_point : view) {
internal::Utf8Encode(result, code_point);
}
result.shrink_to_fit();
return result;
}),
view_);
}
void SourceContentView::AppendToString(std::string& dest) const {
absl::visit(absl::Overload(
[&dest](absl::Span<const char> view) {
dest.append(view.data(), view.size());
},
[&dest](absl::Span<const uint8_t> view) {
for (const auto& code_point : view) {
internal::Utf8Encode(dest, code_point);
}
},
[&dest](absl::Span<const char16_t> view) {
for (const auto& code_point : view) {
internal::Utf8Encode(dest, code_point);
}
},
[&dest](absl::Span<const char32_t> view) {
for (const auto& code_point : view) {
internal::Utf8Encode(dest, code_point);
}
}),
view_);
}
namespace common_internal {
class SourceImpl : public Source {
public:
SourceImpl(std::string description,
absl::InlinedVector<SourcePosition, 1> line_offsets)
: description_(std::move(description)),
line_offsets_(std::move(line_offsets)) {}
absl::string_view description() const final { return description_; }
absl::Span<const SourcePosition> line_offsets() const final {
return absl::MakeConstSpan(line_offsets_);
}
private:
const std::string description_;
const absl::InlinedVector<SourcePosition, 1> line_offsets_;
};
namespace {
class AsciiSource final : public SourceImpl {
public:
AsciiSource(std::string description,
absl::InlinedVector<SourcePosition, 1> line_offsets,
std::vector<char> text)
: SourceImpl(std::move(description), std::move(line_offsets)),
text_(std::move(text)) {}
ContentView content() const override {
return MakeContentView(absl::MakeConstSpan(text_));
}
private:
const std::vector<char> text_;
};
class Latin1Source final : public SourceImpl {
public:
Latin1Source(std::string description,
absl::InlinedVector<SourcePosition, 1> line_offsets,
std::vector<uint8_t> text)
: SourceImpl(std::move(description), std::move(line_offsets)),
text_(std::move(text)) {}
ContentView content() const override {
return MakeContentView(absl::MakeConstSpan(text_));
}
private:
const std::vector<uint8_t> text_;
};
class BasicPlaneSource final : public SourceImpl {
public:
BasicPlaneSource(std::string description,
absl::InlinedVector<SourcePosition, 1> line_offsets,
std::vector<char16_t> text)
: SourceImpl(std::move(description), std::move(line_offsets)),
text_(std::move(text)) {}
ContentView content() const override {
return MakeContentView(absl::MakeConstSpan(text_));
}
private:
const std::vector<char16_t> text_;
};
class SupplementalPlaneSource final : public SourceImpl {
public:
SupplementalPlaneSource(std::string description,
absl::InlinedVector<SourcePosition, 1> line_offsets,
std::vector<char32_t> text)
: SourceImpl(std::move(description), std::move(line_offsets)),
text_(std::move(text)) {}
ContentView content() const override {
return MakeContentView(absl::MakeConstSpan(text_));
}
private:
const std::vector<char32_t> text_;
};
template <typename T>
struct SourceTextTraits;
template <>
struct SourceTextTraits<absl::string_view> {
using iterator_type = absl::string_view;
static iterator_type Begin(absl::string_view text) { return text; }
static void Advance(iterator_type& it, size_t n) { it.remove_prefix(n); }
static void AppendTo(std::vector<uint8_t>& out, absl::string_view text,
size_t n) {
const auto* in = reinterpret_cast<const uint8_t*>(text.data());
out.insert(out.end(), in, in + n);
}
static std::vector<char> ToVector(absl::string_view in) {
std::vector<char> out;
out.reserve(in.size());
out.insert(out.end(), in.begin(), in.end());
return out;
}
};
template <>
struct SourceTextTraits<absl::Cord> {
using iterator_type = absl::Cord::CharIterator;
static iterator_type Begin(const absl::Cord& text) {
return text.char_begin();
}
static void Advance(iterator_type& it, size_t n) {
absl::Cord::Advance(&it, n);
}
static void AppendTo(std::vector<uint8_t>& out, const absl::Cord& text,
size_t n) {
auto it = text.char_begin();
while (n > 0) {
auto str = absl::Cord::ChunkRemaining(it);
size_t to_append = std::min(n, str.size());
const auto* in = reinterpret_cast<const uint8_t*>(str.data());
out.insert(out.end(), in, in + to_append);
n -= to_append;
absl::Cord::Advance(&it, to_append);
}
}
static std::vector<char> ToVector(const absl::Cord& in) {
std::vector<char> out;
out.reserve(in.size());
for (const auto& chunk : in.Chunks()) {
out.insert(out.end(), chunk.begin(), chunk.end());
}
return out;
}
};
template <typename T>
absl::StatusOr<SourcePtr> NewSourceImpl(std::string description, const T& text,
const size_t text_size) {
if (ABSL_PREDICT_FALSE(
text_size >
static_cast<size_t>(std::numeric_limits<int32_t>::max()))) {
return absl::InvalidArgumentError("expression larger than 2GiB limit");
}
using Traits = SourceTextTraits<T>;
size_t index = 0;
typename Traits::iterator_type it = Traits::Begin(text);
SourcePosition offset = 0;
char32_t code_point;
size_t code_units;
std::vector<uint8_t> data8;
std::vector<char16_t> data16;
std::vector<char32_t> data32;
absl::InlinedVector<SourcePosition, 1> line_offsets;
while (index < text_size) {
std::tie(code_point, code_units) = cel::internal::Utf8Decode(it);
if (ABSL_PREDICT_FALSE(code_point ==
cel::internal::kUnicodeReplacementCharacter &&
code_units == 1)) {
return absl::InvalidArgumentError("cannot parse malformed UTF-8 input");
}
if (code_point == '\n') {
line_offsets.push_back(offset + 1);
}
if (code_point <= 0x7f) {
Traits::Advance(it, code_units);
index += code_units;
++offset;
continue;
}
if (code_point <= 0xff) {
data8.reserve(text_size);
Traits::AppendTo(data8, text, index);
data8.push_back(static_cast<uint8_t>(code_point));
Traits::Advance(it, code_units);
index += code_units;
++offset;
goto latin1;
}
if (code_point <= 0xffff) {
data16.reserve(text_size);
for (size_t offset = 0; offset < index; offset++) {
data16.push_back(static_cast<uint8_t>(text[offset]));
}
data16.push_back(static_cast<char16_t>(code_point));
Traits::Advance(it, code_units);
index += code_units;
++offset;
goto basic;
}
data32.reserve(text_size);
for (size_t offset = 0; offset < index; offset++) {
data32.push_back(static_cast<char32_t>(text[offset]));
}
data32.push_back(code_point);
Traits::Advance(it, code_units);
index += code_units;
++offset;
goto supplemental;
}
line_offsets.push_back(offset + 1);
return std::make_unique<AsciiSource>(
std::move(description), std::move(line_offsets), Traits::ToVector(text));
latin1:
while (index < text_size) {
std::tie(code_point, code_units) = internal::Utf8Decode(it);
if (ABSL_PREDICT_FALSE(code_point ==
internal::kUnicodeReplacementCharacter &&
code_units == 1)) {
return absl::InvalidArgumentError("cannot parse malformed UTF-8 input");
}
if (code_point == '\n') {
line_offsets.push_back(offset + 1);
}
if (code_point <= 0xff) {
data8.push_back(static_cast<uint8_t>(code_point));
Traits::Advance(it, code_units);
index += code_units;
++offset;
continue;
}
if (code_point <= 0xffff) {
data16.reserve(text_size);
for (const auto& value : data8) {
data16.push_back(value);
}
std::vector<uint8_t>().swap(data8);
data16.push_back(static_cast<char16_t>(code_point));
Traits::Advance(it, code_units);
index += code_units;
++offset;
goto basic;
}
data32.reserve(text_size);
for (const auto& value : data8) {
data32.push_back(value);
}
std::vector<uint8_t>().swap(data8);
data32.push_back(code_point);
Traits::Advance(it, code_units);
index += code_units;
++offset;
goto supplemental;
}
line_offsets.push_back(offset + 1);
return std::make_unique<Latin1Source>(
std::move(description), std::move(line_offsets), std::move(data8));
basic:
while (index < text_size) {
std::tie(code_point, code_units) = internal::Utf8Decode(it);
if (ABSL_PREDICT_FALSE(code_point ==
internal::kUnicodeReplacementCharacter &&
code_units == 1)) {
return absl::InvalidArgumentError("cannot parse malformed UTF-8 input");
}
if (code_point == '\n') {
line_offsets.push_back(offset + 1);
}
if (code_point <= 0xffff) {
data16.push_back(static_cast<char16_t>(code_point));
Traits::Advance(it, code_units);
index += code_units;
++offset;
continue;
}
data32.reserve(text_size);
for (const auto& value : data16) {
data32.push_back(static_cast<char32_t>(value));
}
std::vector<char16_t>().swap(data16);
data32.push_back(code_point);
Traits::Advance(it, code_units);
index += code_units;
++offset;
goto supplemental;
}
line_offsets.push_back(offset + 1);
return std::make_unique<BasicPlaneSource>(
std::move(description), std::move(line_offsets), std::move(data16));
supplemental:
while (index < text_size) {
std::tie(code_point, code_units) = internal::Utf8Decode(it);
if (ABSL_PREDICT_FALSE(code_point ==
internal::kUnicodeReplacementCharacter &&
code_units == 1)) {
return absl::InvalidArgumentError("cannot parse malformed UTF-8 input");
}
if (code_point == '\n') {
line_offsets.push_back(offset + 1);
}
data32.push_back(code_point);
Traits::Advance(it, code_units);
index += code_units;
++offset;
}
line_offsets.push_back(offset + 1);
return std::make_unique<SupplementalPlaneSource>(
std::move(description), std::move(line_offsets), std::move(data32));
}
}
}
absl::optional<SourceLocation> Source::GetLocation(
SourcePosition position) const {
if (auto line_and_offset = FindLine(position);
ABSL_PREDICT_TRUE(line_and_offset.has_value())) {
return SourceLocation{line_and_offset->first,
position - line_and_offset->second};
}
return absl::nullopt;
}
absl::optional<SourcePosition> Source::GetPosition(
const SourceLocation& location) const {
if (ABSL_PREDICT_FALSE(location.line < 1 || location.column < 0)) {
return absl::nullopt;
}
if (auto position = FindLinePosition(location.line);
ABSL_PREDICT_TRUE(position.has_value())) {
return *position + location.column;
}
return absl::nullopt;
}
absl::optional<std::string> Source::Snippet(int32_t line) const {
auto content = this->content();
auto start = FindLinePosition(line);
if (ABSL_PREDICT_FALSE(!start.has_value() || content.empty())) {
return absl::nullopt;
}
auto end = FindLinePosition(line + 1);
if (end.has_value()) {
return content.ToString(*start, *end - 1);
}
return content.ToString(*start);
}
std::string Source::DisplayErrorLocation(SourceLocation location) const {
constexpr char32_t kDot = '.';
constexpr char32_t kHat = '^';
constexpr char32_t kWideDot = 0xff0e;
constexpr char32_t kWideHat = 0xff3e;
absl::optional<std::string> snippet = Snippet(location.line);
if (!snippet || snippet->empty()) {
return "";
}
*snippet = absl::StrReplaceAll(*snippet, {{"\t", " "}});
absl::string_view snippet_view(*snippet);
std::string result;
absl::StrAppend(&result, "\n | ", *snippet);
absl::StrAppend(&result, "\n | ");
std::string index_line;
for (int32_t i = 0; i < location.column && !snippet_view.empty(); ++i) {
size_t count;
std::tie(std::ignore, count) = internal::Utf8Decode(snippet_view);
snippet_view.remove_prefix(count);
if (count > 1) {
internal::Utf8Encode(index_line, kWideDot);
} else {
internal::Utf8Encode(index_line, kDot);
}
}
size_t count = 0;
if (!snippet_view.empty()) {
std::tie(std::ignore, count) = internal::Utf8Decode(snippet_view);
}
if (count > 1) {
internal::Utf8Encode(index_line, kWideHat);
} else {
internal::Utf8Encode(index_line, kHat);
}
absl::StrAppend(&result, index_line);
return result;
}
absl::optional<SourcePosition> Source::FindLinePosition(int32_t line) const {
if (ABSL_PREDICT_FALSE(line < 1)) {
return absl::nullopt;
}
if (line == 1) {
return SourcePosition{0};
}
const auto line_offsets = this->line_offsets();
if (ABSL_PREDICT_TRUE(line <= static_cast<int32_t>(line_offsets.size()))) {
return line_offsets[static_cast<size_t>(line - 2)];
}
return absl::nullopt;
}
absl::optional<std::pair<int32_t, SourcePosition>> Source::FindLine(
SourcePosition position) const {
if (ABSL_PREDICT_FALSE(position < 0)) {
return absl::nullopt;
}
int32_t line = 1;
const auto line_offsets = this->line_offsets();
for (const auto& line_offset : line_offsets) {
if (line_offset > position) {
break;
}
++line;
}
if (line == 1) {
return std::make_pair(line, SourcePosition{0});
}
return std::make_pair(line, line_offsets[static_cast<size_t>(line) - 2]);
}
absl::StatusOr<absl::Nonnull<SourcePtr>> NewSource(absl::string_view content,
std::string description) {
return common_internal::NewSourceImpl(std::move(description), content,
content.size());
}
absl::StatusOr<absl::Nonnull<SourcePtr>> NewSource(const absl::Cord& content,
std::string description) {
return common_internal::NewSourceImpl(std::move(description), content,
content.size());
}
} | #include "common/source.h"
#include "absl/strings/cord.h"
#include "absl/types/optional.h"
#include "internal/testing.h"
namespace cel {
namespace {
using testing::ElementsAre;
using testing::Eq;
using testing::Ne;
using testing::Optional;
TEST(SourceRange, Default) {
SourceRange range;
EXPECT_EQ(range.begin, -1);
EXPECT_EQ(range.end, -1);
}
TEST(SourceRange, Equality) {
EXPECT_THAT((SourceRange{}), (Eq(SourceRange{})));
EXPECT_THAT((SourceRange{0, 1}), (Ne(SourceRange{0, 0})));
}
TEST(SourceLocation, Default) {
SourceLocation location;
EXPECT_EQ(location.line, -1);
EXPECT_EQ(location.column, -1);
}
TEST(SourceLocation, Equality) {
EXPECT_THAT((SourceLocation{}), (Eq(SourceLocation{})));
EXPECT_THAT((SourceLocation{1, 1}), (Ne(SourceLocation{1, 0})));
}
TEST(StringSource, Description) {
ASSERT_OK_AND_ASSIGN(
auto source,
NewSource("c.d &&\n\t b.c.arg(10) &&\n\t test(10)", "offset-test"));
EXPECT_THAT(source->description(), Eq("offset-test"));
}
TEST(StringSource, Content) {
ASSERT_OK_AND_ASSIGN(
auto source,
NewSource("c.d &&\n\t b.c.arg(10) &&\n\t test(10)", "offset-test"));
EXPECT_THAT(source->content().ToString(),
Eq("c.d &&\n\t b.c.arg(10) &&\n\t test(10)"));
}
TEST(StringSource, PositionAndLocation) {
ASSERT_OK_AND_ASSIGN(
auto source,
NewSource("c.d &&\n\t b.c.arg(10) &&\n\t test(10)", "offset-test"));
EXPECT_THAT(source->line_offsets(), ElementsAre(7, 24, 35));
auto start = source->GetPosition(SourceLocation{int32_t{1}, int32_t{2}});
auto end = source->GetPosition(SourceLocation{int32_t{3}, int32_t{2}});
ASSERT_TRUE(start.has_value());
ASSERT_TRUE(end.has_value());
EXPECT_THAT(source->GetLocation(*start),
Optional(Eq(SourceLocation{int32_t{1}, int32_t{2}})));
EXPECT_THAT(source->GetLocation(*end),
Optional(Eq(SourceLocation{int32_t{3}, int32_t{2}})));
EXPECT_THAT(source->GetLocation(-1), Eq(absl::nullopt));
EXPECT_THAT(source->content().ToString(*start, *end),
Eq("d &&\n\t b.c.arg(10) &&\n\t "));
EXPECT_THAT(source->GetPosition(SourceLocation{int32_t{0}, int32_t{0}}),
Eq(absl::nullopt));
EXPECT_THAT(source->GetPosition(SourceLocation{int32_t{1}, int32_t{-1}}),
Eq(absl::nullopt));
EXPECT_THAT(source->GetPosition(SourceLocation{int32_t{4}, int32_t{0}}),
Eq(absl::nullopt));
}
TEST(StringSource, SnippetSingle) {
ASSERT_OK_AND_ASSIGN(auto source, NewSource("hello, world", "one-line-test"));
EXPECT_THAT(source->Snippet(1), Optional(Eq("hello, world")));
EXPECT_THAT(source->Snippet(2), Eq(absl::nullopt));
}
TEST(StringSource, SnippetMulti) {
ASSERT_OK_AND_ASSIGN(auto source,
NewSource("hello\nworld\nmy\nbub\n", "four-line-test"));
EXPECT_THAT(source->Snippet(0), Eq(absl::nullopt));
EXPECT_THAT(source->Snippet(1), Optional(Eq("hello")));
EXPECT_THAT(source->Snippet(2), Optional(Eq("world")));
EXPECT_THAT(source->Snippet(3), Optional(Eq("my")));
EXPECT_THAT(source->Snippet(4), Optional(Eq("bub")));
EXPECT_THAT(source->Snippet(5), Optional(Eq("")));
EXPECT_THAT(source->Snippet(6), Eq(absl::nullopt));
}
TEST(CordSource, Description) {
ASSERT_OK_AND_ASSIGN(
auto source,
NewSource(absl::Cord("c.d &&\n\t b.c.arg(10) &&\n\t test(10)"),
"offset-test"));
EXPECT_THAT(source->description(), Eq("offset-test"));
}
TEST(CordSource, Content) {
ASSERT_OK_AND_ASSIGN(
auto source,
NewSource(absl::Cord("c.d &&\n\t b.c.arg(10) &&\n\t test(10)"),
"offset-test"));
EXPECT_THAT(source->content().ToString(),
Eq("c.d &&\n\t b.c.arg(10) &&\n\t test(10)"));
}
TEST(CordSource, PositionAndLocation) {
ASSERT_OK_AND_ASSIGN(
auto source,
NewSource(absl::Cord("c.d &&\n\t b.c.arg(10) &&\n\t test(10)"),
"offset-test"));
EXPECT_THAT(source->line_offsets(), ElementsAre(7, 24, 35));
auto start = source->GetPosition(SourceLocation{int32_t{1}, int32_t{2}});
auto end = source->GetPosition(SourceLocation{int32_t{3}, int32_t{2}});
ASSERT_TRUE(start.has_value());
ASSERT_TRUE(end.has_value());
EXPECT_THAT(source->GetLocation(*start),
Optional(Eq(SourceLocation{int32_t{1}, int32_t{2}})));
EXPECT_THAT(source->GetLocation(*end),
Optional(Eq(SourceLocation{int32_t{3}, int32_t{2}})));
EXPECT_THAT(source->GetLocation(-1), Eq(absl::nullopt));
EXPECT_THAT(source->content().ToString(*start, *end),
Eq("d &&\n\t b.c.arg(10) &&\n\t "));
EXPECT_THAT(source->GetPosition(SourceLocation{int32_t{0}, int32_t{0}}),
Eq(absl::nullopt));
EXPECT_THAT(source->GetPosition(SourceLocation{int32_t{1}, int32_t{-1}}),
Eq(absl::nullopt));
EXPECT_THAT(source->GetPosition(SourceLocation{int32_t{4}, int32_t{0}}),
Eq(absl::nullopt));
}
TEST(CordSource, SnippetSingle) {
ASSERT_OK_AND_ASSIGN(auto source,
NewSource(absl::Cord("hello, world"), "one-line-test"));
EXPECT_THAT(source->Snippet(1), Optional(Eq("hello, world")));
EXPECT_THAT(source->Snippet(2), Eq(absl::nullopt));
}
TEST(CordSource, SnippetMulti) {
ASSERT_OK_AND_ASSIGN(
auto source,
NewSource(absl::Cord("hello\nworld\nmy\nbub\n"), "four-line-test"));
EXPECT_THAT(source->Snippet(0), Eq(absl::nullopt));
EXPECT_THAT(source->Snippet(1), Optional(Eq("hello")));
EXPECT_THAT(source->Snippet(2), Optional(Eq("world")));
EXPECT_THAT(source->Snippet(3), Optional(Eq("my")));
EXPECT_THAT(source->Snippet(4), Optional(Eq("bub")));
EXPECT_THAT(source->Snippet(5), Optional(Eq("")));
EXPECT_THAT(source->Snippet(6), Eq(absl::nullopt));
}
TEST(Source, DisplayErrorLocationBasic) {
ASSERT_OK_AND_ASSIGN(auto source, NewSource("'Hello' +\n 'world'"));
SourceLocation location{2, 3};
EXPECT_EQ(source->DisplayErrorLocation(location),
"\n | 'world'"
"\n | ...^");
}
TEST(Source, DisplayErrorLocationOutOfRange) {
ASSERT_OK_AND_ASSIGN(auto source, NewSource("'Hello world!'"));
SourceLocation location{3, 3};
EXPECT_EQ(source->DisplayErrorLocation(location), "");
}
TEST(Source, DisplayErrorLocationTabsShortened) {
ASSERT_OK_AND_ASSIGN(auto source, NewSource("'Hello' +\n\t\t'world!'"));
SourceLocation location{2, 4};
EXPECT_EQ(source->DisplayErrorLocation(location),
"\n | 'world!'"
"\n | ....^");
}
TEST(Source, DisplayErrorLocationFullWidth) {
ASSERT_OK_AND_ASSIGN(auto source, NewSource("'Hello'"));
SourceLocation location{1, 2};
EXPECT_EQ(source->DisplayErrorLocation(location),
"\n | 'Hello'"
"\n | ..^");
}
}
} |
Dataset Card for Open Source Code and Unit Tests
Dataset Details
Dataset Description
This dataset contains c++ code snippets and their corresponding ground truth unit tests collected from various open-source GitHub repositories. The primary purpose of this dataset is to aid in the development and evaluation of automated testing tools, code quality analysis, and LLM models for test generation.
- Curated by: Vaishnavi Bhargava
- Language(s): C++
Dataset Structure
from datasets import Dataset, load_dataset
# Load the dataset
dataset = load_dataset("Nutanix/cpp_unit_tests_benchmark_dataset")
# View dataset structure
DatasetDict({
train: Dataset({
features: ['ID', 'Language', 'Repository Name', 'File Name', 'File Path in Repository', 'File Path for Unit Test', 'Code', 'Unit Test - (Ground Truth)'],
num_rows: 2653
})
})
The dataset consists of the following columns:
ID
: A unique identifier for each entry in the dataset. [Example: "0"]Language
: The programming language of the file. [Example: "cpp"]Repository Name
: The name of the GitHub repository, formatted as organisation/repository. [Example: "google/googletest"]File Name
: The base name of the file (without extension) where the code or test is located. [Example: "sample1"]File Path in Repository
: The relative path to the file within the GitHub repository. [Example: "googletest/samples/sample1.cc"]File Path for Unit Test
: The relative path to the unit test file, if applicable. [Example: "googletest/samples/sample1_unittest.cc"]Code
: The code content of the file, excluding any documentation or comments.Unit Test - (Ground Truth)
: The content of the unit test file that tests the code.
Dataset Sources
- Repository: The dataset is sourced from the following GitHub repositories: [Latest Commit before 2 July 24]
Some analysis of the dataset:
The box plot representation depicting number of Code and Unit Test lines across different repositories
Uses
Direct Use
This dataset is suitable for :
- Developing and evaluating automated testing tools.
- Analyzing code quality by comparing code with its corresponding unit tests.
- Training and testing LLM models for automated unit test generation.
Dataset Creation
Curation Rationale
The motivation for creating this dataset is to provide a comprehensive collection of code and unit tests from various reputable open-source projects. This can facilitate research and development in the areas of automated testing, code quality analysis, and LLM for software engineering.
Source Data
Data Collection and Processing
The data was collected from public GitHub repositories. The selection criteria included repositories with well-documented code and corresponding unit tests. The data was filtered and normalized to ensure consistency.
Who are the source data producers?
The source data producers are the contributors to the respective open-source GitHub repositories.
Bias, Risks, and Limitations
The dataset may have biases based on the coding practices and testing methodologies of the included repositories. It may not cover all possible scenarios and edge cases in software testing.
Citation [optional]
- Downloads last month
- 11