flag.h 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660
  1. //
  2. // Copyright 2019 The Abseil Authors.
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // https://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. #ifndef ABSL_FLAGS_INTERNAL_FLAG_H_
  16. #define ABSL_FLAGS_INTERNAL_FLAG_H_
  17. #include <stdint.h>
  18. #include <atomic>
  19. #include <cstring>
  20. #include <memory>
  21. #include <string>
  22. #include <type_traits>
  23. #include "absl/base/call_once.h"
  24. #include "absl/base/config.h"
  25. #include "absl/base/thread_annotations.h"
  26. #include "absl/flags/config.h"
  27. #include "absl/flags/internal/commandlineflag.h"
  28. #include "absl/flags/internal/registry.h"
  29. #include "absl/memory/memory.h"
  30. #include "absl/strings/str_cat.h"
  31. #include "absl/strings/string_view.h"
  32. #include "absl/synchronization/mutex.h"
  33. namespace absl {
  34. ABSL_NAMESPACE_BEGIN
  35. namespace flags_internal {
  36. template <typename T>
  37. class Flag;
  38. ///////////////////////////////////////////////////////////////////////////////
  39. // Type-specific operations, eg., parsing, copying, etc. are provided
  40. // by function specific to that type with a signature matching FlagOpFn.
  41. enum FlagOp {
  42. kDelete,
  43. kClone,
  44. kCopy,
  45. kCopyConstruct,
  46. kSizeof,
  47. kStaticTypeId,
  48. kParse,
  49. kUnparse,
  50. };
  51. using FlagOpFn = void* (*)(FlagOp, const void*, void*, void*);
  52. // The per-type function
  53. template <typename T>
  54. void* FlagOps(FlagOp op, const void* v1, void* v2, void* v3) {
  55. switch (op) {
  56. case flags_internal::kDelete:
  57. delete static_cast<const T*>(v1);
  58. return nullptr;
  59. case flags_internal::kClone:
  60. return new T(*static_cast<const T*>(v1));
  61. case flags_internal::kCopy:
  62. *static_cast<T*>(v2) = *static_cast<const T*>(v1);
  63. return nullptr;
  64. case flags_internal::kCopyConstruct:
  65. new (v2) T(*static_cast<const T*>(v1));
  66. return nullptr;
  67. case flags_internal::kSizeof:
  68. return reinterpret_cast<void*>(sizeof(T));
  69. case flags_internal::kStaticTypeId:
  70. return reinterpret_cast<void*>(&FlagStaticTypeIdGen<T>);
  71. case flags_internal::kParse: {
  72. // Initialize the temporary instance of type T based on current value in
  73. // destination (which is going to be flag's default value).
  74. T temp(*static_cast<T*>(v2));
  75. if (!absl::ParseFlag<T>(*static_cast<const absl::string_view*>(v1), &temp,
  76. static_cast<std::string*>(v3))) {
  77. return nullptr;
  78. }
  79. *static_cast<T*>(v2) = std::move(temp);
  80. return v2;
  81. }
  82. case flags_internal::kUnparse:
  83. *static_cast<std::string*>(v2) =
  84. absl::UnparseFlag<T>(*static_cast<const T*>(v1));
  85. return nullptr;
  86. default:
  87. return nullptr;
  88. }
  89. }
  90. // Functions that invoke flag-type-specific operations.
  91. inline void Delete(FlagOpFn op, const void* obj) {
  92. op(flags_internal::kDelete, obj, nullptr, nullptr);
  93. }
  94. inline void* Clone(FlagOpFn op, const void* obj) {
  95. return op(flags_internal::kClone, obj, nullptr, nullptr);
  96. }
  97. inline void Copy(FlagOpFn op, const void* src, void* dst) {
  98. op(flags_internal::kCopy, src, dst, nullptr);
  99. }
  100. inline void CopyConstruct(FlagOpFn op, const void* src, void* dst) {
  101. op(flags_internal::kCopyConstruct, src, dst, nullptr);
  102. }
  103. inline bool Parse(FlagOpFn op, absl::string_view text, void* dst,
  104. std::string* error) {
  105. return op(flags_internal::kParse, &text, dst, error) != nullptr;
  106. }
  107. inline std::string Unparse(FlagOpFn op, const void* val) {
  108. std::string result;
  109. op(flags_internal::kUnparse, val, &result, nullptr);
  110. return result;
  111. }
  112. inline size_t Sizeof(FlagOpFn op) {
  113. // This sequence of casts reverses the sequence from
  114. // `flags_internal::FlagOps()`
  115. return static_cast<size_t>(reinterpret_cast<intptr_t>(
  116. op(flags_internal::kSizeof, nullptr, nullptr, nullptr)));
  117. }
  118. inline FlagStaticTypeId StaticTypeId(FlagOpFn op) {
  119. return reinterpret_cast<FlagStaticTypeId>(
  120. op(flags_internal::kStaticTypeId, nullptr, nullptr, nullptr));
  121. }
  122. ///////////////////////////////////////////////////////////////////////////////
  123. // Persistent state of the flag data.
  124. template <typename T>
  125. class FlagState : public flags_internal::FlagStateInterface {
  126. public:
  127. FlagState(Flag<T>* flag, T&& cur, bool modified, bool on_command_line,
  128. int64_t counter)
  129. : flag_(flag),
  130. cur_value_(std::move(cur)),
  131. modified_(modified),
  132. on_command_line_(on_command_line),
  133. counter_(counter) {}
  134. ~FlagState() override = default;
  135. private:
  136. friend class Flag<T>;
  137. // Restores the flag to the saved state.
  138. void Restore() const override;
  139. // Flag and saved flag data.
  140. Flag<T>* flag_;
  141. T cur_value_;
  142. bool modified_;
  143. bool on_command_line_;
  144. int64_t counter_;
  145. };
  146. ///////////////////////////////////////////////////////////////////////////////
  147. // Flag help auxiliary structs.
  148. // This is help argument for absl::Flag encapsulating the string literal pointer
  149. // or pointer to function generating it as well as enum descriminating two
  150. // cases.
  151. using HelpGenFunc = std::string (*)();
  152. union FlagHelpMsg {
  153. constexpr explicit FlagHelpMsg(const char* help_msg) : literal(help_msg) {}
  154. constexpr explicit FlagHelpMsg(HelpGenFunc help_gen) : gen_func(help_gen) {}
  155. const char* literal;
  156. HelpGenFunc gen_func;
  157. };
  158. enum class FlagHelpKind : uint8_t { kLiteral = 0, kGenFunc = 1 };
  159. struct FlagHelpArg {
  160. FlagHelpMsg source;
  161. FlagHelpKind kind;
  162. };
  163. extern const char kStrippedFlagHelp[];
  164. // HelpConstexprWrap is used by struct AbslFlagHelpGenFor##name generated by
  165. // ABSL_FLAG macro. It is only used to silence the compiler in the case where
  166. // help message expression is not constexpr and does not have type const char*.
  167. // If help message expression is indeed constexpr const char* HelpConstexprWrap
  168. // is just a trivial identity function.
  169. template <typename T>
  170. const char* HelpConstexprWrap(const T&) {
  171. return nullptr;
  172. }
  173. constexpr const char* HelpConstexprWrap(const char* p) { return p; }
  174. constexpr const char* HelpConstexprWrap(char* p) { return p; }
  175. // These two HelpArg overloads allows us to select at compile time one of two
  176. // way to pass Help argument to absl::Flag. We'll be passing
  177. // AbslFlagHelpGenFor##name as T and integer 0 as a single argument to prefer
  178. // first overload if possible. If T::Const is evaluatable on constexpr
  179. // context (see non template int parameter below) we'll choose first overload.
  180. // In this case the help message expression is immediately evaluated and is used
  181. // to construct the absl::Flag. No additionl code is generated by ABSL_FLAG.
  182. // Otherwise SFINAE kicks in and first overload is dropped from the
  183. // consideration, in which case the second overload will be used. The second
  184. // overload does not attempt to evaluate the help message expression
  185. // immediately and instead delays the evaluation by returing the function
  186. // pointer (&T::NonConst) genering the help message when necessary. This is
  187. // evaluatable in constexpr context, but the cost is an extra function being
  188. // generated in the ABSL_FLAG code.
  189. template <typename T, int = (T::Const(), 1)>
  190. constexpr FlagHelpArg HelpArg(int) {
  191. return {FlagHelpMsg(T::Const()), FlagHelpKind::kLiteral};
  192. }
  193. template <typename T>
  194. constexpr FlagHelpArg HelpArg(char) {
  195. return {FlagHelpMsg(&T::NonConst), FlagHelpKind::kGenFunc};
  196. }
  197. ///////////////////////////////////////////////////////////////////////////////
  198. // Flag default value auxiliary structs.
  199. // Signature for the function generating the initial flag value (usually
  200. // based on default value supplied in flag's definition)
  201. using FlagDfltGenFunc = void* (*)();
  202. union FlagDefaultSrc {
  203. constexpr explicit FlagDefaultSrc(FlagDfltGenFunc gen_func_arg)
  204. : gen_func(gen_func_arg) {}
  205. void* dynamic_value;
  206. FlagDfltGenFunc gen_func;
  207. };
  208. enum class FlagDefaultKind : uint8_t { kDynamicValue = 0, kGenFunc = 1 };
  209. ///////////////////////////////////////////////////////////////////////////////
  210. // Flag current value auxiliary structs.
  211. // The minimum atomic size we believe to generate lock free code, i.e. all
  212. // trivially copyable types not bigger this size generate lock free code.
  213. static constexpr int kMinLockFreeAtomicSize = 8;
  214. // The same as kMinLockFreeAtomicSize but maximum atomic size. As double words
  215. // might use two registers, we want to dispatch the logic for them.
  216. #if defined(ABSL_FLAGS_INTERNAL_ATOMIC_DOUBLE_WORD)
  217. static constexpr int kMaxLockFreeAtomicSize = 16;
  218. #else
  219. static constexpr int kMaxLockFreeAtomicSize = 8;
  220. #endif
  221. // We can use atomic in cases when it fits in the register, trivially copyable
  222. // in order to make memcpy operations.
  223. template <typename T>
  224. struct IsAtomicFlagTypeTrait {
  225. static constexpr bool value =
  226. (sizeof(T) <= kMaxLockFreeAtomicSize &&
  227. type_traits_internal::is_trivially_copyable<T>::value);
  228. };
  229. // Clang does not always produce cmpxchg16b instruction when alignment of a 16
  230. // bytes type is not 16.
  231. struct alignas(16) FlagsInternalTwoWordsType {
  232. int64_t first;
  233. int64_t second;
  234. };
  235. constexpr bool operator==(const FlagsInternalTwoWordsType& that,
  236. const FlagsInternalTwoWordsType& other) {
  237. return that.first == other.first && that.second == other.second;
  238. }
  239. constexpr bool operator!=(const FlagsInternalTwoWordsType& that,
  240. const FlagsInternalTwoWordsType& other) {
  241. return !(that == other);
  242. }
  243. constexpr int64_t SmallAtomicInit() { return 0xababababababababll; }
  244. template <typename T, typename S = void>
  245. struct BestAtomicType {
  246. using type = int64_t;
  247. static constexpr int64_t AtomicInit() { return SmallAtomicInit(); }
  248. };
  249. template <typename T>
  250. struct BestAtomicType<
  251. T, typename std::enable_if<(kMinLockFreeAtomicSize < sizeof(T) &&
  252. sizeof(T) <= kMaxLockFreeAtomicSize),
  253. void>::type> {
  254. using type = FlagsInternalTwoWordsType;
  255. static constexpr FlagsInternalTwoWordsType AtomicInit() {
  256. return {SmallAtomicInit(), SmallAtomicInit()};
  257. }
  258. };
  259. struct FlagValue {
  260. // Heap allocated value.
  261. void* dynamic = nullptr;
  262. // For some types, a copy of the current value is kept in an atomically
  263. // accessible field.
  264. union Atomics {
  265. // Using small atomic for small types.
  266. std::atomic<int64_t> small_atomic;
  267. template <typename T,
  268. typename K = typename std::enable_if<
  269. (sizeof(T) <= kMinLockFreeAtomicSize), void>::type>
  270. int64_t load() const {
  271. return small_atomic.load(std::memory_order_acquire);
  272. }
  273. #if defined(ABSL_FLAGS_INTERNAL_ATOMIC_DOUBLE_WORD)
  274. // Using big atomics for big types.
  275. std::atomic<FlagsInternalTwoWordsType> big_atomic;
  276. template <typename T, typename K = typename std::enable_if<
  277. (kMinLockFreeAtomicSize < sizeof(T) &&
  278. sizeof(T) <= kMaxLockFreeAtomicSize),
  279. void>::type>
  280. FlagsInternalTwoWordsType load() const {
  281. return big_atomic.load(std::memory_order_acquire);
  282. }
  283. constexpr Atomics()
  284. : big_atomic{FlagsInternalTwoWordsType{SmallAtomicInit(),
  285. SmallAtomicInit()}} {}
  286. #else
  287. constexpr Atomics() : small_atomic{SmallAtomicInit()} {}
  288. #endif
  289. };
  290. Atomics atomics{};
  291. };
  292. ///////////////////////////////////////////////////////////////////////////////
  293. // Flag callback auxiliary structs.
  294. // Signature for the mutation callback used by watched Flags
  295. // The callback is noexcept.
  296. // TODO(rogeeff): add noexcept after C++17 support is added.
  297. using FlagCallbackFunc = void (*)();
  298. struct FlagCallback {
  299. FlagCallbackFunc func;
  300. absl::Mutex guard; // Guard for concurrent callback invocations.
  301. };
  302. ///////////////////////////////////////////////////////////////////////////////
  303. // Flag implementation, which does not depend on flag value type.
  304. // The class encapsulates the Flag's data and access to it.
  305. struct DynValueDeleter {
  306. explicit DynValueDeleter(FlagOpFn op_arg = nullptr) : op(op_arg) {}
  307. void operator()(void* ptr) const {
  308. if (op != nullptr) Delete(op, ptr);
  309. }
  310. const FlagOpFn op;
  311. };
  312. class FlagImpl {
  313. public:
  314. constexpr FlagImpl(const char* name, const char* filename, FlagOpFn op,
  315. FlagHelpArg help, FlagDfltGenFunc default_value_gen)
  316. : name_(name),
  317. filename_(filename),
  318. op_(op),
  319. help_(help.source),
  320. help_source_kind_(static_cast<uint8_t>(help.kind)),
  321. def_kind_(static_cast<uint8_t>(FlagDefaultKind::kGenFunc)),
  322. modified_(false),
  323. on_command_line_(false),
  324. counter_(0),
  325. callback_(nullptr),
  326. default_src_(default_value_gen),
  327. data_guard_{} {}
  328. // Constant access methods
  329. absl::string_view Name() const;
  330. std::string Filename() const;
  331. std::string Help() const;
  332. bool IsModified() const ABSL_LOCKS_EXCLUDED(*DataGuard());
  333. bool IsSpecifiedOnCommandLine() const ABSL_LOCKS_EXCLUDED(*DataGuard());
  334. std::string DefaultValue() const ABSL_LOCKS_EXCLUDED(*DataGuard());
  335. std::string CurrentValue() const ABSL_LOCKS_EXCLUDED(*DataGuard());
  336. void Read(void* dst) const ABSL_LOCKS_EXCLUDED(*DataGuard());
  337. // Attempts to parse supplied `value` std::string. If parsing is successful, then
  338. // it replaces `dst` with the new value.
  339. bool TryParse(void** dst, absl::string_view value, std::string* err) const
  340. ABSL_EXCLUSIVE_LOCKS_REQUIRED(*DataGuard());
  341. template <typename T, typename std::enable_if<
  342. !IsAtomicFlagTypeTrait<T>::value, int>::type = 0>
  343. void Get(T* dst) const {
  344. AssertValidType(&flags_internal::FlagStaticTypeIdGen<T>);
  345. Read(dst);
  346. }
  347. // Overload for `GetFlag()` for types that support lock-free reads.
  348. template <typename T, typename std::enable_if<IsAtomicFlagTypeTrait<T>::value,
  349. int>::type = 0>
  350. void Get(T* dst) const {
  351. // For flags of types which can be accessed "atomically" we want to avoid
  352. // slowing down flag value access due to type validation. That's why
  353. // this validation is hidden behind !NDEBUG
  354. #ifndef NDEBUG
  355. AssertValidType(&flags_internal::FlagStaticTypeIdGen<T>);
  356. #endif
  357. using U = flags_internal::BestAtomicType<T>;
  358. typename U::type r = value_.atomics.template load<T>();
  359. if (r != U::AtomicInit()) {
  360. std::memcpy(static_cast<void*>(dst), &r, sizeof(T));
  361. } else {
  362. Read(dst);
  363. }
  364. }
  365. template <typename T>
  366. void Set(const T& src) {
  367. AssertValidType(&flags_internal::FlagStaticTypeIdGen<T>);
  368. Write(&src);
  369. }
  370. // Mutating access methods
  371. void Write(const void* src) ABSL_LOCKS_EXCLUDED(*DataGuard());
  372. bool SetFromString(absl::string_view value, FlagSettingMode set_mode,
  373. ValueSource source, std::string* err)
  374. ABSL_LOCKS_EXCLUDED(*DataGuard());
  375. // If possible, updates copy of the Flag's value that is stored in an
  376. // atomic word.
  377. void StoreAtomic() ABSL_EXCLUSIVE_LOCKS_REQUIRED(*DataGuard());
  378. // Interfaces to operate on callbacks.
  379. void SetCallback(const FlagCallbackFunc mutation_callback)
  380. ABSL_LOCKS_EXCLUDED(*DataGuard());
  381. void InvokeCallback() const ABSL_EXCLUSIVE_LOCKS_REQUIRED(*DataGuard());
  382. // Interfaces to save/restore mutable flag data
  383. template <typename T>
  384. std::unique_ptr<FlagStateInterface> SaveState(Flag<T>* flag) const
  385. ABSL_LOCKS_EXCLUDED(*DataGuard()) {
  386. T&& cur_value = flag->Get();
  387. absl::MutexLock l(DataGuard());
  388. return absl::make_unique<FlagState<T>>(
  389. flag, std::move(cur_value), modified_, on_command_line_, counter_);
  390. }
  391. bool RestoreState(const void* value, bool modified, bool on_command_line,
  392. int64_t counter) ABSL_LOCKS_EXCLUDED(*DataGuard());
  393. // Value validation interfaces.
  394. void CheckDefaultValueParsingRoundtrip() const
  395. ABSL_LOCKS_EXCLUDED(*DataGuard());
  396. bool ValidateInputValue(absl::string_view value) const
  397. ABSL_LOCKS_EXCLUDED(*DataGuard());
  398. private:
  399. // Ensures that `data_guard_` is initialized and returns it.
  400. absl::Mutex* DataGuard() const ABSL_LOCK_RETURNED((absl::Mutex*)&data_guard_);
  401. // Returns heap allocated value of type T initialized with default value.
  402. std::unique_ptr<void, DynValueDeleter> MakeInitValue() const
  403. ABSL_EXCLUSIVE_LOCKS_REQUIRED(*DataGuard());
  404. // Lazy initialization of the Flag's data.
  405. void Init();
  406. FlagHelpKind HelpSourceKind() const {
  407. return static_cast<FlagHelpKind>(help_source_kind_);
  408. }
  409. FlagDefaultKind DefaultKind() const
  410. ABSL_EXCLUSIVE_LOCKS_REQUIRED(*DataGuard()) {
  411. return static_cast<FlagDefaultKind>(def_kind_);
  412. }
  413. // Used in read/write operations to validate source/target has correct type.
  414. // For example if flag is declared as absl::Flag<int> FLAGS_foo, a call to
  415. // absl::GetFlag(FLAGS_foo) validates that the type of FLAGS_foo is indeed
  416. // int. To do that we pass the "assumed" type id (which is deduced from type
  417. // int) as an argument `op`, which is in turn is validated against the type id
  418. // stored in flag object by flag definition statement.
  419. void AssertValidType(FlagStaticTypeId type_id) const;
  420. // Immutable flag's state.
  421. // Flags name passed to ABSL_FLAG as second arg.
  422. const char* const name_;
  423. // The file name where ABSL_FLAG resides.
  424. const char* const filename_;
  425. // Type-specific operations "vtable".
  426. const FlagOpFn op_;
  427. // Help message literal or function to generate it.
  428. const FlagHelpMsg help_;
  429. // Indicates if help message was supplied as literal or generator func.
  430. const uint8_t help_source_kind_ : 1;
  431. // ------------------------------------------------------------------------
  432. // The bytes containing the const bitfields must not be shared with bytes
  433. // containing the mutable bitfields.
  434. // ------------------------------------------------------------------------
  435. // Unique tag for absl::call_once call to initialize this flag.
  436. //
  437. // The placement of this variable between the immutable and mutable bitfields
  438. // is important as prevents them from occupying the same byte. If you remove
  439. // this variable, make sure to maintain this property.
  440. absl::once_flag init_control_;
  441. // Mutable flag's state (guarded by `data_guard_`).
  442. // If def_kind_ == kDynamicValue, default_src_ holds a dynamically allocated
  443. // value.
  444. uint8_t def_kind_ : 1 ABSL_GUARDED_BY(*DataGuard());
  445. // Has this flag's value been modified?
  446. bool modified_ : 1 ABSL_GUARDED_BY(*DataGuard());
  447. // Has this flag been specified on command line.
  448. bool on_command_line_ : 1 ABSL_GUARDED_BY(*DataGuard());
  449. // Mutation counter
  450. int64_t counter_ ABSL_GUARDED_BY(*DataGuard());
  451. // Optional flag's callback and absl::Mutex to guard the invocations.
  452. FlagCallback* callback_ ABSL_GUARDED_BY(*DataGuard());
  453. // Either a pointer to the function generating the default value based on the
  454. // value specified in ABSL_FLAG or pointer to the dynamically set default
  455. // value via SetCommandLineOptionWithMode. def_kind_ is used to distinguish
  456. // these two cases.
  457. FlagDefaultSrc default_src_ ABSL_GUARDED_BY(*DataGuard());
  458. // Current Flag Value
  459. FlagValue value_;
  460. // This is reserved space for an absl::Mutex to guard flag data. It will be
  461. // initialized in FlagImpl::Init via placement new.
  462. // We can't use "absl::Mutex data_guard_", since this class is not literal.
  463. // We do not want to use "absl::Mutex* data_guard_", since this would require
  464. // heap allocation during initialization, which is both slows program startup
  465. // and can fail. Using reserved space + placement new allows us to avoid both
  466. // problems.
  467. alignas(absl::Mutex) mutable char data_guard_[sizeof(absl::Mutex)];
  468. };
  469. ///////////////////////////////////////////////////////////////////////////////
  470. // The "unspecified" implementation of Flag object parameterized by the
  471. // flag's value type.
  472. template <typename T>
  473. class Flag final : public flags_internal::CommandLineFlag {
  474. public:
  475. constexpr Flag(const char* name, const char* filename, const FlagHelpArg help,
  476. const FlagDfltGenFunc default_value_gen)
  477. : impl_(name, filename, &FlagOps<T>, help, default_value_gen) {}
  478. T Get() const {
  479. // See implementation notes in CommandLineFlag::Get().
  480. union U {
  481. T value;
  482. U() {}
  483. ~U() { value.~T(); }
  484. };
  485. U u;
  486. impl_.Get(&u.value);
  487. return std::move(u.value);
  488. }
  489. void Set(const T& v) { impl_.Set(v); }
  490. void SetCallback(const FlagCallbackFunc mutation_callback) {
  491. impl_.SetCallback(mutation_callback);
  492. }
  493. // CommandLineFlag interface
  494. absl::string_view Name() const override { return impl_.Name(); }
  495. std::string Filename() const override { return impl_.Filename(); }
  496. absl::string_view Typename() const override { return ""; }
  497. std::string Help() const override { return impl_.Help(); }
  498. bool IsModified() const override { return impl_.IsModified(); }
  499. bool IsSpecifiedOnCommandLine() const override {
  500. return impl_.IsSpecifiedOnCommandLine();
  501. }
  502. std::string DefaultValue() const override { return impl_.DefaultValue(); }
  503. std::string CurrentValue() const override { return impl_.CurrentValue(); }
  504. bool ValidateInputValue(absl::string_view value) const override {
  505. return impl_.ValidateInputValue(value);
  506. }
  507. // Interfaces to save and restore flags to/from persistent state.
  508. // Returns current flag state or nullptr if flag does not support
  509. // saving and restoring a state.
  510. std::unique_ptr<FlagStateInterface> SaveState() override {
  511. return impl_.SaveState(this);
  512. }
  513. // Restores the flag state to the supplied state object. If there is
  514. // nothing to restore returns false. Otherwise returns true.
  515. bool RestoreState(const FlagState<T>& flag_state) {
  516. return impl_.RestoreState(&flag_state.cur_value_, flag_state.modified_,
  517. flag_state.on_command_line_, flag_state.counter_);
  518. }
  519. bool SetFromString(absl::string_view value, FlagSettingMode set_mode,
  520. ValueSource source, std::string* error) override {
  521. return impl_.SetFromString(value, set_mode, source, error);
  522. }
  523. void CheckDefaultValueParsingRoundtrip() const override {
  524. impl_.CheckDefaultValueParsingRoundtrip();
  525. }
  526. private:
  527. friend class FlagState<T>;
  528. void Read(void* dst) const override { impl_.Read(dst); }
  529. FlagStaticTypeId TypeId() const override { return &FlagStaticTypeIdGen<T>; }
  530. // Flag's data
  531. FlagImpl impl_;
  532. };
  533. template <typename T>
  534. inline void FlagState<T>::Restore() const {
  535. if (flag_->RestoreState(*this)) {
  536. ABSL_INTERNAL_LOG(INFO,
  537. absl::StrCat("Restore saved value of ", flag_->Name(),
  538. " to: ", flag_->CurrentValue()));
  539. }
  540. }
  541. // This class facilitates Flag object registration and tail expression-based
  542. // flag definition, for example:
  543. // ABSL_FLAG(int, foo, 42, "Foo help").OnUpdate(NotifyFooWatcher);
  544. template <typename T, bool do_register>
  545. class FlagRegistrar {
  546. public:
  547. explicit FlagRegistrar(Flag<T>* flag) : flag_(flag) {
  548. if (do_register) flags_internal::RegisterCommandLineFlag(flag_);
  549. }
  550. FlagRegistrar& OnUpdate(FlagCallbackFunc cb) && {
  551. flag_->SetCallback(cb);
  552. return *this;
  553. }
  554. // Make the registrar "die" gracefully as a bool on a line where registration
  555. // happens. Registrar objects are intended to live only as temporary.
  556. operator bool() const { return true; } // NOLINT
  557. private:
  558. Flag<T>* flag_; // Flag being registered (not owned).
  559. };
  560. // This struct and corresponding overload to MakeDefaultValue are used to
  561. // facilitate usage of {} as default value in ABSL_FLAG macro.
  562. struct EmptyBraces {};
  563. template <typename T>
  564. T* MakeFromDefaultValue(T t) {
  565. return new T(std::move(t));
  566. }
  567. template <typename T>
  568. T* MakeFromDefaultValue(EmptyBraces) {
  569. return new T;
  570. }
  571. } // namespace flags_internal
  572. ABSL_NAMESPACE_END
  573. } // namespace absl
  574. #endif // ABSL_FLAGS_INTERNAL_FLAG_H_