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

Kenton Varda's avatar
Kenton Varda committed
22 23
// This program is a code generator plugin for `capnp compile` which writes the schema back to
// stdout in roughly capnpc format.
24

25
#include <capnp/schema.capnp.h>
26
#include "../serialize.h"
Kenton Varda's avatar
Kenton Varda committed
27
#include <kj/debug.h>
28
#include <kj/io.h>
29
#include <kj/string-tree.h>
30
#include <kj/vector.h>
31 32
#include "../schema-loader.h"
#include "../dynamic.h"
33 34
#include <unistd.h>
#include <unordered_map>
35
#include <kj/main.h>
Kenton Varda's avatar
Kenton Varda committed
36
#include <algorithm>
Kenton Varda's avatar
Kenton Varda committed
37
#include <map>
38 39 40

#if HAVE_CONFIG_H
#include "config.h"
Kenton Varda's avatar
Kenton Varda committed
41 42 43 44
#endif

#ifndef VERSION
#define VERSION "(unknown)"
45
#endif
46

47
namespace capnp {
48 49
namespace {

50 51 52 53
bool hasDiscriminantValue(const schema::Field::Reader& reader) {
  return reader.getDiscriminantValue() != schema::Field::NO_DISCRIMINANT;
}

54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
struct Indent {
  uint amount;
  Indent() = default;
  inline Indent(int amount): amount(amount) {}

  Indent next() {
    return Indent(amount + 2);
  }

  struct Iterator {
    uint i;
    Iterator() = default;
    inline Iterator(uint i): i(i) {}
    inline char operator*() const { return ' '; }
    inline Iterator& operator++() { ++i; return *this; }
    inline Iterator operator++(int) { Iterator result = *this; ++i; return result; }
    inline bool operator==(const Iterator& other) const { return i == other.i; }
    inline bool operator!=(const Iterator& other) const { return i != other.i; }
  };

  inline size_t size() const { return amount; }

  inline Iterator begin() const { return Iterator(0); }
  inline Iterator end() const { return Iterator(amount); }
};

80 81 82 83
inline Indent KJ_STRINGIFY(const Indent& indent) {
  return indent;
}

84 85
// =======================================================================================

86 87 88 89 90 91 92 93 94 95 96 97 98
class CapnpcCapnpMain {
public:
  CapnpcCapnpMain(kj::ProcessContext& context): context(context) {}

  kj::MainFunc getMain() {
    return kj::MainBuilder(context, "Cap'n Proto loopback plugin version " VERSION,
          "This is a Cap'n Proto compiler plugin which \"de-compiles\" the schema back into "
          "Cap'n Proto schema language format, with comments showing the offsets chosen by the "
          "compiler.  This is meant to be run using the Cap'n Proto compiler, e.g.:\n"
          "    capnp compile -ocapnp foo.capnp")
        .callAfterParsing(KJ_BIND_METHOD(*this, run))
        .build();
  }
99

100 101 102 103 104 105 106 107 108 109 110 111
private:
  kj::ProcessContext& context;
  SchemaLoader schemaLoader;

  Text::Reader getUnqualifiedName(Schema schema) {
    auto proto = schema.getProto();
    KJ_CONTEXT(proto.getDisplayName());
    auto parent = schemaLoader.get(proto.getScopeId());
    for (auto nested: parent.getProto().getNestedNodes()) {
      if (nested.getId() == proto.getId()) {
        return nested.getName();
      }
112
    }
113 114
    KJ_FAIL_REQUIRE("A schema Node's supposed scope did not contain the node as a NestedNode.");
    return "(?)";
115 116
  }

117 118
  kj::StringTree nodeName(Schema target, Schema scope, schema::Brand::Reader brand,
                          kj::Maybe<InterfaceSchema::Method> method) {
Kenton Varda's avatar
Kenton Varda committed
119
    kj::Vector<Schema> targetPath;
120
    kj::Vector<Schema> scopeParts;
121

Kenton Varda's avatar
Kenton Varda committed
122 123
    targetPath.add(target);

124 125 126 127 128
    std::map<uint64_t, List<schema::Brand::Binding>::Reader> scopeBindings;
    for (auto scopeBrand: brand.getScopes()) {
      switch (scopeBrand.which()) {
        case schema::Brand::Scope::BIND:
          scopeBindings[scopeBrand.getScopeId()] = scopeBrand.getBind();
129
          break;
130
        case schema::Brand::Scope::INHERIT:
131 132 133 134 135
          // TODO(someday): We need to pay attention to INHERIT and be sure to explicitly override
          //   any bindings that are not inherited. This requires a way to determine which of our
          //   parent scopes have a non-empty parameter list.
          break;
      }
Kenton Varda's avatar
Kenton Varda committed
136 137
    }

138 139 140 141
    {
      Schema parent = target;
      while (parent.getProto().getScopeId() != 0) {
        parent = schemaLoader.get(parent.getProto().getScopeId());
Kenton Varda's avatar
Kenton Varda committed
142
        targetPath.add(parent);
143
      }
144 145
    }

146 147 148 149 150 151 152
    {
      Schema parent = scope;
      scopeParts.add(parent);
      while (parent.getProto().getScopeId() != 0) {
        parent = schemaLoader.get(parent.getProto().getScopeId());
        scopeParts.add(parent);
      }
153 154
    }

Kenton Varda's avatar
Kenton Varda committed
155 156 157 158 159
    // Remove common scope (unless it has been reparameterized).
    // TODO(someday):  This is broken in that we aren't checking for shadowing.
    while (!scopeParts.empty() && targetPath.size() > 1 &&
           scopeParts.back() == targetPath.back() &&
           scopeBindings.count(scopeParts.back().getProto().getId()) == 0) {
160
      scopeParts.removeLast();
Kenton Varda's avatar
Kenton Varda committed
161
      targetPath.removeLast();
162
    }
163

Kenton Varda's avatar
Kenton Varda committed
164 165 166
    auto parts = kj::heapArrayBuilder<kj::StringTree>(targetPath.size());
    while (!targetPath.empty()) {
      auto part = targetPath.back();
167
      auto proto = part.getProto();
Kenton Varda's avatar
Kenton Varda committed
168
      kj::StringTree partStr;
169
      if (proto.getScopeId() == 0) {
Kenton Varda's avatar
Kenton Varda committed
170
        partStr = kj::strTree("import \"/", proto.getDisplayName(), '\"');
171
      } else {
Kenton Varda's avatar
Kenton Varda committed
172 173 174 175 176 177 178
        partStr = kj::strTree(getUnqualifiedName(part));
      }

      auto iter = scopeBindings.find(proto.getId());
      if (iter != scopeBindings.end()) {
        auto bindings = KJ_MAP(binding, iter->second) {
          switch (binding.which()) {
179
            case schema::Brand::Binding::UNBOUND:
Kenton Varda's avatar
Kenton Varda committed
180
              return kj::strTree("AnyPointer");
181
            case schema::Brand::Binding::TYPE:
182
              return genType(binding.getType(), scope, method);
Kenton Varda's avatar
Kenton Varda committed
183 184 185 186
          }
          return kj::strTree("<unknown binding>");
        };
        partStr = kj::strTree(kj::mv(partStr), "(", kj::StringTree(kj::mv(bindings), ", "), ")");
187
      }
Kenton Varda's avatar
Kenton Varda committed
188 189 190

      parts.add(kj::mv(partStr));
      targetPath.removeLast();
191 192
    }

Kenton Varda's avatar
Kenton Varda committed
193
    return kj::StringTree(parts.finish(), ".");
194 195
  }

196 197
  kj::StringTree genType(schema::Type::Reader type, Schema scope,
                         kj::Maybe<InterfaceSchema::Method> method) {
Kenton Varda's avatar
Kenton Varda committed
198
    switch (type.which()) {
Kenton Varda's avatar
Kenton Varda committed
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
      case schema::Type::VOID: return kj::strTree("Void");
      case schema::Type::BOOL: return kj::strTree("Bool");
      case schema::Type::INT8: return kj::strTree("Int8");
      case schema::Type::INT16: return kj::strTree("Int16");
      case schema::Type::INT32: return kj::strTree("Int32");
      case schema::Type::INT64: return kj::strTree("Int64");
      case schema::Type::UINT8: return kj::strTree("UInt8");
      case schema::Type::UINT16: return kj::strTree("UInt16");
      case schema::Type::UINT32: return kj::strTree("UInt32");
      case schema::Type::UINT64: return kj::strTree("UInt64");
      case schema::Type::FLOAT32: return kj::strTree("Float32");
      case schema::Type::FLOAT64: return kj::strTree("Float64");
      case schema::Type::TEXT: return kj::strTree("Text");
      case schema::Type::DATA: return kj::strTree("Data");
      case schema::Type::LIST:
214
        return kj::strTree("List(", genType(type.getList().getElementType(), scope, method), ")");
Kenton Varda's avatar
Kenton Varda committed
215
      case schema::Type::ENUM:
Kenton Varda's avatar
Kenton Varda committed
216
        return nodeName(schemaLoader.get(type.getEnum().getTypeId()), scope,
217
                        type.getEnum().getBrand(), method);
Kenton Varda's avatar
Kenton Varda committed
218
      case schema::Type::STRUCT:
Kenton Varda's avatar
Kenton Varda committed
219
        return nodeName(schemaLoader.get(type.getStruct().getTypeId()), scope,
220
                        type.getStruct().getBrand(), method);
Kenton Varda's avatar
Kenton Varda committed
221
      case schema::Type::INTERFACE:
Kenton Varda's avatar
Kenton Varda committed
222
        return nodeName(schemaLoader.get(type.getInterface().getTypeId()), scope,
223
                        type.getInterface().getBrand(), method);
Kenton Varda's avatar
Kenton Varda committed
224 225 226 227 228 229 230 231
      case schema::Type::ANY_POINTER: {
        auto anyPointer = type.getAnyPointer();
        switch (anyPointer.which()) {
          case schema::Type::AnyPointer::UNCONSTRAINED:
            return kj::strTree("AnyPointer");
          case schema::Type::AnyPointer::PARAMETER: {
            auto param = anyPointer.getParameter();
            auto scopeProto = scope.getProto();
232
            auto targetScopeId = param.getScopeId();
Kenton Varda's avatar
Kenton Varda committed
233
            while (scopeProto.getId() != targetScopeId) {
234
              scopeProto = schemaLoader.get(param.getScopeId()).getProto();
Kenton Varda's avatar
Kenton Varda committed
235 236 237 238 239
            }
            auto params = scopeProto.getParameters();
            KJ_REQUIRE(param.getParameterIndex() < params.size());
            return kj::strTree(params[param.getParameterIndex()].getName());
          }
240 241 242 243 244 245
          case schema::Type::AnyPointer::IMPLICIT_METHOD_PARAMETER: {
            auto params = KJ_REQUIRE_NONNULL(method).getProto().getImplicitParameters();
            uint index = anyPointer.getImplicitMethodParameter().getParameterIndex();
            KJ_REQUIRE(index < params.size());
            return kj::strTree(params[index].getName());
          }
Kenton Varda's avatar
Kenton Varda committed
246 247 248
        }
        KJ_UNREACHABLE;
      }
249 250
    }
    return kj::strTree();
251 252
  }

Kenton Varda's avatar
Kenton Varda committed
253
  int typeSizeBits(schema::Type::Reader type) {
Kenton Varda's avatar
Kenton Varda committed
254
    switch (type.which()) {
Kenton Varda's avatar
Kenton Varda committed
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
      case schema::Type::VOID: return 0;
      case schema::Type::BOOL: return 1;
      case schema::Type::INT8: return 8;
      case schema::Type::INT16: return 16;
      case schema::Type::INT32: return 32;
      case schema::Type::INT64: return 64;
      case schema::Type::UINT8: return 8;
      case schema::Type::UINT16: return 16;
      case schema::Type::UINT32: return 32;
      case schema::Type::UINT64: return 64;
      case schema::Type::FLOAT32: return 32;
      case schema::Type::FLOAT64: return 64;
      case schema::Type::TEXT: return -1;
      case schema::Type::DATA: return -1;
      case schema::Type::LIST: return -1;
      case schema::Type::ENUM: return 16;
      case schema::Type::STRUCT: return -1;
      case schema::Type::INTERFACE: return -1;
273
      case schema::Type::ANY_POINTER: return -1;
274 275
    }
    return 0;
276 277
  }

Kenton Varda's avatar
Kenton Varda committed
278
  bool isEmptyValue(schema::Value::Reader value) {
Kenton Varda's avatar
Kenton Varda committed
279
    switch (value.which()) {
Kenton Varda's avatar
Kenton Varda committed
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
      case schema::Value::VOID: return true;
      case schema::Value::BOOL: return value.getBool() == false;
      case schema::Value::INT8: return value.getInt8() == 0;
      case schema::Value::INT16: return value.getInt16() == 0;
      case schema::Value::INT32: return value.getInt32() == 0;
      case schema::Value::INT64: return value.getInt64() == 0;
      case schema::Value::UINT8: return value.getUint8() == 0;
      case schema::Value::UINT16: return value.getUint16() == 0;
      case schema::Value::UINT32: return value.getUint32() == 0;
      case schema::Value::UINT64: return value.getUint64() == 0;
      case schema::Value::FLOAT32: return value.getFloat32() == 0;
      case schema::Value::FLOAT64: return value.getFloat64() == 0;
      case schema::Value::TEXT: return !value.hasText();
      case schema::Value::DATA: return !value.hasData();
      case schema::Value::LIST: return !value.hasList();
      case schema::Value::ENUM: return value.getEnum() == 0;
      case schema::Value::STRUCT: return !value.hasStruct();
      case schema::Value::INTERFACE: return true;
298
      case schema::Value::ANY_POINTER: return true;
299
    }
300
    return true;
301 302
  }

303
  kj::StringTree genValue(Type type, schema::Value::Reader value) {
Kenton Varda's avatar
Kenton Varda committed
304
    switch (value.which()) {
Kenton Varda's avatar
Kenton Varda committed
305 306
      case schema::Value::VOID: return kj::strTree("void");
      case schema::Value::BOOL:
Kenton Varda's avatar
Kenton Varda committed
307
        return kj::strTree(value.getBool() ? "true" : "false");
Kenton Varda's avatar
Kenton Varda committed
308 309 310 311 312 313 314 315 316 317 318
      case schema::Value::INT8: return kj::strTree((int)value.getInt8());
      case schema::Value::INT16: return kj::strTree(value.getInt16());
      case schema::Value::INT32: return kj::strTree(value.getInt32());
      case schema::Value::INT64: return kj::strTree(value.getInt64());
      case schema::Value::UINT8: return kj::strTree((uint)value.getUint8());
      case schema::Value::UINT16: return kj::strTree(value.getUint16());
      case schema::Value::UINT32: return kj::strTree(value.getUint32());
      case schema::Value::UINT64: return kj::strTree(value.getUint64());
      case schema::Value::FLOAT32: return kj::strTree(value.getFloat32());
      case schema::Value::FLOAT64: return kj::strTree(value.getFloat64());
      case schema::Value::TEXT:
Kenton Varda's avatar
Kenton Varda committed
319
        return kj::strTree(DynamicValue::Reader(value.getText()));
Kenton Varda's avatar
Kenton Varda committed
320
      case schema::Value::DATA:
Kenton Varda's avatar
Kenton Varda committed
321
        return kj::strTree(DynamicValue::Reader(value.getData()));
Kenton Varda's avatar
Kenton Varda committed
322
      case schema::Value::LIST: {
323
        auto listValue = value.getList().getAs<DynamicList>(type.asList());
Kenton Varda's avatar
Kenton Varda committed
324
        return kj::strTree(listValue);
325
      }
Kenton Varda's avatar
Kenton Varda committed
326
      case schema::Value::ENUM: {
327
        auto enumNode = type.asEnum().getProto();
328
        auto enumerants = enumNode.getEnum().getEnumerants();
Kenton Varda's avatar
Kenton Varda committed
329 330 331
        KJ_REQUIRE(value.getEnum() < enumerants.size(),
                "Enum value out-of-range.", value.getEnum(), enumNode.getDisplayName());
        return kj::strTree(enumerants[value.getEnum()].getName());
332
      }
Kenton Varda's avatar
Kenton Varda committed
333
      case schema::Value::STRUCT: {
334 335
        KJ_REQUIRE(type.which() == schema::Type::STRUCT, "type/value mismatch");
        auto structValue = value.getStruct().getAs<DynamicStruct>(type.asStruct());
Kenton Varda's avatar
Kenton Varda committed
336
        return kj::strTree(structValue);
337
      }
Kenton Varda's avatar
Kenton Varda committed
338
      case schema::Value::INTERFACE: {
339 340
        return kj::strTree("");
      }
341
      case schema::Value::ANY_POINTER: {
342 343 344 345 346
        return kj::strTree("");
      }
    }
    return kj::strTree("");
  }
347

Kenton Varda's avatar
Kenton Varda committed
348 349 350 351 352 353 354 355 356 357 358 359 360
  kj::StringTree genGenericParams(List<schema::Node::Parameter>::Reader params, Schema scope) {
    if (params.size() == 0) {
      return kj::strTree();
    }

    return kj::strTree(" (", kj::StringTree(
        KJ_MAP(param, params) { return kj::strTree(param.getName()); }, ", "), ')');
  }
  kj::StringTree genGenericParams(Schema schema) {
    auto proto = schema.getProto();
    return genGenericParams(proto.getParameters(), schemaLoader.get(proto.getScopeId()));
  }

Kenton Varda's avatar
Kenton Varda committed
361
  kj::StringTree genAnnotation(schema::Annotation::Reader annotation,
362 363
                               Schema scope,
                               const char* prefix = " ", const char* suffix = "") {
364
    auto decl = schemaLoader.get(annotation.getId(), annotation.getBrand(), scope);
Kenton Varda's avatar
Kenton Varda committed
365
    auto proto = decl.getProto();
366
    KJ_REQUIRE(proto.isAnnotation());
Kenton Varda's avatar
Kenton Varda committed
367
    auto annDecl = proto.getAnnotation();
368

369 370
    auto value = genValue(schemaLoader.getType(annDecl.getType(), decl),
                          annotation.getValue()).flatten();
371
    if (value.startsWith("(")) {
372
      return kj::strTree(prefix, "$", nodeName(decl, scope, annotation.getBrand(), nullptr),
Kenton Varda's avatar
Kenton Varda committed
373
                         value, suffix);
374
    } else {
375
      return kj::strTree(prefix, "$", nodeName(decl, scope, annotation.getBrand(), nullptr),
Kenton Varda's avatar
Kenton Varda committed
376
                         "(", value, ")", suffix);
377
    }
378
  }
379

Kenton Varda's avatar
Kenton Varda committed
380
  kj::StringTree genAnnotations(List<schema::Annotation>::Reader list, Schema scope) {
381
    return kj::strTree(KJ_MAP(ann, list) { return genAnnotation(ann, scope); });
382 383 384 385
  }
  kj::StringTree genAnnotations(Schema schema) {
    auto proto = schema.getProto();
    return genAnnotations(proto.getAnnotations(), schemaLoader.get(proto.getScopeId()));
386 387
  }

Kenton Varda's avatar
Kenton Varda committed
388
  const char* elementSizeName(schema::ElementSize size) {
389
    switch (size) {
Kenton Varda's avatar
Kenton Varda committed
390 391 392 393 394 395 396 397
      case schema::ElementSize::EMPTY: return "void";
      case schema::ElementSize::BIT: return "1-bit";
      case schema::ElementSize::BYTE: return "8-bit";
      case schema::ElementSize::TWO_BYTES: return "16-bit";
      case schema::ElementSize::FOUR_BYTES: return "32-bit";
      case schema::ElementSize::EIGHT_BYTES: return "64-bit";
      case schema::ElementSize::POINTER: return "pointer";
      case schema::ElementSize::INLINE_COMPOSITE: return "inline composite";
398
    }
399
    return "";
400 401
  }

Kenton Varda's avatar
Kenton Varda committed
402 403 404 405 406 407 408 409 410
  struct OrderByCodeOrder {
    template <typename T>
    inline bool operator()(const T& a, const T& b) const {
      return a.getProto().getCodeOrder() < b.getProto().getCodeOrder();
    }
  };

  template <typename MemberList>
  kj::Array<decltype(kj::instance<MemberList>()[0])> sortByCodeOrder(MemberList&& list) {
411
    auto sorted = KJ_MAP(item, list) { return item; };
Kenton Varda's avatar
Kenton Varda committed
412 413 414 415 416 417 418 419 420 421 422
    std::sort(sorted.begin(), sorted.end(), OrderByCodeOrder());
    return kj::mv(sorted);
  }

  kj::Array<kj::StringTree> genStructFields(StructSchema schema, Indent indent) {
    // Slightly hacky:  We want to print in code order, but we also need to print the union in one
    //   chunk.  Its fields should be together in code order anyway, but it's easier to simply
    //   output the whole union in place of the first union field, and then output nothing for the
    //   subsequent fields.

    bool seenUnion = false;
423
    return KJ_MAP(field, sortByCodeOrder(schema.getFields())) {
424
      if (hasDiscriminantValue(field.getProto())) {
Kenton Varda's avatar
Kenton Varda committed
425 426 427 428 429
        if (seenUnion) {
          return kj::strTree();
        } else {
          seenUnion = true;
          uint offset = schema.getProto().getStruct().getDiscriminantOffset();
Kenton Varda's avatar
Kenton Varda committed
430 431 432

          // GCC 4.7.3 crashes if you inline unionFields.
          auto unionFields = sortByCodeOrder(schema.getUnionFields());
Kenton Varda's avatar
Kenton Varda committed
433 434
          return kj::strTree(
              indent, "union {  # tag bits [", offset * 16, ", ", offset * 16 + 16, ")\n",
435
              KJ_MAP(uField, unionFields) {
436
                return genStructField(uField, schema, indent.next());
Kenton Varda's avatar
Kenton Varda committed
437 438 439 440
              },
              indent, "}\n");
        }
      } else {
441
        return genStructField(field, schema, indent);
442
      }
Kenton Varda's avatar
Kenton Varda committed
443 444 445
    };
  }

446 447 448
  kj::StringTree genStructField(StructSchema::Field field, Schema scope, Indent indent) {
    auto proto = field.getProto();
    switch (proto.which()) {
449
      case schema::Field::SLOT: {
450
        auto slot = proto.getSlot();
451
        int size = typeSizeBits(slot.getType());
452
        return kj::strTree(
453
            indent, proto.getName(), " @", proto.getOrdinal().getExplicit(),
454
            " :", genType(slot.getType(), scope, nullptr),
455
            isEmptyValue(slot.getDefaultValue()) ? kj::strTree("") :
456 457
                kj::strTree(" = ", genValue(field.getType(), slot.getDefaultValue())),
            genAnnotations(proto.getAnnotations(), scope),
458 459 460
            ";  # ", size == -1 ? kj::strTree("ptr[", slot.getOffset(), "]")
                                : kj::strTree("bits[", slot.getOffset() * size, ", ",
                                              (slot.getOffset() + 1) * size, ")"),
461 462
            hasDiscriminantValue(proto)
                ? kj::strTree(", union tag = ", proto.getDiscriminantValue()) : kj::strTree(),
Kenton Varda's avatar
Kenton Varda committed
463
            "\n");
464
      }
Kenton Varda's avatar
Kenton Varda committed
465
      case schema::Field::GROUP: {
466
        auto group = field.getType().asStruct();
467
        return kj::strTree(
468 469 470 471
            indent, proto.getName(),
            " :group", genAnnotations(proto.getAnnotations(), scope), " {",
            hasDiscriminantValue(proto)
                ? kj::strTree("  # union tag = ", proto.getDiscriminantValue()) : kj::strTree(),
Kenton Varda's avatar
Kenton Varda committed
472 473
            "\n",
            genStructFields(group, indent.next()),
474 475 476 477
            indent, "}\n");
      }
    }
    return kj::strTree();
478 479
  }

Kenton Varda's avatar
Kenton Varda committed
480
  kj::StringTree genParamList(InterfaceSchema interface, StructSchema schema,
481
                              schema::Brand::Reader brand, InterfaceSchema::Method method) {
482 483 484 485 486 487 488 489
    if (schema.getProto().getScopeId() == 0) {
      // A named parameter list.
      return kj::strTree("(", kj::StringTree(
          KJ_MAP(field, schema.getFields()) {
            auto proto = field.getProto();
            auto slot = proto.getSlot();

            return kj::strTree(
490
                proto.getName(), " :", genType(slot.getType(), interface, nullptr),
491
                isEmptyValue(slot.getDefaultValue()) ? kj::strTree("") :
492
                    kj::strTree(" = ", genValue(field.getType(), slot.getDefaultValue())),
493
                genAnnotations(proto.getAnnotations(), interface));
494 495
          }, ", "), ")");
    } else {
496
      return nodeName(schema, interface, brand, method);
497 498 499
    }
  }

500 501 502
  kj::StringTree genSuperclasses(InterfaceSchema interface) {
    auto superclasses = interface.getProto().getInterface().getSuperclasses();
    if (superclasses.size() == 0) {
503
      return kj::strTree();
Kenton Varda's avatar
Kenton Varda committed
504
    } else {
505 506
      return kj::strTree(" superclasses(", kj::StringTree(
          KJ_MAP(superclass, superclasses) {
507 508
            return nodeName(schemaLoader.get(superclass.getId()), interface,
                            superclass.getBrand(), nullptr);
509
          }, ", "), ")");
Kenton Varda's avatar
Kenton Varda committed
510
    }
511 512
  }

513 514 515 516 517
  kj::StringTree genDecl(Schema schema, Text::Reader name, uint64_t scopeId, Indent indent) {
    auto proto = schema.getProto();
    if (proto.getScopeId() != scopeId) {
      // This appears to be an alias for something declared elsewhere.
      KJ_FAIL_REQUIRE("Aliases not implemented.");
518
    }
519

Kenton Varda's avatar
Kenton Varda committed
520
    switch (proto.which()) {
Kenton Varda's avatar
Kenton Varda committed
521
      case schema::Node::FILE:
522 523
        KJ_FAIL_REQUIRE("Encountered nested file node.");
        break;
Kenton Varda's avatar
Kenton Varda committed
524
      case schema::Node::STRUCT: {
Kenton Varda's avatar
Kenton Varda committed
525
        auto structProto = proto.getStruct();
526 527
        return kj::strTree(
            indent, "struct ", name,
Kenton Varda's avatar
Kenton Varda committed
528 529
            " @0x", kj::hex(proto.getId()), genGenericParams(schema),
            genAnnotations(schema), " {  # ",
530 531
            structProto.getDataWordCount() * 8, " bytes, ",
            structProto.getPointerCount(), " ptrs",
Kenton Varda's avatar
Kenton Varda committed
532
            structProto.getPreferredListEncoding() == schema::ElementSize::INLINE_COMPOSITE
533
                ? kj::strTree()
534 535
                : kj::strTree(", packed as ",
                              elementSizeName(structProto.getPreferredListEncoding())),
536
            "\n",
Kenton Varda's avatar
Kenton Varda committed
537
            genStructFields(schema.asStruct(), indent.next()),
538 539 540
            genNestedDecls(schema, indent.next()),
            indent, "}\n");
      }
Kenton Varda's avatar
Kenton Varda committed
541
      case schema::Node::ENUM: {
542 543
        return kj::strTree(
            indent, "enum ", name, " @0x", kj::hex(proto.getId()), genAnnotations(schema), " {\n",
544
            KJ_MAP(enumerant, sortByCodeOrder(schema.asEnum().getEnumerants())) {
Kenton Varda's avatar
Kenton Varda committed
545 546 547 548
              return kj::strTree(indent.next(), enumerant.getProto().getName(), " @",
                                 enumerant.getIndex(),
                                 genAnnotations(enumerant.getProto().getAnnotations(), schema),
                                 ";\n");
549 550 551 552
            },
            genNestedDecls(schema, indent.next()),
            indent, "}\n");
      }
Kenton Varda's avatar
Kenton Varda committed
553
      case schema::Node::INTERFACE: {
554
        auto interface = schema.asInterface();
555
        return kj::strTree(
Kenton Varda's avatar
Kenton Varda committed
556
            indent, "interface ", name, " @0x", kj::hex(proto.getId()), genGenericParams(schema),
557
            genSuperclasses(interface),
558
            genAnnotations(schema), " {\n",
559
            KJ_MAP(method, sortByCodeOrder(interface.getMethods())) {
Kenton Varda's avatar
Kenton Varda committed
560
              auto methodProto = method.getProto();
561 562 563 564 565 566 567 568 569 570

              auto implicits = methodProto.getImplicitParameters();
              kj::StringTree implicitsStr;
              if (implicits.size() > 0) {
                implicitsStr = kj::strTree(
                    "[", kj::StringTree(KJ_MAP(implicit, implicits) {
                      return kj::strTree(implicit.getName());
                    }, ", "), "] ");
              }

571 572
              auto params = schemaLoader.get(methodProto.getParamStructType()).asStruct();
              auto results = schemaLoader.get(methodProto.getResultStructType()).asStruct();
573
              return kj::strTree(
574 575 576 577
                  indent.next(), methodProto.getName(),
                  " @", method.getIndex(), " ", kj::mv(implicitsStr),
                  genParamList(interface, params, methodProto.getParamBrand(), method), " -> ",
                  genParamList(interface, results, methodProto.getResultBrand(), method),
578
                  genAnnotations(methodProto.getAnnotations(), interface), ";\n");
579 580 581 582
            },
            genNestedDecls(schema, indent.next()),
            indent, "}\n");
      }
Kenton Varda's avatar
Kenton Varda committed
583
      case schema::Node::CONST: {
Kenton Varda's avatar
Kenton Varda committed
584
        auto constProto = proto.getConst();
585 586
        return kj::strTree(
            indent, "const ", name, " @0x", kj::hex(proto.getId()), " :",
587
            genType(constProto.getType(), schema, nullptr), " = ",
588
            genValue(schema.asConst().getType(), constProto.getValue()),
589
            genAnnotations(schema), ";\n");
590
      }
Kenton Varda's avatar
Kenton Varda committed
591
      case schema::Node::ANNOTATION: {
Kenton Varda's avatar
Kenton Varda committed
592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608
        auto annotationProto = proto.getAnnotation();

        kj::Vector<kj::String> targets(8);
        bool targetsAll = true;

        auto dynamic = toDynamic(annotationProto);
        for (auto field: dynamic.getSchema().getFields()) {
          auto fieldName = field.getProto().getName();
          if (fieldName.startsWith("targets")) {
            if (dynamic.get(field).as<bool>()) {
              auto target = kj::str(fieldName.slice(strlen("targets")));
              target[0] = target[0] - 'A' + 'a';
              targets.add(kj::mv(target));
            } else {
              targetsAll = false;
            }
          }
609
        }
Kenton Varda's avatar
Kenton Varda committed
610 611 612

        if (targetsAll) {
          targets = kj::Vector<kj::String>(1);
Kenton Varda's avatar
Kenton Varda committed
613
          targets.add(kj::heapString("*"));
Kenton Varda's avatar
Kenton Varda committed
614 615
        }

616 617 618
        return kj::strTree(
            indent, "annotation ", name, " @0x", kj::hex(proto.getId()),
            " (", strArray(targets, ", "), ") :",
619
            genType(annotationProto.getType(), schema, nullptr), genAnnotations(schema), ";\n");
620 621
      }
    }
622 623

    return kj::strTree();
624 625
  }

626 627
  kj::StringTree genNestedDecls(Schema schema, Indent indent) {
    uint64_t id = schema.getProto().getId();
628
    return kj::strTree(KJ_MAP(nested, schema.getProto().getNestedNodes()) {
629 630 631
      return genDecl(schemaLoader.get(nested.getId()), nested.getName(), id, indent);
    });
  }
632

633 634
  kj::StringTree genFile(Schema file) {
    auto proto = file.getProto();
635
    KJ_REQUIRE(proto.isFile(), "Expected a file node.", (uint)proto.which());
636 637 638 639

    return kj::strTree(
      "# ", proto.getDisplayName(), "\n",
      "@0x", kj::hex(proto.getId()), ";\n",
640
      KJ_MAP(ann, proto.getAnnotations()) { return genAnnotation(ann, file, "", ";\n"); },
641 642
      genNestedDecls(file, Indent(0)));
  }
643

644 645 646 647
  kj::MainBuilder::Validity run() {
    ReaderOptions options;
    options.traversalLimitInWords = 1 << 30;  // Don't limit.
    StreamFdMessageReader reader(STDIN_FILENO, options);
Kenton Varda's avatar
Kenton Varda committed
648
    auto request = reader.getRoot<schema::CodeGeneratorRequest>();
649

650 651 652
    for (auto node: request.getNodes()) {
      schemaLoader.load(node);
    }
653

654 655
    kj::FdOutputStream rawOut(STDOUT_FILENO);
    kj::BufferedOutputStreamWrapper out(rawOut);
656

Kenton Varda's avatar
Kenton Varda committed
657 658
    for (auto requestedFile: request.getRequestedFiles()) {
      genFile(schemaLoader.get(requestedFile.getId())).visit(
659 660 661 662
          [&](kj::ArrayPtr<const char> text) {
            out.write(text.begin(), text.size());
          });
    }
663

664
    return true;
665
  }
666
};
667 668

}  // namespace
669
}  // namespace capnp
670

671
KJ_MAIN(capnp::CapnpcCapnpMain);