From d439bbccd4b90583a89d209d2cc81308aabca8ac Mon Sep 17 00:00:00 2001 From: Gil Date: Tue, 22 May 2018 13:21:08 -0700 Subject: Add a HARD_ASSERT C++ assertion macro (#1304) * Add HARD_ASSERT * Use HARD_ASSERT * Remove FIREBASE_ASSERT * Remove StringPrintf --- .../auth/firebase_credentials_provider_apple.mm | 16 ++- Firestore/core/src/firebase/firestore/auth/token.h | 4 +- Firestore/core/src/firebase/firestore/auth/user.cc | 4 +- Firestore/core/src/firebase/firestore/geo_point.cc | 14 +-- .../firestore/immutable/array_sorted_map.h | 6 +- .../firestore/immutable/llrb_node_iterator.h | 6 +- .../src/firebase/firestore/immutable/sorted_map.h | 26 ++--- .../firestore/immutable/sorted_map_iterator.h | 4 +- .../src/firebase/firestore/immutable/sorted_set.h | 2 +- .../firestore/local/leveldb_transaction.cc | 28 +++-- .../core/src/firebase/firestore/model/base_path.h | 16 ++- .../src/firebase/firestore/model/database_id.cc | 6 +- .../core/src/firebase/firestore/model/document.cc | 4 +- .../src/firebase/firestore/model/document_key.cc | 7 +- .../src/firebase/firestore/model/field_path.cc | 27 ++--- .../src/firebase/firestore/model/field_value.cc | 28 +++-- .../src/firebase/firestore/model/field_value.h | 12 +-- .../src/firebase/firestore/model/maybe_document.cc | 2 - .../src/firebase/firestore/model/precondition.cc | 4 +- .../src/firebase/firestore/model/precondition.h | 9 +- .../src/firebase/firestore/model/resource_path.cc | 8 +- .../firestore/model/transform_operations.h | 6 +- .../core/src/firebase/firestore/nanopb/reader.cc | 4 +- .../core/src/firebase/firestore/nanopb/reader.h | 4 +- .../core/src/firebase/firestore/nanopb/writer.cc | 16 ++- .../src/firebase/firestore/remote/serializer.cc | 50 ++++----- .../src/firebase/firestore/remote/serializer.h | 2 +- Firestore/core/src/firebase/firestore/timestamp.cc | 22 ++-- .../src/firebase/firestore/util/CMakeLists.txt | 11 +- .../src/firebase/firestore/util/assert_apple.mm | 49 --------- .../src/firebase/firestore/util/assert_stdio.cc | 53 --------- .../src/firebase/firestore/util/async_queue.cc | 46 ++++---- Firestore/core/src/firebase/firestore/util/bits.cc | 4 +- .../firebase/firestore/util/executor_libdispatch.h | 1 - .../firestore/util/executor_libdispatch.mm | 8 +- .../src/firebase/firestore/util/executor_std.cc | 3 +- .../src/firebase/firestore/util/executor_std.h | 6 +- .../src/firebase/firestore/util/firebase_assert.h | 119 --------------------- .../core/src/firebase/firestore/util/hard_assert.h | 88 +++++++++++++++ .../firebase/firestore/util/hard_assert_apple.mm | 60 +++++++++++ .../firebase/firestore/util/hard_assert_stdio.cc | 64 +++++++++++ .../src/firebase/firestore/util/ordered_code.cc | 43 ++++---- .../core/src/firebase/firestore/util/status.cc | 4 +- .../core/src/firebase/firestore/util/status.h | 13 +-- .../core/src/firebase/firestore/util/statusor.cc | 8 +- .../src/firebase/firestore/util/string_printf.cc | 102 ------------------ .../src/firebase/firestore/util/string_printf.h | 46 -------- 47 files changed, 427 insertions(+), 638 deletions(-) delete mode 100644 Firestore/core/src/firebase/firestore/util/assert_apple.mm delete mode 100644 Firestore/core/src/firebase/firestore/util/assert_stdio.cc delete mode 100644 Firestore/core/src/firebase/firestore/util/firebase_assert.h create mode 100644 Firestore/core/src/firebase/firestore/util/hard_assert.h create mode 100644 Firestore/core/src/firebase/firestore/util/hard_assert_apple.mm create mode 100644 Firestore/core/src/firebase/firestore/util/hard_assert_stdio.cc delete mode 100644 Firestore/core/src/firebase/firestore/util/string_printf.cc delete mode 100644 Firestore/core/src/firebase/firestore/util/string_printf.h (limited to 'Firestore/core/src/firebase') diff --git a/Firestore/core/src/firebase/firestore/auth/firebase_credentials_provider_apple.mm b/Firestore/core/src/firebase/firestore/auth/firebase_credentials_provider_apple.mm index ff2d5f7..9d5b89e 100644 --- a/Firestore/core/src/firebase/firestore/auth/firebase_credentials_provider_apple.mm +++ b/Firestore/core/src/firebase/firestore/auth/firebase_credentials_provider_apple.mm @@ -20,7 +20,7 @@ #import #import -#include "Firestore/core/src/firebase/firestore/util/firebase_assert.h" +#include "Firestore/core/src/firebase/firestore/util/hard_assert.h" #include "Firestore/core/src/firebase/firestore/util/string_apple.h" // NB: This is also defined in Firestore/Source/Public/FIRFirestoreErrors.h @@ -80,8 +80,8 @@ FirebaseCredentialsProvider::~FirebaseCredentialsProvider() { void FirebaseCredentialsProvider::GetToken(bool force_refresh, TokenListener completion) { - FIREBASE_ASSERT_MESSAGE(auth_listener_handle_, - "GetToken cannot be called after listener removed."); + HARD_ASSERT(auth_listener_handle_, + "GetToken cannot be called after listener removed."); // Take note of the current value of the userCounter so that this method can // fail if there is a user change while the request is outstanding. @@ -129,15 +129,13 @@ void FirebaseCredentialsProvider::SetUserChangeListener( UserChangeListener listener) { std::unique_lock lock(contents_->mutex); if (listener) { - FIREBASE_ASSERT_MESSAGE(!user_change_listener_, - "set user_change_listener twice!"); + HARD_ASSERT(!user_change_listener_, "set user_change_listener twice!"); // Fire initial event. listener(contents_->current_user); } else { - FIREBASE_ASSERT_MESSAGE(auth_listener_handle_, - "removed user_change_listener twice!"); - FIREBASE_ASSERT_MESSAGE(user_change_listener_, - "user_change_listener removed without being set!"); + HARD_ASSERT(auth_listener_handle_, "removed user_change_listener twice!"); + HARD_ASSERT(user_change_listener_, + "user_change_listener removed without being set!"); [[NSNotificationCenter defaultCenter] removeObserver:auth_listener_handle_]; auth_listener_handle_ = nil; } diff --git a/Firestore/core/src/firebase/firestore/auth/token.h b/Firestore/core/src/firebase/firestore/auth/token.h index 56084f8..b0d7075 100644 --- a/Firestore/core/src/firebase/firestore/auth/token.h +++ b/Firestore/core/src/firebase/firestore/auth/token.h @@ -20,7 +20,7 @@ #include #include "Firestore/core/src/firebase/firestore/auth/user.h" -#include "Firestore/core/src/firebase/firestore/util/firebase_assert.h" +#include "Firestore/core/src/firebase/firestore/util/hard_assert.h" #include "absl/strings/string_view.h" namespace firebase { @@ -46,7 +46,7 @@ class Token { /** The actual raw token. */ const std::string& token() const { - FIREBASE_ASSERT(user_.is_authenticated()); + HARD_ASSERT(user_.is_authenticated()); return token_; } diff --git a/Firestore/core/src/firebase/firestore/auth/user.cc b/Firestore/core/src/firebase/firestore/auth/user.cc index 4793fed..4fc10f6 100644 --- a/Firestore/core/src/firebase/firestore/auth/user.cc +++ b/Firestore/core/src/firebase/firestore/auth/user.cc @@ -16,7 +16,7 @@ #include "Firestore/core/src/firebase/firestore/auth/user.h" -#include "Firestore/core/src/firebase/firestore/util/firebase_assert.h" +#include "Firestore/core/src/firebase/firestore/util/hard_assert.h" namespace firebase { namespace firestore { @@ -26,7 +26,7 @@ User::User() : is_authenticated_(false) { } User::User(const absl::string_view uid) : uid_(uid), is_authenticated_(true) { - FIREBASE_ASSERT(!uid.empty()); + HARD_ASSERT(!uid.empty()); } const User& User::Unauthenticated() { diff --git a/Firestore/core/src/firebase/firestore/geo_point.cc b/Firestore/core/src/firebase/firestore/geo_point.cc index 5aae156..393b8f2 100644 --- a/Firestore/core/src/firebase/firestore/geo_point.cc +++ b/Firestore/core/src/firebase/firestore/geo_point.cc @@ -18,7 +18,7 @@ #include -#include "Firestore/core/src/firebase/firestore/util/firebase_assert.h" +#include "Firestore/core/src/firebase/firestore/util/hard_assert.h" namespace firebase { namespace firestore { @@ -28,14 +28,10 @@ GeoPoint::GeoPoint() : GeoPoint(0, 0) { GeoPoint::GeoPoint(double latitude, double longitude) : latitude_(latitude), longitude_(longitude) { - FIREBASE_ASSERT_MESSAGE_WITH_EXPRESSION( - !std::isnan(latitude) && -90 <= latitude && latitude <= 90, - -90 <= latitude && latitude <= 90, - "Latitude must be in the range of [-90, 90]"); - FIREBASE_ASSERT_MESSAGE_WITH_EXPRESSION( - !std::isnan(longitude) && -180 <= longitude && longitude <= 180, - -180 <= longitude && longitude <= 180, - "Latitude must be in the range of [-180, 180]"); + HARD_ASSERT(!std::isnan(latitude) && -90 <= latitude && latitude <= 90, + "Latitude must be in the range of [-90, 90]"); + HARD_ASSERT(!std::isnan(longitude) && -180 <= longitude && longitude <= 180, + "Latitude must be in the range of [-180, 180]"); } bool operator<(const GeoPoint& lhs, const GeoPoint& rhs) { diff --git a/Firestore/core/src/firebase/firestore/immutable/array_sorted_map.h b/Firestore/core/src/firebase/firestore/immutable/array_sorted_map.h index db53969..b1c9398 100644 --- a/Firestore/core/src/firebase/firestore/immutable/array_sorted_map.h +++ b/Firestore/core/src/firebase/firestore/immutable/array_sorted_map.h @@ -28,7 +28,7 @@ #include "Firestore/core/src/firebase/firestore/immutable/map_entry.h" #include "Firestore/core/src/firebase/firestore/immutable/sorted_map_base.h" #include "Firestore/core/src/firebase/firestore/util/comparison.h" -#include "Firestore/core/src/firebase/firestore/util/firebase_assert.h" +#include "Firestore/core/src/firebase/firestore/util/hard_assert.h" #include "Firestore/core/src/firebase/firestore/util/range.h" namespace firebase { @@ -74,7 +74,7 @@ class FixedArray { void append(SourceIterator src_begin, SourceIterator src_end) { auto appending = static_cast(src_end - src_begin); auto new_size = size_ + appending; - FIREBASE_ASSERT(new_size <= SortedMapBase::kFixedSize); + HARD_ASSERT(new_size <= SortedMapBase::kFixedSize); std::copy(src_begin, src_end, end()); size_ = new_size; @@ -85,7 +85,7 @@ class FixedArray { */ void append(T&& value) { size_type new_size = size_ + 1; - FIREBASE_ASSERT(new_size <= SortedMapBase::kFixedSize); + HARD_ASSERT(new_size <= SortedMapBase::kFixedSize); *end() = std::move(value); size_ = new_size; diff --git a/Firestore/core/src/firebase/firestore/immutable/llrb_node_iterator.h b/Firestore/core/src/firebase/firestore/immutable/llrb_node_iterator.h index 5011947..3092678 100644 --- a/Firestore/core/src/firebase/firestore/immutable/llrb_node_iterator.h +++ b/Firestore/core/src/firebase/firestore/immutable/llrb_node_iterator.h @@ -23,7 +23,7 @@ #include "Firestore/core/src/firebase/firestore/immutable/llrb_node.h" #include "Firestore/core/src/firebase/firestore/util/comparison.h" -#include "Firestore/core/src/firebase/firestore/util/firebase_assert.h" +#include "Firestore/core/src/firebase/firestore/util/hard_assert.h" namespace firebase { namespace firestore { @@ -149,7 +149,7 @@ class LlrbNodeIterator { * This can only be called if `end()` is false. */ pointer get() const { - FIREBASE_ASSERT(!is_end()); + HARD_ASSERT(!is_end()); return &(stack_.top()->entry()); } @@ -162,7 +162,7 @@ class LlrbNodeIterator { } LlrbNodeIterator& operator++() { - FIREBASE_ASSERT(!is_end()); + HARD_ASSERT(!is_end()); // Pop the stack, moving the currently pointed to node to the parent. const node_type* node = stack_.top(); diff --git a/Firestore/core/src/firebase/firestore/immutable/sorted_map.h b/Firestore/core/src/firebase/firestore/immutable/sorted_map.h index 647bab0..3a50020 100644 --- a/Firestore/core/src/firebase/firestore/immutable/sorted_map.h +++ b/Firestore/core/src/firebase/firestore/immutable/sorted_map.h @@ -144,7 +144,7 @@ class SortedMap : public impl::SortedMapBase { case Tag::Tree: return tree_.empty(); } - FIREBASE_UNREACHABLE(); + UNREACHABLE(); } /** Returns the number of items in this map. */ @@ -155,7 +155,7 @@ class SortedMap : public impl::SortedMapBase { case Tag::Tree: return tree_.size(); } - FIREBASE_UNREACHABLE(); + UNREACHABLE(); } /** @@ -184,7 +184,7 @@ class SortedMap : public impl::SortedMapBase { case Tag::Tree: return SortedMap{tree_.insert(key, value)}; } - FIREBASE_UNREACHABLE(); + UNREACHABLE(); } /** @@ -205,7 +205,7 @@ class SortedMap : public impl::SortedMapBase { } return SortedMap{std::move(result)}; } - FIREBASE_UNREACHABLE(); + UNREACHABLE(); } bool contains(const K& key) const { @@ -215,7 +215,7 @@ class SortedMap : public impl::SortedMapBase { case Tag::Tree: return tree_.contains(key); } - FIREBASE_UNREACHABLE(); + UNREACHABLE(); } /** @@ -232,7 +232,7 @@ class SortedMap : public impl::SortedMapBase { case Tag::Tree: return const_iterator{tree_.find(key)}; } - FIREBASE_UNREACHABLE(); + UNREACHABLE(); } /** @@ -248,7 +248,7 @@ class SortedMap : public impl::SortedMapBase { case Tag::Tree: return tree_.find_index(key); } - FIREBASE_UNREACHABLE(); + UNREACHABLE(); } /** @@ -267,7 +267,7 @@ class SortedMap : public impl::SortedMapBase { case Tag::Tree: return const_iterator{tree_.lower_bound(key)}; } - FIREBASE_UNREACHABLE(); + UNREACHABLE(); } const_iterator min() const { @@ -277,7 +277,7 @@ class SortedMap : public impl::SortedMapBase { case Tag::Tree: return const_iterator{tree_.min()}; } - FIREBASE_UNREACHABLE(); + UNREACHABLE(); } const_iterator max() const { @@ -287,7 +287,7 @@ class SortedMap : public impl::SortedMapBase { case Tag::Tree: return const_iterator{tree_.max()}; } - FIREBASE_UNREACHABLE(); + UNREACHABLE(); } /** @@ -301,7 +301,7 @@ class SortedMap : public impl::SortedMapBase { case Tag::Tree: return const_iterator{tree_.begin()}; } - FIREBASE_UNREACHABLE(); + UNREACHABLE(); } /** @@ -314,7 +314,7 @@ class SortedMap : public impl::SortedMapBase { case Tag::Tree: return const_iterator{tree_.end()}; } - FIREBASE_UNREACHABLE(); + UNREACHABLE(); } /** @@ -359,7 +359,7 @@ class SortedMap : public impl::SortedMapBase { case Tag::Tree: return tree_.comparator(); } - FIREBASE_UNREACHABLE(); + UNREACHABLE(); } enum class Tag { diff --git a/Firestore/core/src/firebase/firestore/immutable/sorted_map_iterator.h b/Firestore/core/src/firebase/firestore/immutable/sorted_map_iterator.h index a79f9f5..960e3f6 100644 --- a/Firestore/core/src/firebase/firestore/immutable/sorted_map_iterator.h +++ b/Firestore/core/src/firebase/firestore/immutable/sorted_map_iterator.h @@ -123,7 +123,7 @@ class SortedMapIterator { case Tag::Tree: return tree_iter_.get(); } - FIREBASE_UNREACHABLE(); + UNREACHABLE(); } reference operator*() const { @@ -164,7 +164,7 @@ class SortedMapIterator { case Tag::Tree: return a.tree_iter_ == b.tree_iter_; } - FIREBASE_UNREACHABLE(); + UNREACHABLE(); } bool operator!=(const SortedMapIterator& b) const { diff --git a/Firestore/core/src/firebase/firestore/immutable/sorted_set.h b/Firestore/core/src/firebase/firestore/immutable/sorted_set.h index d78fd61..1fe91bd 100644 --- a/Firestore/core/src/firebase/firestore/immutable/sorted_set.h +++ b/Firestore/core/src/firebase/firestore/immutable/sorted_set.h @@ -23,7 +23,7 @@ #include "Firestore/core/src/firebase/firestore/immutable/sorted_map.h" #include "Firestore/core/src/firebase/firestore/immutable/sorted_map_base.h" #include "Firestore/core/src/firebase/firestore/util/comparison.h" -#include "Firestore/core/src/firebase/firestore/util/firebase_assert.h" +#include "Firestore/core/src/firebase/firestore/util/hard_assert.h" #include "Firestore/core/src/firebase/firestore/util/hashing.h" namespace firebase { diff --git a/Firestore/core/src/firebase/firestore/local/leveldb_transaction.cc b/Firestore/core/src/firebase/firestore/local/leveldb_transaction.cc index 561d1e2..3581ef5 100644 --- a/Firestore/core/src/firebase/firestore/local/leveldb_transaction.cc +++ b/Firestore/core/src/firebase/firestore/local/leveldb_transaction.cc @@ -17,7 +17,7 @@ #include "Firestore/core/src/firebase/firestore/local/leveldb_transaction.h" #include "Firestore/core/src/firebase/firestore/local/leveldb_key.h" -#include "Firestore/core/src/firebase/firestore/util/firebase_assert.h" +#include "Firestore/core/src/firebase/firestore/util/hard_assert.h" #include "Firestore/core/src/firebase/firestore/util/log.h" #include "absl/memory/memory.h" #include "leveldb/write_batch.h" @@ -71,26 +71,24 @@ void LevelDbTransaction::Iterator::UpdateCurrent() { void LevelDbTransaction::Iterator::Seek(const std::string& key) { db_iter_->Seek(key); - FIREBASE_ASSERT_MESSAGE(db_iter_->status().ok(), - "leveldb iterator reported an error: %s", - db_iter_->status().ToString().c_str()); + HARD_ASSERT(db_iter_->status().ok(), "leveldb iterator reported an error: %s", + db_iter_->status().ToString()); for (; db_iter_->Valid() && IsDeleted(db_iter_->key()); db_iter_->Next()) { } - FIREBASE_ASSERT_MESSAGE(db_iter_->status().ok(), - "leveldb iterator reported an error: %s", - db_iter_->status().ToString().c_str()); + HARD_ASSERT(db_iter_->status().ok(), "leveldb iterator reported an error: %s", + db_iter_->status().ToString()); mutations_iter_ = txn_->mutations_.lower_bound(key); UpdateCurrent(); last_version_ = txn_->version_; } absl::string_view LevelDbTransaction::Iterator::key() { - FIREBASE_ASSERT_MESSAGE(Valid(), "key() called on invalid iterator"); + HARD_ASSERT(Valid(), "key() called on invalid iterator"); return current_.first; } absl::string_view LevelDbTransaction::Iterator::value() { - FIREBASE_ASSERT_MESSAGE(Valid(), "value() called on invalid iterator"); + HARD_ASSERT(Valid(), "value() called on invalid iterator"); return current_.second; } @@ -115,13 +113,12 @@ void LevelDbTransaction::Iterator::AdvanceLDB() { do { db_iter_->Next(); } while (db_iter_->Valid() && IsDeleted(db_iter_->key())); - FIREBASE_ASSERT_MESSAGE(db_iter_->status().ok(), - "leveldb iterator reported an error: %s", - db_iter_->status().ToString().c_str()); + HARD_ASSERT(db_iter_->status().ok(), "leveldb iterator reported an error: %s", + db_iter_->status().ToString()); } void LevelDbTransaction::Iterator::Next() { - FIREBASE_ASSERT_MESSAGE(Valid(), "Next() called on invalid iterator"); + HARD_ASSERT(Valid(), "Next() called on invalid iterator"); bool advanced = SyncToTransaction(); if (!advanced && is_valid_) { if (is_mutation_) { @@ -220,9 +217,8 @@ void LevelDbTransaction::Commit() { } Status status = db_->Write(write_options_, &batch); - FIREBASE_ASSERT_MESSAGE(status.ok(), - "Failed to commit transaction:\n%s\n Failed: %s", - ToString().c_str(), status.ToString().c_str()); + HARD_ASSERT(status.ok(), "Failed to commit transaction:\n%s\n Failed: %s", + ToString(), status.ToString()); } std::string LevelDbTransaction::ToString() { diff --git a/Firestore/core/src/firebase/firestore/model/base_path.h b/Firestore/core/src/firebase/firestore/model/base_path.h index 58df6f0..7608829 100644 --- a/Firestore/core/src/firebase/firestore/model/base_path.h +++ b/Firestore/core/src/firebase/firestore/model/base_path.h @@ -24,7 +24,7 @@ #include #include -#include "Firestore/core/src/firebase/firestore/util/firebase_assert.h" +#include "Firestore/core/src/firebase/firestore/util/hard_assert.h" #include "Firestore/core/src/firebase/firestore/util/hashing.h" namespace firebase { @@ -57,19 +57,18 @@ class BasePath { /** Returns i-th segment of the path. */ const std::string& operator[](const size_t i) const { - FIREBASE_ASSERT_MESSAGE(i < segments_.size(), "index %u out of range", i); + HARD_ASSERT(i < segments_.size(), "index %s out of range", i); return segments_[i]; } /** Returns the first segment of the path. */ const std::string& first_segment() const { - FIREBASE_ASSERT_MESSAGE(!empty(), - "Cannot call first_segment on empty path"); + HARD_ASSERT(!empty(), "Cannot call first_segment on empty path"); return segments_[0]; } /** Returns the last segment of the path. */ const std::string& last_segment() const { - FIREBASE_ASSERT_MESSAGE(!empty(), "Cannot call last_segment on empty path"); + HARD_ASSERT(!empty(), "Cannot call last_segment on empty path"); return segments_[size() - 1]; } @@ -117,9 +116,8 @@ class BasePath { * this path. */ T PopFirst(const size_t n = 1) const { - FIREBASE_ASSERT_MESSAGE(n <= size(), - "Cannot call PopFirst(%u) on path of length %u", n, - size()); + HARD_ASSERT(n <= size(), "Cannot call PopFirst(%s) on path of length %s", n, + size()); return T{begin() + n, end()}; } @@ -128,7 +126,7 @@ class BasePath { * this path. */ T PopLast() const { - FIREBASE_ASSERT_MESSAGE(!empty(), "Cannot call PopLast() on empty path"); + HARD_ASSERT(!empty(), "Cannot call PopLast() on empty path"); return T{begin(), end() - 1}; } diff --git a/Firestore/core/src/firebase/firestore/model/database_id.cc b/Firestore/core/src/firebase/firestore/model/database_id.cc index a756ea7..97e7d92 100644 --- a/Firestore/core/src/firebase/firestore/model/database_id.cc +++ b/Firestore/core/src/firebase/firestore/model/database_id.cc @@ -16,7 +16,7 @@ #include "Firestore/core/src/firebase/firestore/model/database_id.h" -#include "Firestore/core/src/firebase/firestore/util/firebase_assert.h" +#include "Firestore/core/src/firebase/firestore/util/hard_assert.h" namespace firebase { namespace firestore { @@ -27,8 +27,8 @@ constexpr const char* DatabaseId::kDefault; DatabaseId::DatabaseId(const absl::string_view project_id, const absl::string_view database_id) : project_id_(project_id), database_id_(database_id) { - FIREBASE_ASSERT(!project_id.empty()); - FIREBASE_ASSERT(!database_id.empty()); + HARD_ASSERT(!project_id.empty()); + HARD_ASSERT(!database_id.empty()); } } // namespace model diff --git a/Firestore/core/src/firebase/firestore/model/document.cc b/Firestore/core/src/firebase/firestore/model/document.cc index ae59d15..7adf684 100644 --- a/Firestore/core/src/firebase/firestore/model/document.cc +++ b/Firestore/core/src/firebase/firestore/model/document.cc @@ -18,7 +18,7 @@ #include -#include "Firestore/core/src/firebase/firestore/util/firebase_assert.h" +#include "Firestore/core/src/firebase/firestore/util/hard_assert.h" namespace firebase { namespace firestore { @@ -32,7 +32,7 @@ Document::Document(FieldValue&& data, data_(std::move(data)), has_local_mutations_(has_local_mutations) { set_type(Type::Document); - FIREBASE_ASSERT(FieldValue::Type::Object == data.type()); + HARD_ASSERT(FieldValue::Type::Object == data.type()); } bool Document::Equals(const MaybeDocument& other) const { diff --git a/Firestore/core/src/firebase/firestore/model/document_key.cc b/Firestore/core/src/firebase/firestore/model/document_key.cc index ddda4c9..7dae412 100644 --- a/Firestore/core/src/firebase/firestore/model/document_key.cc +++ b/Firestore/core/src/firebase/firestore/model/document_key.cc @@ -18,7 +18,7 @@ #include -#include "Firestore/core/src/firebase/firestore/util/firebase_assert.h" +#include "Firestore/core/src/firebase/firestore/util/hard_assert.h" namespace firebase { namespace firestore { @@ -27,9 +27,8 @@ namespace model { namespace { void AssertValidPath(const ResourcePath& path) { - FIREBASE_ASSERT_MESSAGE(DocumentKey::IsDocumentKey(path), - "invalid document key path: %s", - path.CanonicalString().c_str()); + HARD_ASSERT(DocumentKey::IsDocumentKey(path), "invalid document key path: %s", + path.CanonicalString()); } } // namespace diff --git a/Firestore/core/src/firebase/firestore/model/field_path.cc b/Firestore/core/src/firebase/firestore/model/field_path.cc index bc0e97c..5636b53 100644 --- a/Firestore/core/src/firebase/firestore/model/field_path.cc +++ b/Firestore/core/src/firebase/firestore/model/field_path.cc @@ -19,7 +19,7 @@ #include #include -#include "Firestore/core/src/firebase/firestore/util/firebase_assert.h" +#include "Firestore/core/src/firebase/firestore/util/hard_assert.h" #include "absl/strings/str_join.h" #include "absl/strings/str_replace.h" #include "absl/strings/str_split.h" @@ -71,18 +71,11 @@ FieldPath FieldPath::FromServerFormat(const absl::string_view path) { std::string segment; segment.reserve(path.size()); - // string_view doesn't have a c_str() method, because it might not be - // null-terminated. Assertions expect C strings, so construct std::string on - // the fly, so that c_str() might be called on it. - const auto to_string = [](const absl::string_view view) { - return std::string{view.data(), view.data() + view.size()}; - }; - const auto finish_segment = [&segments, &segment, &path, &to_string] { - FIREBASE_ASSERT_MESSAGE( - !segment.empty(), - "Invalid field path (%s). Paths must not be empty, begin with " - "'.', end with '.', or contain '..'", - to_string(path).c_str()); + const auto finish_segment = [&segments, &segment, &path] { + HARD_ASSERT(!segment.empty(), + "Invalid field path (%s). Paths must not be empty, begin with " + "'.', end with '.', or contain '..'", + path); // Move operation will clear segment, but capacity will remain the same // (not, strictly speaking, required by the standard, but true in practice). segments.push_back(std::move(segment)); @@ -116,9 +109,8 @@ FieldPath FieldPath::FromServerFormat(const absl::string_view path) { case '\\': // TODO(b/37244157): Make this a user-facing exception once we // finalize field escaping. - FIREBASE_ASSERT_MESSAGE(i + 1 != path.size(), - "Trailing escape characters not allowed in %s", - to_string(path).c_str()); + HARD_ASSERT(i + 1 != path.size(), + "Trailing escape characters not allowed in %s", path); ++i; segment += path[i]; break; @@ -131,8 +123,7 @@ FieldPath FieldPath::FromServerFormat(const absl::string_view path) { } finish_segment(); - FIREBASE_ASSERT_MESSAGE(!inside_backticks, "Unterminated ` in path %s", - to_string(path).c_str()); + HARD_ASSERT(!inside_backticks, "Unterminated ` in path %s", path); return FieldPath{std::move(segments)}; } diff --git a/Firestore/core/src/firebase/firestore/model/field_value.cc b/Firestore/core/src/firebase/firestore/model/field_value.cc index 35253c8..4f92c8b 100644 --- a/Firestore/core/src/firebase/firestore/model/field_value.cc +++ b/Firestore/core/src/firebase/firestore/model/field_value.cc @@ -23,7 +23,7 @@ #include #include "Firestore/core/src/firebase/firestore/util/comparison.h" -#include "Firestore/core/src/firebase/firestore/util/firebase_assert.h" +#include "Firestore/core/src/firebase/firestore/util/hard_assert.h" using firebase::firestore::util::Comparator; @@ -130,8 +130,7 @@ FieldValue& FieldValue::operator=(const FieldValue& value) { break; } default: - FIREBASE_ASSERT_MESSAGE_WITH_EXPRESSION( - false, lhs.type(), "Unsupported type %d", value.type()); + HARD_FAIL("Unsupported type %s", value.type()); } return *this; } @@ -168,10 +167,10 @@ FieldValue& FieldValue::operator=(FieldValue&& value) { FieldValue FieldValue::Set(const FieldPath& field_path, FieldValue value) const { - FIREBASE_ASSERT_MESSAGE(type() == Type::Object, - "Cannot set field for non-object FieldValue"); - FIREBASE_ASSERT_MESSAGE(!field_path.empty(), - "Cannot set field for empty path on FieldValue"); + HARD_ASSERT(type() == Type::Object, + "Cannot set field for non-object FieldValue"); + HARD_ASSERT(!field_path.empty(), + "Cannot set field for empty path on FieldValue"); // Set the value by recursively calling on child object. const std::string& child_name = field_path.first_segment(); const ObjectValue::Map& object_map = object_value_.internal_value; @@ -195,10 +194,10 @@ FieldValue FieldValue::Set(const FieldPath& field_path, } FieldValue FieldValue::Delete(const FieldPath& field_path) const { - FIREBASE_ASSERT_MESSAGE(type() == Type::Object, - "Cannot delete field for non-object FieldValue"); - FIREBASE_ASSERT_MESSAGE(!field_path.empty(), - "Cannot delete field for empty path on FieldValue"); + HARD_ASSERT(type() == Type::Object, + "Cannot delete field for non-object FieldValue"); + HARD_ASSERT(!field_path.empty(), + "Cannot delete field for empty path on FieldValue"); // Delete the value by recursively calling on child object. const std::string& child_name = field_path.first_segment(); const ObjectValue::Map& object_map = object_value_.internal_value; @@ -223,8 +222,8 @@ FieldValue FieldValue::Delete(const FieldPath& field_path) const { } absl::optional FieldValue::Get(const FieldPath& field_path) const { - FIREBASE_ASSERT_MESSAGE(type() == Type::Object, - "Cannot get field for non-object FieldValue"); + HARD_ASSERT(type() == Type::Object, + "Cannot get field for non-object FieldValue"); const FieldValue* current = this; for (const auto& path : field_path) { if (current->type() != Type::Object) { @@ -435,8 +434,7 @@ bool operator<(const FieldValue& lhs, const FieldValue& rhs) { case Type::Object: return lhs.object_value_ < rhs.object_value_; default: - FIREBASE_ASSERT_MESSAGE_WITH_EXPRESSION( - false, lhs.type(), "Unsupported type %d", lhs.type()); + HARD_FAIL("Unsupported type %s", lhs.type()); // return false if assertion does not abort the program. We will say // each unsupported type takes only one value thus everything is equal. return false; diff --git a/Firestore/core/src/firebase/firestore/model/field_value.h b/Firestore/core/src/firebase/firestore/model/field_value.h index 0f7dfc4..09c8531 100644 --- a/Firestore/core/src/firebase/firestore/model/field_value.h +++ b/Firestore/core/src/firebase/firestore/model/field_value.h @@ -28,7 +28,7 @@ #include "Firestore/core/src/firebase/firestore/model/database_id.h" #include "Firestore/core/src/firebase/firestore/model/document_key.h" #include "Firestore/core/src/firebase/firestore/model/field_path.h" -#include "Firestore/core/src/firebase/firestore/util/firebase_assert.h" +#include "Firestore/core/src/firebase/firestore/util/hard_assert.h" #include "absl/types/optional.h" namespace firebase { @@ -109,27 +109,27 @@ class FieldValue { } bool boolean_value() const { - FIREBASE_ASSERT(tag_ == Type::Boolean); + HARD_ASSERT(tag_ == Type::Boolean); return boolean_value_; } int64_t integer_value() const { - FIREBASE_ASSERT(tag_ == Type::Integer); + HARD_ASSERT(tag_ == Type::Integer); return integer_value_; } Timestamp timestamp_value() const { - FIREBASE_ASSERT(tag_ == Type::Timestamp); + HARD_ASSERT(tag_ == Type::Timestamp); return timestamp_value_; } const std::string& string_value() const { - FIREBASE_ASSERT(tag_ == Type::String); + HARD_ASSERT(tag_ == Type::String); return string_value_; } ObjectValue object_value() const { - FIREBASE_ASSERT(tag_ == Type::Object); + HARD_ASSERT(tag_ == Type::Object); return ObjectValue{object_value_}; } diff --git a/Firestore/core/src/firebase/firestore/model/maybe_document.cc b/Firestore/core/src/firebase/firestore/model/maybe_document.cc index 4f3be1d..aa5e15a 100644 --- a/Firestore/core/src/firebase/firestore/model/maybe_document.cc +++ b/Firestore/core/src/firebase/firestore/model/maybe_document.cc @@ -18,8 +18,6 @@ #include -#include "Firestore/core/src/firebase/firestore/util/firebase_assert.h" - namespace firebase { namespace firestore { namespace model { diff --git a/Firestore/core/src/firebase/firestore/model/precondition.cc b/Firestore/core/src/firebase/firestore/model/precondition.cc index 423d5a2..179b313 100644 --- a/Firestore/core/src/firebase/firestore/model/precondition.cc +++ b/Firestore/core/src/firebase/firestore/model/precondition.cc @@ -18,7 +18,7 @@ #include "Firestore/core/src/firebase/firestore/model/maybe_document.h" #include "Firestore/core/src/firebase/firestore/model/snapshot_version.h" -#include "Firestore/core/src/firebase/firestore/util/firebase_assert.h" +#include "Firestore/core/src/firebase/firestore/util/hard_assert.h" namespace firebase { namespace firestore { @@ -59,7 +59,7 @@ bool Precondition::IsValidFor(const MaybeDocument& maybe_doc) const { case Type::None: return true; } - FIREBASE_UNREACHABLE(); + UNREACHABLE(); } } // namespace model diff --git a/Firestore/core/src/firebase/firestore/model/precondition.h b/Firestore/core/src/firebase/firestore/model/precondition.h index b98bb45..b015100 100644 --- a/Firestore/core/src/firebase/firestore/model/precondition.h +++ b/Firestore/core/src/firebase/firestore/model/precondition.h @@ -27,7 +27,7 @@ #include "Firestore/core/src/firebase/firestore/model/maybe_document.h" #include "Firestore/core/src/firebase/firestore/model/snapshot_version.h" -#include "Firestore/core/src/firebase/firestore/util/firebase_assert.h" +#include "Firestore/core/src/firebase/firestore/util/hard_assert.h" namespace firebase { namespace firestore { @@ -104,7 +104,7 @@ class Precondition { case Type::None: return true; } - FIREBASE_UNREACHABLE(); + UNREACHABLE(); } // For Objective-C++ hash; to be removed after migration. @@ -131,10 +131,7 @@ class Precondition { stringWithFormat:@"", update_time_.timestamp().ToString().c_str()]; } - // We only raise dev assertion here. This function is mainly used in - // logging. - FIREBASE_DEV_ASSERT_MESSAGE(false, "precondition invalid"); - return @""; + UNREACHABLE(); } #endif // defined(__OBJC__) diff --git a/Firestore/core/src/firebase/firestore/model/resource_path.cc b/Firestore/core/src/firebase/firestore/model/resource_path.cc index c95aa63..cdd795f 100644 --- a/Firestore/core/src/firebase/firestore/model/resource_path.cc +++ b/Firestore/core/src/firebase/firestore/model/resource_path.cc @@ -20,7 +20,7 @@ #include #include -#include "Firestore/core/src/firebase/firestore/util/firebase_assert.h" +#include "Firestore/core/src/firebase/firestore/util/hard_assert.h" #include "absl/strings/str_join.h" #include "absl/strings/str_split.h" @@ -33,10 +33,8 @@ ResourcePath ResourcePath::FromString(const absl::string_view path) { // sequences (e.g. __id123__) and just passes them through raw (they exist // for legacy reasons and should not be used frequently). - FIREBASE_ASSERT_MESSAGE( - path.find("//") == std::string::npos, - "Invalid path (%s). Paths must not contain // in them.", - std::string{path.data(), path.data() + path.size()}.c_str()); + HARD_ASSERT(path.find("//") == std::string::npos, + "Invalid path (%s). Paths must not contain // in them.", path); // SkipEmpty because we may still have an empty segment at the beginning or // end if they had a leading or trailing slash (which we allow). diff --git a/Firestore/core/src/firebase/firestore/model/transform_operations.h b/Firestore/core/src/firebase/firestore/model/transform_operations.h index 8eed7ae..a5c5f82 100644 --- a/Firestore/core/src/firebase/firestore/model/transform_operations.h +++ b/Firestore/core/src/firebase/firestore/model/transform_operations.h @@ -191,8 +191,8 @@ class ArrayTransform : public TransformOperation { static const std::vector& Elements( const TransformOperation& op) { - FIREBASE_ASSERT(op.type() == Type::ArrayUnion || - op.type() == Type::ArrayRemove); + HARD_ASSERT(op.type() == Type::ArrayUnion || + op.type() == Type::ArrayRemove); return static_cast(op).elements(); } @@ -225,7 +225,7 @@ class ArrayTransform : public TransformOperation { [result addObject:element]; } } else { - FIREBASE_ASSERT(type_ == Type::ArrayRemove); + HARD_ASSERT(type_ == Type::ArrayRemove); [result removeObject:element]; } } diff --git a/Firestore/core/src/firebase/firestore/nanopb/reader.cc b/Firestore/core/src/firebase/firestore/nanopb/reader.cc index 86e38ac..7a12900 100644 --- a/Firestore/core/src/firebase/firestore/nanopb/reader.cc +++ b/Firestore/core/src/firebase/firestore/nanopb/reader.cc @@ -41,7 +41,7 @@ Tag Reader::ReadTag() { } // nanopb code always returns a false status when setting eof. - FIREBASE_ASSERT_MESSAGE(!eof, "nanopb set both ok status and eof to true"); + HARD_ASSERT(!eof, "nanopb set both ok status and eof to true"); return tag; } @@ -127,7 +127,7 @@ std::string Reader::ReadString() { // check within pb_close_string_substream. Unfortunately, that's not present // in the current version (0.38). We'll make a stronger assertion and check // to make sure there *are* no remaining characters in the substream. - FIREBASE_ASSERT_MESSAGE( + HARD_ASSERT( substream.bytes_left == 0, "Bytes remaining in substream after supposedly reading all of them."); diff --git a/Firestore/core/src/firebase/firestore/nanopb/reader.h b/Firestore/core/src/firebase/firestore/nanopb/reader.h index 093e20b..930211a 100644 --- a/Firestore/core/src/firebase/firestore/nanopb/reader.h +++ b/Firestore/core/src/firebase/firestore/nanopb/reader.h @@ -26,7 +26,7 @@ #include "Firestore/core/include/firebase/firestore/firestore_errors.h" #include "Firestore/core/src/firebase/firestore/nanopb/tag.h" -#include "Firestore/core/src/firebase/firestore/util/firebase_assert.h" +#include "Firestore/core/src/firebase/firestore/util/hard_assert.h" #include "Firestore/core/src/firebase/firestore/util/status.h" namespace firebase { @@ -159,7 +159,7 @@ T Reader::ReadNestedMessage(const std::function& read_message_fn) { // check within pb_close_string_substream. Unfortunately, that's not present // in the current version (0.38). We'll make a stronger assertion and check // to make sure there *are* no remaining characters in the substream. - FIREBASE_ASSERT_MESSAGE( + HARD_ASSERT( substream.bytes_left() == 0, "Bytes remaining in substream after supposedly reading all of them."); diff --git a/Firestore/core/src/firebase/firestore/nanopb/writer.cc b/Firestore/core/src/firebase/firestore/nanopb/writer.cc index cbee989..c3ffaac 100644 --- a/Firestore/core/src/firebase/firestore/nanopb/writer.cc +++ b/Firestore/core/src/firebase/firestore/nanopb/writer.cc @@ -58,7 +58,7 @@ void Writer::WriteTag(Tag tag) { if (!status_.ok()) return; if (!pb_encode_tag(&stream_, tag.wire_type, tag.field_number)) { - FIREBASE_ASSERT_MESSAGE(false, PB_GET_ERROR(&stream_)); + HARD_FAIL(PB_GET_ERROR(&stream_)); } } @@ -67,7 +67,7 @@ void Writer::WriteNanopbMessage(const pb_field_t fields[], if (!status_.ok()) return; if (!pb_encode(&stream_, fields, src_struct)) { - FIREBASE_ASSERT_MESSAGE(false, PB_GET_ERROR(&stream_)); + HARD_FAIL(PB_GET_ERROR(&stream_)); } } @@ -79,7 +79,7 @@ void Writer::WriteVarint(uint64_t value) { if (!status_.ok()) return; if (!pb_encode_varint(&stream_, value)) { - FIREBASE_ASSERT_MESSAGE(false, PB_GET_ERROR(&stream_)); + HARD_FAIL(PB_GET_ERROR(&stream_)); } } @@ -101,7 +101,7 @@ void Writer::WriteString(const std::string& string_value) { if (!pb_encode_string( &stream_, reinterpret_cast(string_value.c_str()), string_value.length())) { - FIREBASE_ASSERT_MESSAGE(false, PB_GET_ERROR(&stream_)); + HARD_FAIL(PB_GET_ERROR(&stream_)); } } @@ -126,15 +126,14 @@ void Writer::WriteNestedMessage( // fail since sizing streams don't actually have any buffer space.) if (stream_.callback == nullptr) { if (!pb_write(&stream_, nullptr, size)) { - FIREBASE_ASSERT_MESSAGE(false, PB_GET_ERROR(&stream_)); + HARD_FAIL(PB_GET_ERROR(&stream_)); } return; } // Ensure the output stream has enough space if (stream_.bytes_written + size > stream_.max_size) { - FIREBASE_ASSERT_MESSAGE( - false, + HARD_FAIL( "Insufficient space in the output stream to write the given message"); } @@ -155,8 +154,7 @@ void Writer::WriteNestedMessage( if (writer.bytes_written() != size) { // submsg size changed - FIREBASE_ASSERT_MESSAGE( - false, "Parsing the nested message twice yielded different sizes"); + HARD_FAIL("Parsing the nested message twice yielded different sizes"); } } diff --git a/Firestore/core/src/firebase/firestore/remote/serializer.cc b/Firestore/core/src/firebase/firestore/remote/serializer.cc index 3e7212c..47c2abf 100644 --- a/Firestore/core/src/firebase/firestore/remote/serializer.cc +++ b/Firestore/core/src/firebase/firestore/remote/serializer.cc @@ -36,7 +36,7 @@ #include "Firestore/core/src/firebase/firestore/nanopb/tag.h" #include "Firestore/core/src/firebase/firestore/nanopb/writer.h" #include "Firestore/core/src/firebase/firestore/timestamp_internal.h" -#include "Firestore/core/src/firebase/firestore/util/firebase_assert.h" +#include "Firestore/core/src/firebase/firestore/util/hard_assert.h" #include "absl/memory/memory.h" namespace firebase { @@ -203,9 +203,8 @@ FieldValue DecodeFieldValueImpl(Reader* reader) { // TODO(rsgowman): While still in development, we'll contradict the above // and assume the latter. Remove the following assertion when we're // confident that we're handling all the tags in the protos. - FIREBASE_ASSERT_MESSAGE( - false, - "Unhandled message field number (tag): %i. (Or possibly " + HARD_FAIL( + "Unhandled message field number (tag): %s. (Or possibly " "corrupt input bytes)", tag.field_number); reader->set_status(Status( @@ -235,8 +234,7 @@ FieldValue DecodeFieldValueImpl(Reader* reader) { default: // This indicates an internal error as we've already ensured that this is // a valid field_number. - FIREBASE_ASSERT_MESSAGE( - false, + HARD_FAIL( "Somehow got an unexpected field number (tag) after verifying that " "the field number was expected."); } @@ -286,14 +284,14 @@ ObjectValue::Map::value_type DecodeFieldsEntry(Reader* reader, // TODO(rsgowman): figure out error handling: We can do better than a failed // assertion. - FIREBASE_ASSERT(tag.field_number == key_tag); - FIREBASE_ASSERT(tag.wire_type == PB_WT_STRING); + HARD_ASSERT(tag.field_number == key_tag); + HARD_ASSERT(tag.wire_type == PB_WT_STRING); std::string key = reader->ReadString(); tag = reader->ReadTag(); if (!reader->status().ok()) return {}; - FIREBASE_ASSERT(tag.field_number == value_tag); - FIREBASE_ASSERT(tag.wire_type == PB_WT_STRING); + HARD_ASSERT(tag.field_number == value_tag); + HARD_ASSERT(tag.wire_type == PB_WT_STRING); FieldValue value = reader->ReadNestedMessage(DecodeFieldValueImpl); @@ -344,9 +342,9 @@ ObjectValue::Map DecodeMapValue(Reader* reader) { // The MapValue message only has a single valid tag. // TODO(rsgowman): figure out error handling: We can do better than a // failed assertion. - FIREBASE_ASSERT(tag.field_number == - google_firestore_v1beta1_MapValue_fields_tag); - FIREBASE_ASSERT(tag.wire_type == PB_WT_STRING); + HARD_ASSERT(tag.field_number == + google_firestore_v1beta1_MapValue_fields_tag); + HARD_ASSERT(tag.wire_type == PB_WT_STRING); ObjectValue::Map::value_type fv = reader->ReadNestedMessage( @@ -407,9 +405,9 @@ bool IsValidResourceName(const ResourcePath& path) { */ ResourcePath DecodeResourceName(absl::string_view encoded) { ResourcePath resource = ResourcePath::FromString(encoded); - FIREBASE_ASSERT_MESSAGE(IsValidResourceName(resource), - "Tried to deserialize invalid key %s", - resource.CanonicalString().c_str()); + HARD_ASSERT(IsValidResourceName(resource), + "Tried to deserialize invalid key %s", + resource.CanonicalString()); return resource; } @@ -420,10 +418,9 @@ ResourcePath DecodeResourceName(absl::string_view encoded) { */ ResourcePath ExtractLocalPathFromResourceName( const ResourcePath& resource_name) { - FIREBASE_ASSERT_MESSAGE( - resource_name.size() > 4 && resource_name[4] == "documents", - "Tried to deserialize invalid key %s", - resource_name.CanonicalString().c_str()); + HARD_ASSERT(resource_name.size() > 4 && resource_name[4] == "documents", + "Tried to deserialize invalid key %s", + resource_name.CanonicalString()); return resource_name.PopFirst(5); } @@ -453,10 +450,10 @@ std::string Serializer::EncodeKey(const DocumentKey& key) const { DocumentKey Serializer::DecodeKey(absl::string_view name) const { ResourcePath resource = DecodeResourceName(name); - FIREBASE_ASSERT_MESSAGE(resource[1] == database_id_.project_id(), - "Tried to deserialize key from different project."); - FIREBASE_ASSERT_MESSAGE(resource[3] == database_id_.database_id(), - "Tried to deserialize key from different database."); + HARD_ASSERT(resource[1] == database_id_.project_id(), + "Tried to deserialize key from different project."); + HARD_ASSERT(resource[3] == database_id_.database_id(), + "Tried to deserialize key from different database."); return DocumentKey{ExtractLocalPathFromResourceName(resource)}; } @@ -538,8 +535,7 @@ std::unique_ptr Serializer::DecodeBatchGetDocumentsResponse( default: // This indicates an internal error as we've already ensured that this is // a valid field_number. - FIREBASE_ASSERT_MESSAGE( - false, + HARD_FAIL( "Somehow got an unexpected field number (tag) after verifying that " "the field number was expected."); } @@ -555,7 +551,7 @@ std::unique_ptr Serializer::DecodeDocument(Reader* reader) const { while (reader->bytes_left()) { Tag tag = reader->ReadTag(); if (!reader->status().ok()) return nullptr; - FIREBASE_ASSERT(tag.wire_type == PB_WT_STRING); + HARD_ASSERT(tag.wire_type == PB_WT_STRING); switch (tag.field_number) { case google_firestore_v1beta1_Document_name_tag: name = reader->ReadString(); diff --git a/Firestore/core/src/firebase/firestore/remote/serializer.h b/Firestore/core/src/firebase/firestore/remote/serializer.h index e79c238..379069c 100644 --- a/Firestore/core/src/firebase/firestore/remote/serializer.h +++ b/Firestore/core/src/firebase/firestore/remote/serializer.h @@ -30,7 +30,7 @@ #include "Firestore/core/src/firebase/firestore/model/maybe_document.h" #include "Firestore/core/src/firebase/firestore/nanopb/reader.h" #include "Firestore/core/src/firebase/firestore/nanopb/writer.h" -#include "Firestore/core/src/firebase/firestore/util/firebase_assert.h" +#include "Firestore/core/src/firebase/firestore/util/hard_assert.h" #include "Firestore/core/src/firebase/firestore/util/status.h" #include "Firestore/core/src/firebase/firestore/util/statusor.h" #include "absl/base/attributes.h" diff --git a/Firestore/core/src/firebase/firestore/timestamp.cc b/Firestore/core/src/firebase/firestore/timestamp.cc index a5f0121..c35fca1 100644 --- a/Firestore/core/src/firebase/firestore/timestamp.cc +++ b/Firestore/core/src/firebase/firestore/timestamp.cc @@ -16,7 +16,7 @@ #include "Firestore/core/include/firebase/firestore/timestamp.h" -#include "Firestore/core/src/firebase/firestore/util/firebase_assert.h" +#include "Firestore/core/src/firebase/firestore/util/hard_assert.h" namespace firebase { @@ -58,7 +58,7 @@ Timestamp Timestamp::FromTimePoint( const auto epoch_time = time_point.time_since_epoch(); auto seconds = chr::duration_cast>(epoch_time); auto nanoseconds = chr::duration_cast(epoch_time - seconds); - FIREBASE_DEV_ASSERT(nanoseconds.count() < 1 * 1000 * 1000 * 1000); + HARD_ASSERT(nanoseconds.count() < 1 * 1000 * 1000 * 1000); if (nanoseconds.count() < 0) { // Timestamp format always has a positive number of nanoseconds that is @@ -89,19 +89,17 @@ std::string Timestamp::ToString() const { } void Timestamp::ValidateBounds() const { - FIREBASE_ASSERT_MESSAGE(nanoseconds_ >= 0, - "Timestamp nanoseconds out of range: %d", - nanoseconds_); - FIREBASE_ASSERT_MESSAGE(nanoseconds_ < 1e9, - "Timestamp nanoseconds out of range: %d", - nanoseconds_); + HARD_ASSERT(nanoseconds_ >= 0, "Timestamp nanoseconds out of range: %s", + nanoseconds_); + HARD_ASSERT(nanoseconds_ < 1e9, "Timestamp nanoseconds out of range: %s", + nanoseconds_); // Midnight at the beginning of 1/1/1 is the earliest timestamp Firestore // supports. - FIREBASE_ASSERT_MESSAGE(seconds_ >= -62135596800L, - "Timestamp seconds out of range: %lld", seconds_); + HARD_ASSERT(seconds_ >= -62135596800L, "Timestamp seconds out of range: %s", + seconds_); // This will break in the year 10,000. - FIREBASE_ASSERT_MESSAGE(seconds_ < 253402300800L, - "Timestamp seconds out of range: %lld", seconds_); + HARD_ASSERT(seconds_ < 253402300800L, "Timestamp seconds out of range: %s", + seconds_); } } // namespace firebase diff --git a/Firestore/core/src/firebase/firestore/util/CMakeLists.txt b/Firestore/core/src/firebase/firestore/util/CMakeLists.txt index 2c12fa4..043713f 100644 --- a/Firestore/core/src/firebase/firestore/util/CMakeLists.txt +++ b/Firestore/core/src/firebase/firestore/util/CMakeLists.txt @@ -24,8 +24,6 @@ cc_library( SOURCES string_format.cc string_format.h - string_printf.cc - string_printf.h DEPENDS absl_base absl_strings @@ -36,8 +34,8 @@ cc_library( cc_library( firebase_firestore_util_log_stdio SOURCES - firebase_assert.h - assert_stdio.cc + hard_assert_stdio.cc + hard_assert.h log.h log_stdio.cc DEPENDS @@ -49,14 +47,15 @@ cc_library( cc_library( firebase_firestore_util_log_apple SOURCES - firebase_assert.h - assert_apple.mm + hard_assert.h + hard_assert_apple.mm log.h log_apple.mm string_apple.h DEPENDS FirebaseCore absl_strings + firebase_firestore_util_base EXCLUDE_FROM_ALL ) diff --git a/Firestore/core/src/firebase/firestore/util/assert_apple.mm b/Firestore/core/src/firebase/firestore/util/assert_apple.mm deleted file mode 100644 index 9b6a651..0000000 --- a/Firestore/core/src/firebase/firestore/util/assert_apple.mm +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright 2018 Google - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#import - -// TODO(wilhuff): match basenames so this can move up top -#include "Firestore/core/src/firebase/firestore/util/firebase_assert.h" -#include "Firestore/core/src/firebase/firestore/util/string_apple.h" - -namespace firebase { -namespace firestore { -namespace util { - -void FailAssert(const char* file, - const char* func, - const int line, - const char* format, - ...) { - va_list args; - va_start(args, format); - NSString* description = - [[NSString alloc] initWithFormat:WrapNSStringNoCopy(format) - arguments:args]; - va_end(args); - [[NSAssertionHandler currentHandler] - handleFailureInFunction:WrapNSStringNoCopy(func) - file:WrapNSStringNoCopy(file) - lineNumber:line - description:@"FIRESTORE INTERNAL ASSERTION FAILED: %@", - description]; - abort(); -} - -} // namespace util -} // namespace firestore -} // namespace firebase diff --git a/Firestore/core/src/firebase/firestore/util/assert_stdio.cc b/Firestore/core/src/firebase/firestore/util/assert_stdio.cc deleted file mode 100644 index e01e564..0000000 --- a/Firestore/core/src/firebase/firestore/util/assert_stdio.cc +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 2018 Google - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include -#include - -#include "Firestore/core/src/firebase/firestore/util/firebase_assert.h" -#include "Firestore/core/src/firebase/firestore/util/string_printf.h" -#include "absl/base/config.h" - -namespace firebase { -namespace firestore { -namespace util { - -void FailAssert(const char* file, - const char* func, - const int line, - const char* format, - ...) { - std::string message; - StringAppendF(&message, "ASSERT: %s(%d) %s: ", file, line, func); - - va_list args; - va_start(args, format); - StringAppendV(&message, format, args); - va_end(args); - -#if ABSL_HAVE_EXCEPTIONS - throw std::logic_error(message); - -#else - fprintf(stderr, "%s\n", message.c_str()); - std::terminate(); -#endif -} - -} // namespace util -} // namespace firestore -} // namespace firebase diff --git a/Firestore/core/src/firebase/firestore/util/async_queue.cc b/Firestore/core/src/firebase/firestore/util/async_queue.cc index 81aac7c..b42dec3 100644 --- a/Firestore/core/src/firebase/firestore/util/async_queue.cc +++ b/Firestore/core/src/firebase/firestore/util/async_queue.cc @@ -18,7 +18,7 @@ #include -#include "Firestore/core/src/firebase/firestore/util/firebase_assert.h" +#include "Firestore/core/src/firebase/firestore/util/hard_assert.h" #include "absl/memory/memory.h" namespace firebase { @@ -35,27 +35,26 @@ AsyncQueue::AsyncQueue(std::unique_ptr executor) // TODO(varconst): assert in destructor that the queue is empty. void AsyncQueue::VerifyIsCurrentExecutor() const { - FIREBASE_ASSERT_MESSAGE( + HARD_ASSERT( executor_->IsCurrentExecutor(), "Expected to be called by the executor associated with this queue " "(expected executor: '%s', actual executor: '%s')", - executor_->Name().c_str(), executor_->CurrentExecutorName().c_str()); + executor_->Name(), executor_->CurrentExecutorName()); } void AsyncQueue::VerifyIsCurrentQueue() const { VerifyIsCurrentExecutor(); - FIREBASE_ASSERT_MESSAGE( - is_operation_in_progress_, - "VerifyIsCurrentQueue called when no operation is executing " - "(expected executor: '%s', actual executor: '%s')", - executor_->Name().c_str(), executor_->CurrentExecutorName().c_str()); + HARD_ASSERT(is_operation_in_progress_, + "VerifyIsCurrentQueue called when no operation is executing " + "(expected executor: '%s', actual executor: '%s')", + executor_->Name(), executor_->CurrentExecutorName()); } void AsyncQueue::ExecuteBlocking(const Operation& operation) { VerifyIsCurrentExecutor(); - FIREBASE_ASSERT_MESSAGE(!is_operation_in_progress_, - "ExecuteBlocking may not be called " - "before the previous operation finishes executing"); + HARD_ASSERT(!is_operation_in_progress_, + "ExecuteBlocking may not be called " + "before the previous operation finishes executing"); is_operation_in_progress_ = true; operation(); @@ -79,9 +78,8 @@ DelayedOperation AsyncQueue::EnqueueAfterDelay(const Milliseconds delay, // While not necessarily harmful, we currently don't expect to have multiple // callbacks with the same timer_id in the queue, so defensively reject // them. - FIREBASE_ASSERT_MESSAGE( - !IsScheduled(timer_id), - "Attempted to schedule multiple operations with id %d", timer_id); + HARD_ASSERT(!IsScheduled(timer_id), + "Attempted to schedule multiple operations with id %s", timer_id); Executor::TaggedOperation tagged{static_cast(timer_id), Wrap(operation)}; return executor_->Schedule(delay, std::move(tagged)); @@ -97,12 +95,11 @@ AsyncQueue::Operation AsyncQueue::Wrap(const Operation& operation) { void AsyncQueue::VerifySequentialOrder() const { // This is the inverse of `VerifyIsCurrentQueue`. - FIREBASE_ASSERT_MESSAGE( - !is_operation_in_progress_ || !executor_->IsCurrentExecutor(), - "Enqueue methods cannot be called when we are already running on " - "target executor" - "(this queue's executor: '%s', current executor: '%s')", - executor_->Name().c_str(), executor_->CurrentExecutorName().c_str()); + HARD_ASSERT(!is_operation_in_progress_ || !executor_->IsCurrentExecutor(), + "Enqueue methods cannot be called when we are already running on " + "target executor " + "(this queue's executor: '%s', current executor: '%s')", + executor_->Name(), executor_->CurrentExecutorName()); } // Test-only functions @@ -117,14 +114,13 @@ bool AsyncQueue::IsScheduled(const TimerId timer_id) const { } void AsyncQueue::RunScheduledOperationsUntil(const TimerId last_timer_id) { - FIREBASE_ASSERT_MESSAGE( - !executor_->IsCurrentExecutor(), - "RunScheduledOperationsUntil must not be called on the queue"); + HARD_ASSERT(!executor_->IsCurrentExecutor(), + "RunScheduledOperationsUntil must not be called on the queue"); executor_->ExecuteBlocking([this, last_timer_id] { - FIREBASE_ASSERT_MESSAGE( + HARD_ASSERT( last_timer_id == TimerId::All || IsScheduled(last_timer_id), - "Attempted to run scheduled operations until missing timer id: %d", + "Attempted to run scheduled operations until missing timer id: %s", last_timer_id); for (auto next = executor_->PopFromSchedule(); next.has_value(); diff --git a/Firestore/core/src/firebase/firestore/util/bits.cc b/Firestore/core/src/firebase/firestore/util/bits.cc index 0bfe4c3..03d9b77 100644 --- a/Firestore/core/src/firebase/firestore/util/bits.cc +++ b/Firestore/core/src/firebase/firestore/util/bits.cc @@ -16,7 +16,7 @@ #include "Firestore/core/src/firebase/firestore/util/bits.h" -#include "Firestore/core/src/firebase/firestore/util/firebase_assert.h" +#include "Firestore/core/src/firebase/firestore/util/hard_assert.h" namespace firebase { namespace firestore { @@ -34,7 +34,7 @@ int Bits::Log2Floor_Portable(uint32_t n) { log += shift; } } - FIREBASE_ASSERT(value == 1); + HARD_ASSERT(value == 1); return log; } diff --git a/Firestore/core/src/firebase/firestore/util/executor_libdispatch.h b/Firestore/core/src/firebase/firestore/util/executor_libdispatch.h index f913fe5..d356a74 100644 --- a/Firestore/core/src/firebase/firestore/util/executor_libdispatch.h +++ b/Firestore/core/src/firebase/firestore/util/executor_libdispatch.h @@ -26,7 +26,6 @@ #include "dispatch/dispatch.h" #include "Firestore/core/src/firebase/firestore/util/executor.h" -#include "Firestore/core/src/firebase/firestore/util/firebase_assert.h" #include "absl/strings/string_view.h" #if !defined(__OBJC__) diff --git a/Firestore/core/src/firebase/firestore/util/executor_libdispatch.mm b/Firestore/core/src/firebase/firestore/util/executor_libdispatch.mm index 597d450..70d0b3a 100644 --- a/Firestore/core/src/firebase/firestore/util/executor_libdispatch.mm +++ b/Firestore/core/src/firebase/firestore/util/executor_libdispatch.mm @@ -16,6 +16,8 @@ #include "Firestore/core/src/firebase/firestore/util/executor_libdispatch.h" +#include "Firestore/core/src/firebase/firestore/util/hard_assert.h" + namespace firebase { namespace firestore { namespace util { @@ -55,7 +57,7 @@ void DispatchAsync(const dispatch_queue_t queue, std::function&& work) { } void DispatchSync(const dispatch_queue_t queue, std::function work) { - FIREBASE_ASSERT_MESSAGE( + HARD_ASSERT( GetCurrentQueueLabel() != GetQueueLabel(queue), "Calling DispatchSync on the current queue will lead to a deadlock."); @@ -176,8 +178,8 @@ void TimeSlot::Execute() { RemoveFromSchedule(); - FIREBASE_ASSERT_MESSAGE(tagged_.operation, - "TimeSlot contains an invalid function object"); + HARD_ASSERT(tagged_.operation, + "TimeSlot contains an invalid function object"); tagged_.operation(); } diff --git a/Firestore/core/src/firebase/firestore/util/executor_std.cc b/Firestore/core/src/firebase/firestore/util/executor_std.cc index f03a712..a87ec20 100644 --- a/Firestore/core/src/firebase/firestore/util/executor_std.cc +++ b/Firestore/core/src/firebase/firestore/util/executor_std.cc @@ -64,8 +64,7 @@ DelayedOperation ExecutorStd::Schedule(const Milliseconds delay, // While negative delay can be interpreted as a request for immediate // execution, supporting it would provide a hacky way to modify FIFO ordering // of immediate operations. - FIREBASE_ASSERT_MESSAGE(delay.count() >= 0, - "Schedule: delay cannot be negative"); + HARD_ASSERT(delay.count() >= 0, "Schedule: delay cannot be negative"); namespace chr = std::chrono; const auto now = chr::time_point_cast(chr::steady_clock::now()); diff --git a/Firestore/core/src/firebase/firestore/util/executor_std.h b/Firestore/core/src/firebase/firestore/util/executor_std.h index b6f0b6b..efe60db 100644 --- a/Firestore/core/src/firebase/firestore/util/executor_std.h +++ b/Firestore/core/src/firebase/firestore/util/executor_std.h @@ -27,7 +27,7 @@ #include #include "Firestore/core/src/firebase/firestore/util/executor.h" -#include "Firestore/core/src/firebase/firestore/util/firebase_assert.h" +#include "Firestore/core/src/firebase/firestore/util/hard_assert.h" #include "absl/types/optional.h" namespace firebase { @@ -181,8 +181,8 @@ class Schedule { // This function expects the mutex to be already locked. T ExtractLocked(const Iterator where) { - FIREBASE_ASSERT_MESSAGE(!scheduled_.empty(), - "Trying to pop an entry from an empty queue."); + HARD_ASSERT(!scheduled_.empty(), + "Trying to pop an entry from an empty queue."); T result = std::move(where->value); scheduled_.erase(where); diff --git a/Firestore/core/src/firebase/firestore/util/firebase_assert.h b/Firestore/core/src/firebase/firestore/util/firebase_assert.h deleted file mode 100644 index 6a9c2eb..0000000 --- a/Firestore/core/src/firebase/firestore/util/firebase_assert.h +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Copyright 2018 Google - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// To avoid naming-collision, this header is called firebase_assert.h instead -// of assert.h. - -#ifndef FIRESTORE_CORE_SRC_FIREBASE_FIRESTORE_UTIL_FIREBASE_ASSERT_H_ -#define FIRESTORE_CORE_SRC_FIREBASE_FIRESTORE_UTIL_FIREBASE_ASSERT_H_ - -#include - -#include "Firestore/core/src/firebase/firestore/util/log.h" -#include "absl/base/attributes.h" - -#define FIREBASE_EXPAND_STRINGIFY_(X) #X -#define FIREBASE_EXPAND_STRINGIFY(X) FIREBASE_EXPAND_STRINGIFY_(X) - -// FIREBASE_ASSERT_* macros are not compiled out of release builds. They should -// be used for assertions that need to be propagated to end-users of SDKs. -// FIREBASE_DEV_ASSERT_* macros are compiled out of release builds, similar to -// the C assert() macro. They should be used for internal assertions that are -// only shown to SDK developers. - -// Assert condition is true, if it's false log an assert with the specified -// expression as a string. -#define FIREBASE_ASSERT_WITH_EXPRESSION(condition, expression) \ - do { \ - if (!(condition)) { \ - firebase::firestore::util::FailAssert( \ - __FILE__, __PRETTY_FUNCTION__, __LINE__, \ - FIREBASE_EXPAND_STRINGIFY(expression)); \ - } \ - } while (0) - -// Assert condition is true, if it's false log an assert with the specified -// expression as a string. Compiled out of release builds. -#if defined(NDEBUG) -#define FIREBASE_DEV_ASSERT_WITH_EXPRESSION(condition, expression) \ - { (void)(condition); } -#else -#define FIREBASE_DEV_ASSERT_WITH_EXPRESSION(condition, expression) \ - FIREBASE_ASSERT_WITH_EXPRESSION(condition, expression) -#endif // defined(NDEBUG) - -// Custom assert() implementation that is not compiled out in release builds. -#define FIREBASE_ASSERT(expression) \ - FIREBASE_ASSERT_WITH_EXPRESSION(expression, expression) - -// Custom assert() implementation that is compiled out in release builds. -// Compiled out of release builds. -#define FIREBASE_DEV_ASSERT(expression) \ - FIREBASE_DEV_ASSERT_WITH_EXPRESSION(expression, expression) - -// Assert condition is true otherwise display the specified expression, -// message and abort. -#define FIREBASE_ASSERT_MESSAGE_WITH_EXPRESSION(condition, expression, ...) \ - do { \ - if (!(condition)) { \ - firebase::firestore::util::LogError( \ - FIREBASE_EXPAND_STRINGIFY(expression)); \ - firebase::firestore::util::FailAssert(__FILE__, __PRETTY_FUNCTION__, \ - __LINE__, __VA_ARGS__); \ - } \ - } while (0) - -// Assert condition is true otherwise display the specified expression, -// message and abort. Compiled out of release builds. -#if defined(NDEBUG) -#define FIREBASE_DEV_ASSERT_MESSAGE_WITH_EXPRESSION(condition, expression, \ - ...) \ - { (void)(condition); } -#else -#define FIREBASE_DEV_ASSERT_MESSAGE_WITH_EXPRESSION(condition, expression, \ - ...) \ - FIREBASE_ASSERT_MESSAGE_WITH_EXPRESSION(condition, expression, __VA_ARGS__) -#endif // defined(NDEBUG) - -// Assert expression is true otherwise display the specified message and -// abort. -#define FIREBASE_ASSERT_MESSAGE(expression, ...) \ - FIREBASE_ASSERT_MESSAGE_WITH_EXPRESSION(expression, expression, __VA_ARGS__) - -// Assert expression is true otherwise display the specified message and -// abort. Compiled out of release builds. -#define FIREBASE_DEV_ASSERT_MESSAGE(expression, ...) \ - FIREBASE_DEV_ASSERT_MESSAGE_WITH_EXPRESSION(expression, expression, \ - __VA_ARGS__) - -// Indicates an area of the code that cannot be reached (except possibly due to -// undefined behaviour or other similar badness). The only reasonable thing to -// do in these cases is to immediately abort. -#define FIREBASE_UNREACHABLE() abort() - -namespace firebase { -namespace firestore { -namespace util { - -// A no-return helper function. To raise an assertion, use Macro instead. -ABSL_ATTRIBUTE_NORETURN void FailAssert( - const char* file, const char* func, int line, const char* format, ...); - -} // namespace util -} // namespace firestore -} // namespace firebase - -#endif // FIRESTORE_CORE_SRC_FIREBASE_FIRESTORE_UTIL_FIREBASE_ASSERT_H_ diff --git a/Firestore/core/src/firebase/firestore/util/hard_assert.h b/Firestore/core/src/firebase/firestore/util/hard_assert.h new file mode 100644 index 0000000..e60d71a --- /dev/null +++ b/Firestore/core/src/firebase/firestore/util/hard_assert.h @@ -0,0 +1,88 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FIRESTORE_CORE_SRC_FIREBASE_FIRESTORE_UTIL_HARD_ASSERT_H_ +#define FIRESTORE_CORE_SRC_FIREBASE_FIRESTORE_UTIL_HARD_ASSERT_H_ + +#include + +#include "Firestore/core/src/firebase/firestore/util/string_format.h" + +/** + * Fails the current function if the given condition is false. + * + * Unlike assert(3) or NSAssert, this macro is never compiled out. + * + * @param condition The condition to test. + * @param format (optional) A format string suitable for util::StringFormat. + * @param ... format arguments to pass to util::StringFormat. + */ +#define HARD_ASSERT(condition, ...) \ + do { \ + if (!(condition)) { \ + std::string _message = \ + firebase::firestore::util::StringFormat(__VA_ARGS__); \ + firebase::firestore::util::internal::Fail( \ + __FILE__, __PRETTY_FUNCTION__, __LINE__, _message, #condition); \ + } \ + } while (0) + +/** + * Unconditionally fails the current function. + * + * Unlike assert(3) or NSAssert, this macro is never compiled out. + * + * @param format A format string suitable for util::StringFormat. + * @param ... format arguments to pass to util::StringFormat. + */ +#define HARD_FAIL(...) \ + do { \ + std::string _failure = \ + firebase::firestore::util::StringFormat(__VA_ARGS__); \ + firebase::firestore::util::internal::Fail(__FILE__, __PRETTY_FUNCTION__, \ + __LINE__, _failure); \ + } while (0) + +/** + * Indicates an area of the code that cannot be reached (except possibly due to + * undefined behaviour or other similar badness). The only reasonable thing to + * do in these cases is to immediately abort. + */ +#define UNREACHABLE() abort() + +namespace firebase { +namespace firestore { +namespace util { +namespace internal { + +// A no-return helper function. To raise an assertion, use Macro instead. +ABSL_ATTRIBUTE_NORETURN void Fail(const char* file, + const char* func, + int line, + const std::string& message); + +ABSL_ATTRIBUTE_NORETURN void Fail(const char* file, + const char* func, + int line, + const std::string& message, + const char* condition); + +} // namespace internal +} // namespace util +} // namespace firestore +} // namespace firebase + +#endif // FIRESTORE_CORE_SRC_FIREBASE_FIRESTORE_UTIL_HARD_ASSERT_H_ diff --git a/Firestore/core/src/firebase/firestore/util/hard_assert_apple.mm b/Firestore/core/src/firebase/firestore/util/hard_assert_apple.mm new file mode 100644 index 0000000..3324fe8 --- /dev/null +++ b/Firestore/core/src/firebase/firestore/util/hard_assert_apple.mm @@ -0,0 +1,60 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "Firestore/core/src/firebase/firestore/util/hard_assert.h" + +#import + +#include + +#include "Firestore/core/src/firebase/firestore/util/string_apple.h" + +namespace firebase { +namespace firestore { +namespace util { +namespace internal { + +void Fail(const char* file, + const char* func, + const int line, + const std::string& message) { + [[NSAssertionHandler currentHandler] + handleFailureInFunction:WrapNSStringNoCopy(func) + file:WrapNSStringNoCopy(file) + lineNumber:line + description:@"FIRESTORE INTERNAL ASSERTION FAILED: %s", + message.c_str()]; + abort(); +} + +void Fail(const char* file, + const char* func, + const int line, + const std::string& message, + const char* condition) { + std::string failure; + if (message.empty()) { + failure = condition; + } else { + failure = StringFormat("%s (expected %s)", message, condition); + } + Fail(file, func, line, failure); +} + +} // namespace internal +} // namespace util +} // namespace firestore +} // namespace firebase diff --git a/Firestore/core/src/firebase/firestore/util/hard_assert_stdio.cc b/Firestore/core/src/firebase/firestore/util/hard_assert_stdio.cc new file mode 100644 index 0000000..6c50eb7 --- /dev/null +++ b/Firestore/core/src/firebase/firestore/util/hard_assert_stdio.cc @@ -0,0 +1,64 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "Firestore/core/src/firebase/firestore/util/hard_assert.h" + +#include +#include +#include + +#include "Firestore/core/src/firebase/firestore/util/string_format.h" +#include "absl/base/config.h" + +namespace firebase { +namespace firestore { +namespace util { +namespace internal { + +void Fail(const char* file, + const char* func, + const int line, + const std::string& message) { + std::string failure = + StringFormat("ASSERT: %s(%s) %s: %s", file, line, func, message); + +#if ABSL_HAVE_EXCEPTIONS + throw std::logic_error(failure); + +#else + fprintf(stderr, "%s\n", failure.c_str()); + std::terminate(); +#endif +} + +void Fail(const char* file, + const char* func, + const int line, + const std::string& message, + const char* condition) { + std::string failure; + if (message.empty()) { + failure = condition; + } else { + failure = StringFormat("%s (expected %s)", message, condition); + } + Fail(file, func, line, failure); +} + +} // namespace internal +} // namespace util +} // namespace firestore +} // namespace firebase diff --git a/Firestore/core/src/firebase/firestore/util/ordered_code.cc b/Firestore/core/src/firebase/firestore/util/ordered_code.cc index cb53b09..03da08d 100644 --- a/Firestore/core/src/firebase/firestore/util/ordered_code.cc +++ b/Firestore/core/src/firebase/firestore/util/ordered_code.cc @@ -17,7 +17,7 @@ #include "Firestore/core/src/firebase/firestore/util/ordered_code.h" #include "Firestore/core/src/firebase/firestore/util/bits.h" -#include "Firestore/core/src/firebase/firestore/util/firebase_assert.h" +#include "Firestore/core/src/firebase/firestore/util/hard_assert.h" #include "absl/base/internal/endian.h" #include "absl/base/internal/unaligned_access.h" #include "absl/base/port.h" @@ -99,20 +99,20 @@ inline static bool IsSpecialByte(char c) { * assertion checking). */ inline static int AdvanceIfNoSpecialBytes(uint32_t v_32, const char* p) { - FIREBASE_DEV_ASSERT(UNALIGNED_LOAD32(p) == v_32); + HARD_ASSERT(UNALIGNED_LOAD32(p) == v_32); // See comments in SkipToNextSpecialByte if you wish to // understand this expression (which checks for the occurrence // of the special byte values 0 or 255 in any of the bytes of v_32). if ((v_32 - 0x01010101u) & ~(v_32 + 0x01010101u) & 0x80808080u) { // Special byte is in p[0..3] - FIREBASE_DEV_ASSERT(IsSpecialByte(p[0]) || IsSpecialByte(p[1]) || - IsSpecialByte(p[2]) || IsSpecialByte(p[3])); + HARD_ASSERT(IsSpecialByte(p[0]) || IsSpecialByte(p[1]) || + IsSpecialByte(p[2]) || IsSpecialByte(p[3])); return 0; } else { - FIREBASE_DEV_ASSERT(!IsSpecialByte(p[0])); - FIREBASE_DEV_ASSERT(!IsSpecialByte(p[1])); - FIREBASE_DEV_ASSERT(!IsSpecialByte(p[2])); - FIREBASE_DEV_ASSERT(!IsSpecialByte(p[3])); + HARD_ASSERT(!IsSpecialByte(p[0])); + HARD_ASSERT(!IsSpecialByte(p[1])); + HARD_ASSERT(!IsSpecialByte(p[2])); + HARD_ASSERT(!IsSpecialByte(p[3])); return 4; } } @@ -125,8 +125,8 @@ inline static int AdvanceIfNoSpecialBytes(uint32_t v_32, const char* p) { inline static const char* SkipToNextSpecialByte(const char* start, const char* limit) { // If these constants were ever changed, this routine needs to change - FIREBASE_DEV_ASSERT(kEscape1 == 0); - FIREBASE_DEV_ASSERT((kEscape2 & 0xff) == 255); + HARD_ASSERT(kEscape1 == 0); + HARD_ASSERT((kEscape2 & 0xff) == 255); const char* p = start; while (p + 8 <= limit) { // Find out if any of the next 8 bytes are either 0 or 255 (our @@ -164,8 +164,7 @@ inline static const char* SkipToNextSpecialByte(const char* start, if (IsSpecialByte(p[0])) return p; if (IsSpecialByte(p[1])) return p + 1; if (IsSpecialByte(p[2])) return p + 2; - FIREBASE_DEV_ASSERT( - IsSpecialByte(p[3])); // Last byte must be the special one + HARD_ASSERT(IsSpecialByte(p[3])); // Last byte must be the special one return p + 3; } } @@ -198,14 +197,14 @@ inline static void EncodeStringFragment(std::string* dest, p = SkipToNextSpecialByte(p, limit); if (p >= limit) break; // No more special characters that need escaping char c = *(p++); - FIREBASE_DEV_ASSERT(IsSpecialByte(c)); + HARD_ASSERT(IsSpecialByte(c)); if (c == kEscape1) { AppendBytes(dest, copy_start, static_cast(p - copy_start) - 1); dest->push_back(kEscape1); dest->push_back(kNullCharacter); copy_start = p; } else { - FIREBASE_DEV_ASSERT(c == kEscape2); + HARD_ASSERT(c == kEscape2); AppendBytes(dest, copy_start, static_cast(p - copy_start) - 1); dest->push_back(kEscape2); dest->push_back(kFFCharacter); @@ -302,7 +301,7 @@ inline static bool ReadStringInternal(absl::string_view* src, // If inversion is required, instead of inverting 'c', we invert the // character constants to which 'c' is compared. We get the same // behavior but save the runtime cost of inverting 'c'. - FIREBASE_DEV_ASSERT(IsSpecialByte(c)); + HARD_ASSERT(IsSpecialByte(c)); if (c == kEscape1) { if (result) { AppendBytes(result, copy_start, @@ -323,7 +322,7 @@ inline static bool ReadStringInternal(absl::string_view* src, } copy_start = start; } else { - FIREBASE_DEV_ASSERT(c == kEscape2); + HARD_ASSERT(c == kEscape2); if (result) { AppendBytes(result, copy_start, static_cast(start - copy_start) - 1); @@ -359,7 +358,7 @@ bool OrderedCode::ReadNumIncreasing(absl::string_view* src, uint64_t* result) { // If len > 0 and src is longer than 1, the first byte of "payload" // must be non-zero (otherwise the encoding is not minimal). // In opt mode, we don't enforce that encodings must be minimal. - FIREBASE_DEV_ASSERT(0 == len || src->size() == 1 || (*src)[1] != '\0'); + HARD_ASSERT(0 == len || src->size() == 1 || (*src)[1] != '\0'); if (len + 1 > src->size() || len > 8) { return false; // Not enough bytes or too many bytes @@ -557,11 +556,9 @@ void OrderedCode::WriteSignedNumIncreasing(std::string* dest, int64_t val) { }; UNALIGNED_STORE64(buf + 2, absl::ghtonll(static_cast(val))); - FIREBASE_DEV_ASSERT_MESSAGE_WITH_EXPRESSION(sizeof(buf) == kMaxSigned64Length, - sizeof(buf) == kMaxSigned64Length, - "max length size mismatch"); + HARD_ASSERT(sizeof(buf) == kMaxSigned64Length, "max length size mismatch"); const size_t len = static_cast(SignedEncodingLengthPositive(x)); - FIREBASE_DEV_ASSERT(len >= 2); + HARD_ASSERT(len >= 2); char* const begin = buf + sizeof(buf) - len; begin[0] ^= kLengthToHeaderBits[len][0]; begin[1] ^= kLengthToHeaderBits[len][1]; // ok because len >= 2 @@ -608,8 +605,8 @@ bool OrderedCode::ReadSignedNumIncreasing(absl::string_view* src, x ^= kLengthToMask[len]; // remove spurious header bits - FIREBASE_DEV_ASSERT(len == static_cast(SignedEncodingLength( - static_cast(x)))); + HARD_ASSERT(len == static_cast( + SignedEncodingLength(static_cast(x)))); if (result) *result = static_cast(x); src->remove_prefix(static_cast(len)); diff --git a/Firestore/core/src/firebase/firestore/util/status.cc b/Firestore/core/src/firebase/firestore/util/status.cc index e918846..46f3ce6 100644 --- a/Firestore/core/src/firebase/firestore/util/status.cc +++ b/Firestore/core/src/firebase/firestore/util/status.cc @@ -23,7 +23,7 @@ namespace firestore { namespace util { Status::Status(FirestoreErrorCode code, absl::string_view msg) { - FIREBASE_ASSERT(code != FirestoreErrorCode::Ok); + HARD_ASSERT(code != FirestoreErrorCode::Ok); state_ = std::unique_ptr(new State); state_->code = code; state_->msg = static_cast(msg); @@ -117,7 +117,7 @@ void Status::IgnoreError() const { } std::string StatusCheckOpHelperOutOfLine(const Status& v, const char* msg) { - FIREBASE_ASSERT(!v.ok()); + HARD_ASSERT(!v.ok()); std::string r("Non-OK-status: "); r += msg; r += " status: "; diff --git a/Firestore/core/src/firebase/firestore/util/status.h b/Firestore/core/src/firebase/firestore/util/status.h index 13bf320..9121b36 100644 --- a/Firestore/core/src/firebase/firestore/util/status.h +++ b/Firestore/core/src/firebase/firestore/util/status.h @@ -23,7 +23,7 @@ #include #include "Firestore/core/include/firebase/firestore/firestore_errors.h" -#include "Firestore/core/src/firebase/firestore/util/firebase_assert.h" +#include "Firestore/core/src/firebase/firestore/util/hard_assert.h" #include "absl/base/attributes.h" #include "absl/strings/string_view.h" @@ -124,15 +124,8 @@ typedef std::function StatusCallback; extern std::string StatusCheckOpHelperOutOfLine(const Status& v, const char* msg); -#define STATUS_CHECK_OK(val) \ - FIREBASE_ASSERT_MESSAGE_WITH_EXPRESSION( \ - val.ok(), val.ok(), StatusCheckOpHelperOutOfLine(val, #val).c_str()) - -// DEBUG only version of STATUS_CHECK_OK. Compiler still parses 'val' even in -// opt mode. -#define STATUS_DCHECK_OK(val) \ - FIREBASE_DEV_ASSERT_MESSAGE_WITH_EXPRESSION( \ - val.ok(), val.ok(), StatusCheckOpHelperOutOfLine(val, #val).c_str()) +#define STATUS_CHECK_OK(val) \ + HARD_ASSERT(val.ok(), "%s", StatusCheckOpHelperOutOfLine(val, #val)) } // namespace util } // namespace firestore diff --git a/Firestore/core/src/firebase/firestore/util/statusor.cc b/Firestore/core/src/firebase/firestore/util/statusor.cc index be1e03a..bbd5781 100644 --- a/Firestore/core/src/firebase/firestore/util/statusor.cc +++ b/Firestore/core/src/firebase/firestore/util/statusor.cc @@ -15,6 +15,7 @@ */ #include "Firestore/core/src/firebase/firestore/util/statusor.h" +#include "Firestore/core/src/firebase/firestore/util/hard_assert.h" namespace firebase { namespace firestore { @@ -24,15 +25,14 @@ namespace internal_statusor { void Helper::HandleInvalidStatusCtorArg(Status* status) { const char* kMessage = "An OK status is not a valid constructor argument to StatusOr"; - FIREBASE_DEV_ASSERT_MESSAGE(false, kMessage); + HARD_FAIL("%s", kMessage); // Fall back to Internal for non-debug builds *status = Status(FirestoreErrorCode::Internal, kMessage); } void Helper::Crash(const Status& status) { - FIREBASE_ASSERT_MESSAGE( - false, "Attempting to fetch value instead of handling error ", - status.ToString().c_str()); + HARD_FAIL("Attempting to fetch value instead of handling error %s", + status.ToString()); } } // namespace internal_statusor diff --git a/Firestore/core/src/firebase/firestore/util/string_printf.cc b/Firestore/core/src/firebase/firestore/util/string_printf.cc deleted file mode 100644 index c5483f4..0000000 --- a/Firestore/core/src/firebase/firestore/util/string_printf.cc +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright 2018 Google - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "Firestore/core/src/firebase/firestore/util/string_printf.h" - -#include - -namespace firebase { -namespace firestore { -namespace util { - -void StringAppendV(std::string* dst, const char* format, va_list ap) { - // First try with a small fixed size buffer - static const int kSpaceLength = 1024; - char space[kSpaceLength]; - - // It's possible for methods that use a va_list to invalidate - // the data in it upon use. The fix is to make a copy - // of the structure before using it and use that copy instead. - va_list backup_ap; - va_copy(backup_ap, ap); - int result = vsnprintf(space, kSpaceLength, format, backup_ap); - va_end(backup_ap); - - if (result < kSpaceLength) { - if (result >= 0) { - // Normal case -- everything fit. - dst->append(space, static_cast(result)); - return; - } - -#ifdef _MSC_VER - // Error or MSVC running out of space. MSVC 8.0 and higher - // can be asked about space needed with the special idiom below: - va_copy(backup_ap, ap); - result = vsnprintf(nullptr, 0, format, backup_ap); - va_end(backup_ap); -#endif - } - - if (result < 0) { - // Just an error. - return; - } - size_t result_size = static_cast(result); - - // Increase the buffer size to the size requested by vsnprintf, - // plus one for the closing \0. - size_t initial_size = dst->size(); - size_t target_size = initial_size + result_size; - - dst->resize(target_size + 1); - char* buf = &(*dst)[initial_size]; - size_t buf_remain = result_size + 1; - - // Restore the va_list before we use it again - va_copy(backup_ap, ap); - result = vsnprintf(buf, buf_remain, format, backup_ap); - va_end(backup_ap); - - if (result >= 0 && static_cast(result) < buf_remain) { - // It fit and vsnprintf copied in directly. Resize down one to - // remove the trailing \0. - dst->resize(target_size); - } else { - // Didn't fit. Leave the original string unchanged. - dst->resize(initial_size); - } -} - -std::string StringPrintf(const char* format, ...) { - va_list ap; - va_start(ap, format); - std::string result; - StringAppendV(&result, format, ap); - va_end(ap); - return result; -} - -void StringAppendF(std::string* dst, const char* format, ...) { - va_list ap; - va_start(ap, format); - StringAppendV(dst, format, ap); - va_end(ap); -} - -} // namespace util -} // namespace firestore -} // namespace firebase diff --git a/Firestore/core/src/firebase/firestore/util/string_printf.h b/Firestore/core/src/firebase/firestore/util/string_printf.h deleted file mode 100644 index 553af66..0000000 --- a/Firestore/core/src/firebase/firestore/util/string_printf.h +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright 2018 Google - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef FIRESTORE_CORE_SRC_FIREBASE_FIRESTORE_UTIL_STRING_PRINTF_H_ -#define FIRESTORE_CORE_SRC_FIREBASE_FIRESTORE_UTIL_STRING_PRINTF_H_ - -#include -#include - -#include "absl/base/attributes.h" - -namespace firebase { -namespace firestore { -namespace util { - -/** Return a C++ string. */ -std::string StringPrintf(const char* format, ...) ABSL_PRINTF_ATTRIBUTE(1, 2); - -/** Append result to a supplied string. */ -void StringAppendF(std::string* dst, const char* format, ...) - ABSL_PRINTF_ATTRIBUTE(2, 3); - -/** - * Lower-level routine that takes a va_list and appends to a specified - * string. All other routines are just convenience wrappers around it. - */ -void StringAppendV(std::string* dst, const char* format, va_list ap); - -} // namespace util -} // namespace firestore -} // namespace firebase - -#endif // FIRESTORE_CORE_SRC_FIREBASE_FIRESTORE_UTIL_STRING_PRINTF_H_ -- cgit v1.2.3