blob: a9cb2b7994d1b7ff1c63a1ec5780f584601efb7d [file] [log] [blame]
Austin Schuh36244a12019-09-21 17:52:38 -07001//
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// -----------------------------------------------------------------------------
17// File: flag.h
18// -----------------------------------------------------------------------------
19//
20// This header file defines the `absl::Flag<T>` type for holding command-line
21// flag data, and abstractions to create, get and set such flag data.
22//
23// It is important to note that this type is **unspecified** (an implementation
24// detail) and you do not construct or manipulate actual `absl::Flag<T>`
25// instances. Instead, you define and declare flags using the
26// `ABSL_FLAG()` and `ABSL_DECLARE_FLAG()` macros, and get and set flag values
27// using the `absl::GetFlag()` and `absl::SetFlag()` functions.
28
29#ifndef ABSL_FLAGS_FLAG_H_
30#define ABSL_FLAGS_FLAG_H_
31
Austin Schuhb4691e92020-12-31 12:37:18 -080032#include <string>
33#include <type_traits>
34
Austin Schuh36244a12019-09-21 17:52:38 -070035#include "absl/base/attributes.h"
Austin Schuhb4691e92020-12-31 12:37:18 -080036#include "absl/base/config.h"
37#include "absl/base/optimization.h"
Austin Schuh36244a12019-09-21 17:52:38 -070038#include "absl/flags/config.h"
Austin Schuh36244a12019-09-21 17:52:38 -070039#include "absl/flags/internal/flag.h"
Austin Schuhb4691e92020-12-31 12:37:18 -080040#include "absl/flags/internal/registry.h"
41#include "absl/strings/string_view.h"
Austin Schuh36244a12019-09-21 17:52:38 -070042
43namespace absl {
Austin Schuhb4691e92020-12-31 12:37:18 -080044ABSL_NAMESPACE_BEGIN
Austin Schuh36244a12019-09-21 17:52:38 -070045
46// Flag
47//
48// An `absl::Flag` holds a command-line flag value, providing a runtime
49// parameter to a binary. Such flags should be defined in the global namespace
50// and (preferably) in the module containing the binary's `main()` function.
51//
52// You should not construct and cannot use the `absl::Flag` type directly;
53// instead, you should declare flags using the `ABSL_DECLARE_FLAG()` macro
54// within a header file, and define your flag using `ABSL_FLAG()` within your
55// header's associated `.cc` file. Such flags will be named `FLAGS_name`.
56//
57// Example:
58//
59// .h file
60//
61// // Declares usage of a flag named "FLAGS_count"
62// ABSL_DECLARE_FLAG(int, count);
63//
64// .cc file
65//
66// // Defines a flag named "FLAGS_count" with a default `int` value of 0.
67// ABSL_FLAG(int, count, 0, "Count of items to process");
68//
69// No public methods of `absl::Flag<T>` are part of the Abseil Flags API.
Austin Schuhb4691e92020-12-31 12:37:18 -080070#if !defined(_MSC_VER) || defined(__clang__)
Austin Schuh36244a12019-09-21 17:52:38 -070071template <typename T>
72using Flag = flags_internal::Flag<T>;
73#else
Austin Schuhb4691e92020-12-31 12:37:18 -080074// MSVC debug builds do not implement initialization with constexpr constructors
75// correctly. To work around this we add a level of indirection, so that the
76// class `absl::Flag` contains an `internal::Flag*` (instead of being an alias
77// to that class) and dynamically allocates an instance when necessary. We also
78// forward all calls to internal::Flag methods via trampoline methods. In this
79// setup the `absl::Flag` class does not have constructor and virtual methods,
80// all the data members are public and thus MSVC is able to initialize it at
81// link time. To deal with multiple threads accessing the flag for the first
82// time concurrently we use an atomic boolean indicating if flag object is
83// initialized. We also employ the double-checked locking pattern where the
84// second level of protection is a global Mutex, so if two threads attempt to
85// construct the flag concurrently only one wins.
86// This solution is based on a recomendation here:
87// https://developercommunity.visualstudio.com/content/problem/336946/class-with-constexpr-constructor-not-using-static.html?childToView=648454#comment-648454
Austin Schuh36244a12019-09-21 17:52:38 -070088
89namespace flags_internal {
Austin Schuhb4691e92020-12-31 12:37:18 -080090absl::Mutex* GetGlobalConstructionGuard();
Austin Schuh36244a12019-09-21 17:52:38 -070091} // namespace flags_internal
92
93template <typename T>
94class Flag {
95 public:
Austin Schuhb4691e92020-12-31 12:37:18 -080096 // No constructor and destructor to ensure this is an aggregate type.
97 // Visual Studio 2015 still requires the constructor for class to be
98 // constexpr initializable.
99#if _MSC_VER <= 1900
100 constexpr Flag(const char* name, const char* filename,
101 const flags_internal::HelpGenFunc help_gen,
102 const flags_internal::FlagDfltGenFunc default_value_gen)
Austin Schuh36244a12019-09-21 17:52:38 -0700103 : name_(name),
Austin Schuh36244a12019-09-21 17:52:38 -0700104 filename_(filename),
Austin Schuhb4691e92020-12-31 12:37:18 -0800105 help_gen_(help_gen),
106 default_value_gen_(default_value_gen),
107 inited_(false),
108 impl_(nullptr) {}
109#endif
Austin Schuh36244a12019-09-21 17:52:38 -0700110
Austin Schuhb4691e92020-12-31 12:37:18 -0800111 flags_internal::Flag<T>& GetImpl() const {
Austin Schuh36244a12019-09-21 17:52:38 -0700112 if (!inited_.load(std::memory_order_acquire)) {
Austin Schuhb4691e92020-12-31 12:37:18 -0800113 absl::MutexLock l(flags_internal::GetGlobalConstructionGuard());
Austin Schuh36244a12019-09-21 17:52:38 -0700114
115 if (inited_.load(std::memory_order_acquire)) {
Austin Schuhb4691e92020-12-31 12:37:18 -0800116 return *impl_;
Austin Schuh36244a12019-09-21 17:52:38 -0700117 }
118
Austin Schuhb4691e92020-12-31 12:37:18 -0800119 impl_ = new flags_internal::Flag<T>(
120 name_, filename_,
121 {flags_internal::FlagHelpMsg(help_gen_),
122 flags_internal::FlagHelpKind::kGenFunc},
123 {flags_internal::FlagDefaultSrc(default_value_gen_),
124 flags_internal::FlagDefaultKind::kGenFunc});
Austin Schuh36244a12019-09-21 17:52:38 -0700125 inited_.store(true, std::memory_order_release);
Austin Schuh36244a12019-09-21 17:52:38 -0700126 }
127
Austin Schuhb4691e92020-12-31 12:37:18 -0800128 return *impl_;
Austin Schuh36244a12019-09-21 17:52:38 -0700129 }
130
Austin Schuhb4691e92020-12-31 12:37:18 -0800131 // Public methods of `absl::Flag<T>` are NOT part of the Abseil Flags API.
132 // See https://abseil.io/docs/cpp/guides/flags
133 bool IsRetired() const { return GetImpl().IsRetired(); }
134 absl::string_view Name() const { return GetImpl().Name(); }
135 std::string Help() const { return GetImpl().Help(); }
136 bool IsModified() const { return GetImpl().IsModified(); }
Austin Schuh36244a12019-09-21 17:52:38 -0700137 bool IsSpecifiedOnCommandLine() const {
Austin Schuhb4691e92020-12-31 12:37:18 -0800138 return GetImpl().IsSpecifiedOnCommandLine();
Austin Schuh36244a12019-09-21 17:52:38 -0700139 }
Austin Schuhb4691e92020-12-31 12:37:18 -0800140 std::string Filename() const { return GetImpl().Filename(); }
141 std::string DefaultValue() const { return GetImpl().DefaultValue(); }
142 std::string CurrentValue() const { return GetImpl().CurrentValue(); }
143 template <typename U>
Austin Schuh36244a12019-09-21 17:52:38 -0700144 inline bool IsOfType() const {
Austin Schuhb4691e92020-12-31 12:37:18 -0800145 return GetImpl().template IsOfType<U>();
Austin Schuh36244a12019-09-21 17:52:38 -0700146 }
Austin Schuhb4691e92020-12-31 12:37:18 -0800147 T Get() const {
148 return flags_internal::FlagImplPeer::InvokeGet<T>(GetImpl());
Austin Schuh36244a12019-09-21 17:52:38 -0700149 }
Austin Schuhb4691e92020-12-31 12:37:18 -0800150 void Set(const T& v) {
151 flags_internal::FlagImplPeer::InvokeSet(GetImpl(), v);
152 }
153 void InvokeCallback() { GetImpl().InvokeCallback(); }
Austin Schuh36244a12019-09-21 17:52:38 -0700154
Austin Schuhb4691e92020-12-31 12:37:18 -0800155 const CommandLineFlag& Reflect() const {
156 return flags_internal::FlagImplPeer::InvokeReflect(GetImpl());
157 }
158
159 // The data members are logically private, but they need to be public for
160 // this to be an aggregate type.
Austin Schuh36244a12019-09-21 17:52:38 -0700161 const char* name_;
Austin Schuh36244a12019-09-21 17:52:38 -0700162 const char* filename_;
Austin Schuhb4691e92020-12-31 12:37:18 -0800163 const flags_internal::HelpGenFunc help_gen_;
164 const flags_internal::FlagDfltGenFunc default_value_gen_;
Austin Schuh36244a12019-09-21 17:52:38 -0700165
166 mutable std::atomic<bool> inited_;
Austin Schuhb4691e92020-12-31 12:37:18 -0800167 mutable flags_internal::Flag<T>* impl_;
Austin Schuh36244a12019-09-21 17:52:38 -0700168};
169#endif
170
171// GetFlag()
172//
173// Returns the value (of type `T`) of an `absl::Flag<T>` instance, by value. Do
174// not construct an `absl::Flag<T>` directly and call `absl::GetFlag()`;
175// instead, refer to flag's constructed variable name (e.g. `FLAGS_name`).
176// Because this function returns by value and not by reference, it is
177// thread-safe, but note that the operation may be expensive; as a result, avoid
178// `absl::GetFlag()` within any tight loops.
179//
180// Example:
181//
182// // FLAGS_count is a Flag of type `int`
183// int my_count = absl::GetFlag(FLAGS_count);
184//
185// // FLAGS_firstname is a Flag of type `std::string`
186// std::string first_name = absl::GetFlag(FLAGS_firstname);
187template <typename T>
188ABSL_MUST_USE_RESULT T GetFlag(const absl::Flag<T>& flag) {
Austin Schuhb4691e92020-12-31 12:37:18 -0800189 return flags_internal::FlagImplPeer::InvokeGet<T>(flag);
Austin Schuh36244a12019-09-21 17:52:38 -0700190}
191
Austin Schuh36244a12019-09-21 17:52:38 -0700192// SetFlag()
193//
194// Sets the value of an `absl::Flag` to the value `v`. Do not construct an
195// `absl::Flag<T>` directly and call `absl::SetFlag()`; instead, use the
196// flag's variable name (e.g. `FLAGS_name`). This function is
197// thread-safe, but is potentially expensive. Avoid setting flags in general,
198// but especially within performance-critical code.
199template <typename T>
200void SetFlag(absl::Flag<T>* flag, const T& v) {
Austin Schuhb4691e92020-12-31 12:37:18 -0800201 flags_internal::FlagImplPeer::InvokeSet(*flag, v);
Austin Schuh36244a12019-09-21 17:52:38 -0700202}
203
204// Overload of `SetFlag()` to allow callers to pass in a value that is
205// convertible to `T`. E.g., use this overload to pass a "const char*" when `T`
206// is `std::string`.
207template <typename T, typename V>
208void SetFlag(absl::Flag<T>* flag, const V& v) {
209 T value(v);
Austin Schuhb4691e92020-12-31 12:37:18 -0800210 flags_internal::FlagImplPeer::InvokeSet(*flag, value);
Austin Schuh36244a12019-09-21 17:52:38 -0700211}
212
Austin Schuhb4691e92020-12-31 12:37:18 -0800213// GetFlagReflectionHandle()
214//
215// Returns the reflection handle corresponding to specified Abseil Flag
216// instance. Use this handle to access flag's reflection information, like name,
217// location, default value etc.
218//
219// Example:
220//
221// std::string = absl::GetFlagReflectionHandle(FLAGS_count).DefaultValue();
222
223template <typename T>
224const CommandLineFlag& GetFlagReflectionHandle(const absl::Flag<T>& f) {
225 return flags_internal::FlagImplPeer::InvokeReflect(f);
226}
227
228ABSL_NAMESPACE_END
Austin Schuh36244a12019-09-21 17:52:38 -0700229} // namespace absl
230
231
232// ABSL_FLAG()
233//
234// This macro defines an `absl::Flag<T>` instance of a specified type `T`:
235//
236// ABSL_FLAG(T, name, default_value, help);
237//
238// where:
239//
240// * `T` is a supported flag type (see the list of types in `marshalling.h`),
241// * `name` designates the name of the flag (as a global variable
242// `FLAGS_name`),
243// * `default_value` is an expression holding the default value for this flag
244// (which must be implicitly convertible to `T`),
245// * `help` is the help text, which can also be an expression.
246//
247// This macro expands to a flag named 'FLAGS_name' of type 'T':
248//
249// absl::Flag<T> FLAGS_name = ...;
250//
251// Note that all such instances are created as global variables.
252//
253// For `ABSL_FLAG()` values that you wish to expose to other translation units,
254// it is recommended to define those flags within the `.cc` file associated with
255// the header where the flag is declared.
256//
257// Note: do not construct objects of type `absl::Flag<T>` directly. Only use the
258// `ABSL_FLAG()` macro for such construction.
259#define ABSL_FLAG(Type, name, default_value, help) \
260 ABSL_FLAG_IMPL(Type, name, default_value, help)
261
262// ABSL_FLAG().OnUpdate()
263//
264// Defines a flag of type `T` with a callback attached:
265//
266// ABSL_FLAG(T, name, default_value, help).OnUpdate(callback);
267//
268// After any setting of the flag value, the callback will be called at least
269// once. A rapid sequence of changes may be merged together into the same
270// callback. No concurrent calls to the callback will be made for the same
271// flag. Callbacks are allowed to read the current value of the flag but must
272// not mutate that flag.
273//
274// The update mechanism guarantees "eventual consistency"; if the callback
275// derives an auxiliary data structure from the flag value, it is guaranteed
276// that eventually the flag value and the derived data structure will be
277// consistent.
278//
279// Note: ABSL_FLAG.OnUpdate() does not have a public definition. Hence, this
280// comment serves as its API documentation.
281
282
283// -----------------------------------------------------------------------------
284// Implementation details below this section
285// -----------------------------------------------------------------------------
286
287// ABSL_FLAG_IMPL macro definition conditional on ABSL_FLAGS_STRIP_NAMES
Austin Schuhb4691e92020-12-31 12:37:18 -0800288#if !defined(_MSC_VER) || defined(__clang__)
289#define ABSL_FLAG_IMPL_FLAG_PTR(flag) flag
290#define ABSL_FLAG_IMPL_HELP_ARG(name) \
291 absl::flags_internal::HelpArg<AbslFlagHelpGenFor##name>( \
292 FLAGS_help_storage_##name)
293#define ABSL_FLAG_IMPL_DEFAULT_ARG(Type, name) \
294 absl::flags_internal::DefaultArg<Type, AbslFlagDefaultGenFor##name>(0)
295#else
296#define ABSL_FLAG_IMPL_FLAG_PTR(flag) flag.GetImpl()
297#define ABSL_FLAG_IMPL_HELP_ARG(name) &AbslFlagHelpGenFor##name::NonConst
298#define ABSL_FLAG_IMPL_DEFAULT_ARG(Type, name) &AbslFlagDefaultGenFor##name::Gen
299#endif
Austin Schuh36244a12019-09-21 17:52:38 -0700300
301#if ABSL_FLAGS_STRIP_NAMES
302#define ABSL_FLAG_IMPL_FLAGNAME(txt) ""
303#define ABSL_FLAG_IMPL_FILENAME() ""
Austin Schuh36244a12019-09-21 17:52:38 -0700304#define ABSL_FLAG_IMPL_REGISTRAR(T, flag) \
Austin Schuhb4691e92020-12-31 12:37:18 -0800305 absl::flags_internal::FlagRegistrar<T, false>(ABSL_FLAG_IMPL_FLAG_PTR(flag))
Austin Schuh36244a12019-09-21 17:52:38 -0700306#else
307#define ABSL_FLAG_IMPL_FLAGNAME(txt) txt
308#define ABSL_FLAG_IMPL_FILENAME() __FILE__
Austin Schuh36244a12019-09-21 17:52:38 -0700309#define ABSL_FLAG_IMPL_REGISTRAR(T, flag) \
Austin Schuhb4691e92020-12-31 12:37:18 -0800310 absl::flags_internal::FlagRegistrar<T, true>(ABSL_FLAG_IMPL_FLAG_PTR(flag))
Austin Schuh36244a12019-09-21 17:52:38 -0700311#endif
312
313// ABSL_FLAG_IMPL macro definition conditional on ABSL_FLAGS_STRIP_HELP
314
315#if ABSL_FLAGS_STRIP_HELP
316#define ABSL_FLAG_IMPL_FLAGHELP(txt) absl::flags_internal::kStrippedFlagHelp
317#else
318#define ABSL_FLAG_IMPL_FLAGHELP(txt) txt
319#endif
320
Austin Schuhb4691e92020-12-31 12:37:18 -0800321// AbslFlagHelpGenFor##name is used to encapsulate both immediate (method Const)
322// and lazy (method NonConst) evaluation of help message expression. We choose
323// between the two via the call to HelpArg in absl::Flag instantiation below.
324// If help message expression is constexpr evaluable compiler will optimize
325// away this whole struct.
326// TODO(rogeeff): place these generated structs into local namespace and apply
327// ABSL_INTERNAL_UNIQUE_SHORT_NAME.
328// TODO(rogeeff): Apply __attribute__((nodebug)) to FLAGS_help_storage_##name
329#define ABSL_FLAG_IMPL_DECLARE_HELP_WRAPPER(name, txt) \
330 struct AbslFlagHelpGenFor##name { \
331 /* The expression is run in the caller as part of the */ \
332 /* default value argument. That keeps temporaries alive */ \
333 /* long enough for NonConst to work correctly. */ \
334 static constexpr absl::string_view Value( \
335 absl::string_view v = ABSL_FLAG_IMPL_FLAGHELP(txt)) { \
336 return v; \
337 } \
338 static std::string NonConst() { return std::string(Value()); } \
339 }; \
340 constexpr auto FLAGS_help_storage_##name ABSL_INTERNAL_UNIQUE_SMALL_NAME() \
341 ABSL_ATTRIBUTE_SECTION_VARIABLE(flags_help_cold) = \
342 absl::flags_internal::HelpStringAsArray<AbslFlagHelpGenFor##name>( \
343 0);
Austin Schuh36244a12019-09-21 17:52:38 -0700344
Austin Schuhb4691e92020-12-31 12:37:18 -0800345#define ABSL_FLAG_IMPL_DECLARE_DEF_VAL_WRAPPER(name, Type, default_value) \
346 struct AbslFlagDefaultGenFor##name { \
347 Type value = absl::flags_internal::InitDefaultValue<Type>(default_value); \
348 static void Gen(void* p) { \
349 new (p) Type(AbslFlagDefaultGenFor##name{}.value); \
350 } \
351 };
Austin Schuh36244a12019-09-21 17:52:38 -0700352
353// ABSL_FLAG_IMPL
354//
355// Note: Name of registrar object is not arbitrary. It is used to "grab"
356// global name for FLAGS_no<flag_name> symbol, thus preventing the possibility
357// of defining two flags with names foo and nofoo.
Austin Schuhb4691e92020-12-31 12:37:18 -0800358#define ABSL_FLAG_IMPL(Type, name, default_value, help) \
359 namespace absl /* block flags in namespaces */ {} \
360 ABSL_FLAG_IMPL_DECLARE_DEF_VAL_WRAPPER(name, Type, default_value) \
361 ABSL_FLAG_IMPL_DECLARE_HELP_WRAPPER(name, help) \
362 ABSL_CONST_INIT absl::Flag<Type> FLAGS_##name{ \
363 ABSL_FLAG_IMPL_FLAGNAME(#name), ABSL_FLAG_IMPL_FILENAME(), \
364 ABSL_FLAG_IMPL_HELP_ARG(name), ABSL_FLAG_IMPL_DEFAULT_ARG(Type, name)}; \
365 extern absl::flags_internal::FlagRegistrarEmpty FLAGS_no##name; \
366 absl::flags_internal::FlagRegistrarEmpty FLAGS_no##name = \
367 ABSL_FLAG_IMPL_REGISTRAR(Type, FLAGS_##name)
Austin Schuh36244a12019-09-21 17:52:38 -0700368
369// ABSL_RETIRED_FLAG
370//
371// Designates the flag (which is usually pre-existing) as "retired." A retired
372// flag is a flag that is now unused by the program, but may still be passed on
373// the command line, usually by production scripts. A retired flag is ignored
374// and code can't access it at runtime.
375//
376// This macro registers a retired flag with given name and type, with a name
377// identical to the name of the original flag you are retiring. The retired
378// flag's type can change over time, so that you can retire code to support a
379// custom flag type.
380//
381// This macro has the same signature as `ABSL_FLAG`. To retire a flag, simply
382// replace an `ABSL_FLAG` definition with `ABSL_RETIRED_FLAG`, leaving the
383// arguments unchanged (unless of course you actually want to retire the flag
384// type at this time as well).
385//
386// `default_value` is only used as a double check on the type. `explanation` is
387// unused.
Austin Schuhb4691e92020-12-31 12:37:18 -0800388// TODO(rogeeff): replace RETIRED_FLAGS with FLAGS once forward declarations of
389// retired flags are cleaned up.
390#define ABSL_RETIRED_FLAG(type, name, default_value, explanation) \
391 static absl::flags_internal::RetiredFlag<type> RETIRED_FLAGS_##name; \
392 ABSL_ATTRIBUTE_UNUSED static const auto RETIRED_FLAGS_REG_##name = \
393 (RETIRED_FLAGS_##name.Retire(#name), \
394 ::absl::flags_internal::FlagRegistrarEmpty{})
Austin Schuh36244a12019-09-21 17:52:38 -0700395
396#endif // ABSL_FLAGS_FLAG_H_