compiler.c++ 36.6 KB
Newer Older
Kenton Varda's avatar
Kenton Varda committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
// Copyright (c) 2013, Kenton Varda <temporal@gmail.com>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
//    list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
//    this list of conditions and the following disclaimer in the documentation
//    and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "compiler.h"
Kenton Varda's avatar
Kenton Varda committed
25
#include "parser.h"      // only for generateChildId()
Kenton Varda's avatar
Kenton Varda committed
26 27 28 29 30 31
#include <kj/mutex.h>
#include <kj/arena.h>
#include <kj/vector.h>
#include <kj/debug.h>
#include <capnp/message.h>
#include <map>
Kenton Varda's avatar
Kenton Varda committed
32
#include <set>
Kenton Varda's avatar
Kenton Varda committed
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
#include <unordered_map>
#include "node-translator.h"
#include "md5.h"

namespace capnp {
namespace compiler {

class Compiler::Alias {
public:
  Alias(const Node& parent, const DeclName::Reader& targetName)
      : parent(parent), targetName(targetName) {}

  kj::Maybe<const Node&> getTarget() const;

private:
  const Node& parent;
  DeclName::Reader targetName;
  kj::Lazy<kj::Maybe<const Node&>> target;
};

class Compiler::Node: public NodeTranslator::Resolver {
  // Passes through four states:
  // - Stub:  On initial construction, the Node is just a placeholder object.  Its ID has been
  //     determined, and it is placed in its parent's member table as well as the compiler's
  //     nodes-by-ID table.
  // - Expanded:  Nodes have been constructed for all of this Node's nested children.  This happens
  //     the first time a lookup is performed for one of those children.
  // - Bootstrap:  A NodeTranslator has been built and advanced to the bootstrap phase.
  // - Finished:  A final Schema object has been constructed.

public:
  explicit Node(CompiledModule& module);
  // Create a root node representing the given file.  May

  Node(const Node& parent, const Declaration::Reader& declaration);
  // Create a child node.

70
  Node(kj::StringPtr name, Declaration::Which kind);
Kenton Varda's avatar
Kenton Varda committed
71 72
  // Create a dummy node representing a built-in declaration, like "Int32" or "true".

73
  uint64_t getId() const { return id; }
74
  Declaration::Which getKind() const { return kind; }
Kenton Varda's avatar
Kenton Varda committed
75 76 77 78 79 80 81 82 83 84 85

  kj::Maybe<const Node&> lookupMember(kj::StringPtr name) const;
  // Find a direct member of this node with the given name.

  kj::Maybe<const Node&> lookupLexical(kj::StringPtr name) const;
  // Look up the given name first as a member of this Node, then in its parent, and so on, until
  // it is found or there are no more parents to search.

  kj::Maybe<const Node&> lookup(const DeclName::Reader& name) const;
  // Resolve an arbitrary DeclName to a Node.

86
  kj::Maybe<Schema> getBootstrapSchema() const;
Kenton Varda's avatar
Kenton Varda committed
87
  kj::Maybe<schema::Node::Reader> getFinalSchema() const;
88

89
  void traverse(uint eagerness, std::unordered_map<const Node*, uint>& seen) const;
90 91
  // Get the final schema for this node, and also possibly traverse the node's children and
  // dependencies to ensure that they are loaded, depending on the mode.
Kenton Varda's avatar
Kenton Varda committed
92 93 94 95 96 97

  void addError(kj::StringPtr error) const;
  // Report an error on this Node.

  // implements NodeTranslator::Resolver -----------------------------
  kj::Maybe<ResolvedName> resolve(const DeclName::Reader& name) const override;
98
  kj::Maybe<Schema> resolveBootstrapSchema(uint64_t id) const override;
Kenton Varda's avatar
Kenton Varda committed
99
  kj::Maybe<schema::Node::Reader> resolveFinalSchema(uint64_t id) const override;
100
  kj::Maybe<uint64_t> resolveImport(kj::StringPtr name) const override;
Kenton Varda's avatar
Kenton Varda committed
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117

private:
  const CompiledModule* module;  // null iff isBuiltin is true
  kj::Maybe<const Node&> parent;

  Declaration::Reader declaration;
  // AST of the declaration parsed from the schema file.  May become invalid once the content
  // state has reached FINISHED.

  uint64_t id;
  // The ID of this node, either taken from the AST or computed based on the parent.  Or, a dummy
  // value, if duplicates were detected.

  kj::StringPtr displayName;
  // Fully-qualified display name for this node.  For files, this is just the file name, otherwise
  // it is "filename:Path.To.Decl".

118
  Declaration::Which kind;
Kenton Varda's avatar
Kenton Varda committed
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
  // Kind of node.

  bool isBuiltin;
  // Whether this is a bulit-in declaration, like "Int32" or "true".

  uint32_t startByte;
  uint32_t endByte;
  // Start and end byte for reporting general errors.

  struct Content {
    inline Content(): state(STUB) {}

    enum State {
      STUB,
      EXPANDED,
      BOOTSTRAP,
      FINISHED
    };
    State state;
    // Indicates which fields below are valid.  Must update with atomic-release semantics.

    inline bool stateHasReached(State minimumState) const {
      return __atomic_load_n(&state, __ATOMIC_ACQUIRE) >= minimumState;
    }
    inline void advanceState(State newState) {
      __atomic_store_n(&state, newState, __ATOMIC_RELEASE);
    }

    // EXPANDED ------------------------------------

    typedef std::multimap<kj::StringPtr, kj::Own<Node>> NestedNodesMap;
    NestedNodesMap nestedNodes;
151
    kj::Vector<Node*> orderedNestedNodes;
Kenton Varda's avatar
Kenton Varda committed
152 153 154 155 156
    // Filled in when lookupMember() is first called.  multimap in case of duplicate member names --
    // we still want to compile them, even if it's an error.

    typedef std::multimap<kj::StringPtr, kj::Own<Alias>> AliasMap;
    AliasMap aliases;
Kenton Varda's avatar
Kenton Varda committed
157
    // The "using" declarations.  These are just links to nodes elsewhere.
Kenton Varda's avatar
Kenton Varda committed
158 159 160 161 162 163

    // BOOTSTRAP -----------------------------------

    NodeTranslator* translator;
    // Node translator, allocated in the bootstrap arena.

164 165
    kj::Maybe<Schema> bootstrapSchema;
    // The schema built in the bootstrap loader.  Null if the bootstrap loader threw an exception.
Kenton Varda's avatar
Kenton Varda committed
166 167 168

    // FINISHED ------------------------------------

169 170 171
    kj::Maybe<Schema> finalSchema;
    // The complete schema as loaded by the compiler's main SchemaLoader.  Null if the final
    // loader threw an exception.
Kenton Varda's avatar
Kenton Varda committed
172 173 174

    kj::Array<Schema> auxSchemas;
    // Schemas for all auxiliary nodes built by the NodeTranslator.
Kenton Varda's avatar
Kenton Varda committed
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
  };

  kj::MutexGuarded<Content> content;

  // ---------------------------------------------

  static uint64_t generateId(uint64_t parentId, kj::StringPtr declName,
                             Declaration::Id::Reader declId);
  // Extract the ID from the declaration, or if it has none, generate one based on the name and
  // parent ID.

  static kj::StringPtr joinDisplayName(const kj::Arena& arena, const Node& parent,
                                       kj::StringPtr declName);
  // Join the parent's display name with the child's unqualified name to construct the child's
  // display name.

  const Content& getContent(Content::State minimumState) const;
  // Advances the content to at least the given state and returns it.  Does not lock if the content
  // is already at or past the given state.
194

Kenton Varda's avatar
Kenton Varda committed
195
  void traverseNodeDependencies(const schema::Node::Reader& schemaNode, uint eagerness,
Kenton Varda's avatar
Kenton Varda committed
196
                                std::unordered_map<const Node*, uint>& seen) const;
Kenton Varda's avatar
Kenton Varda committed
197
  void traverseType(const schema::Type::Reader& type, uint eagerness,
198
                    std::unordered_map<const Node*, uint>& seen) const;
Kenton Varda's avatar
Kenton Varda committed
199
  void traverseAnnotations(const List<schema::Annotation>::Reader& annotations, uint eagerness,
200 201
                           std::unordered_map<const Node*, uint>& seen) const;
  // Helpers for traverse().
Kenton Varda's avatar
Kenton Varda committed
202 203 204 205
};

class Compiler::CompiledModule {
public:
206
  CompiledModule(const Compiler::Impl& compiler, const Module& parserModule);
Kenton Varda's avatar
Kenton Varda committed
207 208 209 210

  const Compiler::Impl& getCompiler() const { return compiler; }

  const ErrorReporter& getErrorReporter() const { return parserModule; }
211
  ParsedFile::Reader getParsedFile() const { return content.getReader(); }
Kenton Varda's avatar
Kenton Varda committed
212 213 214 215 216
  const Node& getRootNode() const { return rootNode; }
  kj::StringPtr getSourceName() const { return parserModule.getSourceName(); }

  kj::Maybe<const CompiledModule&> importRelative(kj::StringPtr importPath) const;

Kenton Varda's avatar
Kenton Varda committed
217
  Orphan<List<schema::CodeGeneratorRequest::RequestedFile::Import>>
Kenton Varda's avatar
Kenton Varda committed
218 219
      getFileImportTable(Orphanage orphanage) const;

Kenton Varda's avatar
Kenton Varda committed
220 221
private:
  const Compiler::Impl& compiler;
222
  const Module& parserModule;
Kenton Varda's avatar
Kenton Varda committed
223
  MallocMessageBuilder contentArena;
224
  Orphan<ParsedFile> content;
Kenton Varda's avatar
Kenton Varda committed
225 226 227 228 229
  Node rootNode;
};

class Compiler::Impl: public SchemaLoader::LazyLoadCallback {
public:
230
  explicit Impl(AnnotationFlag annotationFlag);
231
  virtual ~Impl() noexcept(false);
Kenton Varda's avatar
Kenton Varda committed
232

233
  uint64_t add(const Module& module) const;
234
  kj::Maybe<uint64_t> lookup(uint64_t parent, kj::StringPtr childName) const;
Kenton Varda's avatar
Kenton Varda committed
235
  Orphan<List<schema::CodeGeneratorRequest::RequestedFile::Import>>
Kenton Varda's avatar
Kenton Varda committed
236
      getFileImportTable(const Module& module, Orphanage orphanage) const;
237 238
  void eagerlyCompile(uint64_t id, uint eagerness) const;
  const CompiledModule& addInternal(const Module& parsedModule) const;
Kenton Varda's avatar
Kenton Varda committed
239 240 241 242 243 244 245

  struct Workspace {
    // Scratch space where stuff can be allocated while working.  The Workspace is available
    // whenever nodes are actively being compiled, then is destroyed once control exits the
    // compiler.  Note that since nodes are compiled lazily, a new Workspace may have to be
    // constructed in order to compile more nodes later.

246
    MallocMessageBuilder message;
Kenton Varda's avatar
Kenton Varda committed
247 248 249
    Orphanage orphanage;
    // Orphanage for allocating temporary Cap'n Proto objects.

250 251 252 253 254
    kj::Arena arena;
    // Arena for allocating temporary native objects.  Note that objects in `arena` may contain
    // pointers into `message` that will be manipulated on destruction, so `arena` must be declared
    // after `message`.

Kenton Varda's avatar
Kenton Varda committed
255 256 257 258 259 260
    SchemaLoader bootstrapLoader;
    // Loader used to load bootstrap schemas.  The bootstrap schema nodes are similar to the final
    // versions except that any value expressions which depend on knowledge of other types (e.g.
    // default values for struct fields) are left unevaluated (the values in the schema are empty).
    // These bootstrap schemas can then be plugged into the dynamic API and used to evaluate these
    // remaining values.
261

262 263 264
    inline explicit Workspace(const SchemaLoader::LazyLoadCallback& loaderCallback)
        : orphanage(message.getOrphanage()),
          bootstrapLoader(loaderCallback) {}
Kenton Varda's avatar
Kenton Varda committed
265 266 267 268 269 270 271 272
  };

  const kj::Arena& getNodeArena() const { return nodeArena; }
  // Arena where nodes and other permanent objects should be allocated.

  const SchemaLoader& getFinalLoader() const { return finalLoader; }
  // Schema loader containing final versions of schemas.

273
  const Workspace& getWorkspace() const { return workspace.getAlreadyLockedShared(); }
274 275 276
  // Temporary workspace that can be used to construct bootstrap objects.  We assume that the
  // caller already holds the workspace lock somewhere up the stack.

277 278 279 280
  inline bool shouldCompileAnnotations() const {
    return annotationFlag == AnnotationFlag::COMPILE_ANNOTATIONS;
  }

281 282
  void clearWorkspace();
  // Reset the temporary workspace.
Kenton Varda's avatar
Kenton Varda committed
283 284 285 286 287 288 289 290 291 292 293 294 295

  uint64_t addNode(uint64_t desiredId, Node& node) const;
  // Add the given node to the by-ID map under the given ID.  If another node with the same ID
  // already exists, choose a new one arbitrarily and use that instead.  Return the ID that was
  // finally used.

  kj::Maybe<const Node&> findNode(uint64_t id) const;

  kj::Maybe<const Node&> lookupBuiltin(kj::StringPtr name) const;

  void load(const SchemaLoader& loader, uint64_t id) const override;

private:
296 297
  AnnotationFlag annotationFlag;

Kenton Varda's avatar
Kenton Varda committed
298 299 300 301 302 303
  kj::Arena nodeArena;
  // Arena used to allocate nodes and other permanent objects.

  SchemaLoader finalLoader;
  // The loader where we put final output of the compiler.

304 305
  kj::MutexGuarded<Workspace> workspace;
  // The temporary workspace.
Kenton Varda's avatar
Kenton Varda committed
306

307
  typedef std::unordered_map<const Module*, kj::Own<CompiledModule>> ModuleMap;
Kenton Varda's avatar
Kenton Varda committed
308 309 310 311 312 313 314 315 316 317
  kj::MutexGuarded<ModuleMap> modules;
  // Map of parser modules to compiler modules.

  typedef std::unordered_map<uint64_t, const Node*> NodeMap;
  kj::MutexGuarded<NodeMap> nodesById;
  // Map of nodes by ID.

  std::map<kj::StringPtr, kj::Own<Node>> builtinDecls;
  // Map of built-in declarations, like "Int32" and "List", which make up the global scope.

318 319 320 321
  mutable uint32_t nextBogusId = 1000;
  // Counter for assigning bogus IDs to nodes whose real ID is a duplicate.  32-bit so that we
  // can atomically increment it on 32-bit machines.  It will never overflow since that would
  // require compiling at least 2^32 nodes in one process.
Kenton Varda's avatar
Kenton Varda committed
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
};

// =======================================================================================

kj::Maybe<const Compiler::Node&> Compiler::Alias::getTarget() const {
  return target.get([this](kj::SpaceFor<kj::Maybe<const Node&>>& space) {
    return space.construct(parent.lookup(targetName));
  });
}

// =======================================================================================

Compiler::Node::Node(CompiledModule& module)
    : module(&module),
      parent(nullptr),
      declaration(module.getParsedFile().getRoot()),
      id(generateId(0, declaration.getName().getValue(), declaration.getId())),
      displayName(module.getSourceName()),
340
      kind(declaration.which()),
Kenton Varda's avatar
Kenton Varda committed
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
      isBuiltin(false) {
  auto name = declaration.getName();
  if (name.getValue().size() > 0) {
    startByte = name.getStartByte();
    endByte = name.getEndByte();
  } else {
    startByte = declaration.getStartByte();
    endByte = declaration.getEndByte();
  }

  id = module.getCompiler().addNode(id, *this);
}

Compiler::Node::Node(const Node& parent, const Declaration::Reader& declaration)
    : module(parent.module),
      parent(parent),
      declaration(declaration),
      id(generateId(parent.id, declaration.getName().getValue(), declaration.getId())),
      displayName(joinDisplayName(parent.module->getCompiler().getNodeArena(),
                                  parent, declaration.getName().getValue())),
361
      kind(declaration.which()),
Kenton Varda's avatar
Kenton Varda committed
362 363 364 365 366 367 368 369 370 371 372 373 374
      isBuiltin(false) {
  auto name = declaration.getName();
  if (name.getValue().size() > 0) {
    startByte = name.getStartByte();
    endByte = name.getEndByte();
  } else {
    startByte = declaration.getStartByte();
    endByte = declaration.getEndByte();
  }

  id = module->getCompiler().addNode(id, *this);
}

375
Compiler::Node::Node(kj::StringPtr name, Declaration::Which kind)
Kenton Varda's avatar
Kenton Varda committed
376 377 378 379 380 381 382 383 384 385 386
    : module(nullptr),
      parent(nullptr),
      id(0),
      displayName(name),
      kind(kind),
      isBuiltin(true),
      startByte(0),
      endByte(0) {}

uint64_t Compiler::Node::generateId(uint64_t parentId, kj::StringPtr declName,
                                    Declaration::Id::Reader declId) {
387
  if (declId.isUid()) {
Kenton Varda's avatar
Kenton Varda committed
388 389 390
    return declId.getUid().getValue();
  }

Kenton Varda's avatar
Kenton Varda committed
391
  return generateChildId(parentId, declName);
Kenton Varda's avatar
Kenton Varda committed
392 393 394 395 396 397 398 399 400 401 402 403
}

kj::StringPtr Compiler::Node::joinDisplayName(
    const kj::Arena& arena, const Node& parent, kj::StringPtr declName) {
  kj::ArrayPtr<char> result = arena.allocateArray<char>(
      parent.displayName.size() + declName.size() + 2);

  size_t separatorPos = parent.displayName.size();
  memcpy(result.begin(), parent.displayName.begin(), separatorPos);
  result[separatorPos] = parent.parent == nullptr ? ':' : '.';
  memcpy(result.begin() + separatorPos + 1, declName.begin(), declName.size());
  result[result.size() - 1] = '\0';
404
  return kj::StringPtr(result.begin(), result.size() - 1);
Kenton Varda's avatar
Kenton Varda committed
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
}

const Compiler::Node::Content& Compiler::Node::getContent(Content::State minimumState) const {
  KJ_REQUIRE(!isBuiltin, "illegal method call for built-in declaration");

  if (content.getWithoutLock().stateHasReached(minimumState)) {
    return content.getWithoutLock();
  }

  auto locked = content.lockExclusive();

  switch (locked->state) {
    case Content::STUB: {
      if (minimumState <= Content::STUB) break;

      // Expand the child nodes.
      auto& arena = module->getCompiler().getNodeArena();

      for (auto nestedDecl: declaration.getNestedDecls()) {
424 425 426 427 428 429 430
        switch (nestedDecl.which()) {
          case Declaration::FILE:
          case Declaration::CONST:
          case Declaration::ANNOTATION:
          case Declaration::ENUM:
          case Declaration::STRUCT:
          case Declaration::INTERFACE: {
Kenton Varda's avatar
Kenton Varda committed
431 432
            kj::Own<Node> subNode = arena.allocateOwn<Node>(*this, nestedDecl);
            kj::StringPtr name = nestedDecl.getName().getValue();
433
            locked->orderedNestedNodes.add(subNode);
Kenton Varda's avatar
Kenton Varda committed
434 435 436 437
            locked->nestedNodes.insert(std::make_pair(name, kj::mv(subNode)));
            break;
          }

438
          case Declaration::USING: {
Kenton Varda's avatar
Kenton Varda committed
439
            kj::Own<Alias> alias = arena.allocateOwn<Alias>(
440
                *this, nestedDecl.getUsing().getTarget());
Kenton Varda's avatar
Kenton Varda committed
441 442 443 444
            kj::StringPtr name = nestedDecl.getName().getValue();
            locked->aliases.insert(std::make_pair(name, kj::mv(alias)));
            break;
          }
445 446 447 448 449 450 451
          case Declaration::ENUMERANT:
          case Declaration::FIELD:
          case Declaration::UNION:
          case Declaration::GROUP:
          case Declaration::METHOD:
          case Declaration::NAKED_ID:
          case Declaration::NAKED_ANNOTATION:
Kenton Varda's avatar
Kenton Varda committed
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
            // Not a node.  Skip.
            break;
          default:
            KJ_FAIL_ASSERT("unknown declaration type", nestedDecl);
            break;
        }
      }

      locked->advanceState(Content::EXPANDED);
      // no break
    }

    case Content::EXPANDED: {
      if (minimumState <= Content::EXPANDED) break;

      // Construct the NodeTranslator.
      auto& workspace = module->getCompiler().getWorkspace();

Kenton Varda's avatar
Kenton Varda committed
470
      auto schemaNode = workspace.orphanage.newOrphan<schema::Node>();
Kenton Varda's avatar
Kenton Varda committed
471 472 473 474 475 476 477
      auto builder = schemaNode.get();
      builder.setId(id);
      builder.setDisplayName(displayName);
      KJ_IF_MAYBE(p, parent) {
        builder.setScopeId(p->id);
      }

Kenton Varda's avatar
Kenton Varda committed
478 479
      auto nestedNodes = builder.initNestedNodes(locked->orderedNestedNodes.size());
      auto nestedIter = nestedNodes.begin();
480 481 482
      for (auto node: locked->orderedNestedNodes) {
        nestedIter->setName(node->declaration.getName().getValue());
        nestedIter->setId(node->id);
Kenton Varda's avatar
Kenton Varda committed
483 484 485 486
        ++nestedIter;
      }

      locked->translator = &workspace.arena.allocate<NodeTranslator>(
487 488
          *this, module->getErrorReporter(), declaration, kj::mv(schemaNode),
          module->getCompiler().shouldCompileAnnotations());
489
      KJ_IF_MAYBE(exception, kj::runCatchingExceptions([&](){
Kenton Varda's avatar
Kenton Varda committed
490 491 492 493 494
        auto nodeSet = locked->translator->getBootstrapNode();
        for (auto& auxNode: nodeSet.auxNodes) {
          workspace.bootstrapLoader.loadOnce(auxNode);
        }
        locked->bootstrapSchema = workspace.bootstrapLoader.loadOnce(nodeSet.node);
495 496
      })) {
        locked->bootstrapSchema = nullptr;
497 498 499 500 501 502
        // Only bother to report validation failures if we think we haven't seen any errors.
        // Otherwise we assume that the errors caused the validation failure.
        if (!module->getErrorReporter().hadErrors()) {
          addError(kj::str("Internal compiler bug: Bootstrap schema failed validation:\n",
                           *exception));
        }
503
      }
Kenton Varda's avatar
Kenton Varda committed
504 505 506 507 508 509

      // If the Workspace is destroyed while this Node is still in the BOOTSTRAP state,
      // revert it to the EXPANDED state, because the NodeTranslator is no longer valid in this
      // case.
      Content* contentPtr = locked.get();
      workspace.arena.copy(kj::defer([contentPtr]() {
510
        contentPtr->bootstrapSchema = nullptr;
Kenton Varda's avatar
Kenton Varda committed
511 512 513 514 515 516 517 518 519 520 521 522 523
        if (contentPtr->state == Content::BOOTSTRAP) {
          contentPtr->state = Content::EXPANDED;
        }
      }));

      locked->advanceState(Content::BOOTSTRAP);
      // no break
    }

    case Content::BOOTSTRAP: {
      if (minimumState <= Content::BOOTSTRAP) break;

      // Create the final schema.
524
      auto nodeSet = locked->translator->finish();
525
      KJ_IF_MAYBE(exception, kj::runCatchingExceptions([&](){
526
        locked->auxSchemas = KJ_MAP(auxNode, nodeSet.auxNodes) {
Kenton Varda's avatar
Kenton Varda committed
527 528 529
          return module->getCompiler().getFinalLoader().loadOnce(auxNode);
        };
        locked->finalSchema = module->getCompiler().getFinalLoader().loadOnce(nodeSet.node);
530 531
      })) {
        locked->finalSchema = nullptr;
532 533 534 535 536 537 538

        // Only bother to report validation failures if we think we haven't seen any errors.
        // Otherwise we assume that the errors caused the validation failure.
        if (!module->getErrorReporter().hadErrors()) {
          addError(kj::str("Internal compiler bug: Schema failed validation:\n",
                           *exception));
        }
539
      }
Kenton Varda's avatar
Kenton Varda committed
540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597

      locked->advanceState(Content::FINISHED);
      // no break
    }

    case Content::FINISHED:
      break;
  }

  return *locked;
}

kj::Maybe<const Compiler::Node&> Compiler::Node::lookupMember(kj::StringPtr name) const {
  if (isBuiltin) return nullptr;

  auto& content = getContent(Content::EXPANDED);
  {
    auto iter = content.nestedNodes.find(name);
    if (iter != content.nestedNodes.end()) {
      return *iter->second;
    }
  }
  {
    auto iter = content.aliases.find(name);
    if (iter != content.aliases.end()) {
      return iter->second->getTarget();
    }
  }
  return nullptr;
}

kj::Maybe<const Compiler::Node&> Compiler::Node::lookupLexical(kj::StringPtr name) const {
  KJ_REQUIRE(!isBuiltin, "illegal method call for built-in declaration");

  auto result = lookupMember(name);
  if (result == nullptr) {
    KJ_IF_MAYBE(p, parent) {
      result = p->lookupLexical(name);
    } else {
      result = module->getCompiler().lookupBuiltin(name);
    }
  }
  return result;
}

kj::Maybe<const Compiler::Node&> Compiler::Node::lookup(const DeclName::Reader& name) const {
  KJ_REQUIRE(!isBuiltin, "illegal method call for built-in declaration");

  const Node* node = nullptr;

  auto base = name.getBase();
  switch (base.which()) {
    case DeclName::Base::ABSOLUTE_NAME: {
      auto absoluteName = base.getAbsoluteName();
      KJ_IF_MAYBE(n, module->getRootNode().lookupMember(absoluteName.getValue())) {
        node = &*n;
      } else {
        module->getErrorReporter().addErrorOn(
598
            absoluteName, kj::str("Not defined: ", absoluteName.getValue()));
Kenton Varda's avatar
Kenton Varda committed
599 600 601 602 603 604 605 606 607 608
        return nullptr;
      }
      break;
    }
    case DeclName::Base::RELATIVE_NAME: {
      auto relativeName = base.getRelativeName();
      KJ_IF_MAYBE(n, lookupLexical(relativeName.getValue())) {
        node = &*n;
      } else {
        module->getErrorReporter().addErrorOn(
609
            relativeName, kj::str("Not defined: ", relativeName.getValue()));
Kenton Varda's avatar
Kenton Varda committed
610 611 612 613 614 615 616 617 618 619
        return nullptr;
      }
      break;
    }
    case DeclName::Base::IMPORT_NAME: {
      auto importName = base.getImportName();
      KJ_IF_MAYBE(m, module->importRelative(importName.getValue())) {
        node = &m->getRootNode();
      } else {
        module->getErrorReporter().addErrorOn(
620
            importName, kj::str("Import failed: ", importName.getValue()));
Kenton Varda's avatar
Kenton Varda committed
621 622 623 624 625 626 627 628 629 630 631 632 633
        return nullptr;
      }
      break;
    }
  }

  KJ_ASSERT(node != nullptr);

  for (auto partName: name.getMemberPath()) {
    KJ_IF_MAYBE(member, node->lookupMember(partName.getValue())) {
      node = &*member;
    } else {
      module->getErrorReporter().addErrorOn(
634
          partName, kj::str("No such member: ", partName.getValue()));
Kenton Varda's avatar
Kenton Varda committed
635 636 637 638 639 640 641
      return nullptr;
    }
  }

  return *node;
}

642
kj::Maybe<Schema> Compiler::Node::getBootstrapSchema() const {
Kenton Varda's avatar
Kenton Varda committed
643 644
  auto& content = getContent(Content::BOOTSTRAP);

645
  if (__atomic_load_n(&content.state, __ATOMIC_ACQUIRE) == Content::FINISHED &&
646 647 648 649 650 651 652 653 654
      content.bootstrapSchema == nullptr) {
    // The bootstrap schema was discarded.  Copy it from the final schema.
    // (We can't just return the final schema because using it could trigger schema loader
    // callbacks that would deadlock.)
    KJ_IF_MAYBE(finalSchema, content.finalSchema) {
      return module->getCompiler().getWorkspace().bootstrapLoader.loadOnce(finalSchema->getProto());
    } else {
      return nullptr;
    }
Kenton Varda's avatar
Kenton Varda committed
655 656 657 658
  } else {
    return content.bootstrapSchema;
  }
}
Kenton Varda's avatar
Kenton Varda committed
659
kj::Maybe<schema::Node::Reader> Compiler::Node::getFinalSchema() const {
660 661
  return getContent(Content::FINISHED).finalSchema.map(
      [](const Schema& schema) { return schema.getProto(); });
Kenton Varda's avatar
Kenton Varda committed
662 663
}

664 665 666 667 668 669 670 671 672 673 674 675 676 677
void Compiler::Node::traverse(uint eagerness, std::unordered_map<const Node*, uint>& seen) const {
  uint& slot = seen[this];
  if ((slot & eagerness) == eagerness) {
    // We've already covered this node.
    return;
  }
  slot |= eagerness;

  KJ_IF_MAYBE(schema, getFinalSchema()) {
    if (eagerness / DEPENDENCIES != 0) {
      // For traversing dependencies, discard the bits lower than DEPENDENCIES and replace
      // them with the bits above DEPENDENCIES shifted over.
      uint newEagerness = (eagerness & ~(DEPENDENCIES - 1)) | (eagerness / DEPENDENCIES);

Kenton Varda's avatar
Kenton Varda committed
678 679 680
      traverseNodeDependencies(*schema, newEagerness, seen);
      for (auto& aux: getContent(Content::FINISHED).auxSchemas) {
        traverseNodeDependencies(aux.getProto(), newEagerness, seen);
681 682 683 684 685 686 687 688 689 690 691
      }
    }
  }

  if (eagerness & PARENTS) {
    KJ_IF_MAYBE(p, parent) {
      p->traverse(eagerness, seen);
    }
  }

  if (eagerness & CHILDREN) {
692 693
    for (auto& child: getContent(Content::EXPANDED).orderedNestedNodes) {
      child->traverse(eagerness, seen);
694 695 696 697
    }
  }
}

Kenton Varda's avatar
Kenton Varda committed
698
void Compiler::Node::traverseNodeDependencies(
Kenton Varda's avatar
Kenton Varda committed
699
    const schema::Node::Reader& schemaNode, uint eagerness,
Kenton Varda's avatar
Kenton Varda committed
700 701
    std::unordered_map<const Node*, uint>& seen) const {
  switch (schemaNode.which()) {
Kenton Varda's avatar
Kenton Varda committed
702
    case schema::Node::STRUCT:
Kenton Varda's avatar
Kenton Varda committed
703 704
      for (auto field: schemaNode.getStruct().getFields()) {
        switch (field.which()) {
705 706
          case schema::Field::SLOT:
            traverseType(field.getSlot().getType(), eagerness, seen);
Kenton Varda's avatar
Kenton Varda committed
707
            break;
Kenton Varda's avatar
Kenton Varda committed
708
          case schema::Field::GROUP:
Kenton Varda's avatar
Kenton Varda committed
709 710 711 712 713 714 715 716
            // Aux node will be scanned later.
            break;
        }

        traverseAnnotations(field.getAnnotations(), eagerness, seen);
      }
      break;

Kenton Varda's avatar
Kenton Varda committed
717
    case schema::Node::ENUM:
718
      for (auto enumerant: schemaNode.getEnum().getEnumerants()) {
Kenton Varda's avatar
Kenton Varda committed
719 720 721 722
        traverseAnnotations(enumerant.getAnnotations(), eagerness, seen);
      }
      break;

Kenton Varda's avatar
Kenton Varda committed
723
    case schema::Node::INTERFACE:
724
      for (auto method: schemaNode.getInterface().getMethods()) {
Kenton Varda's avatar
Kenton Varda committed
725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740
        for (auto param: method.getParams()) {
          traverseType(param.getType(), eagerness, seen);
          traverseAnnotations(param.getAnnotations(), eagerness, seen);
        }
        traverseType(method.getReturnType(), eagerness, seen);
        traverseAnnotations(method.getAnnotations(), eagerness, seen);
      }
      break;

    default:
      break;
  }

  traverseAnnotations(schemaNode.getAnnotations(), eagerness, seen);
}

Kenton Varda's avatar
Kenton Varda committed
741
void Compiler::Node::traverseType(const schema::Type::Reader& type, uint eagerness,
742 743
                                  std::unordered_map<const Node*, uint>& seen) const {
  uint64_t id = 0;
Kenton Varda's avatar
Kenton Varda committed
744
  switch (type.which()) {
Kenton Varda's avatar
Kenton Varda committed
745
    case schema::Type::STRUCT:
746
      id = type.getStruct().getTypeId();
747
      break;
Kenton Varda's avatar
Kenton Varda committed
748
    case schema::Type::ENUM:
749
      id = type.getEnum().getTypeId();
750
      break;
Kenton Varda's avatar
Kenton Varda committed
751
    case schema::Type::INTERFACE:
752
      id = type.getInterface().getTypeId();
753
      break;
Kenton Varda's avatar
Kenton Varda committed
754
    case schema::Type::LIST:
755
      traverseType(type.getList().getElementType(), eagerness, seen);
756 757 758 759 760 761 762 763 764 765 766 767
      return;
    default:
      return;
  }

  KJ_IF_MAYBE(node, module->getCompiler().findNode(id)) {
    node->traverse(eagerness, seen);
  } else {
    KJ_FAIL_ASSERT("Dependency ID not present in compiler?", id);
  }
}

Kenton Varda's avatar
Kenton Varda committed
768
void Compiler::Node::traverseAnnotations(const List<schema::Annotation>::Reader& annotations,
769 770 771 772 773 774 775 776 777 778
                                         uint eagerness,
                                         std::unordered_map<const Node*, uint>& seen) const {
  for (auto annotation: annotations) {
    KJ_IF_MAYBE(node, module->getCompiler().findNode(annotation.getId())) {
      node->traverse(eagerness, seen);
    }
  }
}


Kenton Varda's avatar
Kenton Varda committed
779 780 781 782 783 784 785 786 787 788 789
void Compiler::Node::addError(kj::StringPtr error) const {
  module->getErrorReporter().addError(startByte, endByte, error);
}

kj::Maybe<NodeTranslator::Resolver::ResolvedName> Compiler::Node::resolve(
    const DeclName::Reader& name) const {
  return lookup(name).map([](const Node& node) {
    return ResolvedName { node.id, node.kind };
  });
}

790
kj::Maybe<Schema> Compiler::Node::resolveBootstrapSchema(uint64_t id) const {
Kenton Varda's avatar
Kenton Varda committed
791
  KJ_IF_MAYBE(node, module->getCompiler().findNode(id)) {
792
    return node->getBootstrapSchema();
Kenton Varda's avatar
Kenton Varda committed
793 794 795
  } else {
    KJ_FAIL_REQUIRE("Tried to get schema for ID we haven't seen before.");
  }
Kenton Varda's avatar
Kenton Varda committed
796 797
}

Kenton Varda's avatar
Kenton Varda committed
798
kj::Maybe<schema::Node::Reader> Compiler::Node::resolveFinalSchema(uint64_t id) const {
Kenton Varda's avatar
Kenton Varda committed
799 800 801 802 803
  KJ_IF_MAYBE(node, module->getCompiler().findNode(id)) {
    return node->getFinalSchema();
  } else {
    KJ_FAIL_REQUIRE("Tried to get schema for ID we haven't seen before.");
  }
Kenton Varda's avatar
Kenton Varda committed
804 805
}

806 807 808 809 810 811 812 813
kj::Maybe<uint64_t> Compiler::Node::resolveImport(kj::StringPtr name) const {
  KJ_IF_MAYBE(m, module->importRelative(name)) {
    return m->getRootNode().getId();
  } else {
    return nullptr;
  }
}

Kenton Varda's avatar
Kenton Varda committed
814 815 816
// =======================================================================================

Compiler::CompiledModule::CompiledModule(
817
    const Compiler::Impl& compiler, const Module& parserModule)
Kenton Varda's avatar
Kenton Varda committed
818 819 820 821 822 823 824
    : compiler(compiler), parserModule(parserModule),
      content(parserModule.loadContent(contentArena.getOrphanage())),
      rootNode(*this) {}

kj::Maybe<const Compiler::CompiledModule&> Compiler::CompiledModule::importRelative(
    kj::StringPtr importPath) const {
  return parserModule.importRelative(importPath).map(
825
      [this](const Module& module) -> const Compiler::CompiledModule& {
826
        return compiler.addInternal(module);
Kenton Varda's avatar
Kenton Varda committed
827 828 829
      });
}

Kenton Varda's avatar
Kenton Varda committed
830
static void findImports(DeclName::Reader name, std::set<kj::StringPtr>& output) {
831
  if (name.getBase().isImportName()) {
Kenton Varda's avatar
Kenton Varda committed
832 833 834 835 836 837 838 839 840 841 842 843
    output.insert(name.getBase().getImportName().getValue());
  }
}

static void findImports(TypeExpression::Reader type, std::set<kj::StringPtr>& output) {
  findImports(type.getName(), output);
  for (auto param: type.getParams()) {
    findImports(param, output);
  }
}

static void findImports(Declaration::Reader decl, std::set<kj::StringPtr>& output) {
844 845 846
  switch (decl.which()) {
    case Declaration::USING:
      findImports(decl.getUsing().getTarget(), output);
Kenton Varda's avatar
Kenton Varda committed
847
      break;
848 849
    case Declaration::CONST:
      findImports(decl.getConst().getType(), output);
Kenton Varda's avatar
Kenton Varda committed
850
      break;
851 852
    case Declaration::FIELD:
      findImports(decl.getField().getType(), output);
Kenton Varda's avatar
Kenton Varda committed
853
      break;
854 855
    case Declaration::METHOD: {
      auto method = decl.getMethod();
Kenton Varda's avatar
Kenton Varda committed
856 857 858 859 860 861
      for (auto param: method.getParams()) {
        findImports(param.getType(), output);
        for (auto ann: param.getAnnotations()) {
          findImports(ann.getName(), output);
        }
      }
862
      if (method.getReturnType().isExpression()) {
Kenton Varda's avatar
Kenton Varda committed
863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879
        findImports(method.getReturnType().getExpression(), output);
      }
      break;
    }
    default:
      break;
  }

  for (auto ann: decl.getAnnotations()) {
    findImports(ann.getName(), output);
  }

  for (auto nested: decl.getNestedDecls()) {
    findImports(nested, output);
  }
}

Kenton Varda's avatar
Kenton Varda committed
880
Orphan<List<schema::CodeGeneratorRequest::RequestedFile::Import>>
Kenton Varda's avatar
Kenton Varda committed
881 882 883 884
    Compiler::CompiledModule::getFileImportTable(Orphanage orphanage) const {
  std::set<kj::StringPtr> importNames;
  findImports(content.getReader().getRoot(), importNames);

Kenton Varda's avatar
Kenton Varda committed
885
  auto result = orphanage.newOrphan<List<schema::CodeGeneratorRequest::RequestedFile::Import>>(
Kenton Varda's avatar
Kenton Varda committed
886 887 888 889 890 891 892 893 894 895 896 897 898 899
      importNames.size());
  auto builder = result.get();

  uint i = 0;
  for (auto name: importNames) {
    // We presumably ran this import before, so it shouldn't throw now.
    auto entry = builder[i];
    entry.setId(KJ_ASSERT_NONNULL(importRelative(name)).rootNode.getId());
    entry.setName(name);
  }

  return result;
}

Kenton Varda's avatar
Kenton Varda committed
900 901
// =======================================================================================

902 903
Compiler::Impl::Impl(AnnotationFlag annotationFlag)
    : annotationFlag(annotationFlag), finalLoader(*this), workspace(*this) {
Kenton Varda's avatar
Kenton Varda committed
904 905
  // Reflectively interpret the members of Declaration.body.  Any member prefixed by "builtin"
  // defines a builtin declaration visible in the global scope.
906

907 908 909 910 911 912 913 914 915 916
  StructSchema declSchema = Schema::from<Declaration>();
  for (auto field: declSchema.getFields()) {
    auto fieldProto = field.getProto();
    if (fieldProto.hasDiscriminantValue()) {
      auto name = fieldProto.getName();
      if (name.startsWith("builtin")) {
        kj::StringPtr symbolName = name.slice(strlen("builtin"));
        builtinDecls[symbolName] = nodeArena.allocateOwn<Node>(
            symbolName, static_cast<Declaration::Which>(fieldProto.getDiscriminantValue()));
      }
Kenton Varda's avatar
Kenton Varda committed
917 918 919 920
    }
  }
}

921
Compiler::Impl::~Impl() noexcept(false) {}
922

923 924 925 926 927 928 929 930
void Compiler::Impl::clearWorkspace() {
  auto lock = workspace.lockExclusive();

  // Make sure we reconstruct the workspace even if destroying it throws an exception.
  KJ_DEFER(kj::ctor(*lock, *this));
  kj::dtor(*lock);
}

931
const Compiler::CompiledModule& Compiler::Impl::addInternal(const Module& parsedModule) const {
932 933 934 935 936 937 938 939 940 941
  auto locked = modules.lockExclusive();

  kj::Own<CompiledModule>& slot = (*locked)[&parsedModule];
  if (slot.get() == nullptr) {
    slot = kj::heap<CompiledModule>(*this, parsedModule);
  }

  return *slot;
}

Kenton Varda's avatar
Kenton Varda committed
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
uint64_t Compiler::Impl::addNode(uint64_t desiredId, Node& node) const {
  auto lock = nodesById.lockExclusive();
  for (;;) {
    auto insertResult = lock->insert(std::make_pair(desiredId, &node));
    if (insertResult.second) {
      return desiredId;
    }

    // Only report an error if this ID is not bogus.  Actual IDs specified in the original source
    // code are required to have the upper bit set.  Anything else must have been manufactured
    // at some point to cover up an error.
    if (desiredId & (1ull << 63)) {
      node.addError(kj::str("Duplicate ID @0x", kj::hex(desiredId), "."));
      insertResult.first->second->addError(
          kj::str("ID @0x", kj::hex(desiredId), " originally used here."));
    }

    // Assign a new bogus ID.
    desiredId = __atomic_fetch_add(&nextBogusId, 1, __ATOMIC_RELAXED);
  }
}

kj::Maybe<const Compiler::Node&> Compiler::Impl::findNode(uint64_t id) const {
  auto lock = nodesById.lockShared();
  auto iter = lock->find(id);
  if (iter == lock->end()) {
    return nullptr;
  } else {
    return *iter->second;
  }
}

kj::Maybe<const Compiler::Node&> Compiler::Impl::lookupBuiltin(kj::StringPtr name) const {
  auto iter = builtinDecls.find(name);
  if (iter == builtinDecls.end()) {
    return nullptr;
  } else {
    return *iter->second;
  }
}

983 984
uint64_t Compiler::Impl::add(const Module& module) const {
  return addInternal(module).getRootNode().getId();
985 986
}

987
kj::Maybe<uint64_t> Compiler::Impl::lookup(uint64_t parent, kj::StringPtr childName) const {
988
  // Looking up members does not use the workspace, so we don't need to lock it.
989
  KJ_IF_MAYBE(parentNode, findNode(parent)) {
990 991 992 993 994
    KJ_IF_MAYBE(child, parentNode->lookupMember(childName)) {
      return child->getId();
    } else {
      return nullptr;
    }
995 996 997 998 999
  } else {
    KJ_FAIL_REQUIRE("lookup()s parameter 'parent' must be a known ID.", parent);
  }
}

Kenton Varda's avatar
Kenton Varda committed
1000
Orphan<List<schema::CodeGeneratorRequest::RequestedFile::Import>>
Kenton Varda's avatar
Kenton Varda committed
1001 1002 1003 1004
    Compiler::Impl::getFileImportTable(const Module& module, Orphanage orphanage) const {
  return addInternal(module).getFileImportTable(orphanage);
}

1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
void Compiler::Impl::eagerlyCompile(uint64_t id, uint eagerness) const {
  KJ_IF_MAYBE(node, findNode(id)) {
    auto lock = this->workspace.lockShared();
    std::unordered_map<const Node*, uint> seen;
    node->traverse(eagerness, seen);
  } else {
    KJ_FAIL_REQUIRE("id did not come from this Compiler.", id);
  }
}

Kenton Varda's avatar
Kenton Varda committed
1015 1016 1017
void Compiler::Impl::load(const SchemaLoader& loader, uint64_t id) const {
  KJ_IF_MAYBE(node, findNode(id)) {
    if (&loader == &finalLoader) {
1018
      auto lock = this->workspace.lockShared();
Kenton Varda's avatar
Kenton Varda committed
1019 1020
      node->getFinalSchema();
    } else {
1021 1022
      // Must be the bootstrap loader.  Workspace should already be locked.
      this->workspace.getAlreadyLockedShared();
1023
      node->getBootstrapSchema();
Kenton Varda's avatar
Kenton Varda committed
1024 1025 1026 1027
    }
  }
}

1028 1029
// =======================================================================================

1030 1031
Compiler::Compiler(AnnotationFlag annotationFlag): impl(kj::heap<Impl>(annotationFlag)) {}
Compiler::~Compiler() noexcept(false) {}
1032

1033 1034
uint64_t Compiler::add(const Module& module) const {
  return impl->add(module);
1035 1036
}

1037 1038 1039 1040
kj::Maybe<uint64_t> Compiler::lookup(uint64_t parent, kj::StringPtr childName) const {
  return impl->lookup(parent, childName);
}

Kenton Varda's avatar
Kenton Varda committed
1041
Orphan<List<schema::CodeGeneratorRequest::RequestedFile::Import>>
Kenton Varda's avatar
Kenton Varda committed
1042 1043 1044 1045
    Compiler::getFileImportTable(const Module& module, Orphanage orphanage) const {
  return impl->getFileImportTable(module, orphanage);
}

1046 1047 1048 1049
void Compiler::eagerlyCompile(uint64_t id, uint eagerness) const {
  return impl->eagerlyCompile(id, eagerness);
}

1050 1051 1052 1053
const SchemaLoader& Compiler::getLoader() const {
  return impl->getFinalLoader();
}

1054 1055 1056 1057
void Compiler::clearWorkspace() {
  impl->clearWorkspace();
}

Kenton Varda's avatar
Kenton Varda committed
1058 1059
}  // namespace compiler
}  // namespace capnp