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