capnp.c++ 68.1 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
#include <kj/map.h>
50

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

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

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

70 71 72
namespace capnp {
namespace compiler {

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

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

  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.")
97 98
             .addSubCommand("convert", KJ_BIND_METHOD(*this, getConvertMain),
                            "Convert messages between binary, text, JSON, etc.")
99
             .addSubCommand("decode", KJ_BIND_METHOD(*this, getDecodeMain),
100
                            "DEPRECATED (use `convert`)")
101
             .addSubCommand("encode", KJ_BIND_METHOD(*this, getEncodeMain),
102
                            "DEPRECATED (use `convert`)")
103 104
             .addSubCommand("eval", KJ_BIND_METHOD(*this, getEvalMain),
                            "Evaluate a const from a schema file.");
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
      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() {
120
    return kj::MainBuilder(context, VERSION_STRING,
121 122 123 124 125
          "Generates a new 64-bit unique ID for use in a Cap'n Proto schema.")
        .callAfterParsing(KJ_BIND_METHOD(*this, generateId))
        .build();
  }

126 127 128 129 130 131 132 133 134 135 136 137 138 139
  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"
140
          "    canonical   canonicalized binary single segment, no segment table\n"
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 166
          "    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();
  }

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

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

    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);
179
    builder.addOption({"flat"}, KJ_BIND_METHOD(*this, codeFlat),
180
                      "Interpret the input as one large single-segment message rather than a "
181
                      "stream in standard serialization format.  (Rarely used.)")
182 183
           .addOption({'p', "packed"}, KJ_BIND_METHOD(*this, codePacked),
                      "Expect the input to be packed using standard Cap'n Proto packing, which "
184 185 186 187
                      "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>.)")
188 189 190
           .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.")
191 192 193 194
           .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).")
195 196 197 198 199 200
           .expectArg("<schema-file>", KJ_BIND_METHOD(*this, addSource))
           .expectArg("<type>", KJ_BIND_METHOD(*this, setRootType))
           .callAfterParsing(KJ_BIND_METHOD(*this, decode));
    return builder.build();
  }

201 202 203 204 205 206 207 208 209 210
  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 "
211
          "message is a parenthesized struct literal, like the format used to specify constants "
212 213 214 215
          "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.",
216

217 218 219 220
          "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);
221
    builder.addOption({"flat"}, KJ_BIND_METHOD(*this, codeFlat),
222 223 224 225
                      "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 "
226 227 228
                      "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.)")
229 230 231 232 233
           .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.")
234 235 236 237 238 239
           .expectArg("<schema-file>", KJ_BIND_METHOD(*this, addSource))
           .expectArg("<type>", KJ_BIND_METHOD(*this, setRootType))
           .callAfterParsing(KJ_BIND_METHOD(*this, encode));
    return builder.build();
  }

240 241 242 243 244 245 246
  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;

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

250
    kj::MainBuilder builder(context, VERSION_STRING,
251 252 253 254 255 256 257 258 259
          "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
260
          "import and variable substitution, this can be a convenient way to write text-format "
261
          "config files which are compiled to binary before deployment.",
262 263 264 265 266

          "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);
267 268 269 270 271
    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")
272
           .addOption({"flat"}, KJ_BIND_METHOD(*this, codeFlat),
273
                      "same as -oflat")
274
           .addOption({'p', "packed"}, KJ_BIND_METHOD(*this, codePacked),
275
                      "same as -opacked")
276
           .addOption({"short"}, KJ_BIND_METHOD(*this, printShort),
277 278 279
                      "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.")
280 281 282 283 284
           .expectArg("<schema-file>", KJ_BIND_METHOD(*this, addSource))
           .expectArg("<name>", KJ_BIND_METHOD(*this, evalConst));
    return builder.build();
  }

285 286 287 288 289 290 291 292 293 294 295 296 297 298
  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 "
299
                             "to use.  If <lang> is a simple word, the compiler searches for a plugin "
300 301
                             "called 'capnpc-<lang>' in $PATH.  If <lang> is a file path "
                             "containing slashes, it is interpreted as the exact plugin "
302 303
                             "executable file name, and $PATH is not searched.  If <lang> is '-', "
                             "the compiler dumps the request to standard output.")
304 305 306 307
           .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"
308
                             "    capnp compile --src-prefix=foo/bar -oc++:corge foo/bar/baz/qux.capnp\n"
309 310 311 312 313 314 315 316 317
                             "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) {
318 319 320 321 322 323
    KJ_IF_MAYBE(dir, getSourceDirectory(path, false)) {
      loader.addImportPath(*dir);
      return true;
    } else {
      return "no such directory";
    }
324 325 326 327 328 329 330 331
  }

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

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

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

353 354 355
      addStandardImportPaths = false;
    }

356 357
    auto dirPathPair = interpretSourceFile(file);
    KJ_IF_MAYBE(module, loader.loadModule(dirPathPair.dir, dirPathPair.path)) {
358 359 360 361 362 363 364 365 366 367 368
      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:
369 370 371 372 373
  // =====================================================================================
  // "id" command

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

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

  kj::MainBuilder::Validity addOutput(kj::StringPtr spec) {
    KJ_IF_MAYBE(split, spec.findFirst(':')) {
      kj::StringPtr dir = spec.slice(*split + 1);
383 384
      auto plugin = spec.slice(0, *split);

385 386 387 388 389 390 391 392
      if (*split == 1 && (dir.startsWith("/") || dir.startsWith("\\"))) {
        // The colon is the second character and is immediately followed by a slash or backslash.
        // So, the user passed something like `-o c:/foo`. Is this a request to run the C plugin
        // and output to `/foo`? Or are we on Windows, and is this a request to run the plugin
        // `c:/foo`?
        KJ_IF_MAYBE(split2, dir.findFirst(':')) {
          // There are two colons. The first ':' was the second char, and was followed by '/' or
          // '\', e.g.:
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
          //     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.

          dir = dir.slice(*split2 + 1);
          plugin = spec.slice(0, *split2 + 2);
417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
#if _WIN32
        } else {
          // The user wrote something like:
          //
          //     capnp compile -o c:/foo/bar
          //
          // What does this mean? It depends on what system we're on. On a Unix system, the above
          // clearly is a request to run the `capnpc-c` plugin (perhaps to output C code) and write
          // to the directory /foo/bar. But on Windows, absolute paths do not start with '/', and
          // the above is actually a request to run the plugin `c:/foo/bar`, outputting to the
          // current directory.

          outputs.add(OutputDirective { spec.asArray(), nullptr });
          return true;
#endif
432 433 434
        }
      }

435 436 437 438
      struct stat stats;
      if (stat(dir.cStr(), &stats) < 0 || !S_ISDIR(stats.st_mode)) {
        return "output location is inaccessible or is not a directory";
      }
439
      outputs.add(OutputDirective { plugin, disk->getCurrentPath().evalNative(dir) });
440 441 442 443 444 445 446 447
    } else {
      outputs.add(OutputDirective { spec.asArray(), nullptr });
    }

    return true;
  }

  kj::MainBuilder::Validity addSourcePrefix(kj::StringPtr prefix) {
448 449
    if (getSourceDirectory(prefix, true) == nullptr) {
      return "no such directory";
450
    } else {
451
      return true;
452 453 454 455 456 457 458 459 460
    }
  }

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

461 462
    // 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
463
    KJ_ASSERT(sourceFiles.size() > 0, "Shouldn't have gotten here without sources.");
464

465 466 467 468 469
    if (outputs.size() == 0) {
      return "no outputs specified";
    }

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

472 473 474 475 476
    auto version = request.getCapnpVersion();
    version.setMajor(CAPNP_VERSION_MAJOR);
    version.setMinor(CAPNP_VERSION_MINOR);
    version.setMicro(CAPNP_VERSION_MICRO);

477
    auto schemas = compiler->getLoader().getAllLoaded();
478 479 480 481 482
    auto nodes = request.initNodes(schemas.size());
    for (size_t i = 0; i < schemas.size(); i++) {
      nodes.setWithCaveats(i, schemas[i].getProto());
    }

483
    request.adoptSourceInfo(compiler->getAllSourceInfo(message.getOrphanage()));
484

Kenton Varda's avatar
Kenton Varda committed
485 486 487 488 489 490 491
    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)));
492 493 494
    }

    for (auto& output: outputs) {
495
      if (kj::str(output.name) == "-") {
496 497 498 499
        writeMessageToFd(STDOUT_FILENO, message);
        continue;
      }

500
      int pipeFds[2];
501
      KJ_SYSCALL(kj::miniposix::pipe(pipeFds));
502 503 504 505

      kj::String exeName;
      bool shouldSearchPath = true;
      for (char c: output.name) {
506 507 508
#if _WIN32
        if (c == '/' || c == '\\') {
#else
509
        if (c == '/') {
510
#endif
511 512 513 514 515 516 517 518 519 520
          shouldSearchPath = false;
          break;
        }
      }
      if (shouldSearchPath) {
        exeName = kj::str("capnpc-", output.name);
      } else {
        exeName = kj::heapString(output.name);
      }

521 522 523 524 525 526 527 528 529 530 531 532
      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
533 534 535 536
      pid_t child;
      KJ_SYSCALL(child = fork());
      if (child == 0) {
        // I am the child!
537

538
        KJ_SYSCALL(close(pipeFds[1]));
539 540
#endif  // _WIN32, else

541 542 543
        KJ_SYSCALL(dup2(pipeFds[0], STDIN_FILENO));
        KJ_SYSCALL(close(pipeFds[0]));

544 545 546 547 548 549 550 551
        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
552 553
        }

554 555 556 557 558 559 560 561 562 563 564
#if _WIN32
        // 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. We do the escaping ourselves by wrapping the name in quotes. We know
        // that exeName itself can't contain quotes (since filenames aren't allowed to contain
        // quotes on Windows), so we don't have to account for those.
        KJ_ASSERT(exeName.findFirst('\"') == nullptr,
            "Windows filenames can't contain quotes", exeName);
        auto escapedExeName = kj::str("\"", exeName, "\"");
#endif

565
        if (shouldSearchPath) {
566
#if _WIN32
567
          child = _spawnlp(_P_NOWAIT, exeName.cStr(), escapedExeName.cStr(), nullptr);
568
#else
569
          execlp(exeName.cStr(), exeName.cStr(), nullptr);
570
#endif
571
        } else {
572 573 574 575
#if _WIN32
          if (!exeName.startsWith("/") && !exeName.startsWith("\\") &&
              !(exeName.size() >= 2 && exeName[1] == ':')) {
#else
576
          if (!exeName.startsWith("/")) {
577
#endif
578 579 580 581
            // The name is relative.  Prefix it with our original working directory path.
            exeName = kj::str(pwd.begin(), "/", exeName);
          }

582
#if _WIN32
583
          child = _spawnl(_P_NOWAIT, exeName.cStr(), escapedExeName.cStr(), nullptr);
584
#else
585
          execl(exeName.cStr(), exeName.cStr(), nullptr);
586
#endif
587 588
        }

589 590 591 592 593 594 595 596 597 598 599 600 601 602 603
#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
604
        }
605 606 607 608 609 610 611 612

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

        // Restore current directory.
        KJ_SYSCALL(chdir(pwd.begin()), pwd.begin());
#else  // _WIN32
613 614 615
      }

      KJ_SYSCALL(close(pipeFds[0]));
616
#endif  // _WIN32, else
617 618 619 620

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

621 622 623 624 625 626 627 628 629 630 631
#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
632 633 634
      int status;
      KJ_SYSCALL(waitpid(child, &status, 0));
      if (WIFSIGNALED(status)) {
635
        context.error(kj::str(output.name, ": plugin failed: ", strsignal(WTERMSIG(status))));
636
      } else if (WIFEXITED(status) && WEXITSTATUS(status) != 0) {
637
        context.error(kj::str(output.name, ": plugin failed: exit code ", WEXITSTATUS(status)));
638
      }
639
#endif  // _WIN32, else
640 641 642 643 644
    }

    return true;
  }

645 646 647 648 649 650 651 652 653
  // =====================================================================================
  // "convert" command

private:
  enum class Format {
    BINARY,
    PACKED,
    FLAT,
    FLAT_PACKED,
654
    CANONICAL,
655 656 657 658 659 660 661 662 663
    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;
664
    if (name == "canonical"  ) return Format::CANONICAL;
665 666 667 668 669 670 671 672 673 674 675 676
    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";
677
      case Format::CANONICAL  : return "canonical";
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
      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);
      }

727 728 729 730 731 732 733
      if (convertFrom == Format::JSON || convertTo == Format::JSON) {
        // We need annotations to process JSON.
        // TODO(someday): Find a way that we can process annotations from json.capnp without
        //   requiring other annotation-only imports like c++.capnp
        annotationFlag = Compiler::COMPILE_ANNOTATIONS;
      }

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 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
      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);
      }
1012 1013
      case Format::FLAT:
      case Format::CANONICAL: {
1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024
        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);
1025 1026 1027
        if (convertFrom == Format::CANONICAL) {
          KJ_REQUIRE(message.isCanonical());
        }
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
        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);
1058
        codec.handleByAnnotation(rootType);
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
        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;
      }
1102 1103 1104 1105 1106
      case Format::CANONICAL: {
        auto words = reader.canonicalize();
        output.write(words.begin(), words.asBytes().size());
        return;
      }
1107 1108 1109 1110 1111 1112 1113 1114 1115 1116
      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);
1117
        codec.handleByAnnotation(rootType);
1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128
        auto text = codec.encode(reader.as<DynamicStruct>(rootType));
        output.write({text.asBytes(), kj::StringPtr("\n").asBytes()});
        return;
      }
    }

    KJ_UNREACHABLE;
  }

public:

1129 1130 1131
  // =====================================================================================
  // "decode" command

1132 1133 1134 1135 1136 1137
  kj::MainBuilder::Validity codeBinary() {
    if (packed) return "cannot be used with --packed";
    if (flat) return "cannot be used with --flat";
    binary = true;
    return true;
  }
1138
  kj::MainBuilder::Validity codeFlat() {
1139
    if (binary) return "cannot be used with --binary";
1140 1141 1142 1143
    flat = true;
    return true;
  }
  kj::MainBuilder::Validity codePacked() {
1144
    if (binary) return "cannot be used with --binary";
1145 1146 1147 1148 1149 1150 1151
    packed = true;
    return true;
  }
  kj::MainBuilder::Validity printShort() {
    pretty = false;
    return true;
  }
1152 1153 1154 1155
  kj::MainBuilder::Validity setQuiet() {
    quiet = true;
    return true;
  }
1156 1157 1158 1159 1160 1161 1162 1163 1164
  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;
  }
1165 1166

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

1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
    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) {
1183 1184
      kj::String temp;
      kj::StringPtr part;
1185 1186
      KJ_IF_MAYBE(dotpos, name.findFirst('.')) {
        temp = kj::heapString(name.slice(0, *dotpos));
1187
        part = temp;
1188
        name = name.slice(*dotpos + 1);
1189
      } else {
1190 1191
        part = name;
        name = nullptr;
1192 1193
      }

1194 1195
      KJ_IF_MAYBE(childId, compiler->lookup(scopeId, part)) {
        scopeId = *childId;
1196
      } else {
1197
        return nullptr;
1198 1199
      }
    }
1200
    return compiler->getLoader().get(scopeId);
1201 1202
  }

1203
public:
1204
  kj::MainBuilder::Validity decode() {
1205 1206 1207
    convertTo = Format::TEXT;
    convertFrom = formatFromDeprecatedFlags(Format::BINARY);
    return convert();
1208 1209 1210
  }

private:
1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221
  enum Plausibility {
    IMPOSSIBLE,
    IMPLAUSIBLE,
    WRONG_TYPE,
    PLAUSIBLE
  };

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

1222
  Plausibility isPlausiblyFlat(kj::ArrayPtr<const byte> prefix, uint segmentCount = 1) {
1223 1224 1225 1226 1227
    if (prefix.size() < 8) {
      // Not enough prefix to say.
      return PLAUSIBLE;
    }

1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238
    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;
      }
    }

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 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289
    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);

1290 1291 1292
    // Actually, the bytes store segmentCount - 1.
    ++segmentCount;

1293 1294 1295 1296 1297 1298 1299 1300 1301
    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;
    }

1302 1303
    uint32_t segment0Size = prefix[4] | (prefix[5] << 8)
                          | (prefix[6] << 16) | (prefix[7] << 24);
1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320

    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;
    }

1321
    return isPlausiblyFlat(prefix.slice(segment0Offset, prefix.size()), segmentCount);
1322 1323
  }

1324 1325
  Plausibility isPlausiblyPacked(kj::ArrayPtr<const byte> prefix,
      kj::Function<Plausibility(kj::ArrayPtr<const byte>)> checkUnpacked) {
1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363
    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;
      }
1364
    }
1365

1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376
    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);
    });
1377 1378
  }

1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398
  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;
1399
          }
1400 1401 1402 1403 1404
          break;
        case COMMENT:
          switch (c) {
            case '\n': state = PREAMBLE; continue;
            default: break;
1405 1406
          }
          break;
1407 1408 1409 1410 1411 1412 1413 1414
        case BODY:
          switch (c) {
            case '\"':
            case '\'':
              // String literal. Let's stop here before things get complicated.
              return PLAUSIBLE;
            default:
              break;
1415 1416 1417
          }
          break;
      }
1418

1419 1420
      if ((static_cast<uint8_t>(c) < 0x20 && c != '\n' && c != '\r' && c != '\t' && c != '\v')
          || c == 0x7f) {
1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449
        // 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;
1450 1451
          }
          break;
1452 1453 1454 1455
        case COMMENT:
          switch (c) {
            case '\n': state = PREAMBLE; continue;
            default: break;
1456 1457
          }
          break;
1458 1459 1460 1461 1462 1463 1464
        case BODY:
          switch (c) {
            case '\"':
              // String literal. Let's stop here before things get complicated.
              return PLAUSIBLE;
            default:
              break;
1465 1466
          }
          break;
1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483
      }

      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);
1484
      case Format::CANONICAL  : return isPlausiblyFlat      (prefix);
1485 1486 1487
      case Format::TEXT       : return isPlausiblyText      (prefix);
      case Format::JSON       : return isPlausiblyJson      (prefix);
    }
Kenton Varda's avatar
Kenton Varda committed
1488
    KJ_UNREACHABLE;
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 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545
  }

  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))) {
1546 1547
          context.warning(
              "*** WARNING ***\n"
1548
              "The input data does not appear to match the schema that you specified. I'll try\n"
1549
              "to parse it anyway, but if it doesn't look right, please verify that you\n"
1550 1551 1552 1553
              "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"
1554
              "*** END WARNING ***\n");
1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566
        } 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 {
1567 1568 1569 1570 1571 1572
          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");
1573 1574
        }
        return true;
1575 1576
    }

1577
    KJ_UNREACHABLE;
1578 1579
  }

1580
public:
1581
  // -----------------------------------------------------------------
1582 1583

  kj::MainBuilder::Validity encode() {
1584 1585 1586 1587
    convertFrom = Format::TEXT;
    convertTo = formatFromDeprecatedFlags(Format::BINARY);
    return convert();
  }
1588

1589 1590 1591 1592 1593 1594
  kj::MainBuilder::Validity setEvalOutputFormat(kj::StringPtr format) {
    KJ_IF_MAYBE(f, parseFormatName(format)) {
      convertTo = *f;
      return true;
    } else {
      return kj::str("unknown format: ", format);
1595
    }
1596 1597
  }

1598
  kj::MainBuilder::Validity evalConst(kj::StringPtr name) {
1599 1600
    convertTo = formatFromDeprecatedFlags(convertTo);

1601 1602
    KJ_ASSERT(sourceFiles.size() == 1);

1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644
    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;
1645
      }
1646 1647 1648 1649 1650 1651 1652
    }
    Schema schema = compiler->getLoader().get(scopeId);

    // Evaluate this schema to a DynamicValue.
    DynamicValue::Reader value;
    word zeroWord[1];
    memset(&zeroWord, 0, sizeof(zeroWord));
1653
    kj::ArrayPtr<const word> segments[1] = { kj::arrayPtr(zeroWord, 1) };
1654 1655 1656 1657 1658 1659 1660 1661 1662 1663
    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.");
        }
1664

1665 1666 1667
        // Use the struct's default value.
        value = emptyMessage.getRoot<DynamicStruct>(schema.asStruct());
        break;
1668

1669 1670 1671 1672 1673 1674 1675
      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.");
1676
        }
1677
    }
1678

1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706
    // 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.");
          }
1707
        } else {
1708 1709 1710 1711 1712 1713
          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.");
          }
1714 1715
        }
      }
1716 1717 1718 1719 1720

      stoppedAtSubscript = false;
    }

    // OK, we have a value.  Print it.
1721
    if (convertTo != Format::TEXT) {
1722 1723 1724 1725
      if (value.getType() != DynamicValue::STRUCT) {
        return "not a struct; binary output is only available on structs";
      }

1726 1727 1728 1729
      auto structValue = value.as<DynamicStruct>();
      rootType = structValue.getSchema();
      kj::FdOutputStream output(STDOUT_FILENO);
      writeConversion(structValue, output);
1730
      context.exit();
1731
    } else {
1732 1733 1734 1735 1736 1737 1738
      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));
      }
1739
    }
1740

Kenton Varda's avatar
Kenton Varda committed
1741
    KJ_CLANG_KNOWS_THIS_IS_UNREACHABLE_BUT_GCC_DOESNT;
1742 1743
  }

1744 1745 1746
public:
  // =====================================================================================

1747
  void addError(const kj::ReadableDirectory& directory, kj::PathPtr path,
1748
                SourcePos start, SourcePos end,
1749
                kj::StringPtr message) override {
1750 1751
    auto file = getDisplayName(directory, path);

1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766
    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);
1767
    hadErrors_ = true;
1768 1769
  }

1770 1771
  bool hadErrors() override {
    return hadErrors_;
1772 1773 1774 1775
  }

private:
  kj::ProcessContext& context;
1776
  kj::Own<kj::Filesystem> disk;
1777
  ModuleLoader loader;
1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788
  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.
1789

1790
  struct SourceDirectory {
1791
    kj::Own<const kj::ReadableDirectory> dir;
1792 1793 1794
    bool isSourcePrefix;
  };

1795
  kj::HashMap<kj::Path, SourceDirectory> sourceDirectories;
1796 1797 1798 1799
  // For each import path and source prefix, tracks the directory object we opened for it.
  //
  // Use via getSourceDirectory().

1800
  kj::HashMap<const kj::ReadableDirectory*, kj::String> dirPrefixes;
1801 1802 1803 1804 1805 1806
  // 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().

1807 1808
  bool addStandardImportPaths = true;

1809 1810 1811 1812
  Format convertFrom = Format::BINARY;
  Format convertTo = Format::BINARY;
  // For the "convert" command.

1813
  bool binary = false;
1814 1815 1816
  bool flat = false;
  bool packed = false;
  bool pretty = true;
1817
  bool quiet = false;
1818
  uint segmentSize = 0;
1819
  StructSchema rootType;
1820
  // For the "decode" and "encode" commands.
1821

Kenton Varda's avatar
Kenton Varda committed
1822 1823 1824
  struct SourceFile {
    uint64_t id;
    kj::StringPtr name;
1825
    Module* module;
Kenton Varda's avatar
Kenton Varda committed
1826 1827 1828
  };

  kj::Vector<SourceFile> sourceFiles;
1829 1830 1831

  struct OutputDirective {
    kj::ArrayPtr<const char> name;
1832 1833 1834 1835
    kj::Maybe<kj::Path> dir;

    KJ_DISALLOW_COPY(OutputDirective);
    OutputDirective(OutputDirective&&) = default;
1836 1837
    OutputDirective(kj::ArrayPtr<const char> name, kj::Maybe<kj::Path> dir)
        : name(name), dir(kj::mv(dir)) {}
1838 1839 1840
  };
  kj::Vector<OutputDirective> outputs;

1841
  bool hadErrors_ = false;
1842

1843
  kj::Maybe<const kj::ReadableDirectory&> getSourceDirectory(
1844 1845 1846 1847 1848 1849
      kj::StringPtr pathStr, bool isSourcePrefix) {
    auto cwd = disk->getCurrentPath();
    auto path = cwd.evalNative(pathStr);

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

1850 1851 1852
    KJ_IF_MAYBE(sdir, sourceDirectories.find(path)) {
      sdir->isSourcePrefix = sdir->isSourcePrefix || isSourcePrefix;
      return *sdir->dir;
1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864
    }

    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) {
1865
        kj::Own<const kj::ReadableDirectory> fakeOwn(&result, kj::NullDisposer::instance);
1866
        sourceDirectories.insert(kj::mv(path), { kj::mv(fakeOwn), isSourcePrefix });
1867 1868 1869 1870 1871 1872
      }
      return result;
    }

    KJ_IF_MAYBE(dir, disk->getRoot().tryOpenSubdir(path)) {
      auto& result = *dir->get();
1873
      sourceDirectories.insert(kj::mv(path), { kj::mv(*dir), isSourcePrefix });
1874 1875 1876 1877 1878 1879
#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
1880
      dirPrefixes.insert(&result, kj::mv(prefix));
1881 1882 1883 1884 1885 1886 1887
      return result;
    } else {
      return nullptr;
    }
  }

  struct DirPathPair {
1888
    const kj::ReadableDirectory& dir;
1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900
    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());

1901 1902
      KJ_IF_MAYBE(sdir, sourceDirectories.find(prefix)) {
        return { *sdir->dir, remainder.clone() };
1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929
      }
    }

    // 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) };
    }
  }

1930
  kj::String getDisplayName(const kj::ReadableDirectory& dir, kj::PathPtr path) {
1931 1932
    KJ_IF_MAYBE(prefix, dirPrefixes.find(&dir)) {
      return kj::str(*prefix, path.toNativeString());
1933 1934 1935 1936 1937 1938 1939 1940
    } else if (&dir == &disk->getRoot()) {
      return path.toNativeString(true);
    } else if (&dir == &disk->getCurrent()) {
      return path.toNativeString(false);
    } else {
      KJ_FAIL_ASSERT("unrecognized directory");
    }
  }
1941 1942 1943 1944 1945 1946
};

}  // namespace compiler
}  // namespace capnp

KJ_MAIN(capnp::compiler::CompilerMain);