schema.h 36.5 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
#pragma once
23

24
#if defined(__GNUC__) && !defined(CAPNP_HEADER_WARNINGS)
25 26 27
#pragma GCC system_header
#endif

28 29 30 31
#if CAPNP_LITE
#error "Reflection APIs, including this header, are not available in lite mode."
#endif

Kenton Varda's avatar
Kenton Varda committed
32
#include <capnp/schema.capnp.h>
33
#include <kj/hash.h>
34
#include <kj/windows-sanity.h>  // work-around macro conflict with `VOID`
35

36
namespace capnp {
37 38 39 40 41

class Schema;
class StructSchema;
class EnumSchema;
class InterfaceSchema;
42
class ConstSchema;
43
class ListSchema;
44
class Type;
45 46

template <typename T, Kind k = kind<T>()> struct SchemaType_ { typedef Schema Type; };
Kenton Varda's avatar
Kenton Varda committed
47 48
template <typename T> struct SchemaType_<T, Kind::PRIMITIVE> { typedef schema::Type::Which Type; };
template <typename T> struct SchemaType_<T, Kind::BLOB> { typedef schema::Type::Which Type; };
49 50 51 52 53 54 55 56 57
template <typename T> struct SchemaType_<T, Kind::ENUM> { typedef EnumSchema Type; };
template <typename T> struct SchemaType_<T, Kind::STRUCT> { typedef StructSchema Type; };
template <typename T> struct SchemaType_<T, Kind::INTERFACE> { typedef InterfaceSchema Type; };
template <typename T> struct SchemaType_<T, Kind::LIST> { typedef ListSchema Type; };

template <typename T>
using SchemaType = typename SchemaType_<T>::Type;
// SchemaType<T> is the type of T's schema, e.g. StructSchema if T is a struct.

58 59 60 61 62 63 64 65 66 67
namespace _ {  // private
extern const RawSchema NULL_SCHEMA;
extern const RawSchema NULL_STRUCT_SCHEMA;
extern const RawSchema NULL_ENUM_SCHEMA;
extern const RawSchema NULL_INTERFACE_SCHEMA;
extern const RawSchema NULL_CONST_SCHEMA;
// The schema types default to these null (empty) schemas in case of error, especially when
// exceptions are disabled.
}  // namespace _ (private)

68
class Schema {
69
  // Convenience wrapper around capnp::schema::Node.
70 71

public:
72
  inline Schema(): raw(&_::NULL_SCHEMA.defaultBrand) {}
73 74 75 76 77

  template <typename T>
  static inline SchemaType<T> from() { return SchemaType<T>::template fromImpl<T>(); }
  // Get the Schema for a particular compiled-in type.

Kenton Varda's avatar
Kenton Varda committed
78
  schema::Node::Reader getProto() const;
79 80
  // Get the underlying Cap'n Proto representation of the schema node.  (Note that this accessor
  // has performance comparable to accessors of struct-typed fields on Reader classes.)
81

Kenton Varda's avatar
Kenton Varda committed
82 83 84 85
  kj::ArrayPtr<const word> asUncheckedMessage() const;
  // Get the encoded schema node content as a single message segment.  It is safe to read as an
  // unchecked message.

86
  Schema getDependency(uint64_t id) const CAPNP_DEPRECATED("Does not handle generics correctly.");
87 88 89 90 91
  // DEPRECATED: This method cannot correctly account for generic type parameter bindings that
  //   may apply to the dependency. Instead of using this method, use a method of the Schema API
  //   that corresponds to the exact kind of dependency. For example, to get a field type, use
  //   StructSchema::Field::getType().
  //
92 93
  // Gets the Schema for one of this Schema's dependencies.  For example, if this Schema is for a
  // struct, you could look up the schema for one of its fields' types.  Throws an exception if this
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
  // schema doesn't actually depend on the given id.
  //
  // Note that not all type IDs found in the schema node are considered "dependencies" -- only the
  // ones that are needed to implement the dynamic API are.  That includes:
  // - Field types.
  // - Group types.
  // - scopeId for group nodes, but NOT otherwise.
  // - Method parameter and return types.
  //
  // The following are NOT considered dependencies:
  // - Nested nodes.
  // - scopeId for a non-group node.
  // - Annotations.
  //
  // To obtain schemas for those, you would need a SchemaLoader.
109

110 111 112 113 114 115
  bool isBranded() const;
  // Returns true if this schema represents a non-default parameterization of this type.

  Schema getGeneric() const;
  // Get the version of this schema with any brands removed.

116 117 118 119
  class BrandArgumentList;
  BrandArgumentList getBrandArgumentsAtScope(uint64_t scopeId) const;
  // Gets the values bound to the brand parameters at the given scope.

120 121 122
  StructSchema asStruct() const;
  EnumSchema asEnum() const;
  InterfaceSchema asInterface() const;
123 124 125
  ConstSchema asConst() const;
  // Cast the Schema to a specific type.  Throws an exception if the type doesn't match.  Use
  // getProto() to determine type, e.g. getProto().isStruct().
126 127 128 129 130 131 132

  inline bool operator==(const Schema& other) const { return raw == other.raw; }
  inline bool operator!=(const Schema& other) const { return raw != other.raw; }
  // Determine whether two Schemas are wrapping the exact same underlying data, by identity.  If
  // you want to check if two Schemas represent the same type (but possibly different versions of
  // it), compare their IDs instead.

133 134
  inline uint hashCode() const { return kj::hashCode(raw); }

135
  template <typename T>
136
  void requireUsableAs() const;
137 138 139 140 141 142
  // Throws an exception if a value with this Schema cannot safely be cast to a native value of
  // the given type.  This passes if either:
  // - *this == from<T>()
  // - This schema was loaded with SchemaLoader, the type ID matches typeId<T>(), and
  //   loadCompiledTypeAndDependencies<T>() was called on the SchemaLoader.

143 144 145
  kj::StringPtr getShortDisplayName() const;
  // Get the short version of the node's display name.

146
private:
147
  const _::RawBrandedSchema* raw;
148

149
  inline explicit Schema(const _::RawBrandedSchema* raw): raw(raw) {
150 151 152
    KJ_IREQUIRE(raw->lazyInitializer == nullptr,
        "Must call ensureInitialized() on RawSchema before constructing Schema.");
  }
153 154

  template <typename T> static inline Schema fromImpl() {
155
    return Schema(&_::rawSchema<T>());
156 157
  }

158
  void requireUsableAs(const _::RawSchema* expected) const;
159

160 161
  uint32_t getSchemaOffset(const schema::Value::Reader& value) const;

162 163 164 165 166 167 168 169 170 171 172 173 174 175
  Type getBrandBinding(uint64_t scopeId, uint index) const;
  // Look up the binding for a brand parameter used by this Schema. Returns `AnyPointer` if the
  // parameter is not bound.
  //
  // TODO(someday): Public interface for iterating over all bindings?

  Schema getDependency(uint64_t id, uint location) const;
  // Look up schema for a particular dependency of this schema. `location` is the dependency
  // location number as defined in _::RawBrandedSchema.

  Type interpretType(schema::Type::Reader proto, uint location) const;
  // Interpret a schema::Type in the given location within the schema, compiling it into a
  // Type object.

176 177 178
  friend class StructSchema;
  friend class EnumSchema;
  friend class InterfaceSchema;
179
  friend class ConstSchema;
180 181
  friend class ListSchema;
  friend class SchemaLoader;
182
  friend class Type;
183 184
  friend kj::StringTree _::structString(
      _::StructReader reader, const _::RawBrandedSchema& schema);
185
  friend kj::String _::enumString(uint16_t value, const _::RawBrandedSchema& schema);
186 187
};

188 189
kj::StringPtr KJ_STRINGIFY(const Schema& schema);

190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
class Schema::BrandArgumentList {
  // A list of generic parameter bindings for parameters of some particular type. Note that since
  // parameters on an outer type apply to all inner types as well, a deeply-nested type can have
  // multiple BrandArgumentLists that apply to it.
  //
  // A BrandArgumentList only represents the arguments that the client of the type specified. Since
  // new parameters can be added over time, this list may not cover all defined parameters for the
  // type. Missing parameters should be treated as AnyPointer. This class's implementation of
  // operator[] already does this for you; out-of-bounds access will safely return AnyPointer.

public:
  inline BrandArgumentList(): scopeId(0), size_(0), bindings(nullptr) {}

  inline uint size() const { return size_; }
  Type operator[](uint index) const;

  typedef _::IndexingIterator<const BrandArgumentList, Type> Iterator;
  inline Iterator begin() const { return Iterator(this, 0); }
  inline Iterator end() const { return Iterator(this, size()); }

private:
  uint64_t scopeId;
  uint size_;
  bool isUnbound;
  const _::RawBrandedSchema::Binding* bindings;

  inline BrandArgumentList(uint64_t scopeId, bool isUnbound)
      : scopeId(scopeId), size_(0), isUnbound(isUnbound), bindings(nullptr) {}
  inline BrandArgumentList(uint64_t scopeId, uint size,
                           const _::RawBrandedSchema::Binding* bindings)
      : scopeId(scopeId), size_(size), isUnbound(false), bindings(bindings) {}

  friend class Schema;
};

225 226 227 228
// -------------------------------------------------------------------

class StructSchema: public Schema {
public:
229
  inline StructSchema(): Schema(&_::NULL_STRUCT_SCHEMA.defaultBrand) {}
230

Kenton Varda's avatar
Kenton Varda committed
231
  class Field;
Kenton Varda's avatar
Kenton Varda committed
232 233
  class FieldList;
  class FieldSubset;
234

Kenton Varda's avatar
Kenton Varda committed
235 236 237 238
  FieldList getFields() const;
  // List top-level fields of this struct.  This list will contain top-level groups (including
  // named unions) but not the members of those groups.  The list does, however, contain the
  // members of the unnamed union, if there is one.
Kenton Varda's avatar
Kenton Varda committed
239

Kenton Varda's avatar
Kenton Varda committed
240 241 242 243
  FieldSubset getUnionFields() const;
  // If the field contains an unnamed union, get a list of fields in the union, ordered by
  // ordinal.  Since discriminant values are assigned sequentially by ordinal, you may index this
  // list by discriminant value.
244

Kenton Varda's avatar
Kenton Varda committed
245 246
  FieldSubset getNonUnionFields() const;
  // Get the fields of this struct which are not in an unnamed union, ordered by ordinal.
Kenton Varda's avatar
Kenton Varda committed
247

Kenton Varda's avatar
Kenton Varda committed
248 249 250 251 252 253 254 255 256 257 258 259 260 261
  kj::Maybe<Field> findFieldByName(kj::StringPtr name) const;
  // Find the field with the given name, or return null if there is no such field.  If the struct
  // contains an unnamed union, then this will find fields of that union in addition to fields
  // of the outer struct, since they exist in the same namespace.  It will not, however, find
  // members of groups (including named unions) -- you must first look up the group itself,
  // then dig into its type.

  Field getFieldByName(kj::StringPtr name) const;
  // Like findFieldByName() but throws an exception on failure.

  kj::Maybe<Field> getFieldByDiscriminant(uint16_t discriminant) const;
  // Finds the field whose `discriminantValue` is equal to the given value, or returns null if
  // there is no such field.  (If the schema does not represent a union or a struct containing
  // an unnamed union, then this always returns null.)
262

263
private:
264
  StructSchema(Schema base): Schema(base) {}
265
  template <typename T> static inline StructSchema fromImpl() {
266
    return StructSchema(Schema(&_::rawBrandedSchema<T>()));
267 268
  }
  friend class Schema;
269
  friend class Type;
270 271
};

Kenton Varda's avatar
Kenton Varda committed
272
class StructSchema::Field {
273
public:
Kenton Varda's avatar
Kenton Varda committed
274
  Field() = default;
275

Kenton Varda's avatar
Kenton Varda committed
276
  inline schema::Field::Reader getProto() const { return proto; }
277 278 279
  inline StructSchema getContainingStruct() const { return parent; }

  inline uint getIndex() const { return index; }
Kenton Varda's avatar
Kenton Varda committed
280
  // Get the index of this field within the containing struct or union.
Kenton Varda's avatar
Kenton Varda committed
281

282 283 284 285
  Type getType() const;
  // Get the type of this field. Note that this is preferred over getProto().getType() as this
  // method will apply generics.

Kenton Varda's avatar
Kenton Varda committed
286 287 288 289 290 291 292
  uint32_t getDefaultValueSchemaOffset() const;
  // For struct, list, and object fields, returns the offset, in words, within the first segment of
  // the struct's schema, where this field's default value pointer is located.  The schema is
  // always stored as a single-segment unchecked message, which in turn means that the default
  // value pointer itself can be treated as the root of an unchecked message -- if you know where
  // to find it, which is what this method helps you with.
  //
David Renshaw's avatar
David Renshaw committed
293 294
  // For blobs, returns the offset of the beginning of the blob's content within the first segment
  // of the struct's schema.
Kenton Varda's avatar
Kenton Varda committed
295 296 297 298 299 300 301 302 303 304 305
  //
  // This is primarily useful for code generators.  The C++ code generator, for example, embeds
  // the entire schema as a raw word array within the generated code.  Of course, to implement
  // field accessors, it needs access to those fields' default values.  Embedding separate copies
  // of those default values would be redundant since they are already included in the schema, but
  // seeking through the schema at runtime to find the default values would be ugly.  Instead,
  // the code generator can use getDefaultValueSchemaOffset() to find the offset of the default
  // value within the schema, and can simply apply that offset at runtime.
  //
  // If the above does not make sense, you probably don't need this method.

Kenton Varda's avatar
Kenton Varda committed
306 307
  inline bool operator==(const Field& other) const;
  inline bool operator!=(const Field& other) const { return !(*this == other); }
308
  inline uint hashCode() const;
Kenton Varda's avatar
Kenton Varda committed
309

310
private:
Kenton Varda's avatar
Kenton Varda committed
311 312
  StructSchema parent;
  uint index;
Kenton Varda's avatar
Kenton Varda committed
313
  schema::Field::Reader proto;
Kenton Varda's avatar
Kenton Varda committed
314

Kenton Varda's avatar
Kenton Varda committed
315
  inline Field(StructSchema parent, uint index, schema::Field::Reader proto)
Kenton Varda's avatar
Kenton Varda committed
316
      : parent(parent), index(index), proto(proto) {}
317 318 319 320

  friend class StructSchema;
};

321 322
kj::StringPtr KJ_STRINGIFY(const StructSchema::Field& field);

Kenton Varda's avatar
Kenton Varda committed
323
class StructSchema::FieldList {
Kenton Varda's avatar
Kenton Varda committed
324
public:
Kenton Varda's avatar
Kenton Varda committed
325
  FieldList() = default;  // empty list
Kenton Varda's avatar
Kenton Varda committed
326

Kenton Varda's avatar
Kenton Varda committed
327 328
  inline uint size() const { return list.size(); }
  inline Field operator[](uint index) const { return Field(parent, index, list[index]); }
Kenton Varda's avatar
Kenton Varda committed
329

Kenton Varda's avatar
Kenton Varda committed
330 331 332
  typedef _::IndexingIterator<const FieldList, Field> Iterator;
  inline Iterator begin() const { return Iterator(this, 0); }
  inline Iterator end() const { return Iterator(this, size()); }
Kenton Varda's avatar
Kenton Varda committed
333 334

private:
Kenton Varda's avatar
Kenton Varda committed
335
  StructSchema parent;
Kenton Varda's avatar
Kenton Varda committed
336
  List<schema::Field>::Reader list;
Kenton Varda's avatar
Kenton Varda committed
337

Kenton Varda's avatar
Kenton Varda committed
338
  inline FieldList(StructSchema parent, List<schema::Field>::Reader list)
Kenton Varda's avatar
Kenton Varda committed
339
      : parent(parent), list(list) {}
Kenton Varda's avatar
Kenton Varda committed
340 341 342 343

  friend class StructSchema;
};

Kenton Varda's avatar
Kenton Varda committed
344
class StructSchema::FieldSubset {
345
public:
Kenton Varda's avatar
Kenton Varda committed
346
  FieldSubset() = default;  // empty list
347

Kenton Varda's avatar
Kenton Varda committed
348 349 350 351
  inline uint size() const { return size_; }
  inline Field operator[](uint index) const {
    return Field(parent, indices[index], list[indices[index]]);
  }
352

Kenton Varda's avatar
Kenton Varda committed
353
  typedef _::IndexingIterator<const FieldSubset, Field> Iterator;
354 355
  inline Iterator begin() const { return Iterator(this, 0); }
  inline Iterator end() const { return Iterator(this, size()); }
356 357 358

private:
  StructSchema parent;
Kenton Varda's avatar
Kenton Varda committed
359
  List<schema::Field>::Reader list;
Kenton Varda's avatar
Kenton Varda committed
360 361
  const uint16_t* indices;
  uint size_;
362

Kenton Varda's avatar
Kenton Varda committed
363
  inline FieldSubset(StructSchema parent, List<schema::Field>::Reader list,
Kenton Varda's avatar
Kenton Varda committed
364 365
                     const uint16_t* indices, uint size)
      : parent(parent), list(list), indices(indices), size_(size) {}
366 367 368 369 370 371 372 373

  friend class StructSchema;
};

// -------------------------------------------------------------------

class EnumSchema: public Schema {
public:
374
  inline EnumSchema(): Schema(&_::NULL_ENUM_SCHEMA.defaultBrand) {}
375

376 377 378
  class Enumerant;
  class EnumerantList;

379
  EnumerantList getEnumerants() const;
Kenton Varda's avatar
Kenton Varda committed
380

381
  kj::Maybe<Enumerant> findEnumerantByName(kj::StringPtr name) const;
382

383
  Enumerant getEnumerantByName(kj::StringPtr name) const;
Kenton Varda's avatar
Kenton Varda committed
384 385
  // Like findEnumerantByName() but throws an exception on failure.

386
private:
387
  EnumSchema(Schema base): Schema(base) {}
388
  template <typename T> static inline EnumSchema fromImpl() {
389
    return EnumSchema(Schema(&_::rawBrandedSchema<T>()));
390 391
  }
  friend class Schema;
392
  friend class Type;
393 394 395 396 397 398
};

class EnumSchema::Enumerant {
public:
  Enumerant() = default;

Kenton Varda's avatar
Kenton Varda committed
399
  inline schema::Enumerant::Reader getProto() const { return proto; }
Kenton Varda's avatar
Kenton Varda committed
400
  inline EnumSchema getContainingEnum() const { return parent; }
401

Kenton Varda's avatar
Kenton Varda committed
402 403
  inline uint16_t getOrdinal() const { return ordinal; }
  inline uint getIndex() const { return ordinal; }
404 405 406

  inline bool operator==(const Enumerant& other) const;
  inline bool operator!=(const Enumerant& other) const { return !(*this == other); }
407
  inline uint hashCode() const;
408 409 410 411

private:
  EnumSchema parent;
  uint16_t ordinal;
Kenton Varda's avatar
Kenton Varda committed
412
  schema::Enumerant::Reader proto;
413

Kenton Varda's avatar
Kenton Varda committed
414
  inline Enumerant(EnumSchema parent, uint16_t ordinal, schema::Enumerant::Reader proto)
415 416 417 418 419 420 421
      : parent(parent), ordinal(ordinal), proto(proto) {}

  friend class EnumSchema;
};

class EnumSchema::EnumerantList {
public:
422 423
  EnumerantList() = default;  // empty list

424 425 426
  inline uint size() const { return list.size(); }
  inline Enumerant operator[](uint index) const { return Enumerant(parent, index, list[index]); }

427
  typedef _::IndexingIterator<const EnumerantList, Enumerant> Iterator;
428 429
  inline Iterator begin() const { return Iterator(this, 0); }
  inline Iterator end() const { return Iterator(this, size()); }
430 431 432

private:
  EnumSchema parent;
Kenton Varda's avatar
Kenton Varda committed
433
  List<schema::Enumerant>::Reader list;
434

Kenton Varda's avatar
Kenton Varda committed
435
  inline EnumerantList(EnumSchema parent, List<schema::Enumerant>::Reader list)
436 437 438 439 440 441 442 443 444
      : parent(parent), list(list) {}

  friend class EnumSchema;
};

// -------------------------------------------------------------------

class InterfaceSchema: public Schema {
public:
445
  inline InterfaceSchema(): Schema(&_::NULL_INTERFACE_SCHEMA.defaultBrand) {}
446

447 448 449
  class Method;
  class MethodList;

450
  MethodList getMethods() const;
Kenton Varda's avatar
Kenton Varda committed
451

452
  kj::Maybe<Method> findMethodByName(kj::StringPtr name) const;
453

454
  Method getMethodByName(kj::StringPtr name) const;
Kenton Varda's avatar
Kenton Varda committed
455 456
  // Like findMethodByName() but throws an exception on failure.

457 458 459 460 461
  class SuperclassList;

  SuperclassList getSuperclasses() const;
  // Get the immediate superclasses of this type, after applying generics.

462 463 464 465 466 467 468
  bool extends(InterfaceSchema other) const;
  // Returns true if `other` is a superclass of this interface (including if `other == *this`).

  kj::Maybe<InterfaceSchema> findSuperclass(uint64_t typeId) const;
  // Find the superclass of this interface with the given type ID.  Returns null if the interface
  // extends no such type.

469
private:
470
  InterfaceSchema(Schema base): Schema(base) {}
471
  template <typename T> static inline InterfaceSchema fromImpl() {
472
    return InterfaceSchema(Schema(&_::rawBrandedSchema<T>()));
473 474
  }
  friend class Schema;
475
  friend class Type;
476 477 478 479 480 481

  kj::Maybe<Method> findMethodByName(kj::StringPtr name, uint& counter) const;
  bool extends(InterfaceSchema other, uint& counter) const;
  kj::Maybe<InterfaceSchema> findSuperclass(uint64_t typeId, uint& counter) const;
  // We protect against malicious schemas with large or cyclic hierarchies by cutting off the
  // search when the counter reaches a threshold.
482 483 484 485 486 487
};

class InterfaceSchema::Method {
public:
  Method() = default;

Kenton Varda's avatar
Kenton Varda committed
488
  inline schema::Method::Reader getProto() const { return proto; }
Kenton Varda's avatar
Kenton Varda committed
489
  inline InterfaceSchema getContainingInterface() const { return parent; }
490

Kenton Varda's avatar
Kenton Varda committed
491 492
  inline uint16_t getOrdinal() const { return ordinal; }
  inline uint getIndex() const { return ordinal; }
493

494 495 496 497
  StructSchema getParamType() const;
  StructSchema getResultType() const;
  // Get the parameter and result types, including substituting generic parameters.

498 499
  inline bool operator==(const Method& other) const;
  inline bool operator!=(const Method& other) const { return !(*this == other); }
500
  inline uint hashCode() const;
501 502 503 504

private:
  InterfaceSchema parent;
  uint16_t ordinal;
Kenton Varda's avatar
Kenton Varda committed
505
  schema::Method::Reader proto;
506 507

  inline Method(InterfaceSchema parent, uint16_t ordinal,
Kenton Varda's avatar
Kenton Varda committed
508
                schema::Method::Reader proto)
509 510 511 512 513 514 515
      : parent(parent), ordinal(ordinal), proto(proto) {}

  friend class InterfaceSchema;
};

class InterfaceSchema::MethodList {
public:
516 517
  MethodList() = default;  // empty list

518 519 520
  inline uint size() const { return list.size(); }
  inline Method operator[](uint index) const { return Method(parent, index, list[index]); }

521
  typedef _::IndexingIterator<const MethodList, Method> Iterator;
522 523
  inline Iterator begin() const { return Iterator(this, 0); }
  inline Iterator end() const { return Iterator(this, size()); }
524 525 526

private:
  InterfaceSchema parent;
Kenton Varda's avatar
Kenton Varda committed
527
  List<schema::Method>::Reader list;
528

Kenton Varda's avatar
Kenton Varda committed
529
  inline MethodList(InterfaceSchema parent, List<schema::Method>::Reader list)
530 531 532 533 534
      : parent(parent), list(list) {}

  friend class InterfaceSchema;
};

535 536 537 538 539 540 541
class InterfaceSchema::SuperclassList {
public:
  SuperclassList() = default;  // empty list

  inline uint size() const { return list.size(); }
  InterfaceSchema operator[](uint index) const;

542
  typedef _::IndexingIterator<const SuperclassList, InterfaceSchema> Iterator;
543 544 545 546 547
  inline Iterator begin() const { return Iterator(this, 0); }
  inline Iterator end() const { return Iterator(this, size()); }

private:
  InterfaceSchema parent;
548
  List<schema::Superclass>::Reader list;
549

550
  inline SuperclassList(InterfaceSchema parent, List<schema::Superclass>::Reader list)
551 552 553 554 555
      : parent(parent), list(list) {}

  friend class InterfaceSchema;
};

556 557
// -------------------------------------------------------------------

558 559 560 561 562 563
class ConstSchema: public Schema {
  // Represents a constant declaration.
  //
  // `ConstSchema` can be implicitly cast to DynamicValue to read its value.

public:
564
  inline ConstSchema(): Schema(&_::NULL_CONST_SCHEMA.defaultBrand) {}
565 566 567 568 569 570 571 572 573 574 575 576

  template <typename T>
  ReaderFor<T> as() const;
  // Read the constant's value.  This is a convenience method equivalent to casting the ConstSchema
  // to a DynamicValue and then calling its `as<T>()` method.  For dependency reasons, this method
  // is defined in <capnp/dynamic.h>, which you must #include explicitly.

  uint32_t getValueSchemaOffset() const;
  // Much like StructSchema::Field::getDefaultValueSchemaOffset(), if the constant has pointer
  // type, this gets the offset from the beginning of the constant's schema node to a pointer
  // representing the constant value.

577 578
  Type getType() const;

579
private:
580
  ConstSchema(Schema base): Schema(base) {}
581 582 583 584 585
  friend class Schema;
};

// -------------------------------------------------------------------

586 587 588 589 590 591
class Type {
public:
  struct BrandParameter {
    uint64_t scopeId;
    uint index;
  };
592 593 594
  struct ImplicitParameter {
    uint index;
  };
595 596 597 598 599 600 601

  inline Type();
  inline Type(schema::Type::Which primitive);
  inline Type(StructSchema schema);
  inline Type(EnumSchema schema);
  inline Type(InterfaceSchema schema);
  inline Type(ListSchema schema);
602
  inline Type(schema::Type::AnyPointer::Unconstrained::Which anyPointerKind);
603
  inline Type(BrandParameter param);
604
  inline Type(ImplicitParameter param);
605 606 607

  template <typename T>
  inline static Type from();
608 609
  template <typename T>
  inline static Type from(T&& value);
610 611 612 613 614 615 616 617 618 619 620 621 622

  inline schema::Type::Which which() const;

  StructSchema asStruct() const;
  EnumSchema asEnum() const;
  InterfaceSchema asInterface() const;
  ListSchema asList() const;
  // Each of these methods may only be called if which() returns the corresponding type.

  kj::Maybe<BrandParameter> getBrandParameter() const;
  // Only callable if which() returns ANY_POINTER. Returns null if the type is just a regular
  // AnyPointer and not a parameter.

623 624 625 626
  kj::Maybe<ImplicitParameter> getImplicitParameter() const;
  // Only callable if which() returns ANY_POINTER. Returns null if the type is just a regular
  // AnyPointer and not a parameter. "Implicit parameters" refer to type parameters on methods.

627 628 629
  inline schema::Type::AnyPointer::Unconstrained::Which whichAnyPointerKind() const;
  // Only callable if which() returns ANY_POINTER.

630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652
  inline bool isVoid() const;
  inline bool isBool() const;
  inline bool isInt8() const;
  inline bool isInt16() const;
  inline bool isInt32() const;
  inline bool isInt64() const;
  inline bool isUInt8() const;
  inline bool isUInt16() const;
  inline bool isUInt32() const;
  inline bool isUInt64() const;
  inline bool isFloat32() const;
  inline bool isFloat64() const;
  inline bool isText() const;
  inline bool isData() const;
  inline bool isList() const;
  inline bool isEnum() const;
  inline bool isStruct() const;
  inline bool isInterface() const;
  inline bool isAnyPointer() const;

  bool operator==(const Type& other) const;
  inline bool operator!=(const Type& other) const { return !(*this == other); }

653
  uint hashCode() const;
654

Kenton Varda's avatar
Kenton Varda committed
655 656 657 658 659 660
  inline Type wrapInList(uint depth = 1) const;
  // Return the Type formed by wrapping this type in List() `depth` times.

  inline Type(schema::Type::Which derived, const _::RawBrandedSchema* schema);
  // For internal use.

661 662 663 664
private:
  schema::Type::Which baseType;  // type not including applications of List()
  uint8_t listDepth;             // 0 for T, 1 for List(T), 2 for List(List(T)), ...

665 666 667 668
  bool isImplicitParam;
  // If true, this refers to an implicit method parameter. baseType must be ANY_POINTER, scopeId
  // must be zero, and paramIndex indicates the parameter index.

669 670 671 672 673 674 675 676 677
  union {
    uint16_t paramIndex;
    // If baseType is ANY_POINTER but this Type actually refers to a type parameter, this is the
    // index of the parameter among the parameters at its scope, and `scopeId` below is the type ID
    // of the scope where the parameter was defined.

    schema::Type::AnyPointer::Unconstrained::Which anyPointerKind;
    // If scopeId is zero and isImplicitParam is false.
  };
678 679 680 681 682 683 684

  union {
    const _::RawBrandedSchema* schema;  // if type is struct, enum, interface...
    uint64_t scopeId;  // if type is AnyPointer but it's actually a type parameter...
  };

  Type(schema::Type::Which baseType, uint8_t listDepth, const _::RawBrandedSchema* schema)
Kenton Varda's avatar
Kenton Varda committed
685 686 687
      : baseType(baseType), listDepth(listDepth), schema(schema) {
    KJ_IREQUIRE(baseType != schema::Type::ANY_POINTER);
  }
688 689 690

  void requireUsableAs(Type expected) const;

691 692 693
  template <typename T, Kind k>
  struct FromValueImpl;

694
  friend class ListSchema;  // only for requireUsableAs()
695 696 697 698
};

// -------------------------------------------------------------------

699 700 701 702 703 704 705
class ListSchema {
  // ListSchema is a little different because list types are not described by schema nodes.  So,
  // ListSchema doesn't subclass Schema.

public:
  ListSchema() = default;

Kenton Varda's avatar
Kenton Varda committed
706
  static ListSchema of(schema::Type::Which primitiveType);
707 708 709 710
  static ListSchema of(StructSchema elementType);
  static ListSchema of(EnumSchema elementType);
  static ListSchema of(InterfaceSchema elementType);
  static ListSchema of(ListSchema elementType);
711
  static ListSchema of(Type elementType);
712 713
  // Construct the schema for a list of the given type.

714
  static ListSchema of(schema::Type::Reader elementType, Schema context)
715
      CAPNP_DEPRECATED("Does not handle generics correctly.");
716 717 718 719 720
  // DEPRECATED: This method cannot correctly account for generic type parameter bindings that
  //   may apply to the input type. Instead of using this method, use a method of the Schema API
  //   that corresponds to the exact kind of dependency. For example, to get a field type, use
  //   StructSchema::Field::getType().
  //
721 722 723
  // Construct from an element type schema.  Requires a context which can handle getDependency()
  // requests for any type ID found in the schema.

724 725
  Type getElementType() const;

Kenton Varda's avatar
Kenton Varda committed
726
  inline schema::Type::Which whichElementType() const;
727 728 729 730 731 732 733 734 735 736 737
  // Get the element type's "which()".  ListSchema does not actually store a schema::Type::Reader
  // describing the element type, but if it did, this would be equivalent to calling
  // .getBody().which() on that type.

  StructSchema getStructElementType() const;
  EnumSchema getEnumElementType() const;
  InterfaceSchema getInterfaceElementType() const;
  ListSchema getListElementType() const;
  // Get the schema for complex element types.  Each of these throws an exception if the element
  // type is not of the requested kind.

738 739
  inline bool operator==(const ListSchema& other) const { return elementType == other.elementType; }
  inline bool operator!=(const ListSchema& other) const { return elementType != other.elementType; }
740

741
  template <typename T>
742
  void requireUsableAs() const;
743

744
private:
745 746 747
  Type elementType;

  inline explicit ListSchema(Type elementType): elementType(elementType) {}
748 749 750 751 752 753 754

  template <typename T>
  struct FromImpl;
  template <typename T> static inline ListSchema fromImpl() {
    return FromImpl<T>::get();
  }

755
  void requireUsableAs(ListSchema expected) const;
756

757 758 759 760 761 762
  friend class Schema;
};

// =======================================================================================
// inline implementation

Kenton Varda's avatar
Kenton Varda committed
763 764 765 766 767 768 769 770 771 772 773 774 775 776
template <> inline schema::Type::Which Schema::from<Void>() { return schema::Type::VOID; }
template <> inline schema::Type::Which Schema::from<bool>() { return schema::Type::BOOL; }
template <> inline schema::Type::Which Schema::from<int8_t>() { return schema::Type::INT8; }
template <> inline schema::Type::Which Schema::from<int16_t>() { return schema::Type::INT16; }
template <> inline schema::Type::Which Schema::from<int32_t>() { return schema::Type::INT32; }
template <> inline schema::Type::Which Schema::from<int64_t>() { return schema::Type::INT64; }
template <> inline schema::Type::Which Schema::from<uint8_t>() { return schema::Type::UINT8; }
template <> inline schema::Type::Which Schema::from<uint16_t>() { return schema::Type::UINT16; }
template <> inline schema::Type::Which Schema::from<uint32_t>() { return schema::Type::UINT32; }
template <> inline schema::Type::Which Schema::from<uint64_t>() { return schema::Type::UINT64; }
template <> inline schema::Type::Which Schema::from<float>() { return schema::Type::FLOAT32; }
template <> inline schema::Type::Which Schema::from<double>() { return schema::Type::FLOAT64; }
template <> inline schema::Type::Which Schema::from<Text>() { return schema::Type::TEXT; }
template <> inline schema::Type::Which Schema::from<Data>() { return schema::Type::DATA; }
777

778 779 780 781
inline Schema Schema::getDependency(uint64_t id) const {
  return getDependency(id, 0);
}

782 783 784 785 786 787 788 789
inline bool Schema::isBranded() const {
  return raw != &raw->generic->defaultBrand;
}

inline Schema Schema::getGeneric() const {
  return Schema(&raw->generic->defaultBrand);
}

790
template <typename T>
791
inline void Schema::requireUsableAs() const {
792
  requireUsableAs(&_::rawSchema<T>());
793 794
}

Kenton Varda's avatar
Kenton Varda committed
795 796
inline bool StructSchema::Field::operator==(const Field& other) const {
  return parent == other.parent && index == other.index;
797 798 799 800 801 802 803 804
}
inline bool EnumSchema::Enumerant::operator==(const Enumerant& other) const {
  return parent == other.parent && ordinal == other.ordinal;
}
inline bool InterfaceSchema::Method::operator==(const Method& other) const {
  return parent == other.parent && ordinal == other.ordinal;
}

805 806 807 808
inline uint StructSchema::Field::hashCode() const {
  return kj::hashCode(parent, index);
}
inline uint EnumSchema::Enumerant::hashCode() const {
809
  return kj::hashCode(parent, ordinal);
810 811
}
inline uint InterfaceSchema::Method::hashCode() const {
812
  return kj::hashCode(parent, ordinal);
813 814
}

815
inline ListSchema ListSchema::of(StructSchema elementType) {
816
  return ListSchema(Type(elementType));
817 818
}
inline ListSchema ListSchema::of(EnumSchema elementType) {
819
  return ListSchema(Type(elementType));
820 821
}
inline ListSchema ListSchema::of(InterfaceSchema elementType) {
822
  return ListSchema(Type(elementType));
823 824
}
inline ListSchema ListSchema::of(ListSchema elementType) {
825
  return ListSchema(Type(elementType));
826
}
827
inline ListSchema ListSchema::of(Type elementType) {
828
  return ListSchema(elementType);
829 830 831
}

inline Type ListSchema::getElementType() const {
832
  return elementType;
833
}
834

Kenton Varda's avatar
Kenton Varda committed
835
inline schema::Type::Which ListSchema::whichElementType() const {
836 837 838 839 840 841 842 843 844 845 846 847 848
  return elementType.which();
}

inline StructSchema ListSchema::getStructElementType() const {
  return elementType.asStruct();
}

inline EnumSchema ListSchema::getEnumElementType() const {
  return elementType.asEnum();
}

inline InterfaceSchema ListSchema::getInterfaceElementType() const {
  return elementType.asInterface();
849 850
}

851 852
inline ListSchema ListSchema::getListElementType() const {
  return elementType.asList();
853 854
}

855
template <typename T>
856
inline void ListSchema::requireUsableAs() const {
857 858 859 860 861
  static_assert(kind<T>() == Kind::LIST,
                "ListSchema::requireUsableAs<T>() requires T is a list type.");
  requireUsableAs(Schema::from<T>());
}

862 863 864 865
inline void ListSchema::requireUsableAs(ListSchema expected) const {
  elementType.requireUsableAs(expected.elementType);
}

866 867 868 869 870
template <typename T>
struct ListSchema::FromImpl<List<T>> {
  static inline ListSchema get() { return of(Schema::from<T>()); }
};

871
inline Type::Type(): baseType(schema::Type::VOID), listDepth(0), schema(nullptr) {}
872
inline Type::Type(schema::Type::Which primitive)
Kenton Varda's avatar
Kenton Varda committed
873
    : baseType(primitive), listDepth(0), isImplicitParam(false) {
874 875 876 877
  KJ_IREQUIRE(primitive != schema::Type::STRUCT &&
              primitive != schema::Type::ENUM &&
              primitive != schema::Type::INTERFACE &&
              primitive != schema::Type::LIST);
Kenton Varda's avatar
Kenton Varda committed
878 879
  if (primitive == schema::Type::ANY_POINTER) {
    scopeId = 0;
880
    anyPointerKind = schema::Type::AnyPointer::Unconstrained::ANY_KIND;
Kenton Varda's avatar
Kenton Varda committed
881 882 883 884 885 886 887 888 889
  } else {
    schema = nullptr;
  }
}
inline Type::Type(schema::Type::Which derived, const _::RawBrandedSchema* schema)
    : baseType(derived), listDepth(0), isImplicitParam(false), schema(schema) {
  KJ_IREQUIRE(derived == schema::Type::STRUCT ||
              derived == schema::Type::ENUM ||
              derived == schema::Type::INTERFACE);
890 891 892
}

inline Type::Type(StructSchema schema)
893
    : baseType(schema::Type::STRUCT), listDepth(0), schema(schema.raw) {}
894
inline Type::Type(EnumSchema schema)
895
    : baseType(schema::Type::ENUM), listDepth(0), schema(schema.raw) {}
896
inline Type::Type(InterfaceSchema schema)
897
    : baseType(schema::Type::INTERFACE), listDepth(0), schema(schema.raw) {}
898
inline Type::Type(ListSchema schema)
899
    : Type(schema.getElementType()) { ++listDepth; }
900 901 902
inline Type::Type(schema::Type::AnyPointer::Unconstrained::Which anyPointerKind)
    : baseType(schema::Type::ANY_POINTER), listDepth(0), isImplicitParam(false),
      anyPointerKind(anyPointerKind), scopeId(0) {}
903
inline Type::Type(BrandParameter param)
904 905 906 907 908
    : baseType(schema::Type::ANY_POINTER), listDepth(0), isImplicitParam(false),
      paramIndex(param.index), scopeId(param.scopeId) {}
inline Type::Type(ImplicitParameter param)
    : baseType(schema::Type::ANY_POINTER), listDepth(0), isImplicitParam(true),
      paramIndex(param.index), scopeId(0) {}
909

910 911 912 913
inline schema::Type::Which Type::which() const {
  return listDepth > 0 ? schema::Type::LIST : baseType;
}

914 915 916 917 918 919
inline schema::Type::AnyPointer::Unconstrained::Which Type::whichAnyPointerKind() const {
  KJ_IREQUIRE(baseType == schema::Type::ANY_POINTER);
  return !isImplicitParam && scopeId == 0 ? anyPointerKind
      : schema::Type::AnyPointer::Unconstrained::ANY_KIND;
}

920 921 922
template <typename T>
inline Type Type::from() { return Type(Schema::from<T>()); }

923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945
template <typename T, Kind k>
struct Type::FromValueImpl {
  template <typename U>
  static inline Type type(U&& value) {
    return Type::from<T>();
  }
};

template <typename T>
struct Type::FromValueImpl<T, Kind::OTHER> {
  template <typename U>
  static inline Type type(U&& value) {
    // All dynamic types have getSchema().
    return value.getSchema();
  }
};

template <typename T>
inline Type Type::from(T&& value) {
  typedef FromAny<kj::Decay<T>> Base;
  return Type::FromValueImpl<Base, kind<Base>()>::type(kj::fwd<T>(value));
}

946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968
inline bool Type::isVoid   () const { return baseType == schema::Type::VOID     && listDepth == 0; }
inline bool Type::isBool   () const { return baseType == schema::Type::BOOL     && listDepth == 0; }
inline bool Type::isInt8   () const { return baseType == schema::Type::INT8     && listDepth == 0; }
inline bool Type::isInt16  () const { return baseType == schema::Type::INT16    && listDepth == 0; }
inline bool Type::isInt32  () const { return baseType == schema::Type::INT32    && listDepth == 0; }
inline bool Type::isInt64  () const { return baseType == schema::Type::INT64    && listDepth == 0; }
inline bool Type::isUInt8  () const { return baseType == schema::Type::UINT8    && listDepth == 0; }
inline bool Type::isUInt16 () const { return baseType == schema::Type::UINT16   && listDepth == 0; }
inline bool Type::isUInt32 () const { return baseType == schema::Type::UINT32   && listDepth == 0; }
inline bool Type::isUInt64 () const { return baseType == schema::Type::UINT64   && listDepth == 0; }
inline bool Type::isFloat32() const { return baseType == schema::Type::FLOAT32  && listDepth == 0; }
inline bool Type::isFloat64() const { return baseType == schema::Type::FLOAT64  && listDepth == 0; }
inline bool Type::isText   () const { return baseType == schema::Type::TEXT     && listDepth == 0; }
inline bool Type::isData   () const { return baseType == schema::Type::DATA     && listDepth == 0; }
inline bool Type::isList   () const { return listDepth > 0; }
inline bool Type::isEnum   () const { return baseType == schema::Type::ENUM     && listDepth == 0; }
inline bool Type::isStruct () const { return baseType == schema::Type::STRUCT   && listDepth == 0; }
inline bool Type::isInterface() const {
  return baseType == schema::Type::INTERFACE && listDepth == 0;
}
inline bool Type::isAnyPointer() const {
  return baseType == schema::Type::ANY_POINTER && listDepth == 0;
}
969

Kenton Varda's avatar
Kenton Varda committed
970 971 972 973 974 975
inline Type Type::wrapInList(uint depth) const {
  Type result = *this;
  result.listDepth += depth;
  return result;
}

976
}  // namespace capnp