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 //
71 // For type support of Abseil Flags, see the marshalling.h header file, which
72 // discusses supported standard types, optional flags, and additional Abseil
73 // type support.
74 #if !defined(_MSC_VER) || defined(__clang__)
75 template <typename T>
76 using Flag = flags_internal::Flag<T>;
77 #else
78 #include "absl/flags/internal/flag_msvc.inc"
79 #endif
80
81 // GetFlag()
82 //
83 // Returns the value (of type `T`) of an `absl::Flag<T>` instance, by value. Do
84 // not construct an `absl::Flag<T>` directly and call `absl::GetFlag()`;
85 // instead, refer to flag's constructed variable name (e.g. `FLAGS_name`).
86 // Because this function returns by value and not by reference, it is
87 // thread-safe, but note that the operation may be expensive; as a result, avoid
88 // `absl::GetFlag()` within any tight loops.
89 //
90 // Example:
91 //
92 // // FLAGS_count is a Flag of type `int`
93 // int my_count = absl::GetFlag(FLAGS_count);
94 //
95 // // FLAGS_firstname is a Flag of type `std::string`
96 // std::string first_name = absl::GetFlag(FLAGS_firstname);
97 template <typename T>
GetFlag(const absl::Flag<T> & flag)98 ABSL_MUST_USE_RESULT T GetFlag(const absl::Flag<T>& flag) {
99 return flags_internal::FlagImplPeer::InvokeGet<T>(flag);
100 }
101
102 // SetFlag()
103 //
104 // Sets the value of an `absl::Flag` to the value `v`. Do not construct an
105 // `absl::Flag<T>` directly and call `absl::SetFlag()`; instead, use the
106 // flag's variable name (e.g. `FLAGS_name`). This function is
107 // thread-safe, but is potentially expensive. Avoid setting flags in general,
108 // but especially within performance-critical code.
109 template <typename T>
SetFlag(absl::Flag<T> * flag,const T & v)110 void SetFlag(absl::Flag<T>* flag, const T& v) {
111 flags_internal::FlagImplPeer::InvokeSet(*flag, v);
112 }
113
114 // Overload of `SetFlag()` to allow callers to pass in a value that is
115 // convertible to `T`. E.g., use this overload to pass a "const char*" when `T`
116 // is `std::string`.
117 template <typename T, typename V>
SetFlag(absl::Flag<T> * flag,const V & v)118 void SetFlag(absl::Flag<T>* flag, const V& v) {
119 T value(v);
120 flags_internal::FlagImplPeer::InvokeSet(*flag, value);
121 }
122
123 // GetFlagReflectionHandle()
124 //
125 // Returns the reflection handle corresponding to specified Abseil Flag
126 // instance. Use this handle to access flag's reflection information, like name,
127 // location, default value etc.
128 //
129 // Example:
130 //
131 // std::string = absl::GetFlagReflectionHandle(FLAGS_count).DefaultValue();
132
133 template <typename T>
GetFlagReflectionHandle(const absl::Flag<T> & f)134 const CommandLineFlag& GetFlagReflectionHandle(const absl::Flag<T>& f) {
135 return flags_internal::FlagImplPeer::InvokeReflect(f);
136 }
137
138 ABSL_NAMESPACE_END
139 } // namespace absl
140
141
142 // ABSL_FLAG()
143 //
144 // This macro defines an `absl::Flag<T>` instance of a specified type `T`:
145 //
146 // ABSL_FLAG(T, name, default_value, help);
147 //
148 // where:
149 //
150 // * `T` is a supported flag type (see the list of types in `marshalling.h`),
151 // * `name` designates the name of the flag (as a global variable
152 // `FLAGS_name`),
153 // * `default_value` is an expression holding the default value for this flag
154 // (which must be implicitly convertible to `T`),
155 // * `help` is the help text, which can also be an expression.
156 //
157 // This macro expands to a flag named 'FLAGS_name' of type 'T':
158 //
159 // absl::Flag<T> FLAGS_name = ...;
160 //
161 // Note that all such instances are created as global variables.
162 //
163 // For `ABSL_FLAG()` values that you wish to expose to other translation units,
164 // it is recommended to define those flags within the `.cc` file associated with
165 // the header where the flag is declared.
166 //
167 // Note: do not construct objects of type `absl::Flag<T>` directly. Only use the
168 // `ABSL_FLAG()` macro for such construction.
169 #define ABSL_FLAG(Type, name, default_value, help) \
170 ABSL_FLAG_IMPL(Type, name, default_value, help)
171
172 // ABSL_FLAG().OnUpdate()
173 //
174 // Defines a flag of type `T` with a callback attached:
175 //
176 // ABSL_FLAG(T, name, default_value, help).OnUpdate(callback);
177 //
178 // `callback` should be convertible to `void (*)()`.
179 //
180 // After any setting of the flag value, the callback will be called at least
181 // once. A rapid sequence of changes may be merged together into the same
182 // callback. No concurrent calls to the callback will be made for the same
183 // flag. Callbacks are allowed to read the current value of the flag but must
184 // not mutate that flag.
185 //
186 // The update mechanism guarantees "eventual consistency"; if the callback
187 // derives an auxiliary data structure from the flag value, it is guaranteed
188 // that eventually the flag value and the derived data structure will be
189 // consistent.
190 //
191 // Note: ABSL_FLAG.OnUpdate() does not have a public definition. Hence, this
192 // comment serves as its API documentation.
193
194 // -----------------------------------------------------------------------------
195 // Implementation details below this section
196 // -----------------------------------------------------------------------------
197
198 // ABSL_FLAG_IMPL macro definition conditional on ABSL_FLAGS_STRIP_NAMES
199 #if !defined(_MSC_VER) || defined(__clang__)
200 #define ABSL_FLAG_IMPL_FLAG_PTR(flag) flag
201 #define ABSL_FLAG_IMPL_HELP_ARG(name) \
202 absl::flags_internal::HelpArg<AbslFlagHelpGenFor##name>( \
203 FLAGS_help_storage_##name)
204 #define ABSL_FLAG_IMPL_DEFAULT_ARG(Type, name) \
205 absl::flags_internal::DefaultArg<Type, AbslFlagDefaultGenFor##name>(0)
206 #else
207 #define ABSL_FLAG_IMPL_FLAG_PTR(flag) flag.GetImpl()
208 #define ABSL_FLAG_IMPL_HELP_ARG(name) &AbslFlagHelpGenFor##name::NonConst
209 #define ABSL_FLAG_IMPL_DEFAULT_ARG(Type, name) &AbslFlagDefaultGenFor##name::Gen
210 #endif
211
212 #if ABSL_FLAGS_STRIP_NAMES
213 #define ABSL_FLAG_IMPL_FLAGNAME(txt) ""
214 #define ABSL_FLAG_IMPL_FILENAME() ""
215 #define ABSL_FLAG_IMPL_REGISTRAR(T, flag) \
216 absl::flags_internal::FlagRegistrar<T, false>(ABSL_FLAG_IMPL_FLAG_PTR(flag), \
217 nullptr)
218 #else
219 #define ABSL_FLAG_IMPL_FLAGNAME(txt) txt
220 #define ABSL_FLAG_IMPL_FILENAME() __FILE__
221 #define ABSL_FLAG_IMPL_REGISTRAR(T, flag) \
222 absl::flags_internal::FlagRegistrar<T, true>(ABSL_FLAG_IMPL_FLAG_PTR(flag), \
223 __FILE__)
224 #endif
225
226 // ABSL_FLAG_IMPL macro definition conditional on ABSL_FLAGS_STRIP_HELP
227
228 #if ABSL_FLAGS_STRIP_HELP
229 #define ABSL_FLAG_IMPL_FLAGHELP(txt) absl::flags_internal::kStrippedFlagHelp
230 #else
231 #define ABSL_FLAG_IMPL_FLAGHELP(txt) txt
232 #endif
233
234 // AbslFlagHelpGenFor##name is used to encapsulate both immediate (method Const)
235 // and lazy (method NonConst) evaluation of help message expression. We choose
236 // between the two via the call to HelpArg in absl::Flag instantiation below.
237 // If help message expression is constexpr evaluable compiler will optimize
238 // away this whole struct.
239 // TODO(rogeeff): place these generated structs into local namespace and apply
240 // ABSL_INTERNAL_UNIQUE_SHORT_NAME.
241 // TODO(rogeeff): Apply __attribute__((nodebug)) to FLAGS_help_storage_##name
242 #define ABSL_FLAG_IMPL_DECLARE_HELP_WRAPPER(name, txt) \
243 struct AbslFlagHelpGenFor##name { \
244 /* The expression is run in the caller as part of the */ \
245 /* default value argument. That keeps temporaries alive */ \
246 /* long enough for NonConst to work correctly. */ \
247 static constexpr absl::string_view Value( \
248 absl::string_view absl_flag_help = ABSL_FLAG_IMPL_FLAGHELP(txt)) { \
249 return absl_flag_help; \
250 } \
251 static std::string NonConst() { return std::string(Value()); } \
252 }; \
253 constexpr auto FLAGS_help_storage_##name ABSL_INTERNAL_UNIQUE_SMALL_NAME() \
254 ABSL_ATTRIBUTE_SECTION_VARIABLE(flags_help_cold) = \
255 absl::flags_internal::HelpStringAsArray<AbslFlagHelpGenFor##name>( \
256 0);
257
258 #define ABSL_FLAG_IMPL_DECLARE_DEF_VAL_WRAPPER(name, Type, default_value) \
259 struct AbslFlagDefaultGenFor##name { \
260 Type value = absl::flags_internal::InitDefaultValue<Type>(default_value); \
261 static void Gen(void* absl_flag_default_loc) { \
262 new (absl_flag_default_loc) Type(AbslFlagDefaultGenFor##name{}.value); \
263 } \
264 };
265
266 // ABSL_FLAG_IMPL
267 //
268 // Note: Name of registrar object is not arbitrary. It is used to "grab"
269 // global name for FLAGS_no<flag_name> symbol, thus preventing the possibility
270 // of defining two flags with names foo and nofoo.
271 #define ABSL_FLAG_IMPL(Type, name, default_value, help) \
272 extern ::absl::Flag<Type> FLAGS_##name; \
273 namespace absl /* block flags in namespaces */ {} \
274 ABSL_FLAG_IMPL_DECLARE_DEF_VAL_WRAPPER(name, Type, default_value) \
275 ABSL_FLAG_IMPL_DECLARE_HELP_WRAPPER(name, help) \
276 ABSL_CONST_INIT absl::Flag<Type> FLAGS_##name{ \
277 ABSL_FLAG_IMPL_FLAGNAME(#name), ABSL_FLAG_IMPL_FILENAME(), \
278 ABSL_FLAG_IMPL_HELP_ARG(name), ABSL_FLAG_IMPL_DEFAULT_ARG(Type, name)}; \
279 extern absl::flags_internal::FlagRegistrarEmpty FLAGS_no##name; \
280 absl::flags_internal::FlagRegistrarEmpty FLAGS_no##name = \
281 ABSL_FLAG_IMPL_REGISTRAR(Type, FLAGS_##name)
282
283 // ABSL_RETIRED_FLAG
284 //
285 // Designates the flag (which is usually pre-existing) as "retired." A retired
286 // flag is a flag that is now unused by the program, but may still be passed on
287 // the command line, usually by production scripts. A retired flag is ignored
288 // and code can't access it at runtime.
289 //
290 // This macro registers a retired flag with given name and type, with a name
291 // identical to the name of the original flag you are retiring. The retired
292 // flag's type can change over time, so that you can retire code to support a
293 // custom flag type.
294 //
295 // This macro has the same signature as `ABSL_FLAG`. To retire a flag, simply
296 // replace an `ABSL_FLAG` definition with `ABSL_RETIRED_FLAG`, leaving the
297 // arguments unchanged (unless of course you actually want to retire the flag
298 // type at this time as well).
299 //
300 // `default_value` is only used as a double check on the type. `explanation` is
301 // unused.
302 // TODO(rogeeff): replace RETIRED_FLAGS with FLAGS once forward declarations of
303 // retired flags are cleaned up.
304 #define ABSL_RETIRED_FLAG(type, name, default_value, explanation) \
305 static absl::flags_internal::RetiredFlag<type> RETIRED_FLAGS_##name; \
306 ABSL_ATTRIBUTE_UNUSED static const auto RETIRED_FLAGS_REG_##name = \
307 (RETIRED_FLAGS_##name.Retire(#name), \
308 ::absl::flags_internal::FlagRegistrarEmpty{})
309
310 #endif // ABSL_FLAGS_FLAG_H_
311