annotate win32-mingw/include/kj/main.h @ 52:44a948c37b77

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