capnpc-capnp.c++ 27.2 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
#ifndef _GNU_SOURCE
Ivan Shynkarenka's avatar
Ivan Shynkarenka committed
26 27 28
#define _GNU_SOURCE
#endif

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

#if HAVE_CONFIG_H
#include "config.h"
Kenton Varda's avatar
Kenton Varda committed
45 46 47 48
#endif

#ifndef VERSION
#define VERSION "(unknown)"
49
#endif
50

51
namespace capnp {
52 53
namespace {

54 55 56 57
bool hasDiscriminantValue(const schema::Field::Reader& reader) {
  return reader.getDiscriminantValue() != schema::Field::NO_DISCRIMINANT;
}

58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
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); }
};

84 85 86 87
inline Indent KJ_STRINGIFY(const Indent& indent) {
  return indent;
}

88 89
// =======================================================================================

90 91 92 93 94 95 96 97 98 99 100 101 102
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();
  }
103

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

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

Kenton Varda's avatar
Kenton Varda committed
126 127
    targetPath.add(target);

128 129 130 131 132
    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();
133
          break;
134
        case schema::Brand::Scope::INHERIT:
135 136 137 138 139
          // 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
140 141
    }

142 143 144 145
    {
      Schema parent = target;
      while (parent.getProto().getScopeId() != 0) {
        parent = schemaLoader.get(parent.getProto().getScopeId());
Kenton Varda's avatar
Kenton Varda committed
146
        targetPath.add(parent);
147
      }
148 149
    }

150 151 152 153 154 155 156
    {
      Schema parent = scope;
      scopeParts.add(parent);
      while (parent.getProto().getScopeId() != 0) {
        parent = schemaLoader.get(parent.getProto().getScopeId());
        scopeParts.add(parent);
      }
157 158
    }

Kenton Varda's avatar
Kenton Varda committed
159 160 161 162 163
    // 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) {
164
      scopeParts.removeLast();
Kenton Varda's avatar
Kenton Varda committed
165
      targetPath.removeLast();
166
    }
167

Kenton Varda's avatar
Kenton Varda committed
168 169 170
    auto parts = kj::heapArrayBuilder<kj::StringTree>(targetPath.size());
    while (!targetPath.empty()) {
      auto part = targetPath.back();
171
      auto proto = part.getProto();
Kenton Varda's avatar
Kenton Varda committed
172
      kj::StringTree partStr;
173
      if (proto.getScopeId() == 0) {
Kenton Varda's avatar
Kenton Varda committed
174
        partStr = kj::strTree("import \"/", proto.getDisplayName(), '\"');
175
      } else {
Kenton Varda's avatar
Kenton Varda committed
176 177 178 179 180 181 182
        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()) {
183
            case schema::Brand::Binding::UNBOUND:
Kenton Varda's avatar
Kenton Varda committed
184
              return kj::strTree("AnyPointer");
185
            case schema::Brand::Binding::TYPE:
186
              return genType(binding.getType(), scope, method);
Kenton Varda's avatar
Kenton Varda committed
187 188 189 190
          }
          return kj::strTree("<unknown binding>");
        };
        partStr = kj::strTree(kj::mv(partStr), "(", kj::StringTree(kj::mv(bindings), ", "), ")");
191
      }
Kenton Varda's avatar
Kenton Varda committed
192 193 194

      parts.add(kj::mv(partStr));
      targetPath.removeLast();
195 196
    }

Kenton Varda's avatar
Kenton Varda committed
197
    return kj::StringTree(parts.finish(), ".");
198 199
  }

200 201
  kj::StringTree genType(schema::Type::Reader type, Schema scope,
                         kj::Maybe<InterfaceSchema::Method> method) {
Kenton Varda's avatar
Kenton Varda committed
202
    switch (type.which()) {
Kenton Varda's avatar
Kenton Varda committed
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
      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:
218
        return kj::strTree("List(", genType(type.getList().getElementType(), scope, method), ")");
Kenton Varda's avatar
Kenton Varda committed
219
      case schema::Type::ENUM:
Kenton Varda's avatar
Kenton Varda committed
220
        return nodeName(schemaLoader.get(type.getEnum().getTypeId()), scope,
221
                        type.getEnum().getBrand(), method);
Kenton Varda's avatar
Kenton Varda committed
222
      case schema::Type::STRUCT:
Kenton Varda's avatar
Kenton Varda committed
223
        return nodeName(schemaLoader.get(type.getStruct().getTypeId()), scope,
224
                        type.getStruct().getBrand(), method);
Kenton Varda's avatar
Kenton Varda committed
225
      case schema::Type::INTERFACE:
Kenton Varda's avatar
Kenton Varda committed
226
        return nodeName(schemaLoader.get(type.getInterface().getTypeId()), scope,
227
                        type.getInterface().getBrand(), method);
Kenton Varda's avatar
Kenton Varda committed
228 229 230 231
      case schema::Type::ANY_POINTER: {
        auto anyPointer = type.getAnyPointer();
        switch (anyPointer.which()) {
          case schema::Type::AnyPointer::UNCONSTRAINED:
232 233 234 235 236 237 238 239 240 241 242
            switch (anyPointer.getUnconstrained().which()) {
              case schema::Type::AnyPointer::Unconstrained::ANY_KIND:
                return kj::strTree("AnyPointer");
              case schema::Type::AnyPointer::Unconstrained::STRUCT:
                return kj::strTree("AnyStruct");
              case schema::Type::AnyPointer::Unconstrained::LIST:
                return kj::strTree("AnyList");
              case schema::Type::AnyPointer::Unconstrained::CAPABILITY:
                return kj::strTree("Capability");
            }
            KJ_UNREACHABLE;
Kenton Varda's avatar
Kenton Varda committed
243 244 245
          case schema::Type::AnyPointer::PARAMETER: {
            auto param = anyPointer.getParameter();
            auto scopeProto = scope.getProto();
246
            auto targetScopeId = param.getScopeId();
Kenton Varda's avatar
Kenton Varda committed
247
            while (scopeProto.getId() != targetScopeId) {
248
              scopeProto = schemaLoader.get(param.getScopeId()).getProto();
Kenton Varda's avatar
Kenton Varda committed
249 250 251 252 253
            }
            auto params = scopeProto.getParameters();
            KJ_REQUIRE(param.getParameterIndex() < params.size());
            return kj::strTree(params[param.getParameterIndex()].getName());
          }
254 255 256 257 258 259
          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
260 261 262
        }
        KJ_UNREACHABLE;
      }
263 264
    }
    return kj::strTree();
265 266
  }

Kenton Varda's avatar
Kenton Varda committed
267
  int typeSizeBits(schema::Type::Reader type) {
Kenton Varda's avatar
Kenton Varda committed
268
    switch (type.which()) {
Kenton Varda's avatar
Kenton Varda committed
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
      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;
287
      case schema::Type::ANY_POINTER: return -1;
288 289
    }
    return 0;
290 291
  }

Kenton Varda's avatar
Kenton Varda committed
292
  bool isEmptyValue(schema::Value::Reader value) {
Kenton Varda's avatar
Kenton Varda committed
293
    switch (value.which()) {
Kenton Varda's avatar
Kenton Varda committed
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
      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;
312
      case schema::Value::ANY_POINTER: return true;
313
    }
314
    return true;
315 316
  }

317
  kj::StringTree genValue(Type type, schema::Value::Reader value) {
Kenton Varda's avatar
Kenton Varda committed
318
    switch (value.which()) {
Kenton Varda's avatar
Kenton Varda committed
319 320
      case schema::Value::VOID: return kj::strTree("void");
      case schema::Value::BOOL:
Kenton Varda's avatar
Kenton Varda committed
321
        return kj::strTree(value.getBool() ? "true" : "false");
Kenton Varda's avatar
Kenton Varda committed
322 323 324 325 326 327 328 329 330 331 332
      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
333
        return kj::strTree(DynamicValue::Reader(value.getText()));
Kenton Varda's avatar
Kenton Varda committed
334
      case schema::Value::DATA:
Kenton Varda's avatar
Kenton Varda committed
335
        return kj::strTree(DynamicValue::Reader(value.getData()));
Kenton Varda's avatar
Kenton Varda committed
336
      case schema::Value::LIST: {
337
        auto listValue = value.getList().getAs<DynamicList>(type.asList());
Kenton Varda's avatar
Kenton Varda committed
338
        return kj::strTree(listValue);
339
      }
Kenton Varda's avatar
Kenton Varda committed
340
      case schema::Value::ENUM: {
341
        auto enumNode = type.asEnum().getProto();
342
        auto enumerants = enumNode.getEnum().getEnumerants();
Kenton Varda's avatar
Kenton Varda committed
343 344 345
        KJ_REQUIRE(value.getEnum() < enumerants.size(),
                "Enum value out-of-range.", value.getEnum(), enumNode.getDisplayName());
        return kj::strTree(enumerants[value.getEnum()].getName());
346
      }
Kenton Varda's avatar
Kenton Varda committed
347
      case schema::Value::STRUCT: {
348 349
        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
350
        return kj::strTree(structValue);
351
      }
Kenton Varda's avatar
Kenton Varda committed
352
      case schema::Value::INTERFACE: {
353 354
        return kj::strTree("");
      }
355
      case schema::Value::ANY_POINTER: {
356 357 358 359 360
        return kj::strTree("");
      }
    }
    return kj::strTree("");
  }
361

Kenton Varda's avatar
Kenton Varda committed
362 363 364 365 366 367 368 369 370 371 372 373 374
  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
375
  kj::StringTree genAnnotation(schema::Annotation::Reader annotation,
376 377
                               Schema scope,
                               const char* prefix = " ", const char* suffix = "") {
378
    auto decl = schemaLoader.get(annotation.getId(), annotation.getBrand(), scope);
Kenton Varda's avatar
Kenton Varda committed
379
    auto proto = decl.getProto();
380
    KJ_REQUIRE(proto.isAnnotation());
Kenton Varda's avatar
Kenton Varda committed
381
    auto annDecl = proto.getAnnotation();
382

383 384
    auto value = genValue(schemaLoader.getType(annDecl.getType(), decl),
                          annotation.getValue()).flatten();
385
    if (value.startsWith("(")) {
386
      return kj::strTree(prefix, "$", nodeName(decl, scope, annotation.getBrand(), nullptr),
Kenton Varda's avatar
Kenton Varda committed
387
                         value, suffix);
388
    } else {
389
      return kj::strTree(prefix, "$", nodeName(decl, scope, annotation.getBrand(), nullptr),
Kenton Varda's avatar
Kenton Varda committed
390
                         "(", value, ")", suffix);
391
    }
392
  }
393

Kenton Varda's avatar
Kenton Varda committed
394
  kj::StringTree genAnnotations(List<schema::Annotation>::Reader list, Schema scope) {
395
    return kj::strTree(KJ_MAP(ann, list) { return genAnnotation(ann, scope); });
396 397 398 399
  }
  kj::StringTree genAnnotations(Schema schema) {
    auto proto = schema.getProto();
    return genAnnotations(proto.getAnnotations(), schemaLoader.get(proto.getScopeId()));
400 401
  }

Kenton Varda's avatar
Kenton Varda committed
402
  const char* elementSizeName(schema::ElementSize size) {
403
    switch (size) {
Kenton Varda's avatar
Kenton Varda committed
404 405 406 407 408 409 410 411
      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";
412
    }
413
    return "";
414 415
  }

Kenton Varda's avatar
Kenton Varda committed
416 417 418 419 420 421 422 423 424
  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) {
425
    auto sorted = KJ_MAP(item, list) { return item; };
Kenton Varda's avatar
Kenton Varda committed
426 427 428 429 430 431 432 433 434 435 436
    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;
437
    return KJ_MAP(field, sortByCodeOrder(schema.getFields())) {
438
      if (hasDiscriminantValue(field.getProto())) {
Kenton Varda's avatar
Kenton Varda committed
439 440 441 442 443
        if (seenUnion) {
          return kj::strTree();
        } else {
          seenUnion = true;
          uint offset = schema.getProto().getStruct().getDiscriminantOffset();
Kenton Varda's avatar
Kenton Varda committed
444 445 446

          // GCC 4.7.3 crashes if you inline unionFields.
          auto unionFields = sortByCodeOrder(schema.getUnionFields());
Kenton Varda's avatar
Kenton Varda committed
447 448
          return kj::strTree(
              indent, "union {  # tag bits [", offset * 16, ", ", offset * 16 + 16, ")\n",
449
              KJ_MAP(uField, unionFields) {
450
                return genStructField(uField, schema, indent.next());
Kenton Varda's avatar
Kenton Varda committed
451 452 453 454
              },
              indent, "}\n");
        }
      } else {
455
        return genStructField(field, schema, indent);
456
      }
Kenton Varda's avatar
Kenton Varda committed
457 458 459
    };
  }

460 461 462
  kj::StringTree genStructField(StructSchema::Field field, Schema scope, Indent indent) {
    auto proto = field.getProto();
    switch (proto.which()) {
463
      case schema::Field::SLOT: {
464
        auto slot = proto.getSlot();
465
        int size = typeSizeBits(slot.getType());
466
        return kj::strTree(
467
            indent, proto.getName(), " @", proto.getOrdinal().getExplicit(),
468
            " :", genType(slot.getType(), scope, nullptr),
469
            isEmptyValue(slot.getDefaultValue()) ? kj::strTree("") :
470 471
                kj::strTree(" = ", genValue(field.getType(), slot.getDefaultValue())),
            genAnnotations(proto.getAnnotations(), scope),
472 473 474
            ";  # ", size == -1 ? kj::strTree("ptr[", slot.getOffset(), "]")
                                : kj::strTree("bits[", slot.getOffset() * size, ", ",
                                              (slot.getOffset() + 1) * size, ")"),
475 476
            hasDiscriminantValue(proto)
                ? kj::strTree(", union tag = ", proto.getDiscriminantValue()) : kj::strTree(),
Kenton Varda's avatar
Kenton Varda committed
477
            "\n");
478
      }
Kenton Varda's avatar
Kenton Varda committed
479
      case schema::Field::GROUP: {
480
        auto group = field.getType().asStruct();
481
        return kj::strTree(
482 483 484 485
            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
486 487
            "\n",
            genStructFields(group, indent.next()),
488 489 490 491
            indent, "}\n");
      }
    }
    return kj::strTree();
492 493
  }

Kenton Varda's avatar
Kenton Varda committed
494
  kj::StringTree genParamList(InterfaceSchema interface, StructSchema schema,
495
                              schema::Brand::Reader brand, InterfaceSchema::Method method) {
496 497 498 499 500 501 502 503
    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(
504
                proto.getName(), " :", genType(slot.getType(), interface, nullptr),
505
                isEmptyValue(slot.getDefaultValue()) ? kj::strTree("") :
506
                    kj::strTree(" = ", genValue(field.getType(), slot.getDefaultValue())),
507
                genAnnotations(proto.getAnnotations(), interface));
508 509
          }, ", "), ")");
    } else {
510
      return nodeName(schema, interface, brand, method);
511 512 513
    }
  }

514 515 516
  kj::StringTree genSuperclasses(InterfaceSchema interface) {
    auto superclasses = interface.getProto().getInterface().getSuperclasses();
    if (superclasses.size() == 0) {
517
      return kj::strTree();
Kenton Varda's avatar
Kenton Varda committed
518
    } else {
519 520
      return kj::strTree(" superclasses(", kj::StringTree(
          KJ_MAP(superclass, superclasses) {
521 522
            return nodeName(schemaLoader.get(superclass.getId()), interface,
                            superclass.getBrand(), nullptr);
523
          }, ", "), ")");
Kenton Varda's avatar
Kenton Varda committed
524
    }
525 526
  }

527 528 529 530 531
  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.");
532
    }
533

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

              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());
                    }, ", "), "] ");
              }

585 586
              auto params = schemaLoader.get(methodProto.getParamStructType()).asStruct();
              auto results = schemaLoader.get(methodProto.getResultStructType()).asStruct();
587
              return kj::strTree(
588 589 590 591
                  indent.next(), methodProto.getName(),
                  " @", method.getIndex(), " ", kj::mv(implicitsStr),
                  genParamList(interface, params, methodProto.getParamBrand(), method), " -> ",
                  genParamList(interface, results, methodProto.getResultBrand(), method),
592
                  genAnnotations(methodProto.getAnnotations(), interface), ";\n");
593 594 595 596
            },
            genNestedDecls(schema, indent.next()),
            indent, "}\n");
      }
Kenton Varda's avatar
Kenton Varda committed
597
      case schema::Node::CONST: {
Kenton Varda's avatar
Kenton Varda committed
598
        auto constProto = proto.getConst();
599 600
        return kj::strTree(
            indent, "const ", name, " @0x", kj::hex(proto.getId()), " :",
601
            genType(constProto.getType(), schema, nullptr), " = ",
602
            genValue(schema.asConst().getType(), constProto.getValue()),
603
            genAnnotations(schema), ";\n");
604
      }
Kenton Varda's avatar
Kenton Varda committed
605
      case schema::Node::ANNOTATION: {
Kenton Varda's avatar
Kenton Varda committed
606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
        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;
            }
          }
623
        }
Kenton Varda's avatar
Kenton Varda committed
624 625 626

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

630 631 632
        return kj::strTree(
            indent, "annotation ", name, " @0x", kj::hex(proto.getId()),
            " (", strArray(targets, ", "), ") :",
633
            genType(annotationProto.getType(), schema, nullptr), genAnnotations(schema), ";\n");
634 635
      }
    }
636 637

    return kj::strTree();
638 639
  }

640 641
  kj::StringTree genNestedDecls(Schema schema, Indent indent) {
    uint64_t id = schema.getProto().getId();
642
    return kj::strTree(KJ_MAP(nested, schema.getProto().getNestedNodes()) {
643 644 645
      return genDecl(schemaLoader.get(nested.getId()), nested.getName(), id, indent);
    });
  }
646

647 648
  kj::StringTree genFile(Schema file) {
    auto proto = file.getProto();
649
    KJ_REQUIRE(proto.isFile(), "Expected a file node.", (uint)proto.which());
650 651 652 653

    return kj::strTree(
      "# ", proto.getDisplayName(), "\n",
      "@0x", kj::hex(proto.getId()), ";\n",
654
      KJ_MAP(ann, proto.getAnnotations()) { return genAnnotation(ann, file, "", ";\n"); },
655 656
      genNestedDecls(file, Indent(0)));
  }
657

658 659 660 661
  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
662
    auto request = reader.getRoot<schema::CodeGeneratorRequest>();
663

664 665 666
    for (auto node: request.getNodes()) {
      schemaLoader.load(node);
    }
667

668 669
    kj::FdOutputStream rawOut(STDOUT_FILENO);
    kj::BufferedOutputStreamWrapper out(rawOut);
670

Kenton Varda's avatar
Kenton Varda committed
671 672
    for (auto requestedFile: request.getRequestedFiles()) {
      genFile(schemaLoader.get(requestedFile.getId())).visit(
673 674 675 676
          [&](kj::ArrayPtr<const char> text) {
            out.write(text.begin(), text.size());
          });
    }
677

678
    return true;
679
  }
680
};
681 682

}  // namespace
683
}  // namespace capnp
684

685
KJ_MAIN(capnp::CapnpcCapnpMain);