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

#include "schema.h"
#include "message.h"
Kenton Varda's avatar
Kenton Varda committed
24
#include <kj/debug.h>
25

26
namespace capnp {
27

28 29 30 31 32 33
namespace schema {
  uint KJ_HASHCODE(Type::Which w) { return kj::hashCode(static_cast<uint16_t>(w)); }
  // TODO(cleanup): Cap'n Proto does not declare stringifiers nor hashers for `Which` enums, unlike
  //   all other enums. Fix that and remove this.
}

34 35 36 37
namespace _ {  // private

// Null schemas generated using the below schema file with:
//
38
//     capnp eval -Isrc null-schemas.capnp node --flat |
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
//         hexdump -v -e '8/1 "0x%02x, "' -e '1/8 "\n"'; echo
//
// I totally don't understand hexdump format strings and came up with this command based on trial
// and error.
//
//     @0x879863d4b2cc4a1e;
//
//     using Node = import "/capnp/schema.capnp".Node;
//
//     const node :Node = (
//         id = 0x0000000000000000,
//         displayName = "(null schema)");
//
//     const struct :Node = (
//         id = 0x0000000000000001,
//         displayName = "(null struct schema)",
//         struct = (
//             dataWordCount = 0,
//             pointerCount = 0,
//             preferredListEncoding = empty));
//
//     const enum :Node = (
//         id = 0x0000000000000002,
//         displayName = "(null enum schema)",
//         enum = ());
//
//     const interface :Node = (
//         id = 0x0000000000000003,
//         displayName = "(null interface schema)",
//         interface = ());
//
//     const const :Node = (
//         id = 0x0000000000000004,
//         displayName = "(null const schema)",
//         const = (type = (void = void), value = (void = void)));

static const AlignedData<13> NULL_SCHEMA_BYTES = {{
  0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x05, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00,   // union discriminant intentionally mangled
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x11, 0x00, 0x00, 0x00, 0x72, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x28, 0x6e, 0x75, 0x6c, 0x6c, 0x20, 0x73, 0x63,
  0x68, 0x65, 0x6d, 0x61, 0x29, 0x00, 0x00, 0x00,
}};
const RawSchema NULL_SCHEMA = {
  0x0000000000000000, NULL_SCHEMA_BYTES.words, 13,
92 93
  nullptr, nullptr, 0, 0, nullptr, nullptr, nullptr,
  { &NULL_SCHEMA, nullptr, nullptr, 0, 0, nullptr }
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
};

static const AlignedData<14> NULL_STRUCT_SCHEMA_BYTES = {{
  0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x05, 0x00,
  0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x11, 0x00, 0x00, 0x00, 0xaa, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x28, 0x6e, 0x75, 0x6c, 0x6c, 0x20, 0x73, 0x74,
  0x72, 0x75, 0x63, 0x74, 0x20, 0x73, 0x63, 0x68,
  0x65, 0x6d, 0x61, 0x29, 0x00, 0x00, 0x00, 0x00,
}};
const RawSchema NULL_STRUCT_SCHEMA = {
  0x0000000000000001, NULL_STRUCT_SCHEMA_BYTES.words, 14,
114 115
  nullptr, nullptr, 0, 0, nullptr, nullptr, nullptr,
  { &NULL_STRUCT_SCHEMA, nullptr, nullptr, 0, 0, nullptr }
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
};

static const AlignedData<14> NULL_ENUM_SCHEMA_BYTES = {{
  0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x05, 0x00,
  0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x11, 0x00, 0x00, 0x00, 0x9a, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x28, 0x6e, 0x75, 0x6c, 0x6c, 0x20, 0x65, 0x6e,
  0x75, 0x6d, 0x20, 0x73, 0x63, 0x68, 0x65, 0x6d,
  0x61, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
}};
const RawSchema NULL_ENUM_SCHEMA = {
  0x0000000000000002, NULL_ENUM_SCHEMA_BYTES.words, 14,
136 137
  nullptr, nullptr, 0, 0, nullptr, nullptr, nullptr,
  { &NULL_ENUM_SCHEMA, nullptr, nullptr, 0, 0, nullptr }
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
};

static const AlignedData<14> NULL_INTERFACE_SCHEMA_BYTES = {{
  0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x05, 0x00,
  0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x11, 0x00, 0x00, 0x00, 0xc2, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x28, 0x6e, 0x75, 0x6c, 0x6c, 0x20, 0x69, 0x6e,
  0x74, 0x65, 0x72, 0x66, 0x61, 0x63, 0x65, 0x20,
  0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x29, 0x00,
}};
const RawSchema NULL_INTERFACE_SCHEMA = {
  0x0000000000000003, NULL_INTERFACE_SCHEMA_BYTES.words, 14,
158 159
  nullptr, nullptr, 0, 0, nullptr, nullptr, nullptr,
  { &NULL_INTERFACE_SCHEMA, nullptr, nullptr, 0, 0, nullptr }
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
};

static const AlignedData<20> NULL_CONST_SCHEMA_BYTES = {{
  0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x05, 0x00,
  0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x11, 0x00, 0x00, 0x00, 0xa2, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x10, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00,
  0x18, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00,
  0x28, 0x6e, 0x75, 0x6c, 0x6c, 0x20, 0x63, 0x6f,
  0x6e, 0x73, 0x74, 0x20, 0x73, 0x63, 0x68, 0x65,
  0x6d, 0x61, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
}};
const RawSchema NULL_CONST_SCHEMA = {
  0x0000000000000004, NULL_CONST_SCHEMA_BYTES.words, 20,
186 187
  nullptr, nullptr, 0, 0, nullptr, nullptr, nullptr,
  { &NULL_CONST_SCHEMA, nullptr, nullptr, 0, 0, nullptr }
188 189 190 191 192 193
};

}  // namespace _ (private)

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

Kenton Varda's avatar
Kenton Varda committed
194
schema::Node::Reader Schema::getProto() const {
195
  return readMessageUnchecked<schema::Node>(raw->generic->encodedNode);
196 197
}

Kenton Varda's avatar
Kenton Varda committed
198
kj::ArrayPtr<const word> Schema::asUncheckedMessage() const {
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
  return kj::arrayPtr(raw->generic->encodedNode, raw->generic->encodedSize);
}

Schema Schema::getDependency(uint64_t id, uint location) const {
  {
    // Binary search dependency list.
    uint lower = 0;
    uint upper = raw->dependencyCount;

    while (lower < upper) {
      uint mid = (lower + upper) / 2;

      auto candidate = raw->dependencies[mid];
      if (candidate.location == location) {
        candidate.schema->ensureInitialized();
        return Schema(candidate.schema);
      } else if (candidate.location < location) {
        lower = mid + 1;
      } else {
        upper = mid;
      }
    }
  }
Kenton Varda's avatar
Kenton Varda committed
222

223 224 225
  {
    uint lower = 0;
    uint upper = raw->generic->dependencyCount;
226

227 228
    while (lower < upper) {
      uint mid = (lower + upper) / 2;
229

230
      const _::RawSchema* candidate = raw->generic->dependencies[mid];
231

232 233 234 235 236 237 238 239 240
      uint64_t candidateId = candidate->id;
      if (candidateId == id) {
        candidate->ensureInitialized();
        return Schema(&candidate->defaultBrand);
      } else if (candidateId < id) {
        lower = mid + 1;
      } else {
        upper = mid;
      }
241 242 243
    }
  }

244 245 246
  KJ_FAIL_REQUIRE("Requested ID not found in dependency table.", kj::hex(id)) {
    return Schema();
  }
247 248
}

249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
Schema::BrandArgumentList Schema::getBrandArgumentsAtScope(uint64_t scopeId) const {
  KJ_REQUIRE(getProto().getIsGeneric(), "Not a generic type.", getProto().getDisplayName());

  for (auto scope: kj::range(raw->scopes, raw->scopes + raw->scopeCount)) {
    if (scope->typeId == scopeId) {
      // OK, this scope matches the scope we're looking for.
      if (scope->isUnbound) {
        return BrandArgumentList(scopeId, true);
      } else {
        return BrandArgumentList(scopeId, scope->bindingCount, scope->bindings);
      }
    }
  }

  // This scope is not listed in the scopes list.
  return BrandArgumentList(scopeId, raw->isUnbound());
}

267
StructSchema Schema::asStruct() const {
268
  KJ_REQUIRE(getProto().isStruct(), "Tried to use non-struct schema as a struct.",
269 270 271
             getProto().getDisplayName()) {
    return StructSchema();
  }
272
  return StructSchema(*this);
273 274 275
}

EnumSchema Schema::asEnum() const {
276
  KJ_REQUIRE(getProto().isEnum(), "Tried to use non-enum schema as an enum.",
277 278 279
             getProto().getDisplayName()) {
    return EnumSchema();
  }
280
  return EnumSchema(*this);
281 282 283
}

InterfaceSchema Schema::asInterface() const {
284
  KJ_REQUIRE(getProto().isInterface(), "Tried to use non-interface schema as an interface.",
285 286 287
             getProto().getDisplayName()) {
    return InterfaceSchema();
  }
288
  return InterfaceSchema(*this);
289 290
}

291 292
ConstSchema Schema::asConst() const {
  KJ_REQUIRE(getProto().isConst(), "Tried to use non-constant schema as a constant.",
293 294 295
             getProto().getDisplayName()) {
    return ConstSchema();
  }
296
  return ConstSchema(*this);
297 298
}

299 300 301 302 303
kj::StringPtr Schema::getShortDisplayName() const {
  auto proto = getProto();
  return proto.getDisplayName().slice(proto.getDisplayNamePrefixLength());
}

304
void Schema::requireUsableAs(const _::RawSchema* expected) const {
305 306 307
  KJ_REQUIRE(raw->generic == expected ||
             (expected != nullptr && raw->generic->canCastTo == expected),
             "This schema is not compatible with the requested native type.");
308 309
}

310 311 312 313 314 315 316 317 318 319 320
uint32_t Schema::getSchemaOffset(const schema::Value::Reader& value) const {
  const word* ptr;

  switch (value.which()) {
    case schema::Value::TEXT:
      ptr = reinterpret_cast<const word*>(value.getText().begin());
      break;
    case schema::Value::DATA:
      ptr = reinterpret_cast<const word*>(value.getData().begin());
      break;
    case schema::Value::STRUCT:
321
      ptr = value.getStruct().getAs<_::UncheckedMessage>();
322 323
      break;
    case schema::Value::LIST:
324
      ptr = value.getList().getAs<_::UncheckedMessage>();
325
      break;
326 327
    case schema::Value::ANY_POINTER:
      ptr = value.getAnyPointer().getAs<_::UncheckedMessage>();
328 329 330
      break;
    default:
      KJ_FAIL_ASSERT("getDefaultValueSchemaOffset() can only be called on struct, list, "
331
                     "and any-pointer fields.");
332 333
  }

334 335 336 337
  return ptr - raw->generic->encodedNode;
}

Type Schema::getBrandBinding(uint64_t scopeId, uint index) const {
338
  return getBrandArgumentsAtScope(scopeId)[index];
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
}

Type Schema::interpretType(schema::Type::Reader proto, uint location) const {
  switch (proto.which()) {
    case schema::Type::VOID:
    case schema::Type::BOOL:
    case schema::Type::INT8:
    case schema::Type::INT16:
    case schema::Type::INT32:
    case schema::Type::INT64:
    case schema::Type::UINT8:
    case schema::Type::UINT16:
    case schema::Type::UINT32:
    case schema::Type::UINT64:
    case schema::Type::FLOAT32:
    case schema::Type::FLOAT64:
    case schema::Type::TEXT:
    case schema::Type::DATA:
      return proto.which();

    case schema::Type::STRUCT: {
      auto structType = proto.getStruct();
      return getDependency(structType.getTypeId(), location).asStruct();
    }

    case schema::Type::ENUM: {
      auto enumType = proto.getEnum();
      return getDependency(enumType.getTypeId(), location).asEnum();
    }

    case schema::Type::INTERFACE: {
      auto interfaceType = proto.getInterface();
      return getDependency(interfaceType.getTypeId(), location).asInterface();
    }

    case schema::Type::LIST:
      return ListSchema::of(interpretType(proto.getList().getElementType(), location));

    case schema::Type::ANY_POINTER: {
      auto anyPointer = proto.getAnyPointer();
      switch (anyPointer.which()) {
        case schema::Type::AnyPointer::UNCONSTRAINED:
381
          return anyPointer.getUnconstrained().which();
382 383
        case schema::Type::AnyPointer::PARAMETER: {
          auto param = anyPointer.getParameter();
384
          return getBrandBinding(param.getScopeId(), param.getParameterIndex());
385
        }
386 387 388
        case schema::Type::AnyPointer::IMPLICIT_METHOD_PARAMETER:
          return Type(Type::ImplicitParameter {
              anyPointer.getImplicitMethodParameter().getParameterIndex() });
389 390 391 392 393 394 395
      }

      KJ_UNREACHABLE;
    }
  }

  KJ_UNREACHABLE;
396 397
}

398 399 400 401 402 403 404 405 406 407 408 409 410
Type Schema::BrandArgumentList::operator[](uint index) const {
  if (isUnbound) {
    return Type::BrandParameter { scopeId, index };
  }

  if (index >= size_) {
    // Binding index out-of-range. Treat as AnyPointer. This is important to allow new
    // type parameters to be added to existing types without breaking dependent
    // schemas.
    return schema::Type::ANY_POINTER;
  }

  auto& binding = bindings[index];
Kenton Varda's avatar
Kenton Varda committed
411
  Type result;
412
  if (binding.which == (uint)schema::Type::ANY_POINTER) {
413
    if (binding.scopeId != 0) {
Kenton Varda's avatar
Kenton Varda committed
414
      result = Type::BrandParameter { binding.scopeId, binding.paramIndex };
415
    } else if (binding.isImplicitParameter) {
Kenton Varda's avatar
Kenton Varda committed
416
      result = Type::ImplicitParameter { binding.paramIndex };
417
    } else {
418
      result = static_cast<schema::Type::AnyPointer::Unconstrained::Which>(binding.paramIndex);
419 420 421
    }
  } else if (binding.schema == nullptr) {
    // Builtin / primitive type.
Kenton Varda's avatar
Kenton Varda committed
422
    result = static_cast<schema::Type::Which>(binding.which);
423 424
  } else {
    binding.schema->ensureInitialized();
Kenton Varda's avatar
Kenton Varda committed
425
    result = Type(static_cast<schema::Type::Which>(binding.which), binding.schema);
426
  }
Kenton Varda's avatar
Kenton Varda committed
427 428

  return result.wrapInList(binding.listDepth);
429 430
}

431 432 433 434
kj::StringPtr KJ_STRINGIFY(const Schema& schema) {
  return schema.getProto().getDisplayName();
}

435 436 437 438 439
// =======================================================================================

namespace {

template <typename List>
Kenton Varda's avatar
Kenton Varda committed
440
auto findSchemaMemberByName(const _::RawSchema* raw, kj::StringPtr name, List&& list)
441
    -> kj::Maybe<decltype(list[0])> {
442 443 444 445 446 447
  uint lower = 0;
  uint upper = raw->memberCount;

  while (lower < upper) {
    uint mid = (lower + upper) / 2;

Kenton Varda's avatar
Kenton Varda committed
448 449 450 451 452 453 454
    uint16_t memberIndex = raw->membersByName[mid];

    auto candidate = list[memberIndex];
    kj::StringPtr candidateName = candidate.getProto().getName();
    if (candidateName == name) {
      return candidate;
    } else if (candidateName < name) {
455 456 457 458 459 460 461 462 463 464 465
      lower = mid + 1;
    } else {
      upper = mid;
    }
  }

  return nullptr;
}

}  // namespace

Kenton Varda's avatar
Kenton Varda committed
466 467
StructSchema::FieldList StructSchema::getFields() const {
  return FieldList(*this, getProto().getStruct().getFields());
468 469
}

Kenton Varda's avatar
Kenton Varda committed
470 471 472
StructSchema::FieldSubset StructSchema::getUnionFields() const {
  auto proto = getProto().getStruct();
  return FieldSubset(*this, proto.getFields(),
473
                     raw->generic->membersByDiscriminant, proto.getDiscriminantCount());
Kenton Varda's avatar
Kenton Varda committed
474
}
475

Kenton Varda's avatar
Kenton Varda committed
476 477 478 479 480
StructSchema::FieldSubset StructSchema::getNonUnionFields() const {
  auto proto = getProto().getStruct();
  auto fields = proto.getFields();
  auto offset = proto.getDiscriminantCount();
  auto size = fields.size() - offset;
481
  return FieldSubset(*this, fields, raw->generic->membersByDiscriminant + offset, size);
482 483
}

Kenton Varda's avatar
Kenton Varda committed
484
kj::Maybe<StructSchema::Field> StructSchema::findFieldByName(kj::StringPtr name) const {
485
  return findSchemaMemberByName(raw->generic, name, getFields());
Kenton Varda's avatar
Kenton Varda committed
486 487 488 489
}

StructSchema::Field StructSchema::getFieldByName(kj::StringPtr name) const {
  KJ_IF_MAYBE(member, findFieldByName(name)) {
490 491
    return *member;
  } else {
492
    KJ_FAIL_REQUIRE("struct has no such member", name);
493
  }
Kenton Varda's avatar
Kenton Varda committed
494 495
}

Kenton Varda's avatar
Kenton Varda committed
496 497
kj::Maybe<StructSchema::Field> StructSchema::getFieldByDiscriminant(uint16_t discriminant) const {
  auto unionFields = getUnionFields();
498

Kenton Varda's avatar
Kenton Varda committed
499 500 501 502 503
  if (discriminant >= unionFields.size()) {
    return nullptr;
  } else {
    return unionFields[discriminant];
  }
Kenton Varda's avatar
Kenton Varda committed
504 505
}

506 507 508 509 510 511 512 513 514 515 516 517 518 519
Type StructSchema::Field::getType() const {
  auto proto = getProto();
  uint location = _::RawBrandedSchema::makeDepLocation(_::RawBrandedSchema::DepKind::FIELD, index);

  switch (proto.which()) {
    case schema::Field::SLOT:
      return parent.interpretType(proto.getSlot().getType(), location);

    case schema::Field::GROUP:
      return parent.getDependency(proto.getGroup().getTypeId(), location).asStruct();
  }
  KJ_UNREACHABLE;
}

Kenton Varda's avatar
Kenton Varda committed
520
uint32_t StructSchema::Field::getDefaultValueSchemaOffset() const {
521
  return parent.getSchemaOffset(proto.getSlot().getDefaultValue());
Kenton Varda's avatar
Kenton Varda committed
522 523
}

524 525 526 527
kj::StringPtr KJ_STRINGIFY(const StructSchema::Field& field) {
  return field.getProto().getName();
}

528 529
// -------------------------------------------------------------------

530
EnumSchema::EnumerantList EnumSchema::getEnumerants() const {
531
  return EnumerantList(*this, getProto().getEnum().getEnumerants());
532 533
}

534
kj::Maybe<EnumSchema::Enumerant> EnumSchema::findEnumerantByName(kj::StringPtr name) const {
535
  return findSchemaMemberByName(raw->generic, name, getEnumerants());
536 537
}

538
EnumSchema::Enumerant EnumSchema::getEnumerantByName(kj::StringPtr name) const {
539 540 541
  KJ_IF_MAYBE(enumerant, findEnumerantByName(name)) {
    return *enumerant;
  } else {
542
    KJ_FAIL_REQUIRE("enum has no such enumerant", name);
543
  }
Kenton Varda's avatar
Kenton Varda committed
544 545
}

546 547
// -------------------------------------------------------------------

548
InterfaceSchema::MethodList InterfaceSchema::getMethods() const {
549
  return MethodList(*this, getProto().getInterface().getMethods());
550 551
}

552
kj::Maybe<InterfaceSchema::Method> InterfaceSchema::findMethodByName(kj::StringPtr name) const {
553 554 555 556 557 558 559 560 561 562 563 564 565
  uint counter = 0;
  return findMethodByName(name, counter);
}

static constexpr uint MAX_SUPERCLASSES = 64;

kj::Maybe<InterfaceSchema::Method> InterfaceSchema::findMethodByName(
    kj::StringPtr name, uint& counter) const {
  // Security:  Don't let someone DOS us with a dynamic schema containing cyclic inheritance.
  KJ_REQUIRE(counter++ < MAX_SUPERCLASSES, "Cyclic or absurdly-large inheritance graph detected.") {
    return nullptr;
  }

566
  auto result = findSchemaMemberByName(raw->generic, name, getMethods());
567 568 569 570 571 572 573 574 575

  if (result == nullptr) {
    // Search superclasses.
    // TODO(perf):  This may be somewhat slow, and in the case of lots of diamond dependencies it
    //   could get pathological.  Arguably we should generate a flat list of transitive
    //   superclasses to search and store it in the RawSchema.  It's problematic, though, because
    //   this means that a dynamically-loaded RawSchema cannot be correctly constructed until all
    //   superclasses have been loaded, which imposes an ordering requirement on SchemaLoader or
    //   requires updating subclasses whenever a new superclass is loaded.
576
    auto superclasses = getProto().getInterface().getSuperclasses();
577 578 579 580 581 582
    for (auto i: kj::indices(superclasses)) {
      auto superclass = superclasses[i];
      uint location = _::RawBrandedSchema::makeDepLocation(
          _::RawBrandedSchema::DepKind::SUPERCLASS, i);
      result = getDependency(superclass.getId(), location)
          .asInterface().findMethodByName(name, counter);
583 584 585 586 587 588 589
      if (result != nullptr) {
        break;
      }
    }
  }

  return result;
590 591
}

592
InterfaceSchema::Method InterfaceSchema::getMethodByName(kj::StringPtr name) const {
593 594 595
  KJ_IF_MAYBE(method, findMethodByName(name)) {
    return *method;
  } else {
596
    KJ_FAIL_REQUIRE("interface has no such method", name);
597
  }
Kenton Varda's avatar
Kenton Varda committed
598 599
}

600
InterfaceSchema::SuperclassList InterfaceSchema::getSuperclasses() const {
601
  return SuperclassList(*this, getProto().getInterface().getSuperclasses());
602 603
}

604
bool InterfaceSchema::extends(InterfaceSchema other) const {
605
  if (other.raw->generic == &_::NULL_INTERFACE_SCHEMA) {
606 607 608
    // We consider all interfaces to extend the null schema.
    return true;
  }
609 610 611 612 613 614 615
  uint counter = 0;
  return extends(other, counter);
}

bool InterfaceSchema::extends(InterfaceSchema other, uint& counter) const {
  // Security:  Don't let someone DOS us with a dynamic schema containing cyclic inheritance.
  KJ_REQUIRE(counter++ < MAX_SUPERCLASSES, "Cyclic or absurdly-large inheritance graph detected.") {
616
    return false;
617 618 619 620 621 622 623
  }

  if (other == *this) {
    return true;
  }

  // TODO(perf):  This may be somewhat slow.  See findMethodByName() for discussion.
624
  auto superclasses = getProto().getInterface().getSuperclasses();
625 626 627 628 629
  for (auto i: kj::indices(superclasses)) {
    auto superclass = superclasses[i];
    uint location = _::RawBrandedSchema::makeDepLocation(
        _::RawBrandedSchema::DepKind::SUPERCLASS, i);
    if (getDependency(superclass.getId(), location).asInterface().extends(other, counter)) {
630 631 632 633 634 635 636 637
      return true;
    }
  }

  return false;
}

kj::Maybe<InterfaceSchema> InterfaceSchema::findSuperclass(uint64_t typeId) const {
638 639 640 641
  if (typeId == _::NULL_INTERFACE_SCHEMA.id) {
    // We consider all interfaces to extend the null schema.
    return InterfaceSchema();
  }
642 643 644 645 646 647 648 649 650 651
  uint counter = 0;
  return findSuperclass(typeId, counter);
}

kj::Maybe<InterfaceSchema> InterfaceSchema::findSuperclass(uint64_t typeId, uint& counter) const {
  // Security:  Don't let someone DOS us with a dynamic schema containing cyclic inheritance.
  KJ_REQUIRE(counter++ < MAX_SUPERCLASSES, "Cyclic or absurdly-large inheritance graph detected.") {
    return nullptr;
  }

652
  if (typeId == raw->generic->id) {
653 654 655 656
    return *this;
  }

  // TODO(perf):  This may be somewhat slow.  See findMethodByName() for discussion.
657
  auto superclasses = getProto().getInterface().getSuperclasses();
658 659 660 661 662
  for (auto i: kj::indices(superclasses)) {
    auto superclass = superclasses[i];
    uint location = _::RawBrandedSchema::makeDepLocation(
        _::RawBrandedSchema::DepKind::SUPERCLASS, i);
    KJ_IF_MAYBE(result, getDependency(superclass.getId(), location).asInterface()
Kenton Varda's avatar
Kenton Varda committed
663
                            .findSuperclass(typeId, counter)) {
664 665 666 667 668 669 670
      return *result;
    }
  }

  return nullptr;
}

671 672 673 674 675 676 677 678 679 680 681
StructSchema InterfaceSchema::Method::getParamType() const {
  auto proto = getProto();
  uint location = _::RawBrandedSchema::makeDepLocation(
      _::RawBrandedSchema::DepKind::METHOD_PARAMS, ordinal);
  return parent.getDependency(proto.getParamStructType(), location).asStruct();
}

StructSchema InterfaceSchema::Method::getResultType() const {
  auto proto = getProto();
  uint location = _::RawBrandedSchema::makeDepLocation(
      _::RawBrandedSchema::DepKind::METHOD_RESULTS, ordinal);
Kenton Varda's avatar
Kenton Varda committed
682
  return parent.getDependency(proto.getResultStructType(), location).asStruct();
683 684 685 686 687 688 689 690 691
}

InterfaceSchema InterfaceSchema::SuperclassList::operator[](uint index) const {
  auto superclass = list[index];
  uint location = _::RawBrandedSchema::makeDepLocation(
      _::RawBrandedSchema::DepKind::SUPERCLASS, index);
  return parent.getDependency(superclass.getId(), location).asInterface();
}

692 693 694 695 696 697
// -------------------------------------------------------------------

uint32_t ConstSchema::getValueSchemaOffset() const {
  return getSchemaOffset(getProto().getConst().getValue());
}

698 699 700 701 702
Type ConstSchema::getType() const {
  return interpretType(getProto().getConst().getType(),
      _::RawBrandedSchema::makeDepLocation(_::RawBrandedSchema::DepKind::CONST_TYPE, 0));
}

703 704
// =======================================================================================

Kenton Varda's avatar
Kenton Varda committed
705
ListSchema ListSchema::of(schema::Type::Which primitiveType) {
706
  switch (primitiveType) {
Kenton Varda's avatar
Kenton Varda committed
707 708 709 710 711 712 713 714 715 716 717 718 719 720
    case schema::Type::VOID:
    case schema::Type::BOOL:
    case schema::Type::INT8:
    case schema::Type::INT16:
    case schema::Type::INT32:
    case schema::Type::INT64:
    case schema::Type::UINT8:
    case schema::Type::UINT16:
    case schema::Type::UINT32:
    case schema::Type::UINT64:
    case schema::Type::FLOAT32:
    case schema::Type::FLOAT64:
    case schema::Type::TEXT:
    case schema::Type::DATA:
721 722
      break;

Kenton Varda's avatar
Kenton Varda committed
723 724 725 726
    case schema::Type::STRUCT:
    case schema::Type::ENUM:
    case schema::Type::INTERFACE:
    case schema::Type::LIST:
727
      KJ_FAIL_REQUIRE("Must use one of the other ListSchema::of() overloads for complex types.");
728 729
      break;

730 731
    case schema::Type::ANY_POINTER:
      KJ_FAIL_REQUIRE("List(AnyPointer) not supported.");
732 733 734 735 736 737
      break;
  }

  return ListSchema(primitiveType);
}

Kenton Varda's avatar
Kenton Varda committed
738
ListSchema ListSchema::of(schema::Type::Reader elementType, Schema context) {
Kenton Varda's avatar
Kenton Varda committed
739 740 741 742 743
  // This method is deprecated because it can only be implemented in terms of other deprecated
  // methods. Temporarily disable warnings for those other deprecated methods.
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"

Kenton Varda's avatar
Kenton Varda committed
744
  switch (elementType.which()) {
Kenton Varda's avatar
Kenton Varda committed
745 746 747 748 749 750 751 752 753 754 755 756 757 758
    case schema::Type::VOID:
    case schema::Type::BOOL:
    case schema::Type::INT8:
    case schema::Type::INT16:
    case schema::Type::INT32:
    case schema::Type::INT64:
    case schema::Type::UINT8:
    case schema::Type::UINT16:
    case schema::Type::UINT32:
    case schema::Type::UINT64:
    case schema::Type::FLOAT32:
    case schema::Type::FLOAT64:
    case schema::Type::TEXT:
    case schema::Type::DATA:
Kenton Varda's avatar
Kenton Varda committed
759 760
      return of(elementType.which());

Kenton Varda's avatar
Kenton Varda committed
761
    case schema::Type::STRUCT:
762
      return of(context.getDependency(elementType.getStruct().getTypeId()).asStruct());
Kenton Varda's avatar
Kenton Varda committed
763

Kenton Varda's avatar
Kenton Varda committed
764
    case schema::Type::ENUM:
765
      return of(context.getDependency(elementType.getEnum().getTypeId()).asEnum());
Kenton Varda's avatar
Kenton Varda committed
766

Kenton Varda's avatar
Kenton Varda committed
767
    case schema::Type::INTERFACE:
768
      return of(context.getDependency(elementType.getInterface().getTypeId()).asInterface());
Kenton Varda's avatar
Kenton Varda committed
769

Kenton Varda's avatar
Kenton Varda committed
770
    case schema::Type::LIST:
771
      return of(of(elementType.getList().getElementType(), context));
Kenton Varda's avatar
Kenton Varda committed
772

773 774
    case schema::Type::ANY_POINTER:
      KJ_FAIL_REQUIRE("List(AnyPointer) not supported.");
775 776 777
      return ListSchema();
  }

778
  // Unknown type is acceptable.
Kenton Varda's avatar
Kenton Varda committed
779
  return ListSchema(elementType.which());
Kenton Varda's avatar
Kenton Varda committed
780
#pragma GCC diagnostic pop
781 782
}

783
// =======================================================================================
784

785 786 787 788 789 790
StructSchema Type::asStruct() const {
  KJ_REQUIRE(isStruct(), "Tried to interpret a non-struct type as a struct.") {
    return StructSchema();
  }
  KJ_ASSERT(schema != nullptr);
  return StructSchema(Schema(schema));
791
}
792 793 794 795 796 797
EnumSchema Type::asEnum() const {
  KJ_REQUIRE(isEnum(), "Tried to interpret a non-enum type as an enum.") {
    return EnumSchema();
  }
  KJ_ASSERT(schema != nullptr);
  return EnumSchema(Schema(schema));
798
}
799 800 801 802 803 804 805 806
InterfaceSchema Type::asInterface() const {
  KJ_REQUIRE(isInterface(), "Tried to interpret a non-interface type as an interface.") {
    return InterfaceSchema();
  }
  KJ_ASSERT(schema != nullptr);
  return InterfaceSchema(Schema(schema));
}
ListSchema Type::asList() const {
807 808 809
  KJ_REQUIRE(isList(), "Type::asList(): Not a list.") {
    return ListSchema::of(schema::Type::VOID);
  }
810 811 812 813 814 815 816
  Type elementType = *this;
  --elementType.listDepth;
  return ListSchema::of(elementType);
}

kj::Maybe<Type::BrandParameter> Type::getBrandParameter() const {
  KJ_REQUIRE(isAnyPointer(), "Type::getBrandParameter() can only be called on AnyPointer types.");
817

818 819 820 821 822
  if (scopeId == 0) {
    return nullptr;
  } else {
    return BrandParameter { scopeId, paramIndex };
  }
823 824
}

825 826 827 828 829 830 831 832 833 834 835
kj::Maybe<Type::ImplicitParameter> Type::getImplicitParameter() const {
  KJ_REQUIRE(isAnyPointer(),
      "Type::getImplicitParameter() can only be called on AnyPointer types.");

  if (isImplicitParam) {
    return ImplicitParameter { paramIndex };
  } else {
    return nullptr;
  }
}

836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866
bool Type::operator==(const Type& other) const {
  if (baseType != other.baseType || listDepth != other.listDepth) {
    return false;
  }

  switch (baseType) {
    case schema::Type::VOID:
    case schema::Type::BOOL:
    case schema::Type::INT8:
    case schema::Type::INT16:
    case schema::Type::INT32:
    case schema::Type::INT64:
    case schema::Type::UINT8:
    case schema::Type::UINT16:
    case schema::Type::UINT32:
    case schema::Type::UINT64:
    case schema::Type::FLOAT32:
    case schema::Type::FLOAT64:
    case schema::Type::TEXT:
    case schema::Type::DATA:
      return true;

    case schema::Type::STRUCT:
    case schema::Type::ENUM:
    case schema::Type::INTERFACE:
      return schema == other.schema;

    case schema::Type::LIST:
      KJ_UNREACHABLE;

    case schema::Type::ANY_POINTER:
867
      return scopeId == other.scopeId && isImplicitParam == other.isImplicitParam &&
868 869 870 871
          // Trying to comply with strict aliasing rules. Hopefully the compiler realizes that
          // both branches compile to the same instructions and can optimize it away.
          (scopeId != 0 || isImplicitParam ? paramIndex == other.paramIndex
                                           : anyPointerKind == other.anyPointerKind);
872 873 874
  }

  KJ_UNREACHABLE;
875 876
}

877
uint Type::hashCode() const {
878 879 880 881 882 883 884 885 886 887 888 889 890 891 892
  switch (baseType) {
    case schema::Type::VOID:
    case schema::Type::BOOL:
    case schema::Type::INT8:
    case schema::Type::INT16:
    case schema::Type::INT32:
    case schema::Type::INT64:
    case schema::Type::UINT8:
    case schema::Type::UINT16:
    case schema::Type::UINT32:
    case schema::Type::UINT64:
    case schema::Type::FLOAT32:
    case schema::Type::FLOAT64:
    case schema::Type::TEXT:
    case schema::Type::DATA:
893
      return kj::hashCode(baseType, listDepth);
894 895 896 897

    case schema::Type::STRUCT:
    case schema::Type::ENUM:
    case schema::Type::INTERFACE:
898
      return kj::hashCode(schema, listDepth);
899 900 901 902 903 904 905

    case schema::Type::LIST:
      KJ_UNREACHABLE;

    case schema::Type::ANY_POINTER: {
      // Trying to comply with strict aliasing rules. Hopefully the compiler realizes that
      // both branches compile to the same instructions and can optimize it away.
906
      uint16_t val = scopeId != 0 || isImplicitParam ?
907
          paramIndex : static_cast<uint16_t>(anyPointerKind);
908
      return kj::hashCode(val, isImplicitParam, scopeId);
909 910 911 912 913 914
    }
  }

  KJ_UNREACHABLE;
}

915 916 917
void Type::requireUsableAs(Type expected) const {
  KJ_REQUIRE(baseType == expected.baseType && listDepth == expected.listDepth,
             "This type is not compatible with the requested native type.");
918

919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945
  switch (baseType) {
    case schema::Type::VOID:
    case schema::Type::BOOL:
    case schema::Type::INT8:
    case schema::Type::INT16:
    case schema::Type::INT32:
    case schema::Type::INT64:
    case schema::Type::UINT8:
    case schema::Type::UINT16:
    case schema::Type::UINT32:
    case schema::Type::UINT64:
    case schema::Type::FLOAT32:
    case schema::Type::FLOAT64:
    case schema::Type::TEXT:
    case schema::Type::DATA:
    case schema::Type::ANY_POINTER:
      break;

    case schema::Type::STRUCT:
    case schema::Type::ENUM:
    case schema::Type::INTERFACE:
      Schema(schema).requireUsableAs(expected.schema->generic);
      break;

    case schema::Type::LIST:
      KJ_UNREACHABLE;
  }
946 947
}

948
}  // namespace capnp