capnpc-capnp.c++ 22.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
// 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.

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

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

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

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

48
namespace capnp {
49 50
namespace {

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

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

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

85 86
// =======================================================================================

87 88 89 90 91 92 93 94 95 96 97 98 99
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();
  }
100

101 102 103 104 105 106 107 108 109 110 111 112
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();
      }
113
    }
114 115
    KJ_FAIL_REQUIRE("A schema Node's supposed scope did not contain the node as a NestedNode.");
    return "(?)";
116 117
  }

118 119 120
  kj::StringTree nodeName(Schema target, Schema scope) {
    kj::Vector<Schema> targetParents;
    kj::Vector<Schema> scopeParts;
121

122 123 124 125 126 127
    {
      Schema parent = target;
      while (parent.getProto().getScopeId() != 0) {
        parent = schemaLoader.get(parent.getProto().getScopeId());
        targetParents.add(parent);
      }
128 129
    }

130 131 132 133 134 135 136
    {
      Schema parent = scope;
      scopeParts.add(parent);
      while (parent.getProto().getScopeId() != 0) {
        parent = schemaLoader.get(parent.getProto().getScopeId());
        scopeParts.add(parent);
      }
137 138
    }

139 140 141 142 143 144
    // Remove common scope.
    while (!scopeParts.empty() && !targetParents.empty() &&
           scopeParts.back() == targetParents.back()) {
      scopeParts.removeLast();
      targetParents.removeLast();
    }
145

146
    // TODO(someday):  This is broken in that we aren't checking for shadowing.
147

148 149 150 151 152 153 154 155 156 157
    kj::StringTree path = kj::strTree();
    while (!targetParents.empty()) {
      auto part = targetParents.back();
      auto proto = part.getProto();
      if (proto.getScopeId() == 0) {
        path = kj::strTree(kj::mv(path), "import \"/", proto.getDisplayName(), "\".");
      } else {
        path = kj::strTree(kj::mv(path), getUnqualifiedName(part), ".");
      }
      targetParents.removeLast();
158 159
    }

160
    return kj::strTree(kj::mv(path), getUnqualifiedName(target));
161 162
  }

Kenton Varda's avatar
Kenton Varda committed
163
  kj::StringTree genType(schema::Type::Reader type, Schema scope) {
Kenton Varda's avatar
Kenton Varda committed
164
    switch (type.which()) {
Kenton Varda's avatar
Kenton Varda committed
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
      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:
180
        return kj::strTree("List(", genType(type.getList().getElementType(), scope), ")");
Kenton Varda's avatar
Kenton Varda committed
181
      case schema::Type::ENUM:
182
        return nodeName(schemaLoader.get(type.getEnum().getTypeId()), scope);
Kenton Varda's avatar
Kenton Varda committed
183
      case schema::Type::STRUCT:
184
        return nodeName(schemaLoader.get(type.getStruct().getTypeId()), scope);
Kenton Varda's avatar
Kenton Varda committed
185
      case schema::Type::INTERFACE:
186
        return nodeName(schemaLoader.get(type.getInterface().getTypeId()), scope);
187
      case schema::Type::ANY_POINTER: return kj::strTree("AnyPointer");
188 189
    }
    return kj::strTree();
190 191
  }

Kenton Varda's avatar
Kenton Varda committed
192
  int typeSizeBits(schema::Type::Reader type) {
Kenton Varda's avatar
Kenton Varda committed
193
    switch (type.which()) {
Kenton Varda's avatar
Kenton Varda committed
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
      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;
212
      case schema::Type::ANY_POINTER: return -1;
213 214
    }
    return 0;
215 216
  }

Kenton Varda's avatar
Kenton Varda committed
217
  bool isEmptyValue(schema::Value::Reader value) {
Kenton Varda's avatar
Kenton Varda committed
218
    switch (value.which()) {
Kenton Varda's avatar
Kenton Varda committed
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
      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;
237
      case schema::Value::ANY_POINTER: return true;
238
    }
239
    return true;
240 241
  }

Kenton Varda's avatar
Kenton Varda committed
242
  kj::StringTree genValue(schema::Type::Reader type, schema::Value::Reader value, Schema scope) {
Kenton Varda's avatar
Kenton Varda committed
243
    switch (value.which()) {
Kenton Varda's avatar
Kenton Varda committed
244 245
      case schema::Value::VOID: return kj::strTree("void");
      case schema::Value::BOOL:
Kenton Varda's avatar
Kenton Varda committed
246
        return kj::strTree(value.getBool() ? "true" : "false");
Kenton Varda's avatar
Kenton Varda committed
247 248 249 250 251 252 253 254 255 256 257
      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
258
        return kj::strTree(DynamicValue::Reader(value.getText()));
Kenton Varda's avatar
Kenton Varda committed
259
      case schema::Value::DATA:
Kenton Varda's avatar
Kenton Varda committed
260
        return kj::strTree(DynamicValue::Reader(value.getData()));
Kenton Varda's avatar
Kenton Varda committed
261
      case schema::Value::LIST: {
262
        KJ_REQUIRE(type.isList(), "type/value mismatch");
263
        auto listValue = value.getList().getAs<DynamicList>(
264
            ListSchema::of(type.getList().getElementType(), scope));
Kenton Varda's avatar
Kenton Varda committed
265
        return kj::strTree(listValue);
266
      }
Kenton Varda's avatar
Kenton Varda committed
267
      case schema::Value::ENUM: {
268
        KJ_REQUIRE(type.isEnum(), "type/value mismatch");
269
        auto enumNode = schemaLoader.get(type.getEnum().getTypeId()).asEnum().getProto();
270
        auto enumerants = enumNode.getEnum().getEnumerants();
Kenton Varda's avatar
Kenton Varda committed
271 272 273
        KJ_REQUIRE(value.getEnum() < enumerants.size(),
                "Enum value out-of-range.", value.getEnum(), enumNode.getDisplayName());
        return kj::strTree(enumerants[value.getEnum()].getName());
274
      }
Kenton Varda's avatar
Kenton Varda committed
275
      case schema::Value::STRUCT: {
276
        KJ_REQUIRE(type.isStruct(), "type/value mismatch");
277
        auto structValue = value.getStruct().getAs<DynamicStruct>(
278
            schemaLoader.get(type.getStruct().getTypeId()).asStruct());
Kenton Varda's avatar
Kenton Varda committed
279
        return kj::strTree(structValue);
280
      }
Kenton Varda's avatar
Kenton Varda committed
281
      case schema::Value::INTERFACE: {
282 283
        return kj::strTree("");
      }
284
      case schema::Value::ANY_POINTER: {
285 286 287 288 289
        return kj::strTree("");
      }
    }
    return kj::strTree("");
  }
290

Kenton Varda's avatar
Kenton Varda committed
291
  kj::StringTree genAnnotation(schema::Annotation::Reader annotation,
292 293 294
                               Schema scope,
                               const char* prefix = " ", const char* suffix = "") {
    auto decl = schemaLoader.get(annotation.getId());
Kenton Varda's avatar
Kenton Varda committed
295
    auto proto = decl.getProto();
296
    KJ_REQUIRE(proto.isAnnotation());
Kenton Varda's avatar
Kenton Varda committed
297
    auto annDecl = proto.getAnnotation();
298

299 300 301 302 303 304
    auto value = genValue(annDecl.getType(), annotation.getValue(), decl).flatten();
    if (value.startsWith("(")) {
      return kj::strTree(prefix, "$", nodeName(decl, scope), value, suffix);
    } else {
      return kj::strTree(prefix, "$", nodeName(decl, scope), "(", value, ")", suffix);
    }
305
  }
306

Kenton Varda's avatar
Kenton Varda committed
307
  kj::StringTree genAnnotations(List<schema::Annotation>::Reader list, Schema scope) {
308
    return kj::strTree(KJ_MAP(ann, list) { return genAnnotation(ann, scope); });
309 310 311 312
  }
  kj::StringTree genAnnotations(Schema schema) {
    auto proto = schema.getProto();
    return genAnnotations(proto.getAnnotations(), schemaLoader.get(proto.getScopeId()));
313 314
  }

Kenton Varda's avatar
Kenton Varda committed
315
  const char* elementSizeName(schema::ElementSize size) {
316
    switch (size) {
Kenton Varda's avatar
Kenton Varda committed
317 318 319 320 321 322 323 324
      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";
325
    }
326
    return "";
327 328
  }

Kenton Varda's avatar
Kenton Varda committed
329 330 331 332 333 334 335 336 337
  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) {
338
    auto sorted = KJ_MAP(item, list) { return item; };
Kenton Varda's avatar
Kenton Varda committed
339 340 341 342 343 344 345 346 347 348 349
    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;
350
    return KJ_MAP(field, sortByCodeOrder(schema.getFields())) {
351
      if (hasDiscriminantValue(field.getProto())) {
Kenton Varda's avatar
Kenton Varda committed
352 353 354 355 356
        if (seenUnion) {
          return kj::strTree();
        } else {
          seenUnion = true;
          uint offset = schema.getProto().getStruct().getDiscriminantOffset();
Kenton Varda's avatar
Kenton Varda committed
357 358 359

          // GCC 4.7.3 crashes if you inline unionFields.
          auto unionFields = sortByCodeOrder(schema.getUnionFields());
Kenton Varda's avatar
Kenton Varda committed
360 361
          return kj::strTree(
              indent, "union {  # tag bits [", offset * 16, ", ", offset * 16 + 16, ")\n",
362
              KJ_MAP(uField, unionFields) {
Kenton Varda's avatar
Kenton Varda committed
363 364 365 366 367 368
                return genStructField(uField.getProto(), schema, indent.next());
              },
              indent, "}\n");
        }
      } else {
        return genStructField(field.getProto(), schema, indent);
369
      }
Kenton Varda's avatar
Kenton Varda committed
370 371 372
    };
  }

Kenton Varda's avatar
Kenton Varda committed
373
  kj::StringTree genStructField(schema::Field::Reader field, Schema scope, Indent indent) {
Kenton Varda's avatar
Kenton Varda committed
374
    switch (field.which()) {
375 376 377
      case schema::Field::SLOT: {
        auto slot = field.getSlot();
        int size = typeSizeBits(slot.getType());
378
        return kj::strTree(
Kenton Varda's avatar
Kenton Varda committed
379
            indent, field.getName(), " @", field.getOrdinal().getExplicit(),
380 381
            " :", genType(slot.getType(), scope),
            isEmptyValue(slot.getDefaultValue()) ? kj::strTree("") :
Kenton Varda's avatar
Kenton Varda committed
382
                kj::strTree(" = ", genValue(
383
                    slot.getType(), slot.getDefaultValue(), scope)),
Kenton Varda's avatar
Kenton Varda committed
384
            genAnnotations(field.getAnnotations(), scope),
385 386 387
            ";  # ", size == -1 ? kj::strTree("ptr[", slot.getOffset(), "]")
                                : kj::strTree("bits[", slot.getOffset() * size, ", ",
                                              (slot.getOffset() + 1) * size, ")"),
388
            hasDiscriminantValue(field)
Kenton Varda's avatar
Kenton Varda committed
389 390
                ? kj::strTree(", union tag = ", field.getDiscriminantValue()) : kj::strTree(),
            "\n");
391
      }
Kenton Varda's avatar
Kenton Varda committed
392
      case schema::Field::GROUP: {
393
        auto group = schemaLoader.get(field.getGroup().getTypeId()).asStruct();
394
        return kj::strTree(
Kenton Varda's avatar
Kenton Varda committed
395 396
            indent, field.getName(),
            " :group", genAnnotations(field.getAnnotations(), scope), " {",
397
            hasDiscriminantValue(field)
398
                ? kj::strTree("  # union tag = ", field.getDiscriminantValue()) : kj::strTree(),
Kenton Varda's avatar
Kenton Varda committed
399 400
            "\n",
            genStructFields(group, indent.next()),
401 402 403 404
            indent, "}\n");
      }
    }
    return kj::strTree();
405 406
  }

407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
  kj::StringTree genParamList(InterfaceSchema interface, StructSchema schema) {
    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(
                proto.getName(), " :", genType(slot.getType(), interface),
                isEmptyValue(slot.getDefaultValue()) ? kj::strTree("") :
                    kj::strTree(" = ", genValue(
                        slot.getType(), slot.getDefaultValue(), interface)));
          }, ", "), ")");
    } else {
      return nodeName(schema, interface);
    }
  }

426 427 428 429 430
  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.");
431
    }
432

Kenton Varda's avatar
Kenton Varda committed
433
    switch (proto.which()) {
Kenton Varda's avatar
Kenton Varda committed
434
      case schema::Node::FILE:
435 436
        KJ_FAIL_REQUIRE("Encountered nested file node.");
        break;
Kenton Varda's avatar
Kenton Varda committed
437
      case schema::Node::STRUCT: {
Kenton Varda's avatar
Kenton Varda committed
438
        auto structProto = proto.getStruct();
439 440 441
        return kj::strTree(
            indent, "struct ", name,
            " @0x", kj::hex(proto.getId()), genAnnotations(schema), " {  # ",
442 443
            structProto.getDataWordCount() * 8, " bytes, ",
            structProto.getPointerCount(), " ptrs",
Kenton Varda's avatar
Kenton Varda committed
444
            structProto.getPreferredListEncoding() == schema::ElementSize::INLINE_COMPOSITE
445
                ? kj::strTree()
Kenton Varda's avatar
Kenton Varda committed
446
                : kj::strTree(", packed as ", elementSizeName(structProto.getPreferredListEncoding())),
447
            "\n",
Kenton Varda's avatar
Kenton Varda committed
448
            genStructFields(schema.asStruct(), indent.next()),
449 450 451
            genNestedDecls(schema, indent.next()),
            indent, "}\n");
      }
Kenton Varda's avatar
Kenton Varda committed
452
      case schema::Node::ENUM: {
453 454
        return kj::strTree(
            indent, "enum ", name, " @0x", kj::hex(proto.getId()), genAnnotations(schema), " {\n",
455
            KJ_MAP(enumerant, sortByCodeOrder(schema.asEnum().getEnumerants())) {
Kenton Varda's avatar
Kenton Varda committed
456 457 458 459
              return kj::strTree(indent.next(), enumerant.getProto().getName(), " @",
                                 enumerant.getIndex(),
                                 genAnnotations(enumerant.getProto().getAnnotations(), schema),
                                 ";\n");
460 461 462 463
            },
            genNestedDecls(schema, indent.next()),
            indent, "}\n");
      }
Kenton Varda's avatar
Kenton Varda committed
464
      case schema::Node::INTERFACE: {
465
        auto interface = schema.asInterface();
466 467 468
        return kj::strTree(
            indent, "interface ", name, " @0x", kj::hex(proto.getId()),
            genAnnotations(schema), " {\n",
469
            KJ_MAP(method, sortByCodeOrder(interface.getMethods())) {
Kenton Varda's avatar
Kenton Varda committed
470
              auto methodProto = method.getProto();
471 472
              auto params = schemaLoader.get(methodProto.getParamStructType()).asStruct();
              auto results = schemaLoader.get(methodProto.getResultStructType()).asStruct();
473
              return kj::strTree(
474 475
                  indent.next(), methodProto.getName(), " @", method.getIndex(), " ",
                  genParamList(interface, params), " -> ", genParamList(interface, results), ";\n");
476 477 478 479
            },
            genNestedDecls(schema, indent.next()),
            indent, "}\n");
      }
Kenton Varda's avatar
Kenton Varda committed
480
      case schema::Node::CONST: {
Kenton Varda's avatar
Kenton Varda committed
481
        auto constProto = proto.getConst();
482 483
        return kj::strTree(
            indent, "const ", name, " @0x", kj::hex(proto.getId()), " :",
Kenton Varda's avatar
Kenton Varda committed
484 485
            genType(constProto.getType(), schema), " = ",
            genValue(constProto.getType(), constProto.getValue(), schema), ";\n");
486
      }
Kenton Varda's avatar
Kenton Varda committed
487
      case schema::Node::ANNOTATION: {
Kenton Varda's avatar
Kenton Varda committed
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
        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;
            }
          }
505
        }
Kenton Varda's avatar
Kenton Varda committed
506 507 508

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

512 513 514
        return kj::strTree(
            indent, "annotation ", name, " @0x", kj::hex(proto.getId()),
            " (", strArray(targets, ", "), ") :",
Kenton Varda's avatar
Kenton Varda committed
515
            genType(annotationProto.getType(), schema), genAnnotations(schema), ";\n");
516 517
      }
    }
518 519

    return kj::strTree();
520 521
  }

522 523
  kj::StringTree genNestedDecls(Schema schema, Indent indent) {
    uint64_t id = schema.getProto().getId();
524
    return kj::strTree(KJ_MAP(nested, schema.getProto().getNestedNodes()) {
525 526 527
      return genDecl(schemaLoader.get(nested.getId()), nested.getName(), id, indent);
    });
  }
528

529 530
  kj::StringTree genFile(Schema file) {
    auto proto = file.getProto();
531
    KJ_REQUIRE(proto.isFile(), "Expected a file node.", (uint)proto.which());
532 533 534 535

    return kj::strTree(
      "# ", proto.getDisplayName(), "\n",
      "@0x", kj::hex(proto.getId()), ";\n",
536
      KJ_MAP(ann, proto.getAnnotations()) { return genAnnotation(ann, file, "", ";\n"); },
537 538
      genNestedDecls(file, Indent(0)));
  }
539

540 541 542 543
  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
544
    auto request = reader.getRoot<schema::CodeGeneratorRequest>();
545

546 547 548
    for (auto node: request.getNodes()) {
      schemaLoader.load(node);
    }
549

550 551
    kj::FdOutputStream rawOut(STDOUT_FILENO);
    kj::BufferedOutputStreamWrapper out(rawOut);
552

Kenton Varda's avatar
Kenton Varda committed
553 554
    for (auto requestedFile: request.getRequestedFiles()) {
      genFile(schemaLoader.get(requestedFile.getId())).visit(
555 556 557 558
          [&](kj::ArrayPtr<const char> text) {
            out.write(text.begin(), text.size());
          });
    }
559

560
    return true;
561
  }
562
};
563 564

}  // namespace
565
}  // namespace capnp
566

567
KJ_MAIN(capnp::CapnpcCapnpMain);