docs

你正在阅读 v0.1.0 的文档。Nabi 0.1.0 已不再提供支持。 最新版本:v0.1.3 →

本页尚未翻译,以下为英文原文。

#2.12. reflect - Reflect / Inspect

本页内容

The core::reflect module provides the authoritative signatures for runtime type information and field introspection. The detailed semantics are governed by refs-lang 6.10 reflection; this chapter covers only the standard library's trait shapes.

#2.12.1. Two-level traits

Reflection is split into two levels of traits.

TraitAutomatic / opt-inProvidesWhere used
Reflectautomatic (every type)type_name / size / aligna core trait, in scope everywhere (rarely used)
Inspectopt-in (#[derive(Inspect)])field_names / fields / variant_name / get_field / methodstrait available through the implicit prelude, derive is explicit

The split into automatic and opt-in controls binary size. If every struct carried field reflection metadata, the binary would grow; the opt-in scheme generates the metadata only for the types that need it.

#2.12.2. Reflect - both static and instance

nabi
trait Reflect {
    fn type_name() -> str;        // static: T::type_name()
    fn size() -> usize;
    fn align() -> usize;

    fn type_name_of_val(self) -> str; // instance: x.type_name_of_val() (any / sum also OK)
    fn size_of_val(self) -> usize;
}

This trait is implemented automatically for every type; the compiler attaches the type info to the binary automatically.

The compiler provides Reflect for every type; there is no impl in source.

  • A hand-written impl Reflect for T is an error. The bound T: Reflect always holds.
  • If a type has its own method with the same name, such as size() / type_name(), that method shadows the reflection method.
  • The name (type_name) carries no module path (List<i64>, Config), nor trailing type arguments equal to their default (Dict<str, i32>, refs-lang 2.10.5). The static name of a sum type is written in canonical order (2.6.4) (f64 | i32, with none last). Instance forms such as type_name_of_val(self) report the member present at runtime (for a sum) or the content of an any.
  • core::reflect::cast<T>(value: any) -> T | none extracts a T from an any using the same rules as set_field. There is no free function for a type's methods or fields: they are T::methods() / T::fields() and need #[derive(Inspect)], the type's consent.

#Static vs instance

One suffix rule: the plain form is the type's answer, fixed at compile time; the _of_val form is the value's answer at run time.

nabi
i32::type_name();          //→ "i32"           (static, decided at compile time)
i32::size();               //→ 4
i32::align();              //→ 4

let x: i32 = 42;
x.type_name_of_val();      //→ "i32"           (instance, usually the same as static)

let y: i32 | f64 = 42i32;
y.type_name_of_val();      //→ "i32"           (runtime dispatch, checks the sum tag)

let z: any = "hello";
z.type_name_of_val();      //→ "str"           (runtime, any slot dispatch)

type_name_of_val is a runtime dispatch, so for a sum type or any it returns the name of the variant currently held.

#No global functions

nabi
typeof(x);                 // ERROR: no global typeof
sizeof(T);                 // ERROR: no global sizeof

Instead, everything is uniformly a method.

nabi
x.type_name_of_val()   // instance
T::type_name()             // static
T::size()
T::align()

This is part of refs-lang 3.5 Member access and method calls: all introspection is unified in method form.

#2.12.3. Inspect - opt-in fields / methods

  • get_field returns the field's value as any, or none for an unknown name. Private fields can be read too.
  • set_field assigns and returns true when the value's type is exactly the same as the field's type, or when an integer of a different integer type fits without loss (u.set_field("id", 42) into a u64 field). Otherwise it does not assign and returns false. There are no other conversions (e.g. i32 → f64).
  • methods() returns only the type's inherent methods (excluding trait methods), sorted by name. Methods of a generic impl show the types as written (T).
  • fields() lists every field in declaration order with its type name and whether it is pub. Private fields are listed too: deriving Inspect is the type author's consent, the same as for get_field. The type name is the instantiated one (Box<f64> reports v: f64, items: List<f64>), with no module path, as type_name writes it.
  • An enum has no fields at the type level (field_names() and fields() are empty lists). variant_names() lists its variants in declaration order. On a value, variant_name() is the variant it holds ("Circle"), field_names_of_val() that variant's fields ("0", "1" for a tuple variant, the names for a named one), and get_field reads them. A variant's payload is read-only through Inspect: set_field on an enum is false.
  • On a struct, variant_names() is an empty list, variant_name() is its type name (type_name_of_val()), and field_names_of_val() is its fields.
  • fields(), methods(), variant_names(), variant_name() and field_names_of_val() have default bodies, so a hand-written impl Inspect needs only the first three methods.
  • Calling an Inspect method on a type without the derive is an error whose help says what to write: add `#[derive(Inspect)]` to `Point` .

#Derive example

#Using meta blocks

#[derive(Inspect)] is implemented as a meta block in core::reflect (refs-lang 6.8, 6.9). It writes only the three accessors the type's description points at; every other method has a default body over type_info(). In summary:

#Where dynamic dispatch is needed

Inspect is used in domains that need access by field name, such as config objects, serializers and debuggers. In ordinary code Reflect alone is enough.

nabi
fn dump_struct<T: Inspect>(x: T) {
    for f in T::fields() {
        if let v: any = x.get_field(f.name) {
            println(f"{f.name}: {f.type_name} ({v.type_name_of_val()})");
        }
    }
}

#2.12.4. REPL output

The REPL prints a bare last expression with Display, else Debug, a trailing ? with Debug, and a value without them with this chapter's Reflect::type_name_of_val (2.10 fmt, refs-lang 6.10.3).

>>> let x = 42i32;
>>> x
42

>>> [1, 2, 3]
[1, 2, 3]

>>> [1, 2, 3]?
[1, 2, 3]

>>> User { id: 1, name: "Alice" }?
User { id: 1, name: "Alice" }

A bare expression uses Display, else Debug, and a trailing ? uses Debug. A value without either (Debug for a trailing ?) prints only its type name; an any value, the name of the type it holds.

#2.12.5. Module mapping

ItemLocationMechanism
Reflect (automatic)compiler + core::reflecttype info table, attached to the binary
Inspect derivecore::reflect + meta block #[impl_derive]code generation from template tokens
MethodInfocore::reflectplain struct
FieldInfocore::reflectcompiler field table (instantiated types)
any typecompiler built-intype tag + payload

#2.12.6. Comparison with other languages

AspectRustJavaPythonNabi
Type namestd::any::type_name::<T>()getClass()type(x).__name__x.type_name_of_val() method
Field introspectionnone (libraries such as bincode)Reflection APIvars(x) getattrx.get_field(name) (opt-in)
Runtime dispatchdyn Trait (vtable)automaticautomaticsum type tag + any / any Trait (opt-in)
Automatic implnoneevery objectevery objectReflect automatic, Inspect opt-in
Memory cost0metadata for every classdict for every objectonly Reflect automatic (opt-in split)

Nabi differs in two main ways. First, the two-level split provides the lightweight Reflect automatically and the heavyweight Inspect as opt-in. This is more memory-efficient than the all-automatic model of Java or Python and more ergonomic than Rust's all-manual model. Second, for method consistency there are no global functions such as typeof(x); all introspection is provided in method form.

The detailed reflection semantics are governed by refs-lang 6.10.

#2.12.7. TypeInfo

The description T::type_info() / info::<T>() returns (refs-lang 6.10.7, layout 8.13). Accessors that return a value read it in place and allocate nothing; those that return a List allocate it.

std::nabion::to_value_any and from_value_any (3.8.5) are built on these.

Found a mistake? Edit this page on GitHub. Last updated