cddl
stdlib/extra/cddl.hk: the CDDL schema of a project's CBOR codecs.
generate! returns the RFC 8610 CDDL describing the CBOR that a project's @derive(Encode)/Decode types produce. It resolves the project through compiler.project_modules! and reflects each module with compiler.type_decls, which makes it an action charging [fs_read] alone. hanki cddl prints its result, and schema! returns the text that command prints under --schema-only, which a test comparing a committed schema with the project's types calls.
The argument names a project. A directory is read through its manifest's roots; a file is its own root, with its directory as the project. In both cases the schema covers every module a root reaches, which makes it self-contained. A schema reflected from one file alone would reference rules it never defines (frame: wire.Frame with no wire.Frame rule), and a consumer handed it could validate nothing against it.
Rule names follow the source spelling: bare for a root module's own types, module-qualified for every other module's (Envelope, wire.Frame). RFC 8610's id production admits the dot and §3.1 blesses this use ("to express some module structure, as in tcp.throughput vs udp.throughput"). Its one caveat, that a dot is a name-continuation character and a range or control operator therefore needs surrounding space, cannot reach this generator: every range and control operator here is written with that space.
The mapping mirrors the codec (stdlib/extra/cbor):
- a struct -> a positional array,
[field: type, …];- a sum -> a choice of
[tag, …payloads]arrays, the tag a literal; List<T>->[* T];Option<T>->(T) / null, andnull / [T]whereTis itself anOption;Map<K, V>->{* K => V};Set<T>->[* T];u8/u16/u32->uint .size 1|2|4andu64->uint,i8…i64-> the matching range, each a namedhanki-*rule, since the decoder refuses an integer outside its target width;f64->float64,f32->float32,bool->bool,string->tstr,bytes->bstr;- the exact tier -> a choice, since each of
int/decimal/rationaltakes the in-band sentinels beside its ordinary form and the codec spells those as CBOR's ownundefined/ half-precision infinity;decimalandrationalalso pull in the tag-4 / tag-30 rules the CDDL prelude has no name for, appended only when referenced; - a stdlib value type with a hand-written codec -> what its impl writes: the calendar types as
tstr,Uuid,Nonceand the public-key types as sizedbstrs,Rangeas[hanki-int, hanki-int]; - a nested user type -> a reference to its rule name.
- a sum -> a choice of
A deriving type seeds the schema, and every declaration-shaped type its fields reach contributes a rule in source order. A hand-written canonical Encode or Decode impl can choose a different shape than the declaration; reflection exposes no expression bodies. Every reachable manual impl supplies one validated RFC 8610 type expression through @cddl. That parsed shape replaces both the emitted declaration body and its reachability edges; absent or inconsistent metadata is a CddlError and no schema.
CDDLTYPE_GRAMMAR
_CDDL_TYPE_GRAMMAR: string = "top <- sp type sp !.\ntype <- type1 (sp '/' sp type1)*\ntype1 <- type2 (sp (rangeop / ctlop) sp type2)?\ntype2 <- value / reference / '(' sp type sp ')' / '{' sp group sp '}' / '[' sp group sp ']' / '~' sp reference / '&' sp '(' sp group sp ')' / '&' sp reference / '\#' '6' ('.' uint)? '(' sp type sp ')' / '\#' [0-9] ('.' uint)? / '\#'\ngenericarg <- {:args: '<' sp {:arg: type1 :} sp (',' sp {:arg: type1 :})* '>' :}\nrangeop <- '...' / '..'\nctlop <- '.' id\ngroup <- grpchoice (sp '//' sp grpchoice)*\ngrpchoice <- (grpent optcom)*\ngrpent <- occur? sp memberkey? sp type / occur? sp reference / occur? sp '(' sp group sp ')'\nmemberkey <- type1 sp '^'? sp '=>' / id sp ':' / value sp ':'\noptcom <- sp ','? sp\noccur <- uint? '*' uint? / '+' / '?'\nvalue <- hexfloat / number / text / bytes\nhexfloat <- '-'? '0' [xX] [0-9A-Fa-f]+ ('.' [0-9A-Fa-f]+)? [pP] exponent\nnumber <- '-'? uint ('.' fraction)? ([eE] exponent)?\nfraction <- [0-9]+\nexponent <- [+-]? [0-9]+\nuint <- [1-9] [0-9]* / '0' [xX] [0-9A-Fa-f]+ / '0' [bB] [01]+ / '0'\ntext <- '\"' ('\\\\' . / [^\"\\\\\r\n])* '\"'\nbytes <- bsqual? '\\'' ('\\\\' . / [^'\\\\])* '\\''\nbsqual <- [hH] / [bB] '64'\nreference <- {:ref: {} {id} genericarg? :}\nid <- [A-Za-z@_$] ([-.]* [A-Za-z@_$0-9])*\nsp <- (' ' / '\r\n' / '\n' / ';' [^\r\n]* ('\r\n' / '\n'))*\n"
RFC 8610 Appendix B's structural type production, with the input anchored on both sides. Quoted-value scalar bounds are checked after tokenisation, since Ford notation has no arbitrary-code-point escape. A reference capture records its byte position, spelling and generic arity; validation resolves those uses after parsing, and canonicalisation uses the position to distinguish a type reference from a field label or control-operator name. Starting at type is the contract: a rule definition or a bare group entry has no route through this grammar, and !. rejects any trailing text.
CDDLTOKEN_GRAMMAR
_CDDL_TOKEN_GRAMMAR: string = "top <- sp (token sp)* !.\ntoken <- {:tok: {} {(bytes / text / hexfloat / number / id / punct)} :}\npunct <- '...' / '..' / '//' / '=>' / '/' / '.' / '(' / ')' / '{' / '}' / '[' / ']' / '~' / '&' / '\#' / ',' / '*' / '+' / '?' / ':' / '^' / '<' / '>'\nhexfloat <- '-'? '0' [xX] [0-9A-Fa-f]+ ('.' [0-9A-Fa-f]+)? [pP] exponent\nnumber <- '-'? uint ('.' fraction)? ([eE] exponent)?\nfraction <- [0-9]+\nexponent <- [+-]? [0-9]+\nuint <- [1-9] [0-9]* / '0' [xX] [0-9A-Fa-f]+ / '0' [bB] [01]+ / '0'\ntext <- '\"' ('\\\\' . / [^\"\\\\\r\n])* '\"'\nbytes <- bsqual? '\\'' ('\\\\' . / [^'\\\\])* '\\''\nbsqual <- [hH] / [bB] '64'\nid <- [A-Za-z@_$] ([-.]* [A-Za-z@_$0-9])*\nsp <- (' ' / '\r\n' / '\n' / ';' [^\r\n]* ('\r\n' / '\n'))*\n"
The same lexical productions, this time retaining every significant token with its byte position. The parsed token vector is the canonical form after target-rule generic references are replaced by their positional binding and integer literals by their exact values. Keeping tokens separate avoids conflating a .size b with the single rule name a.size, the whitespace-sensitive edge called out by RFC 8610 §3.1.
_Parsers
struct _Parsers
types: peg.Grammar
tokens: peg.Grammar
end
The two grammars, compiled. A stdlib constant cannot hold them: compile-time evaluation of the stdlib lowers peg.compile before any stdlib constant is resolved, and its body reads one.
compileparsers
def _compile_parsers() -> Result<_Parsers, string>
_CddlRef
struct _CddlRef
at: int
name: string
arity: int
end
_CddlToken
struct _CddlToken
at: int
text: string
end
_ParsedCddl
struct _ParsedCddl
canonical: List<string>
refs: List<_CddlRef>
end
capturedcddlrefarity
def _captured_cddl_ref_arity(kids: List<peg.Capture>) -> int
cddlref
def _cddl_ref(c: peg.Capture) -> Option<_CddlRef>
collectcddl_refs
def _collect_cddl_refs(c: peg.Capture, acc: List<_CddlRef>) -> List<_CddlRef>
cddlrefs
def _cddl_refs(captures: List<peg.Capture>) -> List<_CddlRef>
cddltoken
def _cddl_token(c: peg.Capture) -> Option<_CddlToken>
cddltokens
def _cddl_tokens(captures: List<peg.Capture>) -> List<_CddlToken>
bytequote_at
def _byte_quote_at(text: string) -> Option<int>
cddlscalarpastmax?
def _cddl_scalar_past_max?(b: bytes, at: int) -> bool
Appendix B admits printable ASCII plus Unicode code points 0x80 through 0x10fffd in quoted values. A text string admits no raw line break; a byte string additionally admits raw LF or CRLF, while an escaped control is invalid in either. The PEG captures quoted tokens whole, and this byte walk is sufficient because an ASCII control byte cannot occur inside a multi-byte UTF-8 scalar. UTF-8's last two scalar spellings are the only non-ASCII values beyond the RFC's upper bound.
validcddltexttoken?
def _valid_cddl_text_token?(text: string) -> bool
validcddlbytestoken?
def _valid_cddl_bytes_token?(text: string, quote_at: int) -> bool
validcddlquotedtoken?
def _valid_cddl_quoted_token?(token: _CddlToken) -> bool
validatecddl_tokens
def _validate_cddl_tokens(tokens: List<_CddlToken>) -> Result<List<_CddlToken>, string>
cddldigit_value
def _cddl_digit_value(b: u8) -> Option<int>
canonicalcddl_integer
def _canonical_cddl_integer(text: string) -> Option<string>
Canonicalization parses integers without passing them through a finite host tier. CDDL's decimal, hexadecimal and binary spellings can all exceed 64 bits, while Hanki int retains the value losslessly and displays one stable decimal spelling.
canonicaltoken
def _canonical_token(token: _CddlToken, refs: List<_CddlRef>, generics: List<string>) -> string
parsecddl
def _parse_cddl(parsers: _Parsers, source: string, generics: List<string>) -> Result<_ParsedCddl, string>
Parse once for syntax and reference roles, then lex once for a stable token sequence. Parentheses remain significant in this representation, while spacing and comments do not; generic names in reference position become their target rule-head index and equivalent integer bases compare by value.
derivescodec?
def _derives_codec?(derives: List<string>) -> bool
A type has a CBOR shape only if it derives Encode or Decode.
shapedecl?
def _shape_decl?(decl: Decl) -> bool
Whether this declaration has a CBOR shape: a struct, or a sum with at least one variant (a variant-less type is uninhabited: no value, no shape).
The compiler synthesises an Encode impl on demand for any type a deriving type reaches, and a plain struct named by a codec struct's field is on the wire; measured, struct Envelope @derive(Encode) { plain: Plain } with a bare struct Plain encodes as 81 81 07. The annotation says where the wire format starts, and not every declaration on it. A hand-written codec is the exception: its body chooses its wire representation, and _hand_written_codecs refuses it below.
codecseed?
def _codec_seed?(decl: Decl) -> bool
Whether this declaration seeds the schema: it has a shape and asks for a codec itself, and is not merely pulled in by something that does.
_Module
struct _Module
name: string
qualifier: string
decls: List<Decl>
imports: List<Import>
end
One module of the project, with the prefix its rule heads carry and the use/open directives its type references are written against.
qualifierof
def _qualifier_of(m: ProjectModule, entries: List<string>) -> string
Bare for a root module, name. for every other. The seam spells every path it returns the same way, and matching against entries is exact.
withimports
def _with_imports(m: ProjectModule, entries: List<string>, decls: List<Decl>) -> Result<_Module, string>
moduleof
def _module_of(m: ProjectModule, entries: List<string>) -> Result<_Module, string>
orderedmodules
def _ordered_modules(project: Project) -> List<ProjectModule>
The root modules first, then every other reachable module in the seam's path order. Roots-first puts the types a reader came for at the top.
addmodule
def _add_module(acc: Result<List<_Module>, string>, m: ProjectModule, entries: List<string>) -> Result<List<_Module>, string>
rootedmodules
def _rooted_modules(project: Project) -> Result<List<_Module>, string>
Every reachable module reflected, or the first parse failure. A module that will not parse is fatal here and never skipped: dropping it would emit a schema missing whatever it declares, which is the silence this whole command was rewritten to end.
importname
def _import_name(i: Import) -> string
The name a module imported under i is spelled by: bare for open M, M.name for use M, N.name for use M as N.
_spelling
def _spelling(i: Import, name: string) -> string
_bind
def _bind(acc: Map<string, string>, target: _Module, spell: (string) -> string) -> Map<string, string>
bindimport
def _bind_import(acc: Map<string, string>, i: Import, all: List<_Module>) -> Map<string, string>
One import's contribution to a scope. Only a single-segment path can bind a sibling, since the workspace loader refuses use X.Y, and a dotted stdlib import contributes nothing, as does one naming a module outside the resolved set. Matching on the module name, and never on its qualifier, is what lets a sibling import the entry module: use main then binds main.Envelope to the bare Envelope the entry's own rules are headed with.
scopeof
def _scope_of(m: _Module, all: List<_Module>) -> Map<string, string>
The rule head each type spelling resolves to from inside m: its own codec types, plus those of the modules it imports, keyed by the spelling m itself writes.
This is what makes qualified heads work at all. A reference inside a module is written against that module's scope (struct Frame naming ack: Ack, or frame: Frame under an open wire), and qualifying the heads without rewriting the references would leave every one of them dangling. Own declarations are bound last, and a local type shadows an opened one as it does in the source.
declscope
def _decl_scope(scope: Map<string, string>, generics: List<Generic>) -> Map<string, string>
A declaration's own generic parameters reflect as Name nodes the parser cannot tell from a nominal type, and a project type sharing a parameter's spelling would turn value: T into a reference to that type's rule. Dropping them is what leaves struct Box<T> describing its parameter.
rulehead
def _rule_head(qualifier: string, name: string, generics: List<Generic>) -> string
Head or, for a generic type, Head<a, b> (CDDL generic-rule head).
primcddl
def _prim_cddl(name: string) -> Option<string>
The CBOR/CDDL prelude type a Hanki primitive maps to, or None for anything else: a reference to another rule, or a generic parameter.
One table, since two questions read it: what to emit, and whether a spelling the schema references is one this generator can define. A second copy of the list is how those two would come to disagree.
primor_ref
def _prim_or_ref(scope: Map<string, string>, name: string) -> string
A primitive maps to its prelude type; anything else resolves through the enclosing module's scope, and a spelling in neither is left as written (a generic parameter, or a type from a dependency _undefined_refs refuses).
generatedrules
def _generated_rules(rules: string) -> List<string>
The CDDL rules this generator adds, for the shapes the standard prelude has no name for: each fixed width's range, and the exact tier's three sentinel-carrying choices with the two tag shapes those reference. Tag 4 is RFC 8949 §3.4.4; tag 30 is the IANA-registered rational number.
int spans two forms by size, native where it fits and tag 2/3 beyond, and the prelude's bignum is that pair of tags, and integer (int / bignum) covers its finite half on its own.
Kept only when the schema reaches one, which leaves an unrelated schema free of noise. The test runs against what has been emitted so far, and never the type rules alone: hanki-decimal is what a field names, and it is the only thing that mentions decimal-fraction, and a test of the type rules alone would emit a reference to a rule it had just dropped. Declaration order is therefore referrer-before-referent. A substring test suffices: a false hit would need a user type spelled decimal-fraction, which is not a legal Hanki identifier.
_Kept
struct _Kept
text: string
out: List<string>
end
One rule kept or dropped: text is everything emitted so far (what a later rule's reference must be visible in), out the rules kept in order.
keeprule
def _keep_rule(k: _Kept, d: string) -> _Kept
argtype
def _arg_type(scope: Map<string, string>, args: List<Type>, i: int) -> string
The CDDL of the type at index i, or any? if absent (the _app_type callers guard the arity, and the None arm is unreachable in practice).
genericref
def _generic_ref(scope: Map<string, string>, name: string, args: List<Type>) -> string
A user generic type at concrete args: Name<arg, …>.
_nullable?
def _nullable?(ty: Type) -> bool
Whether the codec can write this type as the None event, which is what Encode.encodes_none? answers: an Option, and no other type a generated rule names. A reachable hand-written codec that overrides the answer is refused in _validate_codec.
apptype
def _app_type(scope: Map<string, string>, name: string, args: List<Type>) -> string
A type application: the List/Option/Map container forms, else a reference to a user generic. The arity guards mirror the Rust slice patterns (("List", [t]) etc.); a mis-arity falls through to the generic ref.
An Option whose payload is itself nullable writes its Some as a one-element array, which distinguishes Some(None) from None.
_container?
def _container?(name: string, args: List<Type>) -> bool
Whether _app_type spells this application as a container, and no reference to a user generic, which leaves its head naming no rule.
cddltype
def _cddl_type(scope: Map<string, string>, ty: Type) -> string
The CDDL for one Hanki type, faithful to the CBOR the codec emits for it. A unit field has no Encode impl (mapped to [] defensively); function-typed and inferred positions are not serializable (any?).
emitstruct
def _emit_struct(scope: Map<string, string>, qualifier: string, decl: Decl, body: StructBody) -> string
A struct as a positional array: Head = [field: type, …].
variantarm
def _variant_arm(scope: Map<string, string>, v: Variant) -> string
One sum variant as a tagged array: [tag, payload…].
emitsum
def _emit_sum(scope: Map<string, string>, qualifier: string, decl: Decl, body: SumBody) -> string
A sum as a choice of tagged arrays: Head = [0, …] / [1, …] / ….
emitdecl
def _emit_decl(scope: Map<string, string>, qualifier: string, decl: Decl) -> string
_Rule
struct _Rule
head: string
qualifier: string
scope: Map<string, string>
decl: Decl
end
One candidate rule: the name it would be headed by (bare of any generic parameters, matching what a reference resolves to), the scope its own field types read against, and the declaration itself.
modulerules
def _module_rules(m: _Module, all: List<_Module>, acc: List<_Rule>) -> List<_Rule>
allrules
def _all_rules(mods: List<_Module>) -> List<_Rule>
Every declaration that could carry a rule, module by module in source order.
addref
def _add_ref(scope: Map<string, string>, name: string, acc: List<string>) -> List<string>
typerefs
def _type_refs(scope: Map<string, string>, ty: Type, acc: List<string>) -> List<string>
Every rule head this type spelling reaches. A container name (List, Map) is in no scope, contributes nothing itself, and the walk descends into its arguments; a generic parameter was dropped from the scope by _decl_scope, and contributes nothing either.
variantrefs
def _variant_refs(scope: Map<string, string>, v: Variant, acc: List<string>) -> List<string>
rulerefs
def _rule_refs(rule: _Rule) -> List<string>
The rule heads one rule's own fields and variant payloads reach.
addunseen
def _add_unseen(acc: List<string>, head: string) -> List<string>
undefinedname
def _undefined_name(scope: Map<string, string>, generics: List<Generic>, name: string, acc: List<string>) -> List<string>
A type spelling this schema would reference and never define: no prelude type, no container, none of the declaration's own generic parameters, and naming no rule.
The normal cause is a use that bound neither the stdlib nor a sibling: a declared dependency, whose resolution would mean fetching and locking, which a reflection call may not do. compiler.project_modules! reports those in unresolved so a tool can say what it could not see; a schema that referenced them anyway would be one no CDDL validator can load.
Refused on the reference, and never on the unresolved import: a project may depend on a package whose types its wire format never mentions, and that schema is complete and should be emitted.
primdefined?
def _prim_defined?(name: string) -> bool
undefinedin
def _undefined_in(scope: Map<string, string>, generics: List<Generic>, ty: Type, acc: List<string>) -> List<string>
Mirrors _cddl_type arm for arm, which leaves the two unable to disagree about which spellings become references.
undefinedapp
def _undefined_app(scope: Map<string, string>, generics: List<Generic>, name: string, args: List<Type>, acc: List<string>) -> List<string>
undefinedvariant
def _undefined_variant(scope: Map<string, string>, generics: List<Generic>, v: Variant, acc: List<string>) -> List<string>
undefinedrule
def _undefined_rule(rule: _Rule, acc: List<string>) -> List<string>
undefinedrefs
def _undefined_refs(rules: List<_Rule>, manual_heads: List<string>) -> List<string>
Every undefined spelling generated declaration-shaped rules reference, in first-seen order. Manual heads are checked against their parsed CDDL names instead; their fields are not necessarily on the wire at all.
UndefinedType
struct UndefinedType
spelling: string
reason: string
end
One spelling the schema would reference and cannot define, with the reason it has no rule.
_qualifier
def _qualifier(spelling: string) -> Option<string>
The module qualifier a type spelling is written under (sql.Row -> sql), or None for a bare name. An opened import spells its types bare, and the qualifier is how a dependency type is told from a standard-library one.
addname
def _add_name(acc: List<string>, name: string) -> List<string>
dependencyqualifiers
def _dependency_qualifiers(mods: List<_Module>, unresolved: List<UnresolvedImport>) -> List<string>
The spellings this project writes a declared dependency under, aliases included: use sql and use sql as db put sql. and db. in front of a type the seam never saw.
dependencyqualifier
def _dependency_qualifier(acc: List<string>, i: Import, unresolved: List<UnresolvedImport>) -> List<string>
opendependencies
def _open_dependencies(mods: List<_Module>, unresolved: List<UnresolvedImport>) -> List<string>
The opened dependencies, whose types carry no qualifier at all. A bare spelling this schema cannot resolve is one of theirs where the project has one, and a standard-library type otherwise.
openeddependency
def _opened_dependency(acc: List<string>, i: Import, unresolved: List<UnresolvedImport>) -> List<string>
stdlibreason
def _stdlib_reason() -> string
dependencyreason
def _dependency_reason(name: string) -> string
undefinedreason
def _undefined_reason(spelling: string, deps: List<string>, opens: List<string>, stdlib: List<string>) -> string
Why one undefined spelling has no rule. The checker gate ran first: every spelling here named a type it accepted. A type this seam cannot read is either a standard-library type, which no rule here describes, or a declared dependency's, whose schema has to be generated in that package.
A qualified spelling is told apart by its qualifier, which is the dependency alias or the standard-library module name it was written under. A bare one under an opened dependency could be that dependency's or the stdlib's, and one message names both in place of a wrong guess.
undefinedtypes
def _undefined_types(mods: List<_Module>, project: Project, names: List<string>) -> List<UndefinedType>
spelltype
def _spell_type(ty: Type) -> string
A Hanki type as the source spells it, for naming one in a refusal.
_spell_type(App("Wrap", [App("Option", [Name("int")])])) => "Wrap<Option<int>>"
ruletypes
def _rule_types(rule: _Rule) -> List<Type>
The field and payload types one rule's body writes.
_param?
def _param?(ty: Type, p: string) -> bool
anyposition?
def _any_position?(xs: List<Type>, pred: (int, Type) -> bool) -> bool
Whether pred is true at some position of xs, given the position and the type there.
rulenamed
def _rule_named(rules: List<_Rule>, scope: Map<string, string>, name: string) -> Option<_Rule>
The generated rule a type spelling inside a rule names, if any.
paramwrapped?
def _param_wrapped?(rules: List<_Rule>, manual: List<string>, rule: _Rule, i: int, seen: List<string>) -> bool
Whether generic parameter i of rule is written directly under an Option, in the rule itself or through a parameter of another generic rule it is passed to. A hand-written codec's rule, a head in manual, counts as wrapping every parameter: its body can encode an Option of one, and reflection does not show whether it does. seen stops a recursive type revisiting a parameter.
_wraps?
def _wraps?(rules: List<_Rule>, manual: List<string>, scope: Map<string, string>, p: string, ty: Type, seen: List<string>) -> bool
nullablegeneric_apps
def _nullable_generic_apps(rules: List<_Rule>, manual: List<string>, scope: Map<string, string>, ty: Type, acc: List<string>) -> List<string>
A user generic applied to a nullable argument at a parameter its rule writes under an Option. A CDDL generic rule is one text for every instantiation, and it writes that Option as (T) / null, where the codec writes null / [T] once the argument is itself nullable.
nullablegeneric_refs
def _nullable_generic_refs(rules: List<_Rule>, manual_heads: List<string>) -> List<string>
Every such application that generated rules write, in first-seen order. A manual head's declaration is not on the wire and is not searched; an application of one is judged by _param_wrapped?.
_HandWrittenCodec
struct _HandWrittenCodec
head: string
impl_name: string
cddl: Option<_Metadata>
generics: List<string>
none_override: Option<string>
end
A source impl whose body can choose a wire shape. Generated derives are not declarations and never appear in compiler.type_decls. Every match here is hand-written.
_Metadata
struct _Metadata
source: string
parsed: Result<_ParsedCddl, string>
end
An impl's @cddl text and its parse, made once when the codec is built and read by the reachability closure and by validation.
declaresmetadata?
def _declares_metadata?(d: Decl) -> bool
parsersfor
def _parsers_for(mods: List<_Module>) -> Result<_Parsers, string>
The grammars, compiled only when some impl in the project has @cddl metadata. With no such impl nothing reads the result.
codecof
def _codec_of(body: ImplBody, head: string, rule: _Rule, parsers: Result<_Parsers, string>) -> _HandWrittenCodec
noneoverride
def _none_override(body: ImplBody) -> Option<string>
The Encode.encodes_none? or Decode.decodes_none? member an impl declares, if any. Its answer decides the wire form of an Option around the type, and an impl body is code reflection does not expose.
declarestrait?
def _declares_trait?(m: _Module, name: string) -> bool
codecdirection
def _codec_direction(m: _Module, name: string) -> Option<string>
Resolve the canonical direction. The two bare names come from the prelude unless a local trait shadows one; core-qualified spellings and explicit import aliases are canonical too.
impltarget
def _impl_target(scope: Map<string, string>, args: List<Type>) -> Option<string>
The declaration rule an impl's first trait argument targets. A generic target reflects as App("Box", args); only its head selects the rule.
manualimpl
def _manual_impl(m: _Module, scope: Map<string, string>, rules: List<_Rule>, d: Decl, parsers: Result<_Parsers, string>) -> Option<_HandWrittenCodec>
modulecodecs
def _module_codecs(m: _Module, all: List<_Module>, rules: List<_Rule>, parsers: Result<_Parsers, string>, acc: List<_HandWrittenCodec>) -> List<_HandWrittenCodec>
handwritten_codecs
def _hand_written_codecs(mods: List<_Module>, rules: List<_Rule>) -> List<_HandWrittenCodec>
Every syntactic hand-written canonical codec targeting a project rule. Reachability is applied after its parsed references have taken part in the closure; an unrelated helper type is then discarded without validating it.
manualcodec_refs
def _manual_codec_refs(codec: _HandWrittenCodec, heads: List<string>, acc: List<string>) -> List<string>
effectiverule_refs
def _effective_rule_refs(rule: _Rule, codecs: List<_HandWrittenCodec>, heads: List<string>) -> List<string>
A manual codec replaces the declaration-shaped traversal at its target. If either peer is invalid, it contributes no references here and validation later fails the reachable target; if valid peers disagree, their union is harmless because no schema is returned after the mismatch.
oneeffective_round
def _one_effective_round(rules: List<_Rule>, codecs: List<_HandWrittenCodec>, included: List<string>) -> List<string>
closeover
def _close_over(rules: List<_Rule>, codecs: List<_HandWrittenCodec>, included: List<string>) -> List<string>
The rule heads the schema must define: deriving seeds plus everything their actual wire shapes reach, transitively. Generated codecs walk declarations; hand-written codecs walk parsed @cddl references. A cycle adds nothing on its second round. The finite set therefore reaches a fixpoint.
schemarules
def _schema_rules(candidates: List<_Rule>, codecs: List<_HandWrittenCodec>) -> List<_Rule>
Every rule the schema is made of, module by module in source order.
CDDLPRELUDE
_CDDL_PRELUDE: List<string> = [
"any",
"uint",
"nint",
"int",
"bstr",
"bytes",
"tstr",
"text",
"tdate",
"time",
"number",
"biguint",
"bignint",
"bigint",
"integer",
"unsigned",
"decfrac",
"bigfloat",
"eb64url",
"eb64legacy",
"eb16",
"encoded-cbor",
"uri",
"b64url",
"b64legacy",
"regexp",
"mime-message",
"cbor-any",
"float16",
"float32",
"float64",
"float16-32",
"float32-64",
"float",
"false",
"true",
"bool",
"nil",
"null",
"undefined"
]
RFC 8610 Appendix D's complete standard prelude. The names below it are rules this generator itself adds when referenced: a fixed width's range and the exact tier's sentinel-carrying choices with the tags they use.
CDDLGENERATED
_CDDL_GENERATED: List<string> = [
"hanki-u8",
"hanki-u16",
"hanki-u32",
"hanki-i8",
"hanki-i16",
"hanki-i32",
"hanki-i64",
"hanki-int",
"hanki-decimal",
"hanki-rational",
"decimal-fraction",
"rational-number"
]
_ManualShape
struct _ManualShape
source: string
canonical: List<string>
impl_name: string
end
cddlref_arity
def _cddl_ref_arity(name: string, codec: _HandWrittenCodec, rules: List<_Rule>) -> Option<int>
knowncddl_ref?
def _known_cddl_ref?(cddl_ref: _CddlRef, codec: _HandWrittenCodec, rules: List<_Rule>) -> bool
unboundcddl_refs
def _unbound_cddl_refs(parsed: _ParsedCddl, codec: _HandWrittenCodec, rules: List<_Rule>) -> List<string>
cddlarity_error
def _cddl_arity_error(cddl_ref: _CddlRef, codec: _HandWrittenCodec, rules: List<_Rule>) -> Option<string>
cddlarity_errors
def _cddl_arity_errors(parsed: _ParsedCddl, codec: _HandWrittenCodec, rules: List<_Rule>) -> List<string>
validatecodec
def _validate_codec(shapes: Map<string, _ManualShape>, codec: _HandWrittenCodec, rules: List<_Rule>) -> Result<Map<string, _ManualShape>, string>
validatecodec_shape
def _validate_codec_shape(shapes: Map<string, _ManualShape>, codec: _HandWrittenCodec, rules: List<_Rule>) -> Result<Map<string, _ManualShape>, string>
validatemanual_codecs
def _validate_manual_codecs(codecs: List<_HandWrittenCodec>, rules: List<_Rule>) -> Result<Map<string, _ManualShape>, string>
emitrule
def _emit_rule(rule: _Rule, shapes: Map<string, _ManualShape>) -> string
_render
def _render(rules: List<_Rule>, shapes: Map<string, _ManualShape>) -> string
The rules, then any generated rule they reference. Empty when no rule is reached, which is the one case with no schema to return.
header
def header(sources: List<string>) -> string
The leading comment of a committed schema, naming what produced it and from what. hanki cddl prints it above the rules unless --schema-only is given.
It names both versions, since they answer different questions. The toolchain version is which hanki wrote the file; the reflection API revision is whether the file's form is still current.
Each source is named by its basename. A committed header that has /home/someone/proj/todo.hk in it would change for every checkout that regenerates it. It names the resolved roots, which gives the directory and file forms of one project the same header.
header(["src/todo.hk"]).starts_with?("; Generated by `hanki cddl` from todo.hk") => true
header(["todo.hk"]).starts_with?("; Generated by `hanki cddl` from todo.hk") => true
header(["a.hk", "b.hk"]).starts_with?("; Generated by `hanki cddl` from a.hk, b.hk") => true
header(["todo.hk"]).contains?("; hanki #{compiler.toolchain_version()}, reflection API") => true
Schema
struct Schema
text: string
entries: List<string>
unreached: List<string>
end
The schema of a project's codec types, and what a caller reports beside it.
CddlError
type CddlError
Unreadable(string)
Unchecked(List<Diagnostic>)
InvalidMetadata(string)
Undefinable(List<UndefinedType>)
NullableGenericArgument(List<string>)
NoCodecTypes(List<string>, List<string>)
end
Why generate! returned no schema. Each variant is one refusal.
_indented
def _indented(items: List<string>) -> string
unreachedlines
def _unreached_lines(paths: List<string>) -> string
impl Display<CddlError>
to_string
def to_string(self) -> string
The refusal as hanki cddl prints it after cddl generation failed: . A list payload renders one indented line per entry.
Unreadable("cannot read a.hk: not found").to_string() => "cannot read a.hk: not found"
NoCodecTypes(["main.hk"], []).to_string() => "no `@derive(Encode)` or `@derive(Decode)` types in main.hk"
NoCodecTypes(["main.hk"], ["wip.hk"]).to_string().ends_with?("\n wip.hk is not reachable from any root") => true
NullableGenericArgument(["Wrap<Option<int>>"]).to_string().starts_with?("the schema would apply a generic rule to a nullable argument 1 time(s):\n Wrap<Option<int>>\n") => true
_contributes?
def _contributes?(source: string) -> bool
A module no root reaches contributes no rules, and a wire type in one (a module written test-first, before its first caller exists) would be absent from the schema with nothing to report it. hanki check reports the module itself as H0627.
Only a module that could contribute is listed. One with no codec types adds nothing to the schema; one that will not parse is listed, since nothing can tell.
_unreached
def _unreached(project: Project) -> List<string>
_found
def _found(text: string, project: Project) -> Result<Schema, CddlError>
schemaof
def _schema_of(mods: List<_Module>, project: Project) -> Result<Schema, CddlError>
filediagnostics!
def _file_diagnostics!(path: string) -> Result<List<Diagnostic>, string> [fs_read]
entrydiagnostics!
def _entry_diagnostics!(project: Project) -> Result<List<Diagnostic>, string> [fs_read]
Every diagnostic hanki check would report for the package, one per entry, with the repeats a second entry's check makes dropped by code and message.
A site is named by its message and no line and column: a diagnostic answers with a span into its own file and the seam reports a file id in place of a path. A path:line:col here would be a guess about which file it belongs to. hanki check renders the sites.
distinctdiagnostics
def _distinct_diagnostics(ds: List<Diagnostic>) -> List<Diagnostic>
adddiagnostic
def _add_diagnostic(acc: List<Diagnostic>, d: Diagnostic) -> List<Diagnostic>
gatediagnostics!
def _gate_diagnostics!(project: Project) -> Result<List<Diagnostic>, string> [fs_read]
The checker gate, over the entries.
It needs the checker's whole view of the package, and the seam reads no source of a dependency it could not bind: project_modules! lists that dependency in unresolved, and project_diagnostics! would then report H0303 for the use and cascade type variables through every expression that reached it, in errors hanki check reports nowhere. A project with an unresolved import is therefore left to hanki check, and to the hanki cddl command, which runs the package check with dependencies resolved first. The other refusals still stand, the undefinable reference among them.
generateproject!
def _generate_project!(project: Project) -> Result<Schema, CddlError> [fs_read]
generate!
def generate!(root: string) -> Result<Schema, CddlError> [fs_read]
The schema of the codec types of the project at root, a project directory or a .hk file, with the roots it was read from and the unreached modules it left out. hanki cddl prints it.
A project the checker refuses has no schema, and neither has one whose schema would be incomplete or wrong: each refusal is a CddlError variant.
@no-doctest: reads a project from the filesystem; covered by the hanki cddl integration tests in crates/hanki-cli/tests/stdlib/cddl.rs
schema!
def schema!(root: string) -> Result<string, CddlError> [fs_read]
What hanki cddl --schema-only prints for the project at root: the rules of generate! with no header. A test comparing a committed schema with the project's types calls it.
@no-doctest: reads a project from the filesystem; covered by the hanki cddl integration tests in crates/hanki-cli/tests/stdlib/cddl.rs