silk.core.reflect.
Compile-time descriptions of the fields of a struct or tuple type, for generic code that visits each field.
When to use#
Use Reflect to write one generic function that works on the fields of many types, such as a
serializer or a formatter. Use Reflect.fields with static for to visit each field, and
Reflect.borrowField to read the value of a field at runtime, or Reflect.borrowFieldMut
to change it.
Details#
Descriptors exist only during static evaluation. They have no runtime value, so reflection adds
no runtime cost. The compiler expands a static for over Reflect.fields into one copy of
the loop body for each field, in declaration order. In each copy, the field has its own type.
A descriptor shows only the fields that are visible from the module that calls the reflection operation. Private fields of a type from another module are not in the list.
Examples#
Add all fields of a struct#
import silk.core.reflect { Reflect }
struct Pair {
pub first: i32,
pub second: i32,
}
fn sum(owner: &Pair) -> i32 {
let mut total = 0
static for field in Reflect.fields<Pair>() {
total = total + Reflect.borrowField<Pair, i32>(owner, field).*
}
return total
}
pub fn main() -> i32 {
let pair = Pair { first: 20, second: 22 }
if sum(&pair) != 42 {
return 1
}
return 0
}Keep an enum by its member name#
import silk.core.option { Option }
import silk.core.reflect { Reflect }
enum Tab { Home, Search, Settings }
pub fn main() -> i32 {
let saved = Reflect.enumLabelOf(Tab.Search)
return match Reflect.enumFromLabel<Tab>(saved) {
Option<Tab>.Some {value} => {
if value != Tab.Search {
return 1
}
return 0
}
Option<Tab>.None => 2
}
}Import as Reflect with import silk.core.reflect { Reflect }.
Public declarations: 12.
namedKind#
pub const namedKind: u8The Reflect.typeKind result for a declared struct with named fields.
positionalKind#
pub const positionalKind: u8The Reflect.typeKind result for a declared tuple type with positional fields.
anonymousNamedKind#
pub const anonymousNamedKind: u8The Reflect.typeKind result for an anonymous record with named fields.
anonymousPositionalKind#
pub const anonymousPositionalKind: u8The Reflect.typeKind result for an anonymous tuple with positional fields.
arrayKind#
pub const arrayKind: u8The Reflect.typeKind result for a fixed array, such as [i32; 3]. It has no fields.
otherKind#
pub const otherKind: u8The Reflect.typeKind result for every other type, such as i32, string, a slice, an
or a structural union A | B. It has no fields.
unionKind#
pub const unionKind: u8The Reflect.typeKind result for a nominal union, such as union Shape { ... }. It has no
fields of its own; list its variants with Reflect.variants.
enumKind#
pub const enumKind: u8The Reflect.typeKind result for a scalar enum, whose values Reflect.enumMembers lists.
labeledFieldKind#
pub const labeledFieldKind: u8The Reflect.fieldKind result for a field with a name. Read the name with
Reflect.fieldLabel.
positionalFieldKind#
pub const positionalFieldKind: u8The Reflect.fieldKind result for a field with a position. Read the position with
Reflect.fieldOrdinal.
variantFieldKind#
pub const variantFieldKind: u8The Reflect.fieldKind result for a field of a union variant, from Reflect.variantFields.
It has both a name, read with Reflect.fieldLabel, and a position in its variant, read with
Reflect.fieldOrdinal.
Reflect#
pub struct ReflectThe owner type of the reflection operations. It has no fields and is never constructed.
Details#
Each operation except Reflect.borrowField and Reflect.borrowFieldMut is static. It
runs only during static evaluation, such as in a static for, a static if, or a static fn.
Implementation Reflect#
impl ReflectAssociated function typeOf#
pub static fn typeOf<Owner>() -> Intrinsic.Type<Owner>Returns the compile-time descriptor of the struct or tuple type Owner.
Details#
Give the descriptor to Reflect.typeKind to find the kind of type.
Associated function fields#
pub static fn fields<Owner>() -> Intrinsic.Fields<Owner>Returns the compile-time descriptors of the fields of Owner, in declaration order.
Details#
Use the result as the sequence of a static for. Each element has the type
Intrinsic.Field<Owner, Value>, where Value is the type of that field.
Gotchas#
The list contains only the pub fields, even when the caller is the module that declares
Owner, because visibility is judged from silk.core.reflect. Call
Intrinsic.reflectFields<Owner>() directly to list the fields that the calling module can
see.
Associated function field#
pub static fn field<Owner, Value>(label: string<'static>) -> Intrinsic.Field<Owner, Value>Returns the compile-time descriptor of the field of Owner named label.
Details#
Use it to name one field by its label, such as a command line option that fills the field
verbose. Pass the descriptor to Reflect.borrowField to read the field at runtime.
Gotchas#
Static evaluation stops at the call when Owner has no pub field named label, or when
that field's type is not Value.
Examples#
import silk.core.reflect { Reflect }
struct Flags {
pub verbose: bool,
pub depth: u32,
}
fn depthOf(flags: &Flags) -> u32 {
return Reflect.borrowField<Flags, u32>(flags, Reflect.field<Flags, u32>("depth")).*
}
pub fn main() -> i32 {
let flags = Flags { verbose: false, depth: 3 }
if depthOf(&flags) != 3 {
return 1
}
return 0
}Associated function fieldNameText#
pub static fn fieldNameText<Owner>(name: Intrinsic.FieldName<Owner>) -> string<'static>Returns the text of name, a field name of Owner that was checked where it was written.
When to use#
Take an Intrinsic.FieldName<Owner> parameter where a library asks for the name of one of the
caller's fields, such as the field a command line option fills. A string literal passed there
must name a field of Owner, so a misspelled name is an error at the literal, and the editor
links the literal to the field.
Examples#
import silk.core.reflect { Reflect }
struct Flags {
pub verbose: bool,
}
static fn optionName<T>(name: Intrinsic.FieldName<T>) -> string<'static> {
return Reflect.fieldNameText<T>(name)
}
pub fn main() -> i32 {
static if optionName<Flags>("verbose") != "verbose" {
compileError("the name is its text")
}
return 0
}Associated function fieldNamed#
pub static fn fieldNamed<Owner, Value>(name: Intrinsic.FieldName<Owner>) -> Intrinsic.Field<
Owner,
Value
>Returns the descriptor of the field that name names, whose type must be Value.
Associated function variantNameText#
pub static fn variantNameText<Union>(name: Intrinsic.VariantName<Union>) -> string<'static>Returns the text of name, a variant name of Union that the compiler checked where it was
written. A string literal is an Intrinsic.VariantName<Union> when that type is expected, and
a literal that names no variant of Union is a compile error at the literal.
Associated function typeKind#
pub static fn typeKind<Owner>(descriptor: Intrinsic.Type<Owner>) -> u8Returns the kind of type that descriptor describes: namedKind, positionalKind,
anonymousNamedKind, anonymousPositionalKind, arrayKind, unionKind,
enumKind, or otherKind. Every type has a kind, so a generic function can branch on the kind of its type parameter.
Associated function typeName#
pub static fn typeName<Owner>() -> string<'static>Returns the name of Owner as a program writes it, with its type arguments and without module
paths, such as Server or Page<String>.
Details#
Lifetimes other than 'static are elided, as in &u32. A function passed as a value is named
by the contract it satisfies, such as fn(&u32) -> bool.
When to use#
Name a type where a library describes it to someone else, such as a JSON Schema definition.
Associated function declarationName#
pub static fn declarationName<Owner>() -> string<'static>Returns the nominal declaration's package, module and owner names separated by /.
The name does not depend on imports or type arguments. A non-nominal type returns empty text.
Associated function enumMembers#
pub static fn enumMembers<Enum>() -> Intrinsic.StaticSequence<Enum>Returns the members of the scalar enum Enum, in declaration order.
Details#
Use the result as the sequence of a static for. Each element is a value of Enum; read
its name with Reflect.enumLabelOf and its discriminant with Reflect.enumValue. The
sequence has no runtime representation.
Associated function enumValue#
pub static fn enumValue<Enum, Repr>(value: Enum) -> ReprReturns the discriminant of the scalar enum member value, as its representation Repr.
When to use#
Read the discriminant of a member in generic code, where Enum.value cannot be named. For
enum(i16) Code { Ok, Failed = 130 }, enumValue<Code, i16>(Code.Failed) is 130.
Gotchas#
It runs only during static evaluation, so value must be known then, such as a member from
Reflect.enumMembers. Static evaluation stops at the call when Repr is not the enum's
representation: u8 for an enum declared without one.
Associated function enumLabelOf#
pub fn enumLabelOf<Enum>(value: Enum) -> string<'static>Returns the name of the member that the scalar enum value value holds, as written in the
enum declaration.
Details#
At runtime it compares value with each member in turn, like a match with one arm for each
member. Static code can call it too, such as on a member from Reflect.enumMembers.
Associated function enumFromLabel#
pub fn enumFromLabel<Enum>(label: string) -> Option<Enum>Returns the member of the scalar enum Enum named label, or none when no member has that
name.
When to use#
Read back a value written with Reflect.enumLabelOf, such as a saved setting. The name
must match exactly, including case.
Associated function enumFromValue#
pub fn enumFromValue<Enum, Repr>(value: Repr) -> Option<Enum>Returns the member of the scalar enum Enum whose discriminant is value, or none when no
member has it.
Details#
It is the inverse of Enum.value for generic code. Repr must be the enum's
representation, u8 for an enum declared without one.
Examples#
import silk.core.option { Option }
import silk.core.reflect { Reflect }
enum(i16) Code { Ok, Failed = 130 }
pub fn main() -> i32 {
if Reflect.enumFromValue<Code, i16>(1).isSome() {
return 1
}
return match Reflect.enumFromValue<Code, i16>(130) {
Option<Code>.Some {value} => {
if value != Code.Failed {
return 2
}
return 0
}
Option<Code>.None => 3
}
}Associated function typeDoc#
pub static fn typeDoc<Owner>() -> string<'static>Returns the /// comment written on the declaration of Owner, without its slashes and with
its lines joined by newlines, or empty text when it has none or is not a named type.
Associated function privateField#
pub static fn privateField<Owner>() -> string<'static>Returns the name of the first field of the struct Owner that is not pub, or empty text
when every field is pub or Owner is no struct.
When to use#
Refuse, at compile time, a type that a library must construct from outside its module. An
errorAt on the returned text points at that field's declaration.
Associated function fieldKind#
pub static fn fieldKind<Owner, Value>(field: Intrinsic.Field<Owner, Value>) -> u8Returns labeledFieldKind for a named field, positionalFieldKind for a positional
field, or variantFieldKind for a field of a union variant.
Associated function fieldLabel#
pub static fn fieldLabel<Owner, Value>(field: Intrinsic.Field<Owner, Value>) -> string<'static>Returns the name of a named field, as written in the type declaration.
Gotchas#
Use this function only for a field where Reflect.fieldKind is labeledFieldKind or
variantFieldKind.
Associated function fieldDoc#
pub static fn fieldDoc<Owner, Value>(field: Intrinsic.Field<Owner, Value>) -> string<'static>Returns the /// comment written on a named struct field or a variant field, without its
slashes and with its lines joined by newlines, or empty text when the field has none.
When to use#
Read a field's comment where a library shows text about the field, such as the help text of the command line option the field fills, so the comment is written once.
Gotchas#
Editing the comment changes what the program shows, as it would for a string literal. A positional field and an anonymous field give empty text. A variant field's descriptor does not name its variant, so when two variants have a field of the same name at the same position, both read the first one's comment.
Examples#
import silk.core.reflect { Reflect }
struct Flags {
/// Say more.
pub verbose: bool,
}
pub fn main() -> i32 {
static for field in Reflect.fields<Flags>() {
static if Reflect.fieldDoc(field) != "Say more." {
compileError("the comment is the field's documentation")
}
}
return 0
}Associated function fieldOrdinal#
pub static fn fieldOrdinal<Owner, Value>(field: Intrinsic.Field<Owner, Value>) -> usizeReturns the zero-based position of a positional field.
Gotchas#
Use this function only for a field where Reflect.fieldKind is positionalFieldKind or
variantFieldKind.
Associated function borrowField#
pub fn borrowField<'o, Owner, Value>(
owner: &'o Owner,
static field: Intrinsic.Field<Owner, Value>,
) -> &'o ValueReturns a shared borrow of the field of owner that field describes.
Details#
field is a static argument, so the compiler selects the field during specialization. At
runtime this function is a plain field access. The borrow lives as long as the borrow of
owner.
Gotchas#
field must come from Reflect.fields for the same Owner type. This function cannot move
a field out of an owned value.
Associated function borrowFieldMut#
pub fn borrowFieldMut<Owner, Value>(
owner: &mut Owner,
static field: Intrinsic.Field<Owner, Value>,
) -> &mut ValueReturns a mutable borrow of the field of owner that field describes.
Details#
field is a static argument, so the compiler selects the field during specialization. At
runtime this function is a plain field access. The borrow lives as long as the mutable borrow
of owner, and owner cannot be used while the field borrow is live.
Examples#
import silk.core.reflect { Reflect }
struct Counters {
pub hits: i32,
pub misses: i32,
}
fn reset(counters: &mut Counters) -> () {
static for field in Reflect.fields<Counters>() {
let place = Reflect.borrowFieldMut<Counters, i32>(&mut counters.*, field)
place.* = 0
}
return ()
}
pub fn main() -> i32 {
let mut counters = Counters { hits: 4, misses: 2 }
reset(&mut counters)
return counters.hits + counters.misses
}Gotchas#
field must come from Reflect.fields for the same Owner type. owner must be a mutable
borrow; a shared borrow is refused.
Associated function variants#
pub static fn variants<Union>() -> Intrinsic.Variants<Union>Returns the compile-time descriptors of the variants of the nominal union Union, in
declaration order.
Details#
Use the result as the sequence of a static for. Each element has the type
Intrinsic.Variant<Union>. Give it to Reflect.variantLabel, Reflect.variantFields,
Reflect.makeVariant or Reflect.isVariant.
Examples#
import silk.core.option { Option }
import silk.core.reflect { Reflect }
union Command {
Status,
Clone { pub url: string<'static>, pub depth: u32 },
}
static fn fieldCount<U>(variant: Intrinsic.Variant<U>) -> usize {
let mut count: usize = 0
static for field in Reflect.variantFields(variant) { count = count + 1 }
return count
}
// Builds the variant of `U` named `word`, if it has no fields.
fn unitNamed<U>(word: string) -> Option<U> {
static for variant in Reflect.variants<U>() {
static if fieldCount(variant) == 0 {
if word == Reflect.variantLabel(variant) {
return Option<U>.some(Reflect.makeVariant(variant, ()))
}
}
}
return Option<U>.none()
}
pub fn main() -> i32 {
let found = unitNamed<Command>("Status")
return match move found {
Option<Command>.Some {value: Command.Status} => 0
_ => 1
}
}Associated function variantLabel#
pub static fn variantLabel<Union>(variant: Intrinsic.Variant<Union>) -> string<'static>Returns the name of a variant, as written in the union declaration.
Associated function variantDoc#
pub static fn variantDoc<Union>(variant: Intrinsic.Variant<Union>) -> string<'static>Returns the /// comment written on a variant, without its slashes and with its lines joined
by newlines, or empty text when the variant has none.
Associated function variantFields#
pub static fn variantFields<Union>(variant: Intrinsic.Variant<Union>) -> Intrinsic.Fields<Union>Returns the compile-time descriptors of the fields of a variant, in declaration order.
Details#
Each element has the type Intrinsic.Field<Union, Value>, where Value is the type of that
field, and the kind variantFieldKind. A unit variant has none.
Gotchas#
The list contains only the pub fields, because visibility is judged from
silk.core.reflect. A field descriptor of a variant cannot be given to
Reflect.borrowField, because the union holds the field only while that variant is active;
read it with Reflect.borrowVariantField.
Associated function makeVariant#
pub fn makeVariant<Union, Fields>(
static variant: Intrinsic.Variant<Union>,
fields: Fields,
) -> UnionReturns the variant that variant describes, built from fields: a tuple of the variant's
fields in declaration order, or () for a variant without fields.
Details#
variant is a static argument, so the compiler selects the variant during specialization.
At runtime this function is a plain variant construction, such as
Shape.Line {length: a, width: b} for makeVariant(line, (a, b)). The tuple is
moved into the variant.
Examples#
import silk.core.reflect { Reflect }
union Shape {
Dot,
Circle { pub radius: u32 },
Line { pub length: u32, pub width: u32 },
}
fn area(shape: Shape) -> u32 {
return match move shape {
Shape.Dot => 0
Shape.Circle {radius} => radius * radius * 3
Shape.Line {length, width} => length * width
}
}
static fn fieldCount<U>(variant: Intrinsic.Variant<U>) -> usize {
let mut count: usize = 0
static for field in Reflect.variantFields(variant) { count = count + 1 }
return count
}
pub fn main() -> i32 {
let two: u32 = 2
let three: u32 = 3
let four: u32 = 4
let mut total: u32 = 0
static for variant in Reflect.variants<Shape>() {
let static count = fieldCount(variant)
static if count == 0 { total = total + area(Reflect.makeVariant(variant, ())) }
static if count == 1 { total = total + area(Reflect.makeVariant(variant, .(two))) }
static if count == 2 { total = total + area(Reflect.makeVariant(variant, (three, four))) }
}
// 0 + 12 + 12
if total != 24 {
return 1
}
return 0
}Gotchas#
The tuple must have exactly the variant's field types in declaration order. Every field of the
variant must be pub, since the variant is built from silk.core.reflect.
Associated function borrowVariantField#
pub fn borrowVariantField<'o, Union, Value>(
owner: &'o Union,
static variant: Intrinsic.Variant<Union>,
static field: Intrinsic.Field<Union, Value>,
) -> &'o ValueReturns a borrow of the field that field describes, of the variant that variant describes.
Details#
variant and field are static arguments, so at runtime this function is a test of the
union's active variant followed by a plain field borrow, like a match arm that binds that
field. field must be one of Reflect.variantFields of variant.
Examples#
import silk.core.reflect { Reflect }
union Shape {
Dot,
Line { pub length: u32, pub width: u32 },
}
// Adds the fields of whichever variant `shape` holds.
fn total(shape: &Shape) -> u32 {
let mut sum: u32 = 0
static for variant in Reflect.variants<Shape>() {
if Reflect.isVariant(shape, variant) {
static for field in Reflect.variantFields(variant) {
sum = sum + Reflect.borrowVariantField<Shape, u32>(shape, variant, field).*
}
}
}
return sum
}
pub fn main() -> i32 {
if total(&Shape.Line {length: 3, width: 4}) != 7 {
return 1
}
if total(&Shape.Dot) != 0 {
return 2
}
return 0
}Gotchas#
It traps when owner holds another variant, so test with Reflect.isVariant first.
Associated function borrowVariantFieldMut#
pub fn borrowVariantFieldMut<Union, Value>(
owner: &mut Union,
static variant: Intrinsic.Variant<Union>,
static field: Intrinsic.Field<Union, Value>,
) -> &mut ValueReturns a mutable borrow of the field that field describes, of the variant that variant
describes.
Details#
variant and field are static arguments, so at runtime this function is a test of the
union's active variant followed by a plain mutable field borrow, like a match arm on
&mut owner that binds that field. field must be one of Reflect.variantFields of
variant.
Examples#
import silk.core.reflect { Reflect }
union Shape {
Dot,
Line { pub length: u32, pub width: u32 },
}
// Doubles the fields of whichever variant `shape` holds.
fn double(shape: &mut Shape) -> () {
static for variant in Reflect.variants<Shape>() {
if Reflect.isVariant(&shape.*, variant) {
static for field in Reflect.variantFields(variant) {
let place = Reflect.borrowVariantFieldMut<Shape, u32>(&mut shape.*, variant, field)
place.* = place.* * 2
}
}
}
}
pub fn main() -> i32 {
let mut shape = Shape.Line {length: 3, width: 4}
double(&mut shape)
return match &shape {
Shape.Line {length, width} => {
if length != 6 || width != 8 {
return 1
}
return 0
}
Shape.Dot => 2
}
}Gotchas#
It traps when owner holds another variant, so test with Reflect.isVariant first.
Associated function isVariant#
pub fn isVariant<Union>(owner: &Union, static variant: Intrinsic.Variant<Union>) -> boolReturns whether owner holds the variant that variant describes.
Details#
variant is a static argument, so at runtime this function is a plain test of the union's
active variant, like a match with one arm for that variant.
Category: Core.
Profiles: aarch64-apple-darwin, aarch64-unknown-linux-gnu, aarch64-unknown-linux-gnu-no-libc, x86_64-unknown-linux-gnu, x86_64-unknown-linux-gnu-no-libc, wasm32-unknown-unknown, wasm32-wasip1, wasm32-wasip2, x86_64-pc-windows-msvc, wasm64-unknown-unknown.