capnp.c++ 67.6 KB
Newer Older
Kenton Varda's avatar
Kenton Varda committed
1 2
// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
3
//
Kenton Varda's avatar
Kenton Varda committed
4 5 6 7 8 9
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
10
//
Kenton Varda's avatar
Kenton Varda committed
11 12
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
13
//
Kenton Varda's avatar
Kenton Varda committed
14 15 16 17 18 19 20
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
21

22
#ifndef _GNU_SOURCE
Ivan Shynkarenka's avatar
Ivan Shynkarenka committed
23 24 25
#define _GNU_SOURCE
#endif

26 27 28 29
#include "lexer.h"
#include "parser.h"
#include "compiler.h"
#include "module-loader.h"
30
#include "node-translator.h"
31 32 33 34
#include <capnp/pretty-print.h>
#include <capnp/schema.capnp.h>
#include <kj/vector.h>
#include <kj/io.h>
35
#include <kj/miniposix.h>
36 37 38 39
#include <kj/debug.h>
#include "../message.h"
#include <iostream>
#include <kj/main.h>
40
#include <kj/parse/char.h>
41 42 43 44
#include <sys/stat.h>
#include <sys/types.h>
#include <capnp/serialize.h>
#include <capnp/serialize-packed.h>
45 46
#include <capnp/serialize-text.h>
#include <capnp/compat/json.h>
47
#include <errno.h>
Kenton Varda's avatar
Kenton Varda committed
48
#include <stdlib.h>
49

50 51
#if _WIN32
#include <process.h>
52 53 54 55 56
#define WIN32_LEAN_AND_MEAN  // ::eyeroll::
#include <windows.h>
#include <kj/windows-sanity.h>
#undef VOID
#undef CONST
57 58 59 60
#else
#include <sys/wait.h>
#endif

61 62
#if HAVE_CONFIG_H
#include "config.h"
Kenton Varda's avatar
Kenton Varda committed
63 64 65 66
#endif

#ifndef VERSION
#define VERSION "(unknown)"
67 68
#endif

69 70 71
namespace capnp {
namespace compiler {

72
static const char VERSION_STRING[] = "Cap'n Proto version " VERSION;
73 74 75 76

class CompilerMain final: public GlobalErrorReporter {
public:
  explicit CompilerMain(kj::ProcessContext& context)
77
      : context(context), disk(kj::newDiskFilesystem()), loader(*this) {}
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95

  kj::MainFunc getMain() {
    if (context.getProgramName().endsWith("capnpc")) {
      kj::MainBuilder builder(context, VERSION_STRING,
            "Compiles Cap'n Proto schema files and generates corresponding source code in one or "
            "more languages.");
      addGlobalOptions(builder);
      addCompileOptions(builder);
      builder.addOption({'i', "generate-id"}, KJ_BIND_METHOD(*this, generateId),
                        "Generate a new 64-bit unique ID for use in a Cap'n Proto schema.");
      return builder.build();
    } else {
      kj::MainBuilder builder(context, VERSION_STRING,
            "Command-line tool for Cap'n Proto development and debugging.");
      builder.addSubCommand("compile", KJ_BIND_METHOD(*this, getCompileMain),
                            "Generate source code from schema files.")
             .addSubCommand("id", KJ_BIND_METHOD(*this, getGenIdMain),
                            "Generate a new unique ID.")
96 97
             .addSubCommand("convert", KJ_BIND_METHOD(*this, getConvertMain),
                            "Convert messages between binary, text, JSON, etc.")
98
             .addSubCommand("decode", KJ_BIND_METHOD(*this, getDecodeMain),
99
                            "DEPRECATED (use `convert`)")
100
             .addSubCommand("encode", KJ_BIND_METHOD(*this, getEncodeMain),
101
                            "DEPRECATED (use `convert`)")
102 103
             .addSubCommand("eval", KJ_BIND_METHOD(*this, getEvalMain),
                            "Evaluate a const from a schema file.");
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
      addGlobalOptions(builder);
      return builder.build();
    }
  }

  kj::MainFunc getCompileMain() {
    kj::MainBuilder builder(context, VERSION_STRING,
          "Compiles Cap'n Proto schema files and generates corresponding source code in one or "
          "more languages.");
    addGlobalOptions(builder);
    addCompileOptions(builder);
    return builder.build();
  }

  kj::MainFunc getGenIdMain() {
119
    return kj::MainBuilder(context, VERSION_STRING,
120 121 122 123 124
          "Generates a new 64-bit unique ID for use in a Cap'n Proto schema.")
        .callAfterParsing(KJ_BIND_METHOD(*this, generateId))
        .build();
  }

125 126 127 128 129 130 131 132 133 134 135 136 137 138
  kj::MainFunc getConvertMain() {
    // Only parse the schemas we actually need for decoding.
    compileEagerness = Compiler::NODE;

    // Drop annotations since we don't need them.  This avoids importing files like c++.capnp.
    annotationFlag = Compiler::DROP_ANNOTATIONS;

    kj::MainBuilder builder(context, VERSION_STRING,
          "Convers messages between formats. Reads a stream of messages from stdin in format "
          "<from> and writes them to stdout in format <to>. Valid formats are:\n"
          "    binary      standard binary format\n"
          "    packed      packed binary format (deflates zeroes)\n"
          "    flat        binary single segment, no segment table (rare)\n"
          "    flat-packed flat and packed\n"
139
          "    canonical   canonicalized binary single segment, no segment table\n"
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
          "    text        schema language struct literal format\n"
          "    json        JSON format\n"
          "When using \"text\" or \"json\" format, you must specify <schema-file> and <type> "
          "(but they are ignored and can be omitted for binary-to-binary conversions). "
          "<type> names names a struct type defined in <schema-file>, which is the root type "
          "of the message(s).");
    addGlobalOptions(builder);
    builder.addOption({"short"}, KJ_BIND_METHOD(*this, printShort),
               "Write text or JSON output in short (non-pretty) format. Each message will "
               "be printed on one line, without using whitespace to improve readability.")
           .addOptionWithArg({"segment-size"}, KJ_BIND_METHOD(*this, setSegmentSize), "<n>",
               "For binary output, sets the preferred segment size on the MallocMessageBuilder to <n> "
               "words and turns off heuristic growth.  This flag is mainly useful "
               "for testing.  Without it, each message will be written as a single "
               "segment.")
           .addOption({"quiet"}, KJ_BIND_METHOD(*this, setQuiet),
               "Do not print warning messages about the input being in the wrong format.  "
               "Use this if you find the warnings are wrong (but also let us know so "
               "we can improve them).")
           .expectArg("<from>:<to>", KJ_BIND_METHOD(*this, setConversion))
           .expectOptionalArg("<schema-file>", KJ_BIND_METHOD(*this, addSource))
           .expectOptionalArg("<type>", KJ_BIND_METHOD(*this, setRootType))
           .callAfterParsing(KJ_BIND_METHOD(*this, convert));
    return builder.build();
  }

166 167
  kj::MainFunc getDecodeMain() {
    // Only parse the schemas we actually need for decoding.
168 169 170 171
    compileEagerness = Compiler::NODE;

    // Drop annotations since we don't need them.  This avoids importing files like c++.capnp.
    annotationFlag = Compiler::DROP_ANNOTATIONS;
172 173 174 175 176 177

    kj::MainBuilder builder(context, VERSION_STRING,
          "Decodes one or more encoded Cap'n Proto messages as text.  The messages have root "
          "type <type> defined in <schema-file>.  Messages are read from standard input and "
          "by default are expected to be in standard Cap'n Proto serialization format.");
    addGlobalOptions(builder);
178
    builder.addOption({"flat"}, KJ_BIND_METHOD(*this, codeFlat),
179
                      "Interpret the input as one large single-segment message rather than a "
180
                      "stream in standard serialization format.  (Rarely used.)")
181 182
           .addOption({'p', "packed"}, KJ_BIND_METHOD(*this, codePacked),
                      "Expect the input to be packed using standard Cap'n Proto packing, which "
183 184 185 186
                      "deflates zero-valued bytes.  (This reads messages written with "
                      "capnp::writePackedMessage*() from <capnp/serialize-packed.h>.  Do not use "
                      "this for messages written with capnp::writeMessage*() from "
                      "<capnp/serialize.h>.)")
187 188 189
           .addOption({"short"}, KJ_BIND_METHOD(*this, printShort),
                      "Print in short (non-pretty) format.  Each message will be printed on one "
                      "line, without using whitespace to improve readability.")
190 191 192 193
           .addOption({"quiet"}, KJ_BIND_METHOD(*this, setQuiet),
                      "Do not print warning messages about the input being in the wrong format.  "
                      "Use this if you find the warnings are wrong (but also let us know so "
                      "we can improve them).")
194 195 196 197 198 199
           .expectArg("<schema-file>", KJ_BIND_METHOD(*this, addSource))
           .expectArg("<type>", KJ_BIND_METHOD(*this, setRootType))
           .callAfterParsing(KJ_BIND_METHOD(*this, decode));
    return builder.build();
  }

200 201 202 203 204 205 206 207 208 209
  kj::MainFunc getEncodeMain() {
    // Only parse the schemas we actually need for decoding.
    compileEagerness = Compiler::NODE;

    // Drop annotations since we don't need them.  This avoids importing files like c++.capnp.
    annotationFlag = Compiler::DROP_ANNOTATIONS;

    kj::MainBuilder builder(context, VERSION_STRING,
          "Encodes one or more textual Cap'n Proto messages to binary.  The messages have root "
          "type <type> defined in <schema-file>.  Messages are read from standard input.  Each "
210
          "message is a parenthesized struct literal, like the format used to specify constants "
211 212 213 214
          "and default values of struct type in the schema language.  For example:\n"
          "    (foo = 123, bar = \"hello\", baz = [true, false, true])\n"
          "The input may contain any number of such values; each will be encoded as a separate "
          "message.",
215

216 217 218 219
          "Note that the current implementation reads the entire input into memory before "
          "beginning to encode.  A better implementation would read and encode one message at "
          "a time.");
    addGlobalOptions(builder);
220
    builder.addOption({"flat"}, KJ_BIND_METHOD(*this, codeFlat),
221 222 223 224
                      "Expect only one input value, serializing it as a single-segment message "
                      "with no framing.")
           .addOption({'p', "packed"}, KJ_BIND_METHOD(*this, codePacked),
                      "Pack the output message with standard Cap'n Proto packing, which "
225 226 227
                      "deflates zero-valued bytes.  (This writes messages using "
                      "capnp::writePackedMessage() from <capnp/serialize-packed.h>.  Without "
                      "this, capnp::writeMessage() from <capnp/serialize.h> is used.)")
228 229 230 231 232
           .addOptionWithArg({"segment-size"}, KJ_BIND_METHOD(*this, setSegmentSize), "<n>",
                             "Sets the preferred segment size on the MallocMessageBuilder to <n> "
                             "words and turns off heuristic growth.  This flag is mainly useful "
                             "for testing.  Without it, each message will be written as a single "
                             "segment.")
233 234 235 236 237 238
           .expectArg("<schema-file>", KJ_BIND_METHOD(*this, addSource))
           .expectArg("<type>", KJ_BIND_METHOD(*this, setRootType))
           .callAfterParsing(KJ_BIND_METHOD(*this, encode));
    return builder.build();
  }

239 240 241 242 243 244 245
  kj::MainFunc getEvalMain() {
    // Only parse the schemas we actually need for decoding.
    compileEagerness = Compiler::NODE;

    // Drop annotations since we don't need them.  This avoids importing files like c++.capnp.
    annotationFlag = Compiler::DROP_ANNOTATIONS;

246 247 248
    // Default convert to text unless -o is given.
    convertTo = Format::TEXT;

249
    kj::MainBuilder builder(context, VERSION_STRING,
250 251 252 253 254 255 256 257 258
          "Prints (or encodes) the value of <name>, which must be defined in <schema-file>.  "
          "<name> must refer to a const declaration, a field of a struct type (prints the default "
          "value), or a field or list element nested within some other value.  Examples:\n"
          "    capnp eval myschema.capnp MyType.someField\n"
          "    capnp eval myschema.capnp someConstant\n"
          "    capnp eval myschema.capnp someConstant.someField\n"
          "    capnp eval myschema.capnp someConstant.someList[4]\n"
          "    capnp eval myschema.capnp someConstant.someList[4].anotherField[1][2][3]\n"
          "Since consts can have complex struct types, and since you can define a const using "
Kenton Varda's avatar
Kenton Varda committed
259
          "import and variable substitution, this can be a convenient way to write text-format "
260
          "config files which are compiled to binary before deployment.",
261 262 263 264 265

          "By default the value is written in text format and can have any type.  The -b, -p, "
          "and --flat flags specify binary output, in which case the const must be of struct "
          "type.");
    addGlobalOptions(builder);
266 267 268 269 270
    builder.addOptionWithArg({'o', "output"}, KJ_BIND_METHOD(*this, setEvalOutputFormat),
                      "<format>", "Encode the output in the given format. See `capnp help convert` "
                      "for a list of formats. Defaults to \"text\".")
           .addOption({'b', "binary"}, KJ_BIND_METHOD(*this, codeBinary),
                      "same as -obinary")
271
           .addOption({"flat"}, KJ_BIND_METHOD(*this, codeFlat),
272
                      "same as -oflat")
273
           .addOption({'p', "packed"}, KJ_BIND_METHOD(*this, codePacked),
274
                      "same as -opacked")
275
           .addOption({"short"}, KJ_BIND_METHOD(*this, printShort),
276 277 278
                      "If output format is text or JSON, write in short (non-pretty) format. The "
                      "message will be printed on one line, without using whitespace to improve "
                      "readability.")
279 280 281 282 283
           .expectArg("<schema-file>", KJ_BIND_METHOD(*this, addSource))
           .expectArg("<name>", KJ_BIND_METHOD(*this, evalConst));
    return builder.build();
  }

284 285 286 287 288 289 290 291 292 293 294 295 296 297
  void addGlobalOptions(kj::MainBuilder& builder) {
    builder.addOptionWithArg({'I', "import-path"}, KJ_BIND_METHOD(*this, addImportPath), "<dir>",
                             "Add <dir> to the list of directories searched for non-relative "
                             "imports (ones that start with a '/').")
           .addOption({"no-standard-import"}, KJ_BIND_METHOD(*this, noStandardImport),
                      "Do not add any default import paths; use only those specified by -I.  "
                      "Otherwise, typically /usr/include and /usr/local/include are added by "
                      "default.");
  }

  void addCompileOptions(kj::MainBuilder& builder) {
    builder.addOptionWithArg({'o', "output"}, KJ_BIND_METHOD(*this, addOutput), "<lang>[:<dir>]",
                             "Generate source code for language <lang> in directory <dir> "
                             "(default: current directory).  <lang> actually specifies a plugin "
298
                             "to use.  If <lang> is a simple word, the compiler searches for a plugin "
299 300
                             "called 'capnpc-<lang>' in $PATH.  If <lang> is a file path "
                             "containing slashes, it is interpreted as the exact plugin "
301 302
                             "executable file name, and $PATH is not searched.  If <lang> is '-', "
                             "the compiler dumps the request to standard output.")
303 304 305 306
           .addOptionWithArg({"src-prefix"}, KJ_BIND_METHOD(*this, addSourcePrefix), "<prefix>",
                             "If a file specified for compilation starts with <prefix>, remove "
                             "the prefix for the purpose of deciding the names of output files.  "
                             "For example, the following command:\n"
307
                             "    capnp compile --src-prefix=foo/bar -oc++:corge foo/bar/baz/qux.capnp\n"
308 309 310 311 312 313 314 315 316
                             "would generate the files corge/baz/qux.capnp.{h,c++}.")
           .expectOneOrMoreArgs("<source>", KJ_BIND_METHOD(*this, addSource))
           .callAfterParsing(KJ_BIND_METHOD(*this, generateOutput));
  }

  // =====================================================================================
  // shared options

  kj::MainBuilder::Validity addImportPath(kj::StringPtr path) {
317 318 319 320 321 322
    KJ_IF_MAYBE(dir, getSourceDirectory(path, false)) {
      loader.addImportPath(*dir);
      return true;
    } else {
      return "no such directory";
    }
323 324 325 326 327 328 329 330
  }

  kj::MainBuilder::Validity noStandardImport() {
    addStandardImportPaths = false;
    return true;
  }

  kj::MainBuilder::Validity addSource(kj::StringPtr file) {
331 332 333 334 335
    if (!compilerConstructed) {
      compiler = compilerSpace.construct(annotationFlag);
      compilerConstructed = true;
    }

336
    if (addStandardImportPaths) {
337 338 339
      static constexpr kj::StringPtr STANDARD_IMPORT_PATHS[] = {
        "/usr/local/include"_kj,
        "/usr/include"_kj,
340
#ifdef CAPNP_INCLUDE_DIR
341
        KJ_CONCAT(CAPNP_INCLUDE_DIR, _kj),
342
#endif
343 344 345 346 347 348 349 350 351
      };
      for (auto path: STANDARD_IMPORT_PATHS) {
        KJ_IF_MAYBE(dir, getSourceDirectory(path, false)) {
          loader.addImportPath(*dir);
        } else {
          // ignore standard path that doesn't exist
        }
      }

352 353 354
      addStandardImportPaths = false;
    }

355 356
    auto dirPathPair = interpretSourceFile(file);
    KJ_IF_MAYBE(module, loader.loadModule(dirPathPair.dir, dirPathPair.path)) {
357 358 359 360 361 362 363 364 365 366 367
      uint64_t id = compiler->add(*module);
      compiler->eagerlyCompile(id, compileEagerness);
      sourceFiles.add(SourceFile { id, module->getSourceName(), &*module });
    } else {
      return "no such file";
    }

    return true;
  }

public:
368 369 370 371 372
  // =====================================================================================
  // "id" command

  kj::MainBuilder::Validity generateId() {
    context.exitInfo(kj::str("@0x", kj::hex(generateRandomId())));
Kenton Varda's avatar
Kenton Varda committed
373
    KJ_CLANG_KNOWS_THIS_IS_UNREACHABLE_BUT_GCC_DOESNT;
374 375 376 377 378 379 380 381
  }

  // =====================================================================================
  // "compile" command

  kj::MainBuilder::Validity addOutput(kj::StringPtr spec) {
    KJ_IF_MAYBE(split, spec.findFirst(':')) {
      kj::StringPtr dir = spec.slice(*split + 1);
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
      auto plugin = spec.slice(0, *split);

      KJ_IF_MAYBE(split2, dir.findFirst(':')) {
        // Grr, there are two colons. Might this be a Windows path? Let's do some heuristics.
        if (*split == 1 && (dir.startsWith("/") || dir.startsWith("\\"))) {
          // So, the first ':' was the second char, and was followed by '/' or '\', e.g.:
          //     capnp compile -o c:/foo.exe:bar
          //
          // In this case we can conclude that the second colon is actually meant to be the
          // plugin/location separator, and the first colon was simply signifying a drive letter.
          //
          // Proof by contradiction:
          // - Say that none of the colons were meant to be plugin/location separators; i.e. the
          //   whole argument is meant to be a plugin indicator and the location defaults to ".".
          //   -> In this case, the plugin path has two colons, which is not valid.
          //   -> CONTRADICTION
          // - Say that the first colon was meant to be the plugin/location separator.
          //   -> In this case, the second colon must be the drive letter separator for the
          //      output location.
          //   -> However, the output location begins with '/' or '\', which is not a drive letter.
          //   -> CONTRADICTION
          // - Say that there are more colons beyond the first two, and one of these is meant to
          //   be the plugin/location separator.
          //   -> In this case, the plugin path has two or more colons, which is not valid.
          //   -> CONTRADICTION
          //
          // We therefore conclude that the *second* colon is in fact the plugin/location separator.
          //
          // Note that there is still an ambiguous case:
          //     capnp compile -o c:/foo
          //
          // In this unfortunate case, we have no way to tell if the user meant "use the 'c' plugin
          // and output to /foo" or "use the plugin c:/foo and output to the default location". We
          // prefer the former interpretation, because the latter is Windows-specific and such
          // users can always explicitly specify the output location like:
          //     capnp compile -o c:/foo:.

          dir = dir.slice(*split2 + 1);
          plugin = spec.slice(0, *split2 + 2);
        }
      }

424 425 426 427
      struct stat stats;
      if (stat(dir.cStr(), &stats) < 0 || !S_ISDIR(stats.st_mode)) {
        return "output location is inaccessible or is not a directory";
      }
428
      outputs.add(OutputDirective { plugin, disk->getCurrentPath().evalNative(dir) });
429 430 431 432 433 434 435 436
    } else {
      outputs.add(OutputDirective { spec.asArray(), nullptr });
    }

    return true;
  }

  kj::MainBuilder::Validity addSourcePrefix(kj::StringPtr prefix) {
437 438
    if (getSourceDirectory(prefix, true) == nullptr) {
      return "no such directory";
439
    } else {
440
      return true;
441 442 443 444 445 446 447 448 449
    }
  }

  kj::MainBuilder::Validity generateOutput() {
    if (hadErrors()) {
      // Skip output if we had any errors.
      return true;
    }

450 451
    // We require one or more sources and if they failed to compile we quit above, so this should
    // pass.  (This assertion also guarantees that `compiler` has been initialized.)
Kenton Varda's avatar
Kenton Varda committed
452
    KJ_ASSERT(sourceFiles.size() > 0, "Shouldn't have gotten here without sources.");
453

454 455 456 457 458
    if (outputs.size() == 0) {
      return "no outputs specified";
    }

    MallocMessageBuilder message;
Kenton Varda's avatar
Kenton Varda committed
459
    auto request = message.initRoot<schema::CodeGeneratorRequest>();
460

461 462 463 464 465
    auto version = request.getCapnpVersion();
    version.setMajor(CAPNP_VERSION_MAJOR);
    version.setMinor(CAPNP_VERSION_MINOR);
    version.setMicro(CAPNP_VERSION_MICRO);

466
    auto schemas = compiler->getLoader().getAllLoaded();
467 468 469 470 471
    auto nodes = request.initNodes(schemas.size());
    for (size_t i = 0; i < schemas.size(); i++) {
      nodes.setWithCaveats(i, schemas[i].getProto());
    }

472
    request.adoptSourceInfo(compiler->getAllSourceInfo(message.getOrphanage()));
473

Kenton Varda's avatar
Kenton Varda committed
474 475 476 477 478 479 480
    auto requestedFiles = request.initRequestedFiles(sourceFiles.size());
    for (size_t i = 0; i < sourceFiles.size(); i++) {
      auto requestedFile = requestedFiles[i];
      requestedFile.setId(sourceFiles[i].id);
      requestedFile.setFilename(sourceFiles[i].name);
      requestedFile.adoptImports(compiler->getFileImportTable(
          *sourceFiles[i].module, Orphanage::getForMessageContaining(requestedFile)));
481 482 483
    }

    for (auto& output: outputs) {
484
      if (kj::str(output.name) == "-") {
485 486 487 488
        writeMessageToFd(STDOUT_FILENO, message);
        continue;
      }

489
      int pipeFds[2];
490
      KJ_SYSCALL(kj::miniposix::pipe(pipeFds));
491 492 493 494

      kj::String exeName;
      bool shouldSearchPath = true;
      for (char c: output.name) {
495 496 497
#if _WIN32
        if (c == '/' || c == '\\') {
#else
498
        if (c == '/') {
499
#endif
500 501 502 503 504 505 506 507 508 509
          shouldSearchPath = false;
          break;
        }
      }
      if (shouldSearchPath) {
        exeName = kj::str("capnpc-", output.name);
      } else {
        exeName = kj::heapString(output.name);
      }

510 511 512 513 514 515 516 517 518 519 520 521
      kj::Array<char> pwd = kj::heapArray<char>(256);
      while (getcwd(pwd.begin(), pwd.size()) == nullptr) {
        KJ_REQUIRE(pwd.size() < 8192, "WTF your working directory path is more than 8k?");
        pwd = kj::heapArray<char>(pwd.size() * 2);
      }

#if _WIN32
      int oldStdin;
      KJ_SYSCALL(oldStdin = dup(STDIN_FILENO));
      intptr_t child;

#else  // _WIN32
522 523 524 525
      pid_t child;
      KJ_SYSCALL(child = fork());
      if (child == 0) {
        // I am the child!
526

527
        KJ_SYSCALL(close(pipeFds[1]));
528 529
#endif  // _WIN32, else

530 531 532
        KJ_SYSCALL(dup2(pipeFds[0], STDIN_FILENO));
        KJ_SYSCALL(close(pipeFds[0]));

533 534 535 536 537 538 539 540
        KJ_IF_MAYBE(d, output.dir) {
#if _WIN32
          KJ_SYSCALL(SetCurrentDirectoryW(d->forWin32Api(true).begin()), d->toWin32String(true));
#else
          auto wd = d->toString(true);
          KJ_SYSCALL(chdir(wd.cStr()), wd);
          KJ_SYSCALL(setenv("PWD", wd.cStr(), true));
#endif
541 542 543
        }

        if (shouldSearchPath) {
544
#if _WIN32
545 546 547 548 549
          // MSVCRT's spawn*() don't correctly escape arguments, which is necessary on Windows
          // since the underlying system call takes a single command line string rather than
          // an arg list. Instead of trying to do the escaping ourselves, we just pass "plugin"
          // for argv[0].
          child = _spawnlp(_P_NOWAIT, exeName.cStr(), "plugin", nullptr);
550
#else
551
          execlp(exeName.cStr(), exeName.cStr(), nullptr);
552
#endif
553
        } else {
554 555 556 557
#if _WIN32
          if (!exeName.startsWith("/") && !exeName.startsWith("\\") &&
              !(exeName.size() >= 2 && exeName[1] == ':')) {
#else
558
          if (!exeName.startsWith("/")) {
559
#endif
560 561 562 563
            // The name is relative.  Prefix it with our original working directory path.
            exeName = kj::str(pwd.begin(), "/", exeName);
          }

564
#if _WIN32
565 566 567 568 569
          // MSVCRT's spawn*() don't correctly escape arguments, which is necessary on Windows
          // since the underlying system call takes a single command line string rather than
          // an arg list. Instead of trying to do the escaping ourselves, we just pass "plugin"
          // for argv[0].
          child = _spawnl(_P_NOWAIT, exeName.cStr(), "plugin", nullptr);
570
#else
571
          execl(exeName.cStr(), exeName.cStr(), nullptr);
572
#endif
573 574
        }

575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
#if _WIN32
        if (child == -1) {
#endif
          int error = errno;
          if (error == ENOENT) {
            context.exitError(kj::str(output.name, ": no such plugin (executable should be '",
                                      exeName, "')"));
          } else {
#if _WIN32
            KJ_FAIL_SYSCALL("spawn()", error);
#else
            KJ_FAIL_SYSCALL("exec()", error);
#endif
          }
#if _WIN32
590
        }
591 592 593 594 595 596 597 598

        // Restore stdin.
        KJ_SYSCALL(dup2(oldStdin, STDIN_FILENO));
        KJ_SYSCALL(close(oldStdin));

        // Restore current directory.
        KJ_SYSCALL(chdir(pwd.begin()), pwd.begin());
#else  // _WIN32
599 600 601
      }

      KJ_SYSCALL(close(pipeFds[0]));
602
#endif  // _WIN32, else
603 604 605 606

      writeMessageToFd(pipeFds[1], message);
      KJ_SYSCALL(close(pipeFds[1]));

607 608 609 610 611 612 613 614 615 616 617
#if _WIN32
      int status;
      if (_cwait(&status, child, 0) == -1) {
        KJ_FAIL_SYSCALL("_cwait()", errno);
      }

      if (status != 0) {
        context.error(kj::str(output.name, ": plugin failed: exit code ", status));
      }

#else  // _WIN32
618 619 620
      int status;
      KJ_SYSCALL(waitpid(child, &status, 0));
      if (WIFSIGNALED(status)) {
621
        context.error(kj::str(output.name, ": plugin failed: ", strsignal(WTERMSIG(status))));
622
      } else if (WIFEXITED(status) && WEXITSTATUS(status) != 0) {
623
        context.error(kj::str(output.name, ": plugin failed: exit code ", WEXITSTATUS(status)));
624
      }
625
#endif  // _WIN32, else
626 627 628 629 630
    }

    return true;
  }

631 632 633 634 635 636 637 638 639
  // =====================================================================================
  // "convert" command

private:
  enum class Format {
    BINARY,
    PACKED,
    FLAT,
    FLAT_PACKED,
640
    CANONICAL,
641 642 643 644 645 646 647 648 649
    TEXT,
    JSON
  };

  kj::Maybe<Format> parseFormatName(kj::StringPtr name) {
    if (name == "binary"     ) return Format::BINARY;
    if (name == "packed"     ) return Format::PACKED;
    if (name == "flat"       ) return Format::FLAT;
    if (name == "flat-packed") return Format::FLAT_PACKED;
650
    if (name == "canonical"  ) return Format::CANONICAL;
651 652 653 654 655 656 657 658 659 660 661 662
    if (name == "text"       ) return Format::TEXT;
    if (name == "json"       ) return Format::JSON;

    return nullptr;
  }

  kj::StringPtr toString(Format format) {
    switch (format) {
      case Format::BINARY     : return "binary";
      case Format::PACKED     : return "packed";
      case Format::FLAT       : return "flat";
      case Format::FLAT_PACKED: return "flat-packed";
663
      case Format::CANONICAL  : return "canonical";
664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990
      case Format::TEXT       : return "text";
      case Format::JSON       : return "json";
    }
    KJ_UNREACHABLE;
  }

  Format formatFromDeprecatedFlags(Format defaultFormat) {
    // For deprecated commands "decode" and "encode".
    if (flat) {
      if (packed) {
        return Format::FLAT_PACKED;
      } else {
        return Format::FLAT;
      }
    } if (packed) {
      return Format::PACKED;
    } else if (binary) {
      return Format::BINARY;
    } else {
      return defaultFormat;
    }
  }

  kj::MainBuilder::Validity verifyRequirements(Format format) {
    if ((format == Format::TEXT || format == Format::JSON) && rootType == StructSchema()) {
      return kj::str("format requires schema: ", toString(format));
    } else {
      return true;
    }
  }

public:
  kj::MainBuilder::Validity setConversion(kj::StringPtr conversion) {
    KJ_IF_MAYBE(colon, conversion.findFirst(':')) {
      auto from = kj::str(conversion.slice(0, *colon));
      auto to = conversion.slice(*colon + 1);

      KJ_IF_MAYBE(f, parseFormatName(from)) {
        convertFrom = *f;
      } else {
        return kj::str("unknown format: ", from);
      }

      KJ_IF_MAYBE(t, parseFormatName(to)) {
        convertTo = *t;
      } else {
        return kj::str("unknown format: ", to);
      }

      return true;
    } else {
      return "invalid conversion, format is: <from>:<to>";
    }
  }

  kj::MainBuilder::Validity convert() {
    {
      auto result = verifyRequirements(convertFrom);
      if (result.getError() != nullptr) return result;
    }
    {
      auto result = verifyRequirements(convertTo);
      if (result.getError() != nullptr) return result;
    }

    kj::FdInputStream rawInput(STDIN_FILENO);
    kj::BufferedInputStreamWrapper input(rawInput);

    kj::FdOutputStream output(STDOUT_FILENO);

    if (!quiet) {
      auto result = checkPlausibility(convertFrom, input.getReadBuffer());
      if (result.getError() != nullptr) {
        return kj::mv(result);
      }
    }

    while (input.tryGetReadBuffer().size() > 0) {
      readOneAndConvert(input, output);
    }

    context.exit();
    KJ_CLANG_KNOWS_THIS_IS_UNREACHABLE_BUT_GCC_DOESNT;
  }

private:
  kj::Vector<byte> readAll(kj::BufferedInputStreamWrapper& input) {
    kj::Vector<byte> allBytes;
    for (;;) {
      auto buffer = input.tryGetReadBuffer();
      if (buffer.size() == 0) break;
      allBytes.addAll(buffer);
      input.skip(buffer.size());
    }
    return allBytes;
  }

  kj::String readOneText(kj::BufferedInputStreamWrapper& input) {
    // Consume and return one parentheses-delimited message from the input.
    //
    // Accounts for nested parentheses, comments, and string literals.

    enum {
      NORMAL,
      COMMENT,
      QUOTE,
      QUOTE_ESCAPE,
      DQUOTE,
      DQUOTE_ESCAPE
    } state = NORMAL;
    uint depth = 0;
    bool sawClose = false;

    kj::Vector<char> chars;

    for (;;) {
      auto buffer = input.tryGetReadBuffer();

      if (buffer == nullptr) {
        // EOF
        chars.add('\0');
        return kj::String(chars.releaseAsArray());
      }

      for (auto i: kj::indices(buffer)) {
        char c = buffer[i];
        switch (state) {
          case NORMAL:
            switch (c) {
              case '#': state = COMMENT; break;
              case '(':
                if (depth == 0 && sawClose) {
                  // We already got one complete message. This is the start of the next message.
                  // Stop here.
                  chars.addAll(buffer.slice(0, i));
                  chars.add('\0');
                  input.skip(i);
                  return kj::String(chars.releaseAsArray());
                }
                ++depth;
                break;
              case ')':
                if (depth > 0) {
                  if (--depth == 0) {
                    sawClose = true;
                  }
                }
                break;
              default: break;
            }
            break;
          case COMMENT:
            switch (c) {
              case '\n': state = NORMAL; break;
              default: break;
            }
            break;
          case QUOTE:
            switch (c) {
              case '\'': state = NORMAL; break;
              case '\\': state = QUOTE_ESCAPE; break;
              default: break;
            }
            break;
          case QUOTE_ESCAPE:
            break;
          case DQUOTE:
            switch (c) {
              case '\"': state = NORMAL; break;
              case '\\': state = DQUOTE_ESCAPE; break;
              default: break;
            }
            break;
          case DQUOTE_ESCAPE:
            break;
        }
      }

      chars.addAll(buffer);
      input.skip(buffer.size());
    }
  }

  kj::String readOneJson(kj::BufferedInputStreamWrapper& input) {
    // Consume and return one brace-delimited message from the input.
    //
    // Accounts for nested braces, string literals, and comments starting with # or //. Technically
    // JSON does not permit comments but this code is lenient in case we change things later.

    enum {
      NORMAL,
      SLASH,
      COMMENT,
      QUOTE,
      QUOTE_ESCAPE,
      DQUOTE,
      DQUOTE_ESCAPE
    } state = NORMAL;
    uint depth = 0;
    bool sawClose = false;

    kj::Vector<char> chars;

    for (;;) {
      auto buffer = input.tryGetReadBuffer();

      if (buffer == nullptr) {
        // EOF
        chars.add('\0');
        return kj::String(chars.releaseAsArray());
      }

      for (auto i: kj::indices(buffer)) {
        char c = buffer[i];
        switch (state) {
          case SLASH:
            if (c == '/') {
              state = COMMENT;
              break;
            }
            // fallthrough
          case NORMAL:
            switch (c) {
              case '#': state = COMMENT; break;
              case '/': state = SLASH; break;
              case '{':
                if (depth == 0 && sawClose) {
                  // We already got one complete message. This is the start of the next message.
                  // Stop here.
                  chars.addAll(buffer.slice(0, i));
                  chars.add('\0');
                  input.skip(i);
                  return kj::String(chars.releaseAsArray());
                }
                ++depth;
                break;
              case '}':
                if (depth > 0) {
                  if (--depth == 0) {
                    sawClose = true;
                  }
                }
                break;
              default: break;
            }
            break;
          case COMMENT:
            switch (c) {
              case '\n': state = NORMAL; break;
              default: break;
            }
            break;
          case QUOTE:
            switch (c) {
              case '\'': state = NORMAL; break;
              case '\\': state = QUOTE_ESCAPE; break;
              default: break;
            }
            break;
          case QUOTE_ESCAPE:
            break;
          case DQUOTE:
            switch (c) {
              case '\"': state = NORMAL; break;
              case '\\': state = DQUOTE_ESCAPE; break;
              default: break;
            }
            break;
          case DQUOTE_ESCAPE:
            break;
        }
      }

      chars.addAll(buffer);
      input.skip(buffer.size());
    }
  }

  class ParseErrorCatcher: public kj::ExceptionCallback {
  public:
    ParseErrorCatcher(kj::ProcessContext& context): context(context) {}
    ~ParseErrorCatcher() noexcept(false) {
      if (!unwindDetector.isUnwinding()) {
        KJ_IF_MAYBE(e, exception) {
          context.error(kj::str(
              "*** ERROR CONVERTING PREVIOUS MESSAGE ***\n"
              "The following error occurred while converting the message above.\n"
              "This probably means the input data is invalid/corrupted.\n",
              "Exception description: ", e->getDescription(), "\n"
              "Code location: ", e->getFile(), ":", e->getLine(), "\n"
              "*** END ERROR ***"));
        }
      }
    }

    void onRecoverableException(kj::Exception&& e) {
      // Only capture the first exception, on the assumption that later exceptions are probably
      // just cascading problems.
      if (exception == nullptr) {
        exception = kj::mv(e);
      }
    }

  private:
    kj::ProcessContext& context;
    kj::Maybe<kj::Exception> exception;
    kj::UnwindDetector unwindDetector;
  };

  void readOneAndConvert(kj::BufferedInputStreamWrapper& input, kj::OutputStream& output) {
    // Since this is a debug tool, lift the usual security limits.  Worse case is the process
    // crashes or has to be killed.
    ReaderOptions options;
    options.nestingLimit = kj::maxValue;
    options.traversalLimitInWords = kj::maxValue;

    ParseErrorCatcher parseErrorCatcher(context);

    switch (convertFrom) {
      case Format::BINARY: {
        capnp::InputStreamMessageReader message(input, options);
        return writeConversion(message.getRoot<AnyStruct>(), output);
      }
      case Format::PACKED: {
        capnp::PackedMessageReader message(input, options);
        return writeConversion(message.getRoot<AnyStruct>(), output);
      }
991 992
      case Format::FLAT:
      case Format::CANONICAL: {
993 994 995 996 997 998 999 1000 1001 1002 1003
        auto allBytes = readAll(input);

        // Technically we don't know if the bytes are aligned so we'd better copy them to a new
        // array. Note that if we have a non-whole number of words we chop off the straggler
        // bytes. This is fine because if those bytes are actually part of the message we will
        // hit an error later and if they are not then who cares?
        auto words = kj::heapArray<word>(allBytes.size() / sizeof(word));
        memcpy(words.begin(), allBytes.begin(), words.size() * sizeof(word));

        kj::ArrayPtr<const word> segments[1] = { words };
        SegmentArrayMessageReader message(segments, options);
1004 1005 1006
        if (convertFrom == Format::CANONICAL) {
          KJ_REQUIRE(message.isCanonical());
        }
1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
        return writeConversion(message.getRoot<AnyStruct>(), output);
      }
      case Format::FLAT_PACKED: {
        auto allBytes = readAll(input);

        auto words = kj::heapArray<word>(computeUnpackedSizeInWords(allBytes));
        kj::ArrayInputStream input(allBytes);
        capnp::_::PackedInputStream unpacker(input);
        unpacker.read(words.asBytes().begin(), words.asBytes().size());
        word dummy;
        KJ_ASSERT(unpacker.tryRead(&dummy, sizeof(dummy), sizeof(dummy)) == 0);

        kj::ArrayPtr<const word> segments[1] = { words };
        SegmentArrayMessageReader message(segments, options);
        return writeConversion(message.getRoot<AnyStruct>(), output);
      }
      case Format::TEXT: {
        auto text = readOneText(input);
        MallocMessageBuilder message;
        TextCodec codec;
        codec.setPrettyPrint(pretty);
        auto root = message.initRoot<DynamicStruct>(rootType);
        codec.decode(text, root);
        return writeConversion(root.asReader(), output);
      }
      case Format::JSON: {
        auto text = readOneJson(input);
        MallocMessageBuilder message;
        JsonCodec codec;
        codec.setPrettyPrint(pretty);
        auto root = message.initRoot<DynamicStruct>(rootType);
        codec.decode(text, root);
        return writeConversion(root.asReader(), output);
      }
    }

    KJ_UNREACHABLE;
  }

  void writeConversion(AnyStruct::Reader reader, kj::OutputStream& output) {
    switch (convertTo) {
      case Format::BINARY: {
        MallocMessageBuilder message(
            segmentSize == 0 ? SUGGESTED_FIRST_SEGMENT_WORDS : segmentSize,
            segmentSize == 0 ? SUGGESTED_ALLOCATION_STRATEGY : AllocationStrategy::FIXED_SIZE);
        message.setRoot(reader);
        capnp::writeMessage(output, message);
        return;
      }
      case Format::PACKED: {
        MallocMessageBuilder message(
            segmentSize == 0 ? SUGGESTED_FIRST_SEGMENT_WORDS : segmentSize,
            segmentSize == 0 ? SUGGESTED_ALLOCATION_STRATEGY : AllocationStrategy::FIXED_SIZE);
        message.setRoot(reader);
        capnp::writePackedMessage(output, message);
        return;
      }
      case Format::FLAT: {
        auto words = kj::heapArray<word>(reader.totalSize().wordCount + 1);
        memset(words.begin(), 0, words.asBytes().size());
        copyToUnchecked(reader, words);
        output.write(words.begin(), words.asBytes().size());
        return;
      }
      case Format::FLAT_PACKED: {
        auto words = kj::heapArray<word>(reader.totalSize().wordCount + 1);
        memset(words.begin(), 0, words.asBytes().size());
        copyToUnchecked(reader, words);
        kj::BufferedOutputStreamWrapper buffered(output);
        capnp::_::PackedOutputStream packed(buffered);
        packed.write(words.begin(), words.asBytes().size());
        return;
      }
1080 1081 1082 1083 1084
      case Format::CANONICAL: {
        auto words = reader.canonicalize();
        output.write(words.begin(), words.asBytes().size());
        return;
      }
1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
      case Format::TEXT: {
        TextCodec codec;
        codec.setPrettyPrint(pretty);
        auto text = codec.encode(reader.as<DynamicStruct>(rootType));
        output.write({text.asBytes(), kj::StringPtr("\n").asBytes()});
        return;
      }
      case Format::JSON: {
        JsonCodec codec;
        codec.setPrettyPrint(pretty);
        auto text = codec.encode(reader.as<DynamicStruct>(rootType));
        output.write({text.asBytes(), kj::StringPtr("\n").asBytes()});
        return;
      }
    }

    KJ_UNREACHABLE;
  }

public:

1106 1107 1108
  // =====================================================================================
  // "decode" command

1109 1110 1111 1112 1113 1114
  kj::MainBuilder::Validity codeBinary() {
    if (packed) return "cannot be used with --packed";
    if (flat) return "cannot be used with --flat";
    binary = true;
    return true;
  }
1115
  kj::MainBuilder::Validity codeFlat() {
1116
    if (binary) return "cannot be used with --binary";
1117 1118 1119 1120
    flat = true;
    return true;
  }
  kj::MainBuilder::Validity codePacked() {
1121
    if (binary) return "cannot be used with --binary";
1122 1123 1124 1125 1126 1127 1128
    packed = true;
    return true;
  }
  kj::MainBuilder::Validity printShort() {
    pretty = false;
    return true;
  }
1129 1130 1131 1132
  kj::MainBuilder::Validity setQuiet() {
    quiet = true;
    return true;
  }
1133 1134 1135 1136 1137 1138 1139 1140 1141
  kj::MainBuilder::Validity setSegmentSize(kj::StringPtr size) {
    if (flat) return "cannot be used with --flat";
    char* end;
    segmentSize = strtol(size.cStr(), &end, 0);
    if (size.size() == 0 || *end != '\0') {
      return "not an integer";
    }
    return true;
  }
1142 1143

  kj::MainBuilder::Validity setRootType(kj::StringPtr type) {
Kenton Varda's avatar
Kenton Varda committed
1144
    KJ_ASSERT(sourceFiles.size() == 1);
1145

1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159
    KJ_IF_MAYBE(schema, resolveName(sourceFiles[0].id, type)) {
      if (schema->getProto().which() != schema::Node::STRUCT) {
        return "not a struct type";
      }
      rootType = schema->asStruct();
      return true;
    } else {
      return "no such type";
    }
  }

private:
  kj::Maybe<Schema> resolveName(uint64_t scopeId, kj::StringPtr name) {
    while (name.size() > 0) {
1160 1161
      kj::String temp;
      kj::StringPtr part;
1162 1163
      KJ_IF_MAYBE(dotpos, name.findFirst('.')) {
        temp = kj::heapString(name.slice(0, *dotpos));
1164
        part = temp;
1165
        name = name.slice(*dotpos + 1);
1166
      } else {
1167 1168
        part = name;
        name = nullptr;
1169 1170
      }

1171 1172
      KJ_IF_MAYBE(childId, compiler->lookup(scopeId, part)) {
        scopeId = *childId;
1173
      } else {
1174
        return nullptr;
1175 1176
      }
    }
1177
    return compiler->getLoader().get(scopeId);
1178 1179
  }

1180
public:
1181
  kj::MainBuilder::Validity decode() {
1182 1183 1184
    convertTo = Format::TEXT;
    convertFrom = formatFromDeprecatedFlags(Format::BINARY);
    return convert();
1185 1186 1187
  }

private:
1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
  enum Plausibility {
    IMPOSSIBLE,
    IMPLAUSIBLE,
    WRONG_TYPE,
    PLAUSIBLE
  };

  bool plausibleOrWrongType(Plausibility p) {
    return p == PLAUSIBLE || p == WRONG_TYPE;
  }

1199
  Plausibility isPlausiblyFlat(kj::ArrayPtr<const byte> prefix, uint segmentCount = 1) {
1200 1201 1202 1203 1204
    if (prefix.size() < 8) {
      // Not enough prefix to say.
      return PLAUSIBLE;
    }

1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215
    if ((prefix[0] & 3) == 2) {
      // Far pointer.  Verify the segment ID.
      uint32_t segmentId = prefix[4] | (prefix[5] << 8)
                         | (prefix[6] << 16) | (prefix[7] << 24);
      if (segmentId == 0 || segmentId >= segmentCount) {
        return IMPOSSIBLE;
      } else {
        return PLAUSIBLE;
      }
    }

1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266
    if ((prefix[0] & 3) != 0) {
      // Not a struct pointer.
      return IMPOSSIBLE;
    }
    if ((prefix[3] & 0x80) != 0) {
      // Offset is negative (invalid).
      return IMPOSSIBLE;
    }
    if ((prefix[3] & 0xe0) != 0) {
      // Offset is over a gigabyte (implausible).
      return IMPLAUSIBLE;
    }

    uint data = prefix[4] | (prefix[5] << 8);
    uint pointers = prefix[6] | (prefix[7] << 8);

    if (data + pointers > 2048) {
      // Root struct is huge (over 16 KiB).
      return IMPLAUSIBLE;
    }

    auto structSchema = rootType.getProto().getStruct();
    if ((data < structSchema.getDataWordCount() && pointers > structSchema.getPointerCount()) ||
        (data > structSchema.getDataWordCount() && pointers < structSchema.getPointerCount())) {
      // Struct is neither older nor newer than the schema.
      return WRONG_TYPE;
    }

    if (data > structSchema.getDataWordCount() &&
        data - structSchema.getDataWordCount() > 128) {
      // Data section appears to have grown by 1k (128 words).  This seems implausible.
      return WRONG_TYPE;
    }
    if (pointers > structSchema.getPointerCount() &&
        pointers - structSchema.getPointerCount() > 128) {
      // Pointer section appears to have grown by 1k (128 words).  This seems implausible.
      return WRONG_TYPE;
    }

    return PLAUSIBLE;
  }

  Plausibility isPlausiblyBinary(kj::ArrayPtr<const byte> prefix) {
    if (prefix.size() < 8) {
      // Not enough prefix to say.
      return PLAUSIBLE;
    }

    uint32_t segmentCount = prefix[0] | (prefix[1] << 8)
                          | (prefix[2] << 16) | (prefix[3] << 24);

1267 1268 1269
    // Actually, the bytes store segmentCount - 1.
    ++segmentCount;

1270 1271 1272 1273 1274 1275 1276 1277 1278
    if (segmentCount > 65536) {
      // While technically possible, this is so implausible that we should mark it impossible.
      // This helps to make sure we fail fast on packed input.
      return IMPOSSIBLE;
    } else if (segmentCount > 256) {
      // Implausible segment count.
      return IMPLAUSIBLE;
    }

1279 1280
    uint32_t segment0Size = prefix[4] | (prefix[5] << 8)
                          | (prefix[6] << 16) | (prefix[7] << 24);
1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297

    if (segment0Size > (1 << 27)) {
      // Segment larger than 1G seems implausible.
      return IMPLAUSIBLE;
    }

    uint32_t segment0Offset = 4 + segmentCount * 4;
    if (segment0Offset % 8 != 0) {
      segment0Offset += 4;
    }
    KJ_ASSERT(segment0Offset % 8 == 0);

    if (prefix.size() < segment0Offset + 8) {
      // Segment 0 is past our prefix, so we can't check it.
      return PLAUSIBLE;
    }

1298
    return isPlausiblyFlat(prefix.slice(segment0Offset, prefix.size()), segmentCount);
1299 1300
  }

1301 1302
  Plausibility isPlausiblyPacked(kj::ArrayPtr<const byte> prefix,
      kj::Function<Plausibility(kj::ArrayPtr<const byte>)> checkUnpacked) {
1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340
    kj::Vector<byte> unpacked;

    // Try to unpack a prefix so that we can check it.
    const byte* pos = prefix.begin();
    const byte* end = prefix.end();
    if (end - pos > 1024) {
      // Don't bother unpacking more than 1k.
      end = pos + 1024;
    }
    while (pos < end) {
      byte tag = *pos++;
      for (uint i = 0; i < 8 && pos < end; i++) {
        if (tag & (1 << i)) {
          byte b = *pos++;
          if (b == 0) {
            // A zero byte should have been deflated away.
            return IMPOSSIBLE;
          }
          unpacked.add(b);
        } else {
          unpacked.add(0);
        }
      }

      if (pos == end) {
        break;
      }

      if (tag == 0) {
        uint count = *pos++ * 8;
        unpacked.addAll(kj::repeat(byte(0), count));
      } else if (tag == 0xff) {
        uint count = *pos++ * 8;
        size_t available = end - pos;
        uint n = kj::min(count, available);
        unpacked.addAll(pos, pos + n);
        pos += n;
      }
1341
    }
1342

1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353
    return checkUnpacked(unpacked);
  }

  Plausibility isPlausiblyPacked(kj::ArrayPtr<const byte> prefix) {
    return isPlausiblyPacked(prefix, KJ_BIND_METHOD(*this, isPlausiblyBinary));
  }

  Plausibility isPlausiblyPackedFlat(kj::ArrayPtr<const byte> prefix) {
    return isPlausiblyPacked(prefix, [this](kj::ArrayPtr<const byte> prefix) {
      return isPlausiblyFlat(prefix);
    });
1354 1355
  }

1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375
  Plausibility isPlausiblyText(kj::ArrayPtr<const byte> prefix) {
    enum { PREAMBLE, COMMENT, BODY } state;

    for (char c: prefix.asChars()) {
      switch (state) {
        case PREAMBLE:
          // Before opening parenthesis.
          switch (c) {
            case '(': state = BODY; continue;
            case '#': state = COMMENT; continue;
            case ' ':
            case '\n':
            case '\r':
            case '\t':
            case '\v':
              // whitespace
              break;
            default:
              // Not whitespace, not comment, not open parenthesis. Impossible!
              return IMPOSSIBLE;
1376
          }
1377 1378 1379 1380 1381
          break;
        case COMMENT:
          switch (c) {
            case '\n': state = PREAMBLE; continue;
            default: break;
1382 1383
          }
          break;
1384 1385 1386 1387 1388 1389 1390 1391
        case BODY:
          switch (c) {
            case '\"':
            case '\'':
              // String literal. Let's stop here before things get complicated.
              return PLAUSIBLE;
            default:
              break;
1392 1393 1394
          }
          break;
      }
1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425

      if ((c >= 0 && c < ' ' && c != '\n' && c != '\r' && c != '\t' && c != '\v') || c == 0x7f) {
        // Unprintable character.
        return IMPOSSIBLE;
      }
    }

    return PLAUSIBLE;
  }

  Plausibility isPlausiblyJson(kj::ArrayPtr<const byte> prefix) {
    enum { PREAMBLE, COMMENT, BODY } state;

    for (char c: prefix.asChars()) {
      switch (state) {
        case PREAMBLE:
          // Before opening parenthesis.
          switch (c) {
            case '{': state = BODY; continue;
            case '#': state = COMMENT; continue;
            case '/': state = COMMENT; continue;
            case ' ':
            case '\n':
            case '\r':
            case '\t':
            case '\v':
              // whitespace
              break;
            default:
              // Not whitespace, not comment, not open brace. Impossible!
              return IMPOSSIBLE;
1426 1427
          }
          break;
1428 1429 1430 1431
        case COMMENT:
          switch (c) {
            case '\n': state = PREAMBLE; continue;
            default: break;
1432 1433
          }
          break;
1434 1435 1436 1437 1438 1439 1440
        case BODY:
          switch (c) {
            case '\"':
              // String literal. Let's stop here before things get complicated.
              return PLAUSIBLE;
            default:
              break;
1441 1442
          }
          break;
1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459
      }

      if ((c > 0 && c < ' ' && c != '\n' && c != '\r' && c != '\t' && c != '\v') || c == 0x7f) {
        // Unprintable character.
        return IMPOSSIBLE;
      }
    }

    return PLAUSIBLE;
  }

  Plausibility isPlausibly(Format format, kj::ArrayPtr<const byte> prefix) {
    switch (format) {
      case Format::BINARY     : return isPlausiblyBinary    (prefix);
      case Format::PACKED     : return isPlausiblyPacked    (prefix);
      case Format::FLAT       : return isPlausiblyFlat      (prefix);
      case Format::FLAT_PACKED: return isPlausiblyPackedFlat(prefix);
1460
      case Format::CANONICAL  : return isPlausiblyFlat      (prefix);
1461 1462 1463
      case Format::TEXT       : return isPlausiblyText      (prefix);
      case Format::JSON       : return isPlausiblyJson      (prefix);
    }
Kenton Varda's avatar
Kenton Varda committed
1464
    KJ_UNREACHABLE;
1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521
  }

  kj::Maybe<Format> guessFormat(kj::ArrayPtr<const byte> prefix) {
    Format candidates[] = {
      Format::BINARY,
      Format::TEXT,
      Format::PACKED,
      Format::JSON,
      Format::FLAT,
      Format::FLAT_PACKED
    };

    for (Format candidate: candidates) {
      if (plausibleOrWrongType(isPlausibly(candidate, prefix))) {
        return candidate;
      }
    }

    return nullptr;
  }

  kj::MainBuilder::Validity checkPlausibility(Format format, kj::ArrayPtr<const byte> prefix) {
    switch (isPlausibly(format, prefix)) {
      case PLAUSIBLE:
        return true;

      case IMPOSSIBLE:
        KJ_IF_MAYBE(guess, guessFormat(prefix)) {
          return kj::str(
             "The input is not in \"", toString(format), "\" format. It looks like it is in \"",
             toString(*guess), "\" format. Try that instead.");
        } else {
          return kj::str(
             "The input is not in \"", toString(format), "\" format.");
        }

      case IMPLAUSIBLE:
        KJ_IF_MAYBE(guess, guessFormat(prefix)) {
          context.warning(kj::str(
              "*** WARNING ***\n"
              "The input data does not appear to be in \"", toString(format), "\" format. It\n"
              "looks like it may be in \"", toString(*guess), "\" format. I'll try to parse\n"
              "it in \"", toString(format), "\" format as you requested, but if it doesn't work,\n"
              "try \"", toString(format), "\" instead. Use --quiet to suppress this warning.\n"
              "*** END WARNING ***\n"));
        } else {
          context.warning(kj::str(
              "*** WARNING ***\n"
              "The input data does not appear to be in \"", toString(format), "\" format, nor\n"
              "in any other known format. I'll try to parse it in \"", toString(format), "\"\n"
              "format anyway, as you requested. Use --quiet to suppress this warning.\n"
              "*** END WARNING ***\n"));
        }
        return true;

      case WRONG_TYPE:
        if (format == Format::FLAT && plausibleOrWrongType(isPlausiblyBinary(prefix))) {
1522 1523
          context.warning(
              "*** WARNING ***\n"
1524
              "The input data does not appear to match the schema that you specified. I'll try\n"
1525
              "to parse it anyway, but if it doesn't look right, please verify that you\n"
1526 1527 1528 1529
              "have the right schema. This could also be because the input is not in \"flat\"\n"
              "format; indeed, it looks like this input may be in regular binary format,\n"
              "so you might want to try \"binary\" instead.  Use --quiet to suppress this\n"
              "warning.\n"
1530
              "*** END WARNING ***\n");
1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542
        } else if (format == Format::FLAT_PACKED &&
                   plausibleOrWrongType(isPlausiblyPacked(prefix))) {
          context.warning(
              "*** WARNING ***\n"
              "The input data does not appear to match the schema that you specified. I'll try\n"
              "to parse it anyway, but if it doesn't look right, please verify that you\n"
              "have the right schema. This could also be because the input is not in \"flat-packed\"\n"
              "format; indeed, it looks like this input may be in regular packed format,\n"
              "so you might want to try \"packed\" instead.  Use --quiet to suppress this\n"
              "warning.\n"
              "*** END WARNING ***\n");
        } else {
1543 1544 1545 1546 1547 1548
          context.warning(
              "*** WARNING ***\n"
              "The input data does not appear to be the type that you specified.  I'll try\n"
              "to parse it anyway, but if it doesn't look right, please verify that you\n"
              "have the right type.  Use --quiet to suppress this warning.\n"
              "*** END WARNING ***\n");
1549 1550
        }
        return true;
1551 1552
    }

1553
    KJ_UNREACHABLE;
1554 1555
  }

1556
public:
1557
  // -----------------------------------------------------------------
1558 1559

  kj::MainBuilder::Validity encode() {
1560 1561 1562 1563
    convertFrom = Format::TEXT;
    convertTo = formatFromDeprecatedFlags(Format::BINARY);
    return convert();
  }
1564

1565 1566 1567 1568 1569 1570
  kj::MainBuilder::Validity setEvalOutputFormat(kj::StringPtr format) {
    KJ_IF_MAYBE(f, parseFormatName(format)) {
      convertTo = *f;
      return true;
    } else {
      return kj::str("unknown format: ", format);
1571
    }
1572 1573
  }

1574
  kj::MainBuilder::Validity evalConst(kj::StringPtr name) {
1575 1576
    convertTo = formatFromDeprecatedFlags(convertTo);

1577 1578
    KJ_ASSERT(sourceFiles.size() == 1);

1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620
    auto parser = kj::parse::sequence(
        kj::parse::many(
            kj::parse::sequence(
                kj::parse::identifier,
                kj::parse::many(
                    kj::parse::sequence(
                        kj::parse::exactChar<'['>(),
                        kj::parse::integer,
                        kj::parse::exactChar<']'>())),
                kj::parse::oneOf(
                    kj::parse::endOfInput,
                    kj::parse::sequence(
                        kj::parse::exactChar<'.'>(),
                        kj::parse::notLookingAt(kj::parse::endOfInput))))),
        kj::parse::endOfInput);

    kj::parse::IteratorInput<char, const char*> input(name.begin(), name.end());

    kj::Array<kj::Tuple<kj::String, kj::Array<uint64_t>>> nameParts;
    KJ_IF_MAYBE(p, parser(input)) {
      nameParts = kj::mv(*p);
    } else {
      return "invalid syntax";
    }

    auto pos = nameParts.begin();

    // Traverse the path to find a schema.
    uint64_t scopeId = sourceFiles[0].id;
    bool stoppedAtSubscript = false;
    for (; pos != nameParts.end(); ++pos) {
      kj::StringPtr part = kj::get<0>(*pos);

      KJ_IF_MAYBE(childId, compiler->lookup(scopeId, part)) {
        scopeId = *childId;

        if (kj::get<1>(*pos).size() > 0) {
          stoppedAtSubscript = true;
          break;
        }
      } else {
        break;
1621
      }
1622 1623 1624 1625 1626 1627 1628
    }
    Schema schema = compiler->getLoader().get(scopeId);

    // Evaluate this schema to a DynamicValue.
    DynamicValue::Reader value;
    word zeroWord[1];
    memset(&zeroWord, 0, sizeof(zeroWord));
1629
    kj::ArrayPtr<const word> segments[1] = { kj::arrayPtr(zeroWord, 1) };
1630 1631 1632 1633 1634 1635 1636 1637 1638 1639
    SegmentArrayMessageReader emptyMessage(segments);
    switch (schema.getProto().which()) {
      case schema::Node::CONST:
        value = schema.asConst();
        break;

      case schema::Node::STRUCT:
        if (pos == nameParts.end()) {
          return kj::str("'", schema.getShortDisplayName(), "' cannot be evaluated.");
        }
1640

1641 1642 1643
        // Use the struct's default value.
        value = emptyMessage.getRoot<DynamicStruct>(schema.asStruct());
        break;
1644

1645 1646 1647 1648 1649 1650 1651
      default:
        if (stoppedAtSubscript) {
          return kj::str("'", schema.getShortDisplayName(), "' is not a list.");
        } else if (pos != nameParts.end()) {
          return kj::str("'", kj::get<0>(*pos), "' is not defined.");
        } else {
          return kj::str("'", schema.getShortDisplayName(), "' cannot be evaluated.");
1652
        }
1653
    }
1654

1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682
    // Traverse the rest of the path as struct fields.
    for (; pos != nameParts.end(); ++pos) {
      kj::StringPtr partName = kj::get<0>(*pos);

      if (!stoppedAtSubscript) {
        if (value.getType() == DynamicValue::STRUCT) {
          auto structValue = value.as<DynamicStruct>();
          KJ_IF_MAYBE(field, structValue.getSchema().findFieldByName(partName)) {
            value = structValue.get(*field);
          } else {
            return kj::str("'", kj::get<0>(pos[-1]), "' has no member '", partName, "'.");
          }
        } else {
          return kj::str("'", kj::get<0>(pos[-1]), "' is not a struct.");
        }
      }

      auto& subscripts = kj::get<1>(*pos);
      for (uint i = 0; i < subscripts.size(); i++) {
        uint64_t subscript = subscripts[i];
        if (value.getType() == DynamicValue::LIST) {
          auto listValue = value.as<DynamicList>();
          if (subscript < listValue.size()) {
            value = listValue[subscript];
          } else {
            return kj::str("'", partName, "[", kj::strArray(subscripts.slice(0, i + 1), "]["),
                           "]' is out-of-bounds.");
          }
1683
        } else {
1684 1685 1686 1687 1688 1689
          if (i > 0) {
            return kj::str("'", partName, "[", kj::strArray(subscripts.slice(0, i), "]["),
                           "]' is not a list.");
          } else {
            return kj::str("'", partName, "' is not a list.");
          }
1690 1691
        }
      }
1692 1693 1694 1695 1696

      stoppedAtSubscript = false;
    }

    // OK, we have a value.  Print it.
1697
    if (convertTo != Format::TEXT) {
1698 1699 1700 1701
      if (value.getType() != DynamicValue::STRUCT) {
        return "not a struct; binary output is only available on structs";
      }

1702 1703 1704 1705
      auto structValue = value.as<DynamicStruct>();
      rootType = structValue.getSchema();
      kj::FdOutputStream output(STDOUT_FILENO);
      writeConversion(structValue, output);
1706
      context.exit();
1707
    } else {
1708 1709 1710 1711 1712 1713 1714
      if (pretty && value.getType() == DynamicValue::STRUCT) {
        context.exitInfo(prettyPrint(value.as<DynamicStruct>()).flatten());
      } else if (pretty && value.getType() == DynamicValue::LIST) {
        context.exitInfo(prettyPrint(value.as<DynamicList>()).flatten());
      } else {
        context.exitInfo(kj::str(value));
      }
1715
    }
1716

Kenton Varda's avatar
Kenton Varda committed
1717
    KJ_CLANG_KNOWS_THIS_IS_UNREACHABLE_BUT_GCC_DOESNT;
1718 1719
  }

1720 1721 1722
public:
  // =====================================================================================

1723
  void addError(const kj::ReadableDirectory& directory, kj::PathPtr path,
1724
                SourcePos start, SourcePos end,
1725
                kj::StringPtr message) override {
1726 1727
    auto file = getDisplayName(directory, path);

1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742
    kj::String wholeMessage;
    if (end.line == start.line) {
      if (end.column == start.column) {
        wholeMessage = kj::str(file, ":", start.line + 1, ":", start.column + 1,
                               ": error: ", message, "\n");
      } else {
        wholeMessage = kj::str(file, ":", start.line + 1, ":", start.column + 1,
                               "-", end.column + 1, ": error: ", message, "\n");
      }
    } else {
      // The error spans multiple lines, so just report it on the first such line.
      wholeMessage = kj::str(file, ":", start.line + 1, ": error: ", message, "\n");
    }

    context.error(wholeMessage);
1743
    hadErrors_ = true;
1744 1745
  }

1746 1747
  bool hadErrors() override {
    return hadErrors_;
1748 1749 1750 1751
  }

private:
  kj::ProcessContext& context;
1752
  kj::Own<kj::Filesystem> disk;
1753
  ModuleLoader loader;
1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764
  kj::SpaceFor<Compiler> compilerSpace;
  bool compilerConstructed = false;
  kj::Own<Compiler> compiler;

  Compiler::AnnotationFlag annotationFlag = Compiler::COMPILE_ANNOTATIONS;

  uint compileEagerness = Compiler::NODE | Compiler::CHILDREN |
                          Compiler::DEPENDENCIES | Compiler::DEPENDENCY_PARENTS;
  // By default we compile each explicitly listed schema in full, plus first-level dependencies
  // of those schemas, plus the parent nodes of any dependencies.  This is what most code generators
  // require to function.
1765

1766 1767
  struct SourceDirectory {
    kj::Path path;
1768
    kj::Own<const kj::ReadableDirectory> dir;
1769 1770 1771 1772 1773 1774 1775 1776
    bool isSourcePrefix;
  };

  std::map<kj::PathPtr, SourceDirectory> sourceDirectories;
  // For each import path and source prefix, tracks the directory object we opened for it.
  //
  // Use via getSourceDirectory().

1777
  std::map<const kj::ReadableDirectory*, kj::String> dirPrefixes;
1778 1779 1780 1781 1782 1783
  // For each open directory object, maps to a path prefix to add when displaying this path in
  // error messages. This keeps track of the original directory name as given by the user, before
  // canonicalization.
  //
  // Use via getDisplayName().

1784 1785
  bool addStandardImportPaths = true;

1786 1787 1788 1789
  Format convertFrom = Format::BINARY;
  Format convertTo = Format::BINARY;
  // For the "convert" command.

1790
  bool binary = false;
1791 1792 1793
  bool flat = false;
  bool packed = false;
  bool pretty = true;
1794
  bool quiet = false;
1795
  uint segmentSize = 0;
1796
  StructSchema rootType;
1797
  // For the "decode" and "encode" commands.
1798

Kenton Varda's avatar
Kenton Varda committed
1799 1800 1801
  struct SourceFile {
    uint64_t id;
    kj::StringPtr name;
1802
    Module* module;
Kenton Varda's avatar
Kenton Varda committed
1803 1804 1805
  };

  kj::Vector<SourceFile> sourceFiles;
1806 1807 1808

  struct OutputDirective {
    kj::ArrayPtr<const char> name;
1809 1810 1811 1812
    kj::Maybe<kj::Path> dir;

    KJ_DISALLOW_COPY(OutputDirective);
    OutputDirective(OutputDirective&&) = default;
1813 1814
    OutputDirective(kj::ArrayPtr<const char> name, kj::Maybe<kj::Path> dir)
        : name(name), dir(kj::mv(dir)) {}
1815 1816 1817
  };
  kj::Vector<OutputDirective> outputs;

1818
  bool hadErrors_ = false;
1819

1820
  kj::Maybe<const kj::ReadableDirectory&> getSourceDirectory(
1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843
      kj::StringPtr pathStr, bool isSourcePrefix) {
    auto cwd = disk->getCurrentPath();
    auto path = cwd.evalNative(pathStr);

    if (path.size() == 0) return disk->getRoot();

    auto iter = sourceDirectories.find(path);
    if (iter != sourceDirectories.end()) {
      iter->second.isSourcePrefix = iter->second.isSourcePrefix || isSourcePrefix;
      return *iter->second.dir;
    }

    if (path == cwd) {
      // Slight hack if the working directory is explicitly specified:
      // - We want to avoid opening a new copy of the working directory, as tryOpenSubdir() would
      //   do.
      // - If isSourcePrefix is true, we need to add it to sourceDirectories to track that.
      //   Otherwise we don't need to add it at all.
      // - We do not need to add it to dirPrefixes since the cwd is already handled in
      //   getDisplayName().
      auto& result = disk->getCurrent();
      if (isSourcePrefix) {
        kj::PathPtr key = path;
1844
        kj::Own<const kj::ReadableDirectory> fakeOwn(&result, kj::NullDisposer::instance);
1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869
        KJ_ASSERT(sourceDirectories.insert(std::make_pair(key,
            SourceDirectory { kj::mv(path), kj::mv(fakeOwn), isSourcePrefix })).second);
      }
      return result;
    }

    KJ_IF_MAYBE(dir, disk->getRoot().tryOpenSubdir(path)) {
      auto& result = *dir->get();
      kj::PathPtr key = path;
      KJ_ASSERT(sourceDirectories.insert(std::make_pair(key,
          SourceDirectory { kj::mv(path), kj::mv(*dir), isSourcePrefix })).second);
#if _WIN32
      kj::String prefix = pathStr.endsWith("/") || pathStr.endsWith("\\")
                        ? kj::str(pathStr) : kj::str(pathStr, '\\');
#else
      kj::String prefix = pathStr.endsWith("/") ? kj::str(pathStr) : kj::str(pathStr, '/');
#endif
      KJ_ASSERT(dirPrefixes.insert(std::make_pair(&result, kj::mv(prefix))).second);
      return result;
    } else {
      return nullptr;
    }
  }

  struct DirPathPair {
1870
    const kj::ReadableDirectory& dir;
1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912
    kj::Path path;
  };

  DirPathPair interpretSourceFile(kj::StringPtr pathStr) {
    auto cwd = disk->getCurrentPath();
    auto path = cwd.evalNative(pathStr);

    KJ_REQUIRE(path.size() > 0);
    for (size_t i = path.size() - 1; i > 0; i--) {
      auto prefix = path.slice(0, i);
      auto remainder = path.slice(i, path.size());

      auto iter = sourceDirectories.find(prefix);
      if (iter != sourceDirectories.end() && iter->second.isSourcePrefix) {
        return { *iter->second.dir, remainder.clone() };
      }
    }

    // No source prefix matched. Fall back to heuristic: try stripping the current directory,
    // otherwise don't strip anything.
    if (path.startsWith(cwd)) {
      return { disk->getCurrent(), path.slice(cwd.size(), path.size()).clone() };
    } else {
      // Hmm, no src-prefix matched and the file isn't even in the current directory. This might
      // be OK if we aren't generating any output anyway, but otherwise the results will almost
      // certainly not be what the user wanted. Let's print a warning, unless the output directives
      // are ones which we know do not produce output files. This is a hack.
      for (auto& output: outputs) {
        auto name = kj::str(output.name);
        if (name != "-" && name != "capnp") {
          context.warning(kj::str(pathStr,
              ": File is not in the current directory and does not match any prefix defined with "
              "--src-prefix. Please pass an appropriate --src-prefix so I can figure out where to "
              "write the output for this file."));
          break;
        }
      }

      return { disk->getRoot(), kj::mv(path) };
    }
  }

1913
  kj::String getDisplayName(const kj::ReadableDirectory& dir, kj::PathPtr path) {
1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924
    auto iter = dirPrefixes.find(&dir);
    if (iter != dirPrefixes.end()) {
      return kj::str(iter->second, path.toNativeString());
    } else if (&dir == &disk->getRoot()) {
      return path.toNativeString(true);
    } else if (&dir == &disk->getCurrent()) {
      return path.toNativeString(false);
    } else {
      KJ_FAIL_ASSERT("unrecognized directory");
    }
  }
1925 1926 1927 1928 1929 1930
};

}  // namespace compiler
}  // namespace capnp

KJ_MAIN(capnp::compiler::CompilerMain);