• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 // -----------------------------------------------------------------------------
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 
32 #include <string>
33 #include <type_traits>
34 
35 #include "absl/base/attributes.h"
36 #include "absl/base/config.h"
37 #include "absl/base/optimization.h"
38 #include "absl/flags/config.h"
39 #include "absl/flags/internal/flag.h"
40 #include "absl/flags/internal/registry.h"
41 #include "absl/strings/string_view.h"
42 
43 namespace absl {
44 ABSL_NAMESPACE_BEGIN
45 
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.
70 #if !defined(_MSC_VER) || defined(__clang__)
71 template <typename T>
72 using Flag = flags_internal::Flag<T>;
73 #else
74 // 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
88 
89 namespace flags_internal {
90 absl::Mutex* GetGlobalConstructionGuard();
91 }  // namespace flags_internal
92 
93 template <typename T>
94 class Flag {
95  public:
96   // 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)
103       : name_(name),
104         filename_(filename),
105         help_gen_(help_gen),
106         default_value_gen_(default_value_gen),
107         inited_(false),
108         impl_(nullptr) {}
109 #endif
110 
111   flags_internal::Flag<T>& GetImpl() const {
112     if (!inited_.load(std::memory_order_acquire)) {
113       absl::MutexLock l(flags_internal::GetGlobalConstructionGuard());
114 
115       if (inited_.load(std::memory_order_acquire)) {
116         return *impl_;
117       }
118 
119       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});
125       inited_.store(true, std::memory_order_release);
126     }
127 
128     return *impl_;
129   }
130 
131   // 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(); }
137   bool IsSpecifiedOnCommandLine() const {
138     return GetImpl().IsSpecifiedOnCommandLine();
139   }
140   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>
144   inline bool IsOfType() const {
145     return GetImpl().template IsOfType<U>();
146   }
147   T Get() const {
148     return flags_internal::FlagImplPeer::InvokeGet<T>(GetImpl());
149   }
150   void Set(const T& v) {
151     flags_internal::FlagImplPeer::InvokeSet(GetImpl(), v);
152   }
153   void InvokeCallback() { GetImpl().InvokeCallback(); }
154 
155   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.
161   const char* name_;
162   const char* filename_;
163   const flags_internal::HelpGenFunc help_gen_;
164   const flags_internal::FlagDfltGenFunc default_value_gen_;
165 
166   mutable std::atomic<bool> inited_;
167   mutable flags_internal::Flag<T>* impl_;
168 };
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);
187 template <typename T>
GetFlag(const absl::Flag<T> & flag)188 ABSL_MUST_USE_RESULT T GetFlag(const absl::Flag<T>& flag) {
189   return flags_internal::FlagImplPeer::InvokeGet<T>(flag);
190 }
191 
192 // 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.
199 template <typename T>
SetFlag(absl::Flag<T> * flag,const T & v)200 void SetFlag(absl::Flag<T>* flag, const T& v) {
201   flags_internal::FlagImplPeer::InvokeSet(*flag, v);
202 }
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`.
207 template <typename T, typename V>
SetFlag(absl::Flag<T> * flag,const V & v)208 void SetFlag(absl::Flag<T>* flag, const V& v) {
209   T value(v);
210   flags_internal::FlagImplPeer::InvokeSet(*flag, value);
211 }
212 
213 // 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 
223 template <typename T>
GetFlagReflectionHandle(const absl::Flag<T> & f)224 const CommandLineFlag& GetFlagReflectionHandle(const absl::Flag<T>& f) {
225   return flags_internal::FlagImplPeer::InvokeReflect(f);
226 }
227 
228 ABSL_NAMESPACE_END
229 }  // 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 // `callback` should be convertible to `void (*)()`.
269 //
270 // After any setting of the flag value, the callback will be called at least
271 // once. A rapid sequence of changes may be merged together into the same
272 // callback. No concurrent calls to the callback will be made for the same
273 // flag. Callbacks are allowed to read the current value of the flag but must
274 // not mutate that flag.
275 //
276 // The update mechanism guarantees "eventual consistency"; if the callback
277 // derives an auxiliary data structure from the flag value, it is guaranteed
278 // that eventually the flag value and the derived data structure will be
279 // consistent.
280 //
281 // Note: ABSL_FLAG.OnUpdate() does not have a public definition. Hence, this
282 // comment serves as its API documentation.
283 
284 // -----------------------------------------------------------------------------
285 // Implementation details below this section
286 // -----------------------------------------------------------------------------
287 
288 // ABSL_FLAG_IMPL macro definition conditional on ABSL_FLAGS_STRIP_NAMES
289 #if !defined(_MSC_VER) || defined(__clang__)
290 #define ABSL_FLAG_IMPL_FLAG_PTR(flag) flag
291 #define ABSL_FLAG_IMPL_HELP_ARG(name)                      \
292   absl::flags_internal::HelpArg<AbslFlagHelpGenFor##name>( \
293       FLAGS_help_storage_##name)
294 #define ABSL_FLAG_IMPL_DEFAULT_ARG(Type, name) \
295   absl::flags_internal::DefaultArg<Type, AbslFlagDefaultGenFor##name>(0)
296 #else
297 #define ABSL_FLAG_IMPL_FLAG_PTR(flag) flag.GetImpl()
298 #define ABSL_FLAG_IMPL_HELP_ARG(name) &AbslFlagHelpGenFor##name::NonConst
299 #define ABSL_FLAG_IMPL_DEFAULT_ARG(Type, name) &AbslFlagDefaultGenFor##name::Gen
300 #endif
301 
302 #if ABSL_FLAGS_STRIP_NAMES
303 #define ABSL_FLAG_IMPL_FLAGNAME(txt) ""
304 #define ABSL_FLAG_IMPL_FILENAME() ""
305 #define ABSL_FLAG_IMPL_REGISTRAR(T, flag)                                      \
306   absl::flags_internal::FlagRegistrar<T, false>(ABSL_FLAG_IMPL_FLAG_PTR(flag), \
307                                                 nullptr)
308 #else
309 #define ABSL_FLAG_IMPL_FLAGNAME(txt) txt
310 #define ABSL_FLAG_IMPL_FILENAME() __FILE__
311 #define ABSL_FLAG_IMPL_REGISTRAR(T, flag)                                     \
312   absl::flags_internal::FlagRegistrar<T, true>(ABSL_FLAG_IMPL_FLAG_PTR(flag), \
313                                                __FILE__)
314 #endif
315 
316 // ABSL_FLAG_IMPL macro definition conditional on ABSL_FLAGS_STRIP_HELP
317 
318 #if ABSL_FLAGS_STRIP_HELP
319 #define ABSL_FLAG_IMPL_FLAGHELP(txt) absl::flags_internal::kStrippedFlagHelp
320 #else
321 #define ABSL_FLAG_IMPL_FLAGHELP(txt) txt
322 #endif
323 
324 // AbslFlagHelpGenFor##name is used to encapsulate both immediate (method Const)
325 // and lazy (method NonConst) evaluation of help message expression. We choose
326 // between the two via the call to HelpArg in absl::Flag instantiation below.
327 // If help message expression is constexpr evaluable compiler will optimize
328 // away this whole struct.
329 // TODO(rogeeff): place these generated structs into local namespace and apply
330 // ABSL_INTERNAL_UNIQUE_SHORT_NAME.
331 // TODO(rogeeff): Apply __attribute__((nodebug)) to FLAGS_help_storage_##name
332 #define ABSL_FLAG_IMPL_DECLARE_HELP_WRAPPER(name, txt)                       \
333   struct AbslFlagHelpGenFor##name {                                          \
334     /* The expression is run in the caller as part of the   */               \
335     /* default value argument. That keeps temporaries alive */               \
336     /* long enough for NonConst to work correctly.          */               \
337     static constexpr absl::string_view Value(                                \
338         absl::string_view v = ABSL_FLAG_IMPL_FLAGHELP(txt)) {                \
339       return v;                                                              \
340     }                                                                        \
341     static std::string NonConst() { return std::string(Value()); }           \
342   };                                                                         \
343   constexpr auto FLAGS_help_storage_##name ABSL_INTERNAL_UNIQUE_SMALL_NAME() \
344       ABSL_ATTRIBUTE_SECTION_VARIABLE(flags_help_cold) =                     \
345           absl::flags_internal::HelpStringAsArray<AbslFlagHelpGenFor##name>( \
346               0);
347 
348 #define ABSL_FLAG_IMPL_DECLARE_DEF_VAL_WRAPPER(name, Type, default_value)     \
349   struct AbslFlagDefaultGenFor##name {                                        \
350     Type value = absl::flags_internal::InitDefaultValue<Type>(default_value); \
351     static void Gen(void* p) {                                                \
352       new (p) Type(AbslFlagDefaultGenFor##name{}.value);                      \
353     }                                                                         \
354   };
355 
356 // ABSL_FLAG_IMPL
357 //
358 // Note: Name of registrar object is not arbitrary. It is used to "grab"
359 // global name for FLAGS_no<flag_name> symbol, thus preventing the possibility
360 // of defining two flags with names foo and nofoo.
361 #define ABSL_FLAG_IMPL(Type, name, default_value, help)                       \
362   namespace absl /* block flags in namespaces */ {}                           \
363   ABSL_FLAG_IMPL_DECLARE_DEF_VAL_WRAPPER(name, Type, default_value)           \
364   ABSL_FLAG_IMPL_DECLARE_HELP_WRAPPER(name, help)                             \
365   ABSL_CONST_INIT absl::Flag<Type> FLAGS_##name{                              \
366       ABSL_FLAG_IMPL_FLAGNAME(#name), ABSL_FLAG_IMPL_FILENAME(),              \
367       ABSL_FLAG_IMPL_HELP_ARG(name), ABSL_FLAG_IMPL_DEFAULT_ARG(Type, name)}; \
368   extern absl::flags_internal::FlagRegistrarEmpty FLAGS_no##name;             \
369   absl::flags_internal::FlagRegistrarEmpty FLAGS_no##name =                   \
370       ABSL_FLAG_IMPL_REGISTRAR(Type, FLAGS_##name)
371 
372 // ABSL_RETIRED_FLAG
373 //
374 // Designates the flag (which is usually pre-existing) as "retired." A retired
375 // flag is a flag that is now unused by the program, but may still be passed on
376 // the command line, usually by production scripts. A retired flag is ignored
377 // and code can't access it at runtime.
378 //
379 // This macro registers a retired flag with given name and type, with a name
380 // identical to the name of the original flag you are retiring. The retired
381 // flag's type can change over time, so that you can retire code to support a
382 // custom flag type.
383 //
384 // This macro has the same signature as `ABSL_FLAG`. To retire a flag, simply
385 // replace an `ABSL_FLAG` definition with `ABSL_RETIRED_FLAG`, leaving the
386 // arguments unchanged (unless of course you actually want to retire the flag
387 // type at this time as well).
388 //
389 // `default_value` is only used as a double check on the type. `explanation` is
390 // unused.
391 // TODO(rogeeff): replace RETIRED_FLAGS with FLAGS once forward declarations of
392 // retired flags are cleaned up.
393 #define ABSL_RETIRED_FLAG(type, name, default_value, explanation)      \
394   static absl::flags_internal::RetiredFlag<type> RETIRED_FLAGS_##name; \
395   ABSL_ATTRIBUTE_UNUSED static const auto RETIRED_FLAGS_REG_##name =   \
396       (RETIRED_FLAGS_##name.Retire(#name),                             \
397        ::absl::flags_internal::FlagRegistrarEmpty{})
398 
399 #endif  // ABSL_FLAGS_FLAG_H_
400