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

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

27
namespace capnp {
28

29 30 31 32 33 34
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.
}

35 36 37 38
namespace _ {  // private

// Null schemas generated using the below schema file with:
//
39
//     capnp eval -Isrc null-schemas.capnp node --flat |
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 92
//         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,
93 94
  nullptr, nullptr, 0, 0, nullptr, nullptr, nullptr,
  { &NULL_SCHEMA, nullptr, nullptr, 0, 0, nullptr }
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
};

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,
115 116
  nullptr, nullptr, 0, 0, nullptr, nullptr, nullptr,
  { &NULL_STRUCT_SCHEMA, nullptr, nullptr, 0, 0, nullptr }
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
};

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,
137 138
  nullptr, nullptr, 0, 0, nullptr, nullptr, nullptr,
  { &NULL_ENUM_SCHEMA, nullptr, nullptr, 0, 0, nullptr }
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
};

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,
159 160
  nullptr, nullptr, 0, 0, nullptr, nullptr, nullptr,
  { &NULL_INTERFACE_SCHEMA, nullptr, nullptr, 0, 0, nullptr }
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 186
};

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,
187 188
  nullptr, nullptr, 0, 0, nullptr, nullptr, nullptr,
  { &NULL_CONST_SCHEMA, nullptr, nullptr, 0, 0, nullptr }
189 190 191 192 193 194
};

}  // namespace _ (private)

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

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

Kenton Varda's avatar
Kenton Varda committed
199
kj::ArrayPtr<const word> Schema::asUncheckedMessage() const {
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
  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
223

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

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

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

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

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

250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
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());
}

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

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

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

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

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

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

311 312 313 314 315 316 317 318 319 320 321
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:
322
      ptr = value.getStruct().getAs<_::UncheckedMessage>();
323 324
      break;
    case schema::Value::LIST:
325
      ptr = value.getList().getAs<_::UncheckedMessage>();
326
      break;
327 328
    case schema::Value::ANY_POINTER:
      ptr = value.getAnyPointer().getAs<_::UncheckedMessage>();
329 330 331
      break;
    default:
      KJ_FAIL_ASSERT("getDefaultValueSchemaOffset() can only be called on struct, list, "
332
                     "and any-pointer fields.");
333 334
  }

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

Type Schema::getBrandBinding(uint64_t scopeId, uint index) const {
339
  return getBrandArgumentsAtScope(scopeId)[index];
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 381
}

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:
382
          return anyPointer.getUnconstrained().which();
383 384
        case schema::Type::AnyPointer::PARAMETER: {
          auto param = anyPointer.getParameter();
385
          return getBrandBinding(param.getScopeId(), param.getParameterIndex());
386
        }
387 388 389
        case schema::Type::AnyPointer::IMPLICIT_METHOD_PARAMETER:
          return Type(Type::ImplicitParameter {
              anyPointer.getImplicitMethodParameter().getParameterIndex() });
390 391 392 393 394 395 396
      }

      KJ_UNREACHABLE;
    }
  }

  KJ_UNREACHABLE;
397 398
}

399 400 401 402 403 404 405 406 407 408 409 410 411
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
412
  Type result;
413
  if (binding.which == (uint)schema::Type::ANY_POINTER) {
414
    if (binding.scopeId != 0) {
Kenton Varda's avatar
Kenton Varda committed
415
      result = Type::BrandParameter { binding.scopeId, binding.paramIndex };
416
    } else if (binding.isImplicitParameter) {
Kenton Varda's avatar
Kenton Varda committed
417
      result = Type::ImplicitParameter { binding.paramIndex };
418
    } else {
419
      result = static_cast<schema::Type::AnyPointer::Unconstrained::Which>(binding.paramIndex);
420 421 422
    }
  } else if (binding.schema == nullptr) {
    // Builtin / primitive type.
Kenton Varda's avatar
Kenton Varda committed
423
    result = static_cast<schema::Type::Which>(binding.which);
424 425
  } else {
    binding.schema->ensureInitialized();
Kenton Varda's avatar
Kenton Varda committed
426
    result = Type(static_cast<schema::Type::Which>(binding.which), binding.schema);
427
  }
Kenton Varda's avatar
Kenton Varda committed
428 429

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

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

436 437 438 439 440
// =======================================================================================

namespace {

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

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

Kenton Varda's avatar
Kenton Varda committed
449 450 451 452 453 454 455
    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) {
456 457 458 459 460 461 462 463 464 465 466
      lower = mid + 1;
    } else {
      upper = mid;
    }
  }

  return nullptr;
}

}  // namespace

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

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

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

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

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

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

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

507 508 509 510 511
bool StructSchema::isStreamResult() const {
  auto& streamRaw = _::rawSchema<StreamResult>();
  return raw->generic == &streamRaw || raw->generic->canCastTo == &streamRaw;
}

512 513 514 515 516 517 518 519 520 521 522 523 524 525
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
526
uint32_t StructSchema::Field::getDefaultValueSchemaOffset() const {
527
  return parent.getSchemaOffset(proto.getSlot().getDefaultValue());
Kenton Varda's avatar
Kenton Varda committed
528 529
}

530 531 532 533
kj::StringPtr KJ_STRINGIFY(const StructSchema::Field& field) {
  return field.getProto().getName();
}

534 535
// -------------------------------------------------------------------

536
EnumSchema::EnumerantList EnumSchema::getEnumerants() const {
537
  return EnumerantList(*this, getProto().getEnum().getEnumerants());
538 539
}

540
kj::Maybe<EnumSchema::Enumerant> EnumSchema::findEnumerantByName(kj::StringPtr name) const {
541
  return findSchemaMemberByName(raw->generic, name, getEnumerants());
542 543
}

544
EnumSchema::Enumerant EnumSchema::getEnumerantByName(kj::StringPtr name) const {
545 546 547
  KJ_IF_MAYBE(enumerant, findEnumerantByName(name)) {
    return *enumerant;
  } else {
548
    KJ_FAIL_REQUIRE("enum has no such enumerant", name);
549
  }
Kenton Varda's avatar
Kenton Varda committed
550 551
}

552 553
// -------------------------------------------------------------------

554
InterfaceSchema::MethodList InterfaceSchema::getMethods() const {
555
  return MethodList(*this, getProto().getInterface().getMethods());
556 557
}

558
kj::Maybe<InterfaceSchema::Method> InterfaceSchema::findMethodByName(kj::StringPtr name) const {
559 560 561 562 563 564 565 566 567 568 569 570 571
  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;
  }

572
  auto result = findSchemaMemberByName(raw->generic, name, getMethods());
573 574 575 576 577 578 579 580 581

  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.
582
    auto superclasses = getProto().getInterface().getSuperclasses();
583 584 585 586 587 588
    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);
589 590 591 592 593 594 595
      if (result != nullptr) {
        break;
      }
    }
  }

  return result;
596 597
}

598
InterfaceSchema::Method InterfaceSchema::getMethodByName(kj::StringPtr name) const {
599 600 601
  KJ_IF_MAYBE(method, findMethodByName(name)) {
    return *method;
  } else {
602
    KJ_FAIL_REQUIRE("interface has no such method", name);
603
  }
Kenton Varda's avatar
Kenton Varda committed
604 605
}

606
InterfaceSchema::SuperclassList InterfaceSchema::getSuperclasses() const {
607
  return SuperclassList(*this, getProto().getInterface().getSuperclasses());
608 609
}

610
bool InterfaceSchema::extends(InterfaceSchema other) const {
611
  if (other.raw->generic == &_::NULL_INTERFACE_SCHEMA) {
612 613 614
    // We consider all interfaces to extend the null schema.
    return true;
  }
615 616 617 618 619 620 621
  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.") {
622
    return false;
623 624 625 626 627 628 629
  }

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

  // TODO(perf):  This may be somewhat slow.  See findMethodByName() for discussion.
630
  auto superclasses = getProto().getInterface().getSuperclasses();
631 632 633 634 635
  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)) {
636 637 638 639 640 641 642 643
      return true;
    }
  }

  return false;
}

kj::Maybe<InterfaceSchema> InterfaceSchema::findSuperclass(uint64_t typeId) const {
644 645 646 647
  if (typeId == _::NULL_INTERFACE_SCHEMA.id) {
    // We consider all interfaces to extend the null schema.
    return InterfaceSchema();
  }
648 649 650 651 652 653 654 655 656 657
  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;
  }

658
  if (typeId == raw->generic->id) {
659 660 661 662
    return *this;
  }

  // TODO(perf):  This may be somewhat slow.  See findMethodByName() for discussion.
663
  auto superclasses = getProto().getInterface().getSuperclasses();
664 665 666 667 668
  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
669
                            .findSuperclass(typeId, counter)) {
670 671 672 673 674 675 676
      return *result;
    }
  }

  return nullptr;
}

677 678 679 680 681 682 683 684 685 686 687
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
688
  return parent.getDependency(proto.getResultStructType(), location).asStruct();
689 690 691 692 693 694 695 696 697
}

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

698 699 700 701 702 703
// -------------------------------------------------------------------

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

704 705 706 707 708
Type ConstSchema::getType() const {
  return interpretType(getProto().getConst().getType(),
      _::RawBrandedSchema::makeDepLocation(_::RawBrandedSchema::DepKind::CONST_TYPE, 0));
}

709 710
// =======================================================================================

Kenton Varda's avatar
Kenton Varda committed
711
ListSchema ListSchema::of(schema::Type::Which primitiveType) {
712
  switch (primitiveType) {
Kenton Varda's avatar
Kenton Varda committed
713 714 715 716 717 718 719 720 721 722 723 724 725 726
    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:
727 728
      break;

Kenton Varda's avatar
Kenton Varda committed
729 730 731 732
    case schema::Type::STRUCT:
    case schema::Type::ENUM:
    case schema::Type::INTERFACE:
    case schema::Type::LIST:
733
      KJ_FAIL_REQUIRE("Must use one of the other ListSchema::of() overloads for complex types.");
734 735
      break;

736 737
    case schema::Type::ANY_POINTER:
      KJ_FAIL_REQUIRE("List(AnyPointer) not supported.");
738 739 740 741 742 743
      break;
  }

  return ListSchema(primitiveType);
}

Kenton Varda's avatar
Kenton Varda committed
744
ListSchema ListSchema::of(schema::Type::Reader elementType, Schema context) {
Kenton Varda's avatar
Kenton Varda committed
745 746 747 748 749
  // 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
750
  switch (elementType.which()) {
Kenton Varda's avatar
Kenton Varda committed
751 752 753 754 755 756 757 758 759 760 761 762 763 764
    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
765 766
      return of(elementType.which());

Kenton Varda's avatar
Kenton Varda committed
767
    case schema::Type::STRUCT:
768
      return of(context.getDependency(elementType.getStruct().getTypeId()).asStruct());
Kenton Varda's avatar
Kenton Varda committed
769

Kenton Varda's avatar
Kenton Varda committed
770
    case schema::Type::ENUM:
771
      return of(context.getDependency(elementType.getEnum().getTypeId()).asEnum());
Kenton Varda's avatar
Kenton Varda committed
772

Kenton Varda's avatar
Kenton Varda committed
773
    case schema::Type::INTERFACE:
774
      return of(context.getDependency(elementType.getInterface().getTypeId()).asInterface());
Kenton Varda's avatar
Kenton Varda committed
775

Kenton Varda's avatar
Kenton Varda committed
776
    case schema::Type::LIST:
777
      return of(of(elementType.getList().getElementType(), context));
Kenton Varda's avatar
Kenton Varda committed
778

779 780
    case schema::Type::ANY_POINTER:
      KJ_FAIL_REQUIRE("List(AnyPointer) not supported.");
781 782 783
      return ListSchema();
  }

784
  // Unknown type is acceptable.
Kenton Varda's avatar
Kenton Varda committed
785
  return ListSchema(elementType.which());
Kenton Varda's avatar
Kenton Varda committed
786
#pragma GCC diagnostic pop
787 788
}

789
// =======================================================================================
790

791 792 793 794 795 796
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));
797
}
798 799 800 801 802 803
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));
804
}
805 806 807 808 809 810 811 812
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 {
813 814 815
  KJ_REQUIRE(isList(), "Type::asList(): Not a list.") {
    return ListSchema::of(schema::Type::VOID);
  }
816 817 818 819 820 821 822
  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.");
823

824 825 826 827 828
  if (scopeId == 0) {
    return nullptr;
  } else {
    return BrandParameter { scopeId, paramIndex };
  }
829 830
}

831 832 833 834 835 836 837 838 839 840 841
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;
  }
}

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 867 868 869 870 871 872
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:
873
      return scopeId == other.scopeId && isImplicitParam == other.isImplicitParam &&
874 875 876 877
          // 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);
878 879 880
  }

  KJ_UNREACHABLE;
881 882
}

883
uint Type::hashCode() const {
884 885 886 887 888 889 890 891 892 893 894 895 896 897 898
  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:
899
      return kj::hashCode(baseType, listDepth);
900 901 902 903

    case schema::Type::STRUCT:
    case schema::Type::ENUM:
    case schema::Type::INTERFACE:
904
      return kj::hashCode(schema, listDepth);
905 906 907 908 909 910 911

    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.
912
      uint16_t val = scopeId != 0 || isImplicitParam ?
913
          paramIndex : static_cast<uint16_t>(anyPointerKind);
914
      return kj::hashCode(val, isImplicitParam, scopeId);
915 916 917 918 919 920
    }
  }

  KJ_UNREACHABLE;
}

921 922 923
void Type::requireUsableAs(Type expected) const {
  KJ_REQUIRE(baseType == expected.baseType && listDepth == expected.listDepth,
             "This type is not compatible with the requested native type.");
924

925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951
  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;
  }
952 953
}

954
}  // namespace capnp