annotate win64-msvc/include/kj/main.h @ 169:223a55898ab9 tip default

Add null config files
author Chris Cannam <cannam@all-day-breakfast.com>
date Mon, 02 Mar 2020 14:03:47 +0000
parents b4bfdf10c4b3
children
rev   line source
cannam@148 1 // Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors
cannam@148 2 // Licensed under the MIT License:
cannam@148 3 //
cannam@148 4 // Permission is hereby granted, free of charge, to any person obtaining a copy
cannam@148 5 // of this software and associated documentation files (the "Software"), to deal
cannam@148 6 // in the Software without restriction, including without limitation the rights
cannam@148 7 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
cannam@148 8 // copies of the Software, and to permit persons to whom the Software is
cannam@148 9 // furnished to do so, subject to the following conditions:
cannam@148 10 //
cannam@148 11 // The above copyright notice and this permission notice shall be included in
cannam@148 12 // all copies or substantial portions of the Software.
cannam@148 13 //
cannam@148 14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
cannam@148 15 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
cannam@148 16 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
cannam@148 17 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
cannam@148 18 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
cannam@148 19 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
cannam@148 20 // THE SOFTWARE.
cannam@148 21
cannam@148 22 #ifndef KJ_MAIN_H_
cannam@148 23 #define KJ_MAIN_H_
cannam@148 24
cannam@148 25 #if defined(__GNUC__) && !KJ_HEADER_WARNINGS
cannam@148 26 #pragma GCC system_header
cannam@148 27 #endif
cannam@148 28
cannam@148 29 #include "array.h"
cannam@148 30 #include "string.h"
cannam@148 31 #include "vector.h"
cannam@148 32 #include "function.h"
cannam@148 33
cannam@148 34 namespace kj {
cannam@148 35
cannam@148 36 class ProcessContext {
cannam@148 37 // Context for command-line programs.
cannam@148 38
cannam@148 39 public:
cannam@148 40 virtual StringPtr getProgramName() = 0;
cannam@148 41 // Get argv[0] as passed to main().
cannam@148 42
cannam@148 43 KJ_NORETURN(virtual void exit()) = 0;
cannam@148 44 // Indicates program completion. The program is considered successful unless `error()` was
cannam@148 45 // called. Typically this exits with _Exit(), meaning that the stack is not unwound, buffers
cannam@148 46 // are not flushed, etc. -- it is the responsibility of the caller to flush any buffers that
cannam@148 47 // matter. However, an alternate context implementation e.g. for unit testing purposes could
cannam@148 48 // choose to throw an exception instead.
cannam@148 49 //
cannam@148 50 // At first this approach may sound crazy. Isn't it much better to shut down cleanly? What if
cannam@148 51 // you lose data? However, it turns out that if you look at each common class of program, _Exit()
cannam@148 52 // is almost always preferable. Let's break it down:
cannam@148 53 //
cannam@148 54 // * Commands: A typical program you might run from the command line is single-threaded and
cannam@148 55 // exits quickly and deterministically. Commands often use buffered I/O and need to flush
cannam@148 56 // those buffers before exit. However, most of the work performed by destructors is not
cannam@148 57 // flushing buffers, but rather freeing up memory, placing objects into freelists, and closing
cannam@148 58 // file descriptors. All of this is irrelevant if the process is about to exit anyway, and
cannam@148 59 // for a command that runs quickly, time wasted freeing heap space may make a real difference
cannam@148 60 // in the overall runtime of a script. Meanwhile, it is usually easy to determine exactly what
cannam@148 61 // resources need to be flushed before exit, and easy to tell if they are not being flushed
cannam@148 62 // (because the command fails to produce the expected output). Therefore, it is reasonably
cannam@148 63 // easy for commands to explicitly ensure all output is flushed before exiting, and it is
cannam@148 64 // probably a good idea for them to do so anyway, because write failures should be detected
cannam@148 65 // and handled. For commands, a good strategy is to allocate any objects that require clean
cannam@148 66 // destruction on the stack, and allow them to go out of scope before the command exits.
cannam@148 67 // Meanwhile, any resources which do not need to be cleaned up should be allocated as members
cannam@148 68 // of the command's main class, whose destructor normally will not be called.
cannam@148 69 //
cannam@148 70 // * Interactive apps: Programs that interact with the user (whether they be graphical apps
cannam@148 71 // with windows or console-based apps like emacs) generally exit only when the user asks them
cannam@148 72 // to. Such applications may store large data structures in memory which need to be synced
cannam@148 73 // to disk, such as documents or user preferences. However, relying on stack unwind or global
cannam@148 74 // destructors as the mechanism for ensuring such syncing occurs is probably wrong. First of
cannam@148 75 // all, it's 2013, and applications ought to be actively syncing changes to non-volatile
cannam@148 76 // storage the moment those changes are made. Applications can crash at any time and a crash
cannam@148 77 // should never lose data that is more than half a second old. Meanwhile, if a user actually
cannam@148 78 // does try to close an application while unsaved changes exist, the application UI should
cannam@148 79 // prompt the user to decide what to do. Such a UI mechanism is obviously too high level to
cannam@148 80 // be implemented via destructors, so KJ's use of _Exit() shouldn't make a difference here.
cannam@148 81 //
cannam@148 82 // * Servers: A good server is fault-tolerant, prepared for the possibility that at any time
cannam@148 83 // it could crash, the OS could decide to kill it off, or the machine it is running on could
cannam@148 84 // just die. So, using _Exit() should be no problem. In fact, servers generally never even
cannam@148 85 // call exit anyway; they are killed externally.
cannam@148 86 //
cannam@148 87 // * Batch jobs: A long-running batch job is something between a command and a server. It
cannam@148 88 // probably knows exactly what needs to be flushed before exiting, and it probably should be
cannam@148 89 // fault-tolerant.
cannam@148 90 //
cannam@148 91 // Meanwhile, regardless of program type, if you are adhering to KJ style, then the use of
cannam@148 92 // _Exit() shouldn't be a problem anyway:
cannam@148 93 //
cannam@148 94 // * KJ style forbids global mutable state (singletons) in general and global constructors and
cannam@148 95 // destructors in particular. Therefore, everything that could possibly need cleanup either
cannam@148 96 // lives on the stack or is transitively owned by something living on the stack.
cannam@148 97 //
cannam@148 98 // * Calling exit() simply means "Don't clean up anything older than this stack frame.". If you
cannam@148 99 // have resources that require cleanup before exit, make sure they are owned by stack frames
cannam@148 100 // beyond the one that eventually calls exit(). To be as safe as possible, don't place any
cannam@148 101 // state in your program's main class, and don't call exit() yourself. Then, runMainAndExit()
cannam@148 102 // will do it, and the only thing on the stack at that time will be your main class, which
cannam@148 103 // has no state anyway.
cannam@148 104 //
cannam@148 105 // TODO(someday): Perhaps we should use the new std::quick_exit(), so that at_quick_exit() is
cannam@148 106 // available for those who really think they need it. Unfortunately, it is not yet available
cannam@148 107 // on many platforms.
cannam@148 108
cannam@148 109 virtual void warning(StringPtr message) = 0;
cannam@148 110 // Print the given message to standard error. A newline is printed after the message if it
cannam@148 111 // doesn't already have one.
cannam@148 112
cannam@148 113 virtual void error(StringPtr message) = 0;
cannam@148 114 // Like `warning()`, but also sets a flag indicating that the process has failed, and that when
cannam@148 115 // it eventually exits it should indicate an error status.
cannam@148 116
cannam@148 117 KJ_NORETURN(virtual void exitError(StringPtr message)) = 0;
cannam@148 118 // Equivalent to `error(message)` followed by `exit()`.
cannam@148 119
cannam@148 120 KJ_NORETURN(virtual void exitInfo(StringPtr message)) = 0;
cannam@148 121 // Displays the given non-error message to the user and then calls `exit()`. This is used to
cannam@148 122 // implement things like --help.
cannam@148 123
cannam@148 124 virtual void increaseLoggingVerbosity() = 0;
cannam@148 125 // Increase the level of detail produced by the debug logging system. `MainBuilder` invokes
cannam@148 126 // this if the caller uses the -v flag.
cannam@148 127
cannam@148 128 // TODO(someday): Add interfaces representing standard OS resources like the filesystem, so that
cannam@148 129 // these things can be mocked out.
cannam@148 130 };
cannam@148 131
cannam@148 132 class TopLevelProcessContext final: public ProcessContext {
cannam@148 133 // A ProcessContext implementation appropriate for use at the actual entry point of a process
cannam@148 134 // (as opposed to when you are trying to call a program's main function from within some other
cannam@148 135 // program). This implementation writes errors to stderr, and its `exit()` method actually
cannam@148 136 // calls the C `quick_exit()` function.
cannam@148 137
cannam@148 138 public:
cannam@148 139 explicit TopLevelProcessContext(StringPtr programName);
cannam@148 140
cannam@148 141 struct CleanShutdownException { int exitCode; };
cannam@148 142 // If the environment variable KJ_CLEAN_SHUTDOWN is set, then exit() will actually throw this
cannam@148 143 // exception rather than exiting. `kj::runMain()` catches this exception and returns normally.
cannam@148 144 // This is useful primarily for testing purposes, to assist tools like memory leak checkers that
cannam@148 145 // are easily confused by quick_exit().
cannam@148 146
cannam@148 147 StringPtr getProgramName() override;
cannam@148 148 KJ_NORETURN(void exit() override);
cannam@148 149 void warning(StringPtr message) override;
cannam@148 150 void error(StringPtr message) override;
cannam@148 151 KJ_NORETURN(void exitError(StringPtr message) override);
cannam@148 152 KJ_NORETURN(void exitInfo(StringPtr message) override);
cannam@148 153 void increaseLoggingVerbosity() override;
cannam@148 154
cannam@148 155 private:
cannam@148 156 StringPtr programName;
cannam@148 157 bool cleanShutdown;
cannam@148 158 bool hadErrors = false;
cannam@148 159 };
cannam@148 160
cannam@148 161 typedef Function<void(StringPtr programName, ArrayPtr<const StringPtr> params)> MainFunc;
cannam@148 162
cannam@148 163 int runMainAndExit(ProcessContext& context, MainFunc&& func, int argc, char* argv[]);
cannam@148 164 // Runs the given main function and then exits using the given context. If an exception is thrown,
cannam@148 165 // this will catch it, report it via the context and exit with an error code.
cannam@148 166 //
cannam@148 167 // Normally this function does not return, because returning would probably lead to wasting time
cannam@148 168 // on cleanup when the process is just going to exit anyway. However, to facilitate memory leak
cannam@148 169 // checkers and other tools that require a clean shutdown to do their job, if the environment
cannam@148 170 // variable KJ_CLEAN_SHUTDOWN is set, the function will in fact return an exit code, which should
cannam@148 171 // then be returned from main().
cannam@148 172 //
cannam@148 173 // Most users will use the KJ_MAIN() macro rather than call this function directly.
cannam@148 174
cannam@148 175 #define KJ_MAIN(MainClass) \
cannam@148 176 int main(int argc, char* argv[]) { \
cannam@148 177 ::kj::TopLevelProcessContext context(argv[0]); \
cannam@148 178 MainClass mainObject(context); \
cannam@148 179 return ::kj::runMainAndExit(context, mainObject.getMain(), argc, argv); \
cannam@148 180 }
cannam@148 181 // Convenience macro for declaring a main function based on the given class. The class must have
cannam@148 182 // a constructor that accepts a ProcessContext& and a method getMain() which returns
cannam@148 183 // kj::MainFunc (probably building it using a MainBuilder).
cannam@148 184
cannam@148 185 class MainBuilder {
cannam@148 186 // Builds a main() function with nice argument parsing. As options and arguments are parsed,
cannam@148 187 // corresponding callbacks are called, so that you never have to write a massive switch()
cannam@148 188 // statement to interpret arguments. Additionally, this approach encourages you to write
cannam@148 189 // main classes that have a reasonable API that can be used as an alternative to their
cannam@148 190 // command-line interface.
cannam@148 191 //
cannam@148 192 // All StringPtrs passed to MainBuilder must remain valid until option parsing completes. The
cannam@148 193 // assumption is that these strings will all be literals, making this an easy requirement. If
cannam@148 194 // not, consider allocating them in an Arena.
cannam@148 195 //
cannam@148 196 // Some flags are automatically recognized by the main functions built by this class:
cannam@148 197 // --help: Prints help text and exits. The help text is constructed based on the
cannam@148 198 // information you provide to the builder as you define each flag.
cannam@148 199 // --verbose: Increase logging verbosity.
cannam@148 200 // --version: Print version information and exit.
cannam@148 201 //
cannam@148 202 // Example usage:
cannam@148 203 //
cannam@148 204 // class FooMain {
cannam@148 205 // public:
cannam@148 206 // FooMain(kj::ProcessContext& context): context(context) {}
cannam@148 207 //
cannam@148 208 // bool setAll() { all = true; return true; }
cannam@148 209 // // Enable the --all flag.
cannam@148 210 //
cannam@148 211 // kj::MainBuilder::Validity setOutput(kj::StringPtr name) {
cannam@148 212 // // Set the output file.
cannam@148 213 //
cannam@148 214 // if (name.endsWith(".foo")) {
cannam@148 215 // outputFile = name;
cannam@148 216 // return true;
cannam@148 217 // } else {
cannam@148 218 // return "Output file must have extension .foo.";
cannam@148 219 // }
cannam@148 220 // }
cannam@148 221 //
cannam@148 222 // kj::MainBuilder::Validity processInput(kj::StringPtr name) {
cannam@148 223 // // Process an input file.
cannam@148 224 //
cannam@148 225 // if (!exists(name)) {
cannam@148 226 // return kj::str(name, ": file not found");
cannam@148 227 // }
cannam@148 228 // // ... process the input file ...
cannam@148 229 // return true;
cannam@148 230 // }
cannam@148 231 //
cannam@148 232 // kj::MainFunc getMain() {
cannam@148 233 // return MainBuilder(context, "Foo Builder v1.5", "Reads <source>s and builds a Foo.")
cannam@148 234 // .addOption({'a', "all"}, KJ_BIND_METHOD(*this, setAll),
cannam@148 235 // "Frob all the widgets. Otherwise, only some widgets are frobbed.")
cannam@148 236 // .addOptionWithArg({'o', "output"}, KJ_BIND_METHOD(*this, setOutput),
cannam@148 237 // "<filename>", "Output to <filename>. Must be a .foo file.")
cannam@148 238 // .expectOneOrMoreArgs("<source>", KJ_BIND_METHOD(*this, processInput))
cannam@148 239 // .build();
cannam@148 240 // }
cannam@148 241 //
cannam@148 242 // private:
cannam@148 243 // bool all = false;
cannam@148 244 // kj::StringPtr outputFile;
cannam@148 245 // kj::ProcessContext& context;
cannam@148 246 // };
cannam@148 247
cannam@148 248 public:
cannam@148 249 MainBuilder(ProcessContext& context, StringPtr version,
cannam@148 250 StringPtr briefDescription, StringPtr extendedDescription = nullptr);
cannam@148 251 ~MainBuilder() noexcept(false);
cannam@148 252
cannam@148 253 class OptionName {
cannam@148 254 public:
cannam@148 255 OptionName() = default;
cannam@148 256 inline OptionName(char shortName): isLong(false), shortName(shortName) {}
cannam@148 257 inline OptionName(const char* longName): isLong(true), longName(longName) {}
cannam@148 258
cannam@148 259 private:
cannam@148 260 bool isLong;
cannam@148 261 union {
cannam@148 262 char shortName;
cannam@148 263 const char* longName;
cannam@148 264 };
cannam@148 265 friend class MainBuilder;
cannam@148 266 };
cannam@148 267
cannam@148 268 class Validity {
cannam@148 269 public:
cannam@148 270 inline Validity(bool valid) {
cannam@148 271 if (!valid) errorMessage = heapString("invalid argument");
cannam@148 272 }
cannam@148 273 inline Validity(const char* errorMessage)
cannam@148 274 : errorMessage(heapString(errorMessage)) {}
cannam@148 275 inline Validity(String&& errorMessage)
cannam@148 276 : errorMessage(kj::mv(errorMessage)) {}
cannam@148 277
cannam@148 278 inline const Maybe<String>& getError() const { return errorMessage; }
cannam@148 279 inline Maybe<String> releaseError() { return kj::mv(errorMessage); }
cannam@148 280
cannam@148 281 private:
cannam@148 282 Maybe<String> errorMessage;
cannam@148 283 friend class MainBuilder;
cannam@148 284 };
cannam@148 285
cannam@148 286 MainBuilder& addOption(std::initializer_list<OptionName> names, Function<Validity()> callback,
cannam@148 287 StringPtr helpText);
cannam@148 288 // Defines a new option (flag). `names` is a list of characters and strings that can be used to
cannam@148 289 // specify the option on the command line. Single-character names are used with "-" while string
cannam@148 290 // names are used with "--". `helpText` is a natural-language description of the flag.
cannam@148 291 //
cannam@148 292 // `callback` is called when the option is seen. Its return value indicates whether the option
cannam@148 293 // was accepted. If not, further option processing stops, and error is written, and the process
cannam@148 294 // exits.
cannam@148 295 //
cannam@148 296 // Example:
cannam@148 297 //
cannam@148 298 // builder.addOption({'a', "all"}, KJ_BIND_METHOD(*this, showAll), "Show all files.");
cannam@148 299 //
cannam@148 300 // This option could be specified in the following ways:
cannam@148 301 //
cannam@148 302 // -a
cannam@148 303 // --all
cannam@148 304 //
cannam@148 305 // Note that single-character option names can be combined into a single argument. For example,
cannam@148 306 // `-abcd` is equivalent to `-a -b -c -d`.
cannam@148 307 //
cannam@148 308 // The help text for this option would look like:
cannam@148 309 //
cannam@148 310 // -a, --all
cannam@148 311 // Show all files.
cannam@148 312 //
cannam@148 313 // Note that help text is automatically word-wrapped.
cannam@148 314
cannam@148 315 MainBuilder& addOptionWithArg(std::initializer_list<OptionName> names,
cannam@148 316 Function<Validity(StringPtr)> callback,
cannam@148 317 StringPtr argumentTitle, StringPtr helpText);
cannam@148 318 // Like `addOption()`, but adds an option which accepts an argument. `argumentTitle` is used in
cannam@148 319 // the help text. The argument text is passed to the callback.
cannam@148 320 //
cannam@148 321 // Example:
cannam@148 322 //
cannam@148 323 // builder.addOptionWithArg({'o', "output"}, KJ_BIND_METHOD(*this, setOutput),
cannam@148 324 // "<filename>", "Output to <filename>.");
cannam@148 325 //
cannam@148 326 // This option could be specified with an argument of "foo" in the following ways:
cannam@148 327 //
cannam@148 328 // -ofoo
cannam@148 329 // -o foo
cannam@148 330 // --output=foo
cannam@148 331 // --output foo
cannam@148 332 //
cannam@148 333 // Note that single-character option names can be combined, but only the last option can have an
cannam@148 334 // argument, since the characters after the option letter are interpreted as the argument. E.g.
cannam@148 335 // `-abofoo` would be equivalent to `-a -b -o foo`.
cannam@148 336 //
cannam@148 337 // The help text for this option would look like:
cannam@148 338 //
cannam@148 339 // -o FILENAME, --output=FILENAME
cannam@148 340 // Output to FILENAME.
cannam@148 341
cannam@148 342 MainBuilder& addSubCommand(StringPtr name, Function<MainFunc()> getSubParser,
cannam@148 343 StringPtr briefHelpText);
cannam@148 344 // If exactly the given name is seen as an argument, invoke getSubParser() and then pass all
cannam@148 345 // remaining arguments to the parser it returns. This is useful for implementing commands which
cannam@148 346 // have lots of sub-commands, like "git" (which has sub-commands "checkout", "branch", "pull",
cannam@148 347 // etc.).
cannam@148 348 //
cannam@148 349 // `getSubParser` is only called if the command is seen. This avoids building main functions
cannam@148 350 // for commands that aren't used.
cannam@148 351 //
cannam@148 352 // `briefHelpText` should be brief enough to show immediately after the command name on a single
cannam@148 353 // line. It will not be wrapped. Users can use the built-in "help" command to get extended
cannam@148 354 // help on a particular command.
cannam@148 355
cannam@148 356 MainBuilder& expectArg(StringPtr title, Function<Validity(StringPtr)> callback);
cannam@148 357 MainBuilder& expectOptionalArg(StringPtr title, Function<Validity(StringPtr)> callback);
cannam@148 358 MainBuilder& expectZeroOrMoreArgs(StringPtr title, Function<Validity(StringPtr)> callback);
cannam@148 359 MainBuilder& expectOneOrMoreArgs(StringPtr title, Function<Validity(StringPtr)> callback);
cannam@148 360 // Set callbacks to handle arguments. `expectArg()` and `expectOptionalArg()` specify positional
cannam@148 361 // arguments with special handling, while `expect{Zero,One}OrMoreArgs()` specifies a handler for
cannam@148 362 // an argument list (the handler is called once for each argument in the list). `title`
cannam@148 363 // specifies how the argument should be represented in the usage text.
cannam@148 364 //
cannam@148 365 // All options callbacks are called before argument callbacks, regardless of their ordering on
cannam@148 366 // the command line. This matches GNU getopt's behavior of permuting non-flag arguments to the
cannam@148 367 // end of the argument list. Also matching getopt, the special option "--" indicates that the
cannam@148 368 // rest of the command line is all arguments, not options, even if they start with '-'.
cannam@148 369 //
cannam@148 370 // The interpretation of positional arguments is fairly flexible. The non-optional arguments can
cannam@148 371 // be expected at the beginning, end, or in the middle. If more arguments are specified than
cannam@148 372 // the number of non-optional args, they are assigned to the optional argument handlers in the
cannam@148 373 // order of registration.
cannam@148 374 //
cannam@148 375 // For example, say you called:
cannam@148 376 // builder.expectArg("<foo>", ...);
cannam@148 377 // builder.expectOptionalArg("<bar>", ...);
cannam@148 378 // builder.expectArg("<baz>", ...);
cannam@148 379 // builder.expectZeroOrMoreArgs("<qux>", ...);
cannam@148 380 // builder.expectArg("<corge>", ...);
cannam@148 381 //
cannam@148 382 // This command requires at least three arguments: foo, baz, and corge. If four arguments are
cannam@148 383 // given, the second is assigned to bar. If five or more arguments are specified, then the
cannam@148 384 // arguments between the third and last are assigned to qux. Note that it never makes sense
cannam@148 385 // to call `expect*OrMoreArgs()` more than once since only the first call would ever be used.
cannam@148 386 //
cannam@148 387 // In practice, you probably shouldn't create such complicated commands as in the above example.
cannam@148 388 // But, this flexibility seems necessary to support commands where the first argument is special
cannam@148 389 // as well as commands (like `cp`) where the last argument is special.
cannam@148 390
cannam@148 391 MainBuilder& callAfterParsing(Function<Validity()> callback);
cannam@148 392 // Call the given function after all arguments have been parsed.
cannam@148 393
cannam@148 394 MainFunc build();
cannam@148 395 // Build the "main" function, which simply parses the arguments. Once this returns, the
cannam@148 396 // `MainBuilder` is no longer valid.
cannam@148 397
cannam@148 398 private:
cannam@148 399 struct Impl;
cannam@148 400 Own<Impl> impl;
cannam@148 401
cannam@148 402 class MainImpl;
cannam@148 403 };
cannam@148 404
cannam@148 405 } // namespace kj
cannam@148 406
cannam@148 407 #endif // KJ_MAIN_H_