annotate src/capnproto-git-20161025/doc/language.md @ 133:1ac99bfc383d

Add Cap'n Proto source
author Chris Cannam <cannam@all-day-breakfast.com>
date Tue, 25 Oct 2016 11:17:01 +0100
parents
children
rev   line source
cannam@133 1 ---
cannam@133 2 layout: page
cannam@133 3 title: Schema Language
cannam@133 4 ---
cannam@133 5
cannam@133 6 # Schema Language
cannam@133 7
cannam@133 8 Like Protocol Buffers and Thrift (but unlike JSON or MessagePack), Cap'n Proto messages are
cannam@133 9 strongly-typed and not self-describing. You must define your message structure in a special
cannam@133 10 language, then invoke the Cap'n Proto compiler (`capnp compile`) to generate source code to
cannam@133 11 manipulate that message type in your desired language.
cannam@133 12
cannam@133 13 For example:
cannam@133 14
cannam@133 15 {% highlight capnp %}
cannam@133 16 @0xdbb9ad1f14bf0b36; # unique file ID, generated by `capnp id`
cannam@133 17
cannam@133 18 struct Person {
cannam@133 19 name @0 :Text;
cannam@133 20 birthdate @3 :Date;
cannam@133 21
cannam@133 22 email @1 :Text;
cannam@133 23 phones @2 :List(PhoneNumber);
cannam@133 24
cannam@133 25 struct PhoneNumber {
cannam@133 26 number @0 :Text;
cannam@133 27 type @1 :Type;
cannam@133 28
cannam@133 29 enum Type {
cannam@133 30 mobile @0;
cannam@133 31 home @1;
cannam@133 32 work @2;
cannam@133 33 }
cannam@133 34 }
cannam@133 35 }
cannam@133 36
cannam@133 37 struct Date {
cannam@133 38 year @0 :Int16;
cannam@133 39 month @1 :UInt8;
cannam@133 40 day @2 :UInt8;
cannam@133 41 }
cannam@133 42 {% endhighlight %}
cannam@133 43
cannam@133 44 Some notes:
cannam@133 45
cannam@133 46 * Types come after names. The name is by far the most important thing to see, especially when
cannam@133 47 quickly skimming, so we put it up front where it is most visible. Sorry, C got it wrong.
cannam@133 48 * The `@N` annotations show how the protocol evolved over time, so that the system can make sure
cannam@133 49 to maintain compatibility with older versions. Fields (and enumerants, and interface methods)
cannam@133 50 must be numbered consecutively starting from zero in the order in which they were added. In this
cannam@133 51 example, it looks like the `birthdate` field was added to the `Person` structure recently -- its
cannam@133 52 number is higher than the `email` and `phones` fields. Unlike Protobufs, you cannot skip numbers
cannam@133 53 when defining fields -- but there was never any reason to do so anyway.
cannam@133 54
cannam@133 55 ## Language Reference
cannam@133 56
cannam@133 57 ### Comments
cannam@133 58
cannam@133 59 Comments are indicated by hash signs and extend to the end of the line:
cannam@133 60
cannam@133 61 {% highlight capnp %}
cannam@133 62 # This is a comment.
cannam@133 63 {% endhighlight %}
cannam@133 64
cannam@133 65 Comments meant as documentation should appear _after_ the declaration, either on the same line, or
cannam@133 66 on a subsequent line. Doc comments for aggregate definitions should appear on the line after the
cannam@133 67 opening brace.
cannam@133 68
cannam@133 69 {% highlight capnp %}
cannam@133 70 struct Date {
cannam@133 71 # A standard Gregorian calendar date.
cannam@133 72
cannam@133 73 year @0 :Int16;
cannam@133 74 # The year. Must include the century.
cannam@133 75 # Negative value indicates BC.
cannam@133 76
cannam@133 77 month @1 :UInt8; # Month number, 1-12.
cannam@133 78 day @2 :UInt8; # Day number, 1-30.
cannam@133 79 }
cannam@133 80 {% endhighlight %}
cannam@133 81
cannam@133 82 Placing the comment _after_ the declaration rather than before makes the code more readable,
cannam@133 83 especially when doc comments grow long. You almost always need to see the declaration before you
cannam@133 84 can start reading the comment.
cannam@133 85
cannam@133 86 ### Built-in Types
cannam@133 87
cannam@133 88 The following types are automatically defined:
cannam@133 89
cannam@133 90 * **Void:** `Void`
cannam@133 91 * **Boolean:** `Bool`
cannam@133 92 * **Integers:** `Int8`, `Int16`, `Int32`, `Int64`
cannam@133 93 * **Unsigned integers:** `UInt8`, `UInt16`, `UInt32`, `UInt64`
cannam@133 94 * **Floating-point:** `Float32`, `Float64`
cannam@133 95 * **Blobs:** `Text`, `Data`
cannam@133 96 * **Lists:** `List(T)`
cannam@133 97
cannam@133 98 Notes:
cannam@133 99
cannam@133 100 * The `Void` type has exactly one possible value, and thus can be encoded in zero bits. It is
cannam@133 101 rarely used, but can be useful as a union member.
cannam@133 102 * `Text` is always UTF-8 encoded and NUL-terminated.
cannam@133 103 * `Data` is a completely arbitrary sequence of bytes.
cannam@133 104 * `List` is a parameterized type, where the parameter is the element type. For example,
cannam@133 105 `List(Int32)`, `List(Person)`, and `List(List(Text))` are all valid.
cannam@133 106
cannam@133 107 ### Structs
cannam@133 108
cannam@133 109 A struct has a set of named, typed fields, numbered consecutively starting from zero.
cannam@133 110
cannam@133 111 {% highlight capnp %}
cannam@133 112 struct Person {
cannam@133 113 name @0 :Text;
cannam@133 114 email @1 :Text;
cannam@133 115 }
cannam@133 116 {% endhighlight %}
cannam@133 117
cannam@133 118 Fields can have default values:
cannam@133 119
cannam@133 120 {% highlight capnp %}
cannam@133 121 foo @0 :Int32 = 123;
cannam@133 122 bar @1 :Text = "blah";
cannam@133 123 baz @2 :List(Bool) = [ true, false, false, true ];
cannam@133 124 qux @3 :Person = (name = "Bob", email = "bob@example.com");
cannam@133 125 corge @4 :Void = void;
cannam@133 126 grault @5 :Data = 0x"a1 40 33";
cannam@133 127 {% endhighlight %}
cannam@133 128
cannam@133 129 ### Unions
cannam@133 130
cannam@133 131 A union is two or more fields of a struct which are stored in the same location. Only one of
cannam@133 132 these fields can be set at a time, and a separate tag is maintained to track which one is
cannam@133 133 currently set. Unlike in C, unions are not types, they are simply properties of fields, therefore
cannam@133 134 union declarations do not look like types.
cannam@133 135
cannam@133 136 {% highlight capnp %}
cannam@133 137 struct Person {
cannam@133 138 # ...
cannam@133 139
cannam@133 140 employment :union {
cannam@133 141 unemployed @4 :Void;
cannam@133 142 employer @5 :Company;
cannam@133 143 school @6 :School;
cannam@133 144 selfEmployed @7 :Void;
cannam@133 145 # We assume that a person is only one of these.
cannam@133 146 }
cannam@133 147 }
cannam@133 148 {% endhighlight %}
cannam@133 149
cannam@133 150 Additionally, unions can be unnamed. Each struct can contain no more than one unnamed union. Use
cannam@133 151 unnamed unions in cases where you would struggle to think of an appropriate name for the union,
cannam@133 152 because the union represents the main body of the struct.
cannam@133 153
cannam@133 154 {% highlight capnp %}
cannam@133 155 struct Shape {
cannam@133 156 area @0 :Float64;
cannam@133 157
cannam@133 158 union {
cannam@133 159 circle @1 :Float64; # radius
cannam@133 160 square @2 :Float64; # width
cannam@133 161 }
cannam@133 162 }
cannam@133 163 {% endhighlight %}
cannam@133 164
cannam@133 165 Notes:
cannam@133 166
cannam@133 167 * Unions members are numbered in the same number space as fields of the containing struct.
cannam@133 168 Remember that the purpose of the numbers is to indicate the evolution order of the
cannam@133 169 struct. The system needs to know when the union fields were declared relative to the non-union
cannam@133 170 fields.
cannam@133 171
cannam@133 172 * Notice that we used the "useless" `Void` type here. We don't have any extra information to store
cannam@133 173 for the `unemployed` or `selfEmployed` cases, but we still want the union to distinguish these
cannam@133 174 states from others.
cannam@133 175
cannam@133 176 * By default, when a struct is initialized, the lowest-numbered field in the union is "set". If
cannam@133 177 you do not want any field set by default, simply declare a field called "unset" and make it the
cannam@133 178 lowest-numbered field.
cannam@133 179
cannam@133 180 * You can move an existing field into a new union without breaking compatibility with existing
cannam@133 181 data, as long as all of the other fields in the union are new. Since the existing field is
cannam@133 182 necessarily the lowest-numbered in the union, it will be the union's default field.
cannam@133 183
cannam@133 184 **Wait, why aren't unions first-class types?**
cannam@133 185
cannam@133 186 Requiring unions to be declared inside a struct, rather than living as free-standing types, has
cannam@133 187 some important advantages:
cannam@133 188
cannam@133 189 * If unions were first-class types, then union members would clearly have to be numbered separately
cannam@133 190 from the containing type's fields. This means that the compiler, when deciding how to position
cannam@133 191 the union in its containing struct, would have to conservatively assume that any kind of new
cannam@133 192 field might be added to the union in the future. To support this, all unions would have to
cannam@133 193 be allocated as separate objects embedded by pointer, wasting space.
cannam@133 194
cannam@133 195 * A free-standing union would be a liability for protocol evolution, because no additional data
cannam@133 196 can be attached to it later on. Consider, for example, a type which represents a parser token.
cannam@133 197 This type is naturally a union: it may be a keyword, identifier, numeric literal, quoted string,
cannam@133 198 etc. So the author defines it as a union, and the type is used widely. Later on, the developer
cannam@133 199 wants to attach information to the token indicating its line and column number in the source
cannam@133 200 file. Unfortunately, this is impossible without updating all users of the type, because the new
cannam@133 201 information ought to apply to _all_ token instances, not just specific members of the union. On
cannam@133 202 the other hand, if unions must be embedded within structs, it is always possible to add new
cannam@133 203 fields to the struct later on.
cannam@133 204
cannam@133 205 * When evolving a protocol it is common to discover that some existing field really should have
cannam@133 206 been enclosed in a union, because new fields being added are mutually exclusive with it. With
cannam@133 207 Cap'n Proto's unions, it is actually possible to "retroactively unionize" such a field without
cannam@133 208 changing its layout. This allows you to continue being able to read old data without wasting
cannam@133 209 space when writing new data. This is only possible when unions are declared within their
cannam@133 210 containing struct.
cannam@133 211
cannam@133 212 Cap'n Proto's unconventional approach to unions provides these advantages without any real down
cannam@133 213 side: where you would conventionally define a free-standing union type, in Cap'n Proto you
cannam@133 214 may simply define a struct type that contains only that union (probably unnamed), and you have
cannam@133 215 achieved the same effect. Thus, aside from being slightly unintuitive, it is strictly superior.
cannam@133 216
cannam@133 217 ### Groups
cannam@133 218
cannam@133 219 A group is a set of fields that are encapsulated in their own scope.
cannam@133 220
cannam@133 221 {% highlight capnp %}
cannam@133 222 struct Person {
cannam@133 223 # ...
cannam@133 224
cannam@133 225 # Note: This is a terrible way to use groups, and meant
cannam@133 226 # only to demonstrate the syntax.
cannam@133 227 address :group {
cannam@133 228 houseNumber @8 :UInt32;
cannam@133 229 street @9 :Text;
cannam@133 230 city @10 :Text;
cannam@133 231 country @11 :Text;
cannam@133 232 }
cannam@133 233 }
cannam@133 234 {% endhighlight %}
cannam@133 235
cannam@133 236 Interface-wise, the above group behaves as if you had defined a nested struct called `Address` and
cannam@133 237 then a field `address :Address`. However, a group is _not_ a separate object from its containing
cannam@133 238 struct: the fields are numbered in the same space as the containing struct's fields, and are laid
cannam@133 239 out exactly the same as if they hadn't been grouped at all. Essentially, a group is just a
cannam@133 240 namespace.
cannam@133 241
cannam@133 242 Groups on their own (as in the above example) are useless, almost as much so as the `Void` type.
cannam@133 243 They become interesting when used together with unions.
cannam@133 244
cannam@133 245 {% highlight capnp %}
cannam@133 246 struct Shape {
cannam@133 247 area @0 :Float64;
cannam@133 248
cannam@133 249 union {
cannam@133 250 circle :group {
cannam@133 251 radius @1 :Float64;
cannam@133 252 }
cannam@133 253 rectangle :group {
cannam@133 254 width @2 :Float64;
cannam@133 255 height @3 :Float64;
cannam@133 256 }
cannam@133 257 }
cannam@133 258 }
cannam@133 259 {% endhighlight %}
cannam@133 260
cannam@133 261 There are two main reason to use groups with unions:
cannam@133 262
cannam@133 263 1. They are often more self-documenting. Notice that `radius` is now a member of `circle`, so
cannam@133 264 we don't need a comment to explain that the value of `circle` is its radius.
cannam@133 265 2. You can add additional members later on, without breaking compatibility. Notice how we upgraded
cannam@133 266 `square` to `rectangle` above, adding a `height` field. This definition is actually
cannam@133 267 wire-compatible with the previous version of the `Shape` example from the "union" section
cannam@133 268 (aside from the fact that `height` will always be zero when reading old data -- hey, it's not
cannam@133 269 a perfect example). In real-world use, it is common to realize after the fact that you need to
cannam@133 270 add some information to a struct that only applies when one particular union field is set.
cannam@133 271 Without the ability to upgrade to a group, you would have to define the new field separately,
cannam@133 272 and have it waste space when not relevant.
cannam@133 273
cannam@133 274 Note that a named union is actually exactly equivalent to a named group containing an unnamed
cannam@133 275 union.
cannam@133 276
cannam@133 277 **Wait, weren't groups considered a misfeature in Protobufs? Why did you do this again?**
cannam@133 278
cannam@133 279 They are useful in unions, which Protobufs did not have. Meanwhile, you cannot have a "repeated
cannam@133 280 group" in Cap'n Proto, which was the case that got into the most trouble with Protobufs.
cannam@133 281
cannam@133 282 ### Dynamically-typed Fields
cannam@133 283
cannam@133 284 A struct may have a field with type `AnyPointer`. This field's value can be of any pointer type --
cannam@133 285 i.e. any struct, interface, list, or blob. This is essentially like a `void*` in C.
cannam@133 286
cannam@133 287 See also [generics](#generic-types).
cannam@133 288
cannam@133 289 ### Enums
cannam@133 290
cannam@133 291 An enum is a type with a small finite set of symbolic values.
cannam@133 292
cannam@133 293 {% highlight capnp %}
cannam@133 294 enum Rfc3092Variable {
cannam@133 295 foo @0;
cannam@133 296 bar @1;
cannam@133 297 baz @2;
cannam@133 298 qux @3;
cannam@133 299 # ...
cannam@133 300 }
cannam@133 301 {% endhighlight %}
cannam@133 302
cannam@133 303 Like fields, enumerants must be numbered sequentially starting from zero. In languages where
cannam@133 304 enums have numeric values, these numbers will be used, but in general Cap'n Proto enums should not
cannam@133 305 be considered numeric.
cannam@133 306
cannam@133 307 ### Interfaces
cannam@133 308
cannam@133 309 An interface has a collection of methods, each of which takes some parameters and return some
cannam@133 310 results. Like struct fields, methods are numbered. Interfaces support inheritance, including
cannam@133 311 multiple inheritance.
cannam@133 312
cannam@133 313 {% highlight capnp %}
cannam@133 314 interface Node {
cannam@133 315 isDirectory @0 () -> (result :Bool);
cannam@133 316 }
cannam@133 317
cannam@133 318 interface Directory extends(Node) {
cannam@133 319 list @0 () -> (list :List(Entry));
cannam@133 320 struct Entry {
cannam@133 321 name @0 :Text;
cannam@133 322 node @1 :Node;
cannam@133 323 }
cannam@133 324
cannam@133 325 create @1 (name :Text) -> (file :File);
cannam@133 326 mkdir @2 (name :Text) -> (directory :Directory);
cannam@133 327 open @3 (name :Text) -> (node :Node);
cannam@133 328 delete @4 (name :Text);
cannam@133 329 link @5 (name :Text, node :Node);
cannam@133 330 }
cannam@133 331
cannam@133 332 interface File extends(Node) {
cannam@133 333 size @0 () -> (size :UInt64);
cannam@133 334 read @1 (startAt :UInt64 = 0, amount :UInt64 = 0xffffffffffffffff)
cannam@133 335 -> (data :Data);
cannam@133 336 # Default params = read entire file.
cannam@133 337
cannam@133 338 write @2 (startAt :UInt64, data :Data);
cannam@133 339 truncate @3 (size :UInt64);
cannam@133 340 }
cannam@133 341 {% endhighlight %}
cannam@133 342
cannam@133 343 Notice something interesting here: `Node`, `Directory`, and `File` are interfaces, but several
cannam@133 344 methods take these types as parameters or return them as results. `Directory.Entry` is a struct,
cannam@133 345 but it contains a `Node`, which is an interface. Structs (and primitive types) are passed over RPC
cannam@133 346 by value, but interfaces are passed by reference. So when `Directory.list` is called remotely, the
cannam@133 347 content of a `List(Entry)` (including the text of each `name`) is transmitted back, but for the
cannam@133 348 `node` field, only a reference to some remote `Node` object is sent.
cannam@133 349
cannam@133 350 When an address of an object is transmitted, the RPC system automatically manages making sure that
cannam@133 351 the recipient gets permission to call the addressed object -- because if the recipient wasn't
cannam@133 352 meant to have access, the sender shouldn't have sent the reference in the first place. This makes
cannam@133 353 it very easy to develop secure protocols with Cap'n Proto -- you almost don't need to think about
cannam@133 354 access control at all. This feature is what makes Cap'n Proto a "capability-based" RPC system -- a
cannam@133 355 reference to an object inherently represents a "capability" to access it.
cannam@133 356
cannam@133 357 ### Generic Types
cannam@133 358
cannam@133 359 A struct or interface type may be parameterized, making it "generic". For example, this is useful
cannam@133 360 for defining type-safe containers:
cannam@133 361
cannam@133 362 {% highlight capnp %}
cannam@133 363 struct Map(Key, Value) {
cannam@133 364 entries @0 :List(Entry);
cannam@133 365 struct Entry {
cannam@133 366 key @0 :Key;
cannam@133 367 value @1 :Value;
cannam@133 368 }
cannam@133 369 }
cannam@133 370
cannam@133 371 struct People {
cannam@133 372 byName @0 :Map(Text, Person);
cannam@133 373 # Maps names to Person instances.
cannam@133 374 }
cannam@133 375 {% endhighlight %}
cannam@133 376
cannam@133 377 Cap'n Proto generics work very similarly to Java generics or C++ templates. Some notes:
cannam@133 378
cannam@133 379 * Only pointer types (structs, lists, blobs, and interfaces) can be used as generic parameters,
cannam@133 380 much like in Java. This is a pragmatic limitation: allowing parameters to have non-pointer types
cannam@133 381 would mean that different parameterizations of a struct could have completely different layouts,
cannam@133 382 which would excessively complicate the Cap'n Proto implementation.
cannam@133 383
cannam@133 384 * A type declaration nested inside a generic type may use the type parameters of the outer type,
cannam@133 385 as you can see in the example above. This differs from Java, but matches C++. If you want to
cannam@133 386 refer to a nested type from outside the outer type, you must specify the parameters on the outer
cannam@133 387 type, not the inner. For example, `Map(Text, Person).Entry` is a valid type;
cannam@133 388 `Map.Entry(Text, Person)` is NOT valid. (Of course, an inner type may declare additional generic
cannam@133 389 parameters.)
cannam@133 390
cannam@133 391 * If you refer to a generic type but omit its parameters (e.g. declare a field of type `Map` rather
cannam@133 392 than `Map(T, U)`), it is as if you specified `AnyPointer` for each parameter. Note that such
cannam@133 393 a type is wire-compatible with any specific parameterization, so long as you interpret the
cannam@133 394 `AnyPointer`s as the correct type at runtime.
cannam@133 395
cannam@133 396 * Relatedly, it is safe to cast an generic interface of a specific parameterization to a generic
cannam@133 397 interface where all parameters are `AnyPointer` and vice versa, as long as the `AnyPointer`s are
cannam@133 398 treated as the correct type at runtime. This means that e.g. you can implement a server in a
cannam@133 399 generic way that is correct for all parameterizations but call it from clients using a specific
cannam@133 400 parameterization.
cannam@133 401
cannam@133 402 * The encoding of a generic type is exactly the same as the encoding of a type produced by
cannam@133 403 substituting the type parameters manually. For example, `Map(Text, Person)` is encoded exactly
cannam@133 404 the same as:
cannam@133 405
cannam@133 406 <div>{% highlight capnp %}
cannam@133 407 struct PersonMap {
cannam@133 408 # Encoded the same as Map(Text, Person).
cannam@133 409 entries @0 :List(Entry);
cannam@133 410 struct Entry {
cannam@133 411 key @0 :Text;
cannam@133 412 value @1 :Person;
cannam@133 413 }
cannam@133 414 }
cannam@133 415 {% endhighlight %}
cannam@133 416 </div>
cannam@133 417
cannam@133 418 Therefore, it is possible to upgrade non-generic types to generic types while retaining
cannam@133 419 backwards-compatibility.
cannam@133 420
cannam@133 421 * Similarly, a generic interface's protocol is exactly the same as the interface obtained by
cannam@133 422 manually substituting the generic parameters.
cannam@133 423
cannam@133 424 ### Generic Methods
cannam@133 425
cannam@133 426 Interface methods may also have "implicit" generic parameters that apply to a particular method
cannam@133 427 call. This commonly applies to "factory" methods. For example:
cannam@133 428
cannam@133 429 {% highlight capnp %}
cannam@133 430 interface Assignable(T) {
cannam@133 431 # A generic interface, with non-generic methods.
cannam@133 432 get @0 () -> (value :T);
cannam@133 433 set @1 (value :T) -> ();
cannam@133 434 }
cannam@133 435
cannam@133 436 interface AssignableFactory {
cannam@133 437 newAssignable @0 [T] (initialValue :T)
cannam@133 438 -> (assignable :Assignable(T));
cannam@133 439 # A generic method.
cannam@133 440 }
cannam@133 441 {% endhighlight %}
cannam@133 442
cannam@133 443 Here, the method `newAssignable()` is generic. The return type of the method depends on the input
cannam@133 444 type.
cannam@133 445
cannam@133 446 Ideally, calls to a generic method should not have to explicitly specify the method's type
cannam@133 447 parameters, because they should be inferred from the types of the method's regular parameters.
cannam@133 448 However, this may not always be possible; it depends on the programming language and API details.
cannam@133 449
cannam@133 450 Note that if a method's generic parameter is used only in its returns, not its parameters, then
cannam@133 451 this implies that the returned value is appropriate for any parameterization. For example:
cannam@133 452
cannam@133 453 {% highlight capnp %}
cannam@133 454 newUnsetAssignable @1 [T] () -> (assignable :Assignable(T));
cannam@133 455 # Create a new assignable. `get()` on the returned object will
cannam@133 456 # throw an exception until `set()` has been called at least once.
cannam@133 457 {% endhighlight %}
cannam@133 458
cannam@133 459 Because of the way this method is designed, the returned `Assignable` is initially valid for any
cannam@133 460 `T`. Effectively, it doesn't take on a type until the first time `set()` is called, and then `T`
cannam@133 461 retroactively becomes the type of value passed to `set()`.
cannam@133 462
cannam@133 463 In contrast, if it's the case that the returned type is unknown, then you should NOT declare it
cannam@133 464 as generic. Instead, use `AnyPointer`, or omit a type's parameters (since they default to
cannam@133 465 `AnyPointer`). For example:
cannam@133 466
cannam@133 467 {% highlight capnp %}
cannam@133 468 getNamedAssignable @2 (name :Text) -> (assignable :Assignable);
cannam@133 469 # Get the `Assignable` with the given name. It is the
cannam@133 470 # responsibility of the caller to keep track of the type of each
cannam@133 471 # named `Assignable` and cast the returned object appropriately.
cannam@133 472 {% endhighlight %}
cannam@133 473
cannam@133 474 Here, we omitted the parameters to `Assignable` in the return type, because the returned object
cannam@133 475 has a specific type parameterization but it is not locally knowable.
cannam@133 476
cannam@133 477 ### Constants
cannam@133 478
cannam@133 479 You can define constants in Cap'n Proto. These don't affect what is sent on the wire, but they
cannam@133 480 will be included in the generated code, and can be [evaluated using the `capnp`
cannam@133 481 tool](capnp-tool.html#evaluating-constants).
cannam@133 482
cannam@133 483 {% highlight capnp %}
cannam@133 484 const pi :Float32 = 3.14159;
cannam@133 485 const bob :Person = (name = "Bob", email = "bob@example.com");
cannam@133 486 const secret :Data = 0x"9f98739c2b53835e 6720a00907abd42f";
cannam@133 487 {% endhighlight %}
cannam@133 488
cannam@133 489 Additionally, you may refer to a constant inside another value (e.g. another constant, or a default
cannam@133 490 value of a field).
cannam@133 491
cannam@133 492 {% highlight capnp %}
cannam@133 493 const foo :Int32 = 123;
cannam@133 494 const bar :Text = "Hello";
cannam@133 495 const baz :SomeStruct = (id = .foo, message = .bar);
cannam@133 496 {% endhighlight %}
cannam@133 497
cannam@133 498 Note that when substituting a constant into another value, the constant's name must be qualified
cannam@133 499 with its scope. E.g. if a constant `qux` is declared nested in a type `Corge`, it would need to
cannam@133 500 be referenced as `Corge.qux` rather than just `qux`, even when used within the `Corge` scope.
cannam@133 501 Constants declared at the top-level scope are prefixed just with `.`. This rule helps to make it
cannam@133 502 clear that the name refers to a user-defined constant, rather than a literal value (like `true` or
cannam@133 503 `inf`) or an enum value.
cannam@133 504
cannam@133 505 ### Nesting, Scope, and Aliases
cannam@133 506
cannam@133 507 You can nest constant, alias, and type definitions inside structs and interfaces (but not enums).
cannam@133 508 This has no effect on any definition involved except to define the scope of its name. So in Java
cannam@133 509 terms, inner classes are always "static". To name a nested type from another scope, separate the
cannam@133 510 path with `.`s.
cannam@133 511
cannam@133 512 {% highlight capnp %}
cannam@133 513 struct Foo {
cannam@133 514 struct Bar {
cannam@133 515 #...
cannam@133 516 }
cannam@133 517 bar @0 :Bar;
cannam@133 518 }
cannam@133 519
cannam@133 520 struct Baz {
cannam@133 521 bar @0 :Foo.Bar;
cannam@133 522 }
cannam@133 523 {% endhighlight %}
cannam@133 524
cannam@133 525 If typing long scopes becomes cumbersome, you can use `using` to declare an alias.
cannam@133 526
cannam@133 527 {% highlight capnp %}
cannam@133 528 struct Qux {
cannam@133 529 using Foo.Bar;
cannam@133 530 bar @0 :Bar;
cannam@133 531 }
cannam@133 532
cannam@133 533 struct Corge {
cannam@133 534 using T = Foo.Bar;
cannam@133 535 bar @0 :T;
cannam@133 536 }
cannam@133 537 {% endhighlight %}
cannam@133 538
cannam@133 539 ### Imports
cannam@133 540
cannam@133 541 An `import` expression names the scope of some other file:
cannam@133 542
cannam@133 543 {% highlight capnp %}
cannam@133 544 struct Foo {
cannam@133 545 # Use type "Baz" defined in bar.capnp.
cannam@133 546 baz @0 :import "bar.capnp".Baz;
cannam@133 547 }
cannam@133 548 {% endhighlight %}
cannam@133 549
cannam@133 550 Of course, typically it's more readable to define an alias:
cannam@133 551
cannam@133 552 {% highlight capnp %}
cannam@133 553 using Bar = import "bar.capnp";
cannam@133 554
cannam@133 555 struct Foo {
cannam@133 556 # Use type "Baz" defined in bar.capnp.
cannam@133 557 baz @0 :Bar.Baz;
cannam@133 558 }
cannam@133 559 {% endhighlight %}
cannam@133 560
cannam@133 561 Or even:
cannam@133 562
cannam@133 563 {% highlight capnp %}
cannam@133 564 using import "bar.capnp".Baz;
cannam@133 565
cannam@133 566 struct Foo {
cannam@133 567 baz @0 :Baz;
cannam@133 568 }
cannam@133 569 {% endhighlight %}
cannam@133 570
cannam@133 571 The above imports specify relative paths. If the path begins with a `/`, it is absolute -- in
cannam@133 572 this case, the `capnp` tool searches for the file in each of the search path directories specified
cannam@133 573 with `-I`.
cannam@133 574
cannam@133 575 ### Annotations
cannam@133 576
cannam@133 577 Sometimes you want to attach extra information to parts of your protocol that isn't part of the
cannam@133 578 Cap'n Proto language. This information might control details of a particular code generator, or
cannam@133 579 you might even read it at run time to assist in some kind of dynamic message processing. For
cannam@133 580 example, you might create a field annotation which means "hide from the public", and when you send
cannam@133 581 a message to an external user, you might invoke some code first that iterates over your message and
cannam@133 582 removes all of these hidden fields.
cannam@133 583
cannam@133 584 You may declare annotations and use them like so:
cannam@133 585
cannam@133 586 {% highlight capnp %}
cannam@133 587 # Declare an annotation 'foo' which applies to struct and enum types.
cannam@133 588 annotation foo(struct, enum) :Text;
cannam@133 589
cannam@133 590 # Apply 'foo' to to MyType.
cannam@133 591 struct MyType $foo("bar") {
cannam@133 592 # ...
cannam@133 593 }
cannam@133 594 {% endhighlight %}
cannam@133 595
cannam@133 596 The possible targets for an annotation are: `file`, `struct`, `field`, `union`, `enum`, `enumerant`,
cannam@133 597 `interface`, `method`, `parameter`, `annotation`, `const`. You may also specify `*` to cover them
cannam@133 598 all.
cannam@133 599
cannam@133 600 {% highlight capnp %}
cannam@133 601 # 'baz' can annotate anything!
cannam@133 602 annotation baz(*) :Int32;
cannam@133 603
cannam@133 604 $baz(1); # Annotate the file.
cannam@133 605
cannam@133 606 struct MyStruct $baz(2) {
cannam@133 607 myField @0 :Text = "default" $baz(3);
cannam@133 608 myUnion :union $baz(4) {
cannam@133 609 # ...
cannam@133 610 }
cannam@133 611 }
cannam@133 612
cannam@133 613 enum MyEnum $baz(5) {
cannam@133 614 myEnumerant @0 $baz(6);
cannam@133 615 }
cannam@133 616
cannam@133 617 interface MyInterface $baz(7) {
cannam@133 618 myMethod @0 (myParam :Text $baz(9)) -> () $baz(8);
cannam@133 619 }
cannam@133 620
cannam@133 621 annotation myAnnotation(struct) :Int32 $baz(10);
cannam@133 622 const myConst :Int32 = 123 $baz(11);
cannam@133 623 {% endhighlight %}
cannam@133 624
cannam@133 625 `Void` annotations can omit the value. Struct-typed annotations are also allowed. Tip: If
cannam@133 626 you want an annotation to have a default value, declare it as a struct with a single field with
cannam@133 627 a default value.
cannam@133 628
cannam@133 629 {% highlight capnp %}
cannam@133 630 annotation qux(struct, field) :Void;
cannam@133 631
cannam@133 632 struct MyStruct $qux {
cannam@133 633 string @0 :Text $qux;
cannam@133 634 number @1 :Int32 $qux;
cannam@133 635 }
cannam@133 636
cannam@133 637 annotation corge(file) :MyStruct;
cannam@133 638
cannam@133 639 $corge(string = "hello", number = 123);
cannam@133 640
cannam@133 641 struct Grault {
cannam@133 642 value @0 :Int32 = 123;
cannam@133 643 }
cannam@133 644
cannam@133 645 annotation grault(file) :Grault;
cannam@133 646
cannam@133 647 $grault(); # value defaults to 123
cannam@133 648 $grault(value = 456);
cannam@133 649 {% endhighlight %}
cannam@133 650
cannam@133 651 ### Unique IDs
cannam@133 652
cannam@133 653 A Cap'n Proto file must have a unique 64-bit ID, and each type and annotation defined therein may
cannam@133 654 also have an ID. Use `capnp id` to generate a new ID randomly. ID specifications begin with `@`:
cannam@133 655
cannam@133 656 {% highlight capnp %}
cannam@133 657 # file ID
cannam@133 658 @0xdbb9ad1f14bf0b36;
cannam@133 659
cannam@133 660 struct Foo @0x8db435604d0d3723 {
cannam@133 661 # ...
cannam@133 662 }
cannam@133 663
cannam@133 664 enum Bar @0xb400f69b5334aab3 {
cannam@133 665 # ...
cannam@133 666 }
cannam@133 667
cannam@133 668 interface Baz @0xf7141baba3c12691 {
cannam@133 669 # ...
cannam@133 670 }
cannam@133 671
cannam@133 672 annotation qux @0xf8a1bedf44c89f00 (field) :Text;
cannam@133 673 {% endhighlight %}
cannam@133 674
cannam@133 675 If you omit the ID for a type or annotation, one will be assigned automatically. This default
cannam@133 676 ID is derived by taking the first 8 bytes of the MD5 hash of the parent scope's ID concatenated
cannam@133 677 with the declaration's name (where the "parent scope" is the file for top-level declarations, or
cannam@133 678 the outer type for nested declarations). You can see the automatically-generated IDs by "compiling"
cannam@133 679 your file with the `-ocapnp` flag, which echos the schema back to the terminal annotated with
cannam@133 680 extra information, e.g. `capnp compile -ocapnp myschema.capnp`. In general, you would only specify
cannam@133 681 an explicit ID for a declaration if that declaration has been renamed or moved and you want the ID
cannam@133 682 to stay the same for backwards-compatibility.
cannam@133 683
cannam@133 684 IDs exist to provide a relatively short yet unambiguous way to refer to a type or annotation from
cannam@133 685 another context. They may be used for representing schemas, for tagging dynamically-typed fields,
cannam@133 686 etc. Most languages prefer instead to define a symbolic global namespace e.g. full of "packages",
cannam@133 687 but this would have some important disadvantages in the context of Cap'n Proto:
cannam@133 688
cannam@133 689 * Programmers often feel the need to change symbolic names and organization in order to make their
cannam@133 690 code cleaner, but the renamed code should still work with existing encoded data.
cannam@133 691 * It's easy for symbolic names to collide, and these collisions could be hard to detect in a large
cannam@133 692 distributed system with many different binaries using different versions of protocols.
cannam@133 693 * Fully-qualified type names may be large and waste space when transmitted on the wire.
cannam@133 694
cannam@133 695 Note that IDs are 64-bit (actually, 63-bit, as the first bit is always 1). Random collisions
cannam@133 696 are possible, but unlikely -- there would have to be on the order of a billion types before this
cannam@133 697 becomes a real concern. Collisions from misuse (e.g. copying an example without changing the ID)
cannam@133 698 are much more likely.
cannam@133 699
cannam@133 700 ## Evolving Your Protocol
cannam@133 701
cannam@133 702 A protocol can be changed in the following ways without breaking backwards-compatibility, and
cannam@133 703 without changing the [canonical](encoding.html#canonicalization) encoding of a message:
cannam@133 704
cannam@133 705 * New types, constants, and aliases can be added anywhere, since they obviously don't affect the
cannam@133 706 encoding of any existing type.
cannam@133 707
cannam@133 708 * New fields, enumerants, and methods may be added to structs, enums, and interfaces, respectively,
cannam@133 709 as long as each new member's number is larger than all previous members. Similarly, new fields
cannam@133 710 may be added to existing groups and unions.
cannam@133 711
cannam@133 712 * New parameters may be added to a method. The new parameters must be added to the end of the
cannam@133 713 parameter list and must have default values.
cannam@133 714
cannam@133 715 * Members can be re-arranged in the source code, so long as their numbers stay the same.
cannam@133 716
cannam@133 717 * Any symbolic name can be changed, as long as the type ID / ordinal numbers stay the same. Note
cannam@133 718 that type declarations have an implicit ID generated based on their name and parent's ID, but
cannam@133 719 you can use `capnp compile -ocapnp myschema.capnp` to find out what that number is, and then
cannam@133 720 declare it explicitly after your rename.
cannam@133 721
cannam@133 722 * Type definitions can be moved to different scopes, as long as the type ID is declared
cannam@133 723 explicitly.
cannam@133 724
cannam@133 725 * A field can be moved into a group or a union, as long as the group/union and all other fields
cannam@133 726 within it are new. In other words, a field can be replaced with a group or union containing an
cannam@133 727 equivalent field and some new fields.
cannam@133 728
cannam@133 729 * A non-generic type can be made [generic](#generic-types), and new generic parameters may be
cannam@133 730 added to an existing generic type. Other types used inside the body of the newly-generic type can
cannam@133 731 be replaced with the new generic parameter so long as all existing users of the type are updated
cannam@133 732 to bind that generic parameter to the type it replaced. For example:
cannam@133 733
cannam@133 734 <div>{% highlight capnp %}
cannam@133 735 struct Map {
cannam@133 736 entries @0 :List(Entry);
cannam@133 737 struct Entry {
cannam@133 738 key @0 :Text;
cannam@133 739 value @1 :Text;
cannam@133 740 }
cannam@133 741 }
cannam@133 742 {% endhighlight %}
cannam@133 743 </div>
cannam@133 744
cannam@133 745 Can change to:
cannam@133 746
cannam@133 747 <div>{% highlight capnp %}
cannam@133 748 struct Map(Key, Value) {
cannam@133 749 entries @0 :List(Entry);
cannam@133 750 struct Entry {
cannam@133 751 key @0 :Key;
cannam@133 752 value @1 :Value;
cannam@133 753 }
cannam@133 754 }
cannam@133 755 {% endhighlight %}
cannam@133 756 </div>
cannam@133 757
cannam@133 758 As long as all existing uses of `Map` are replaced with `Map(Text, Text)` (and any uses of
cannam@133 759 `Map.Entry` are replaced with `Map(Text, Text).Entry`).
cannam@133 760
cannam@133 761 (This rule applies analogously to generic methods.)
cannam@133 762
cannam@133 763 The following changes are backwards-compatible but may change the canonical encoding of a message.
cannam@133 764 Apps that rely on canonicalization (such as some cryptographic protocols) should avoid changes in
cannam@133 765 this list, but most apps can safely use them:
cannam@133 766
cannam@133 767 * A field of type `List(T)`, where `T` is a primitive type, blob, or list, may be changed to type
cannam@133 768 `List(U)`, where `U` is a struct type whose `@0` field is of type `T`. This rule is useful when
cannam@133 769 you realize too late that you need to attach some extra data to each element of your list.
cannam@133 770 Without this rule, you would be stuck defining parallel lists, which are ugly and error-prone.
cannam@133 771 As a special exception to this rule, `List(Bool)` may **not** be upgraded to a list of structs,
cannam@133 772 because implementing this for bit lists has proven unreasonably expensive.
cannam@133 773
cannam@133 774 Any change not listed above should be assumed NOT to be safe. In particular:
cannam@133 775
cannam@133 776 * You cannot change a field, method, or enumerant's number.
cannam@133 777 * You cannot change a field or method parameter's type or default value.
cannam@133 778 * You cannot change a type's ID.
cannam@133 779 * You cannot change the name of a type that doesn't have an explicit ID, as the implicit ID is
cannam@133 780 generated based in part on the type name.
cannam@133 781 * You cannot move a type to a different scope or file unless it has an explicit ID, as the implicit
cannam@133 782 ID is based in part on the scope's ID.
cannam@133 783 * You cannot move an existing field into or out of an existing union, nor can you form a new union
cannam@133 784 containing more than one existing field.
cannam@133 785
cannam@133 786 Also, these rules only apply to the Cap'n Proto native encoding. It is sometimes useful to
cannam@133 787 transcode Cap'n Proto types to other formats, like JSON, which may have different rules (e.g.,
cannam@133 788 field names cannot change in JSON).