The standard librarySlide 52 of 85
52--The standard library
Field annotations
Grammar: field, annotations, annotation
fieldSpecification §2.3
field = IDENT ":" type [ annotations ] ;annotationsSpecification §2.3
annotations = "--" annotation { annotation } ;As the compiler reads it; §2.3 of the specification is out of date here.annotationSpecification §2.3
annotation = ( "JSON" | "URL" | "Flag" ) "as" ( key | STRING ) ";" | "Default" "as" literal ";" ;As the compiler reads it; §2.3 of the specification is out of date here.A field may be annotated after a --, each clause ending at its ;, in any order. Every annotation is about the codecs — what the field is called on the wire, and what to read where the wire has nothing — and none changes the field on the Hive side:
JSON as <key>;is the key the field is read from and written as, in both directions, so a round trip agrees with itself. A key is somebody else's name, held to none of Hive's shapes:user_nameanduser-nameare keys, and anything else is quoted,"user name". It is also how a field whose key is a keyword gets a name of its own:kind: Str -- JSON as type;.URL as <key>;andFlag as <name>;say the same for a query string and for a command-line flag, a flag without its dashes —Flag as dry-run;is--dry-run, andFlag as dry-run n;adds-n, the shorter of two names being the short one.Default as <literal>;is what to read where the key is absent ornull: anInt,Float,Str,BoolorAtomliteral the field can hold, negative numbers included. It covers only what was never said: a value of the wrong type is still an error.
Two fields answering to one key in any format are a compile error, since the decoder would read the member twice. A shared field is annotated once for every variant it joins.
The annotations steer both halves
type User {
name: Str -- JSON as username;
age: Int
firstName: Str -- Default as "";
kind: Str -- JSON as type; Default as "member";
}
proc main(): void {
// The key is username in both directions, so a round trip agrees.
echo encode(User("ada", 36, "Ada", "admin"), hive.json.codec())
// firstName and type are absent here, and each Default stands in.
if User.decode("\{\"username\":\"ada\",\"age\":36}", hive.json.codec()) is Result.Ok(u) {
echo "[{u.firstName}] {u.kind}"
}
}You can edit this program and run it here.Tab indents, Escape leaves the program, and Ctrl+Enter runs it.