docs

您正在閱讀 v0.1.2 的文件。Nabi 0.1.2 已停止支援。 最新版本:v0.1.3 →

本頁尚未翻譯,以下為英文原文。

#0.4. #[lang] slot mapping table

本頁內容

The #[lang(slot_name)] attribute (refs-lang 6.4) registers a standard library item in a slot that the compiler can look up. This chapter collects in one place, in tabular form, every slot name, its meaning, and the item it is attached to.

The slot table is the authoritative location in the spec; the compiler, the standard library and users all refer to it to stay consistent. If slot names drift, the contract between the language and the library breaks down, so any change starts from this table.

#0.4.1. Slot classification

The 100 slots fall into four groups according to their responsibility. The table below shows the role and slot count of each group at a glance, indicating which category the detailed tables in the following sections belong to.

GroupResponsibilitySlots
TypeStandard library types Nabi recognizes as concrete types20
TraitTraits Nabi uses for operator / control-flow desugaring, derive, and thread-boundary checks37
MethodMethods Nabi calls automatically (drop)1
FunctionStandard library functions Nabi calls as intrinsic calls, and the hooks lowered code calls42
Total100

#0.4.2. Type slots (20)

Type slots indicate the concrete type the compiler lowers to when it encounters a literal or keyword. This group divides further into two kinds. First, there are the language default types exposed directly as lowercase identifiers. They need no separate keyword registration and are the primitives users encounter every day.

Language defaults (built-in primitives, no #[keyword] needed):

Slot nameMeaningStandard library itemRef
i32_typei32 primitivebuilt-in (methods: core::num)2.1
i64_typei64 primitivebuilt-in (methods: core::num)2.1
f32_typef32 primitivebuilt-in (methods: core::num)2.1
f64_typef64 primitivebuilt-in (methods: core::num)2.1
usize_typeusize primitivebuilt-in (methods: core::num)2.1
isize_typeisize primitivebuilt-in (methods: core::num)2.1
bool_typebool primitivebuilt-in (methods: core::num)2.1
cchar_typec_char primitive (FFI)built-in (impls: core::num)2.15
str_typestr primitive (UTF-8 view)built-in (methods: core::str)2.15
char_typechar primitive (Unicode scalar)built-in (methods: core::str)2.15

Second, there are the slots tied to language syntax: the auto-promoting int and float, the storage floats f16 and bf16, the none sentinel, and the Range literal. int, float, f16 and bf16 are PascalCase library structs that expose a lowercase name via #[keyword(...)]; none is built in, and the library names its type NoneSentinel with pub type NoneSentinel = none.

Syntax-tied slots:

Slot nameMeaningStandard library itemRef
none_typeType of the none literalbuilt-in (alias: core::marker::NoneSentinel)2.13
int_typeint auto-promote typecore::num::bigint::Int + #[keyword("int")]2.1
float_typefloat auto-promote typecore::num::bigfloat::Float + #[keyword("float")]2.1
f16_typef16 storage float (IEEE 754 binary16)core::num::half::F16 + #[keyword("f16")]2.1
bf16_typebf16 storage float (bfloat16)core::num::half::BF16 + #[keyword("bf16")]2.1
range_typeRange<T> (a..b)core::range::Range + #[literal( expr ".." expr )]2.7
slice_arg_typea slice part a:b:k of a multi-part indexcore::index::SliceArg2.3
rest_axis_type.. beside other parts of an axis indexcore::index::Rest2.3
new_axis_typenone in an axis indexcore::index::NewAxis2.3
ndarray_typea nested list literal in its slotcore::array::Array2.9.14

A compiler that provides the primitive types built in may leave i32_type ... str_type, none_type and char_type unattached. The reference compiler does: these slot names are accepted, but the library attaches no item to them (str and c_char are not library structs, and NoneSentinel is an alias, not a #[lang] item). Where 0.4.6 looks up one of them, the compiler uses its built-in type.

#0.4.3. Trait slots (37)

Trait slots indicate which trait the compiler goes to when user-written syntax is desugared into a standard library trait call. Core syntax such as for loops, indexing, slicing, formatting and await all resolves through the traits registered here, so this table is the thickest bridge between the language syntax and the library.

Slot nameMeaningStandard library traitRef
iterator_traitStepping in for x in xscore::iter::Iterator2.7
into_iterator_traitStart of for x in xscore::iter::IntoIterator2.7
try_iterator_traitStepping in try for x in xscore::iter::TryIterator2.7.13
index_traitarr[i] readcore::index::Index2.3
index_set_traitarr[i] = v writecore::index::IndexSet2.3
slice_traits[1:3] slicingcore::index::Sliceable2.3
display_traitf"{x}" default formatcore::fmt::Display2.10
debug_traitf"{x:?}" debug formatcore::fmt::Debug2.10
future_traitStepping in await exprcore::future::Future2.20
axis_indexed_traitindex parts as axis argumentscore::index::AxisIndexed2.3
broadcastable_traitAn operand of a fused dot expressioncore::ops::Broadcastable2.6.6
broadcast_scalar_traitA scalar wrapper in a fused dot expressioncore::ops::BroadcastScalar2.6.6
materialize_traitThe result of a fused dot expressioncore::ops::Materialize2.6.6
close_traitA close that can fail: the owner closes itcore::io::Close2.23

Next come the operator trait slots. The dispatch target of an operator token is determined by the #[infix] / #[prefix] (refs-lang 6.7) attached to each trait method, and precedence is fixed by the table in refs-lang 3.2; the slots below are fixed locations that let the compiler find "the addition trait", "the comparison trait", etc. by name during primitive lowering and diagnostics. Compound assignment (AddAssign, etc., 2.4), broadcast (DotAdd, etc., 2.6), power (Pow, **) and floored modulo (Modulo, %%) traits need only #[infix] registration and have no slots: lowering and diagnostics never look them up by name. On a primitive, ** calls an ordinary method (pow, powi) and %% is an #[intrinsic] method (0.3), so their lowering needs no slot either.

Slot nameMeaningStandard library traitRef
add_traita + bcore::ops::Add2.3
sub_traita - bcore::ops::Sub2.3
mul_traita * bcore::ops::Mul2.3
div_traita / bcore::ops::Div2.3
rem_traita % bcore::ops::Rem2.3
neg_trait-a (prefix)core::ops::Neg2.3
not_trait!acore::ops::Not2.3
bitnot_trait~acore::ops::BitNot2.3
bitand_traita & bcore::ops::BitAnd2.3
bitor_traita | bcore::ops::BitOr2.3
bitxor_traita ^ bcore::ops::BitXor2.3
shl_traita << bcore::ops::Shl2.3
shr_traita >> bcore::ops::Shr2.3
logical_and_traita && bcore::ops::LogicalAnd2.3
logical_or_traita || bcore::ops::LogicalOr2.3
call_traitv(a) on a value that is not a functioncore::ops::Call2.3
eq_trait== / !=, literal patternscore::ops::PartialEq2.5
cmp_trait< / > / <= / >=, range patternscore::ops::PartialOrd2.5
ord_traitTotal order (#[derive(Ord)])core::cmp::Ord2.5
hash_traitHash (#[derive(Hash)])core::cmp::Hash2.5
clone_traitClone (#[derive(Clone)])core::marker::Clone2.13
send_traitAuto marker: safe to move across threadscore::marker::Send2.13
sync_traitAuto marker: safe to share across threadscore::marker::Sync2.13

Note

Comparison slot names and trait names do not correspond one-to-one. eq_trait is attached to PartialEq, which defines the equality operators, and cmp_trait to PartialOrd, which defines the ordering operators. The marker traits Eq, Copy and Default have no slots: sum types get them structurally (T | none is Eq when T is; its Default is none), so the compiler finds them by their fixed paths in core.

#0.4.4. Function slots (42)

Function slots are for standard library functions that the compiler calls directly, like intrinsics. They mainly cover abnormal termination paths (throw, OOM, unreachable) and are used where a uniform entry point is needed outside normal flow.

Slot nameMeaningStandard library functionRef
panic_fnAbort function called on paniccore::panic::panic2.14
oom_fnOOM abort (runtime allocation failure calls nabi_oom directly)core::panic::oom2.14
unreachable_fnCalled by the compiler at unreachable pointscore::panic::unreachable2.14

The other thirty-nine are hooks: functions that code the compiler writes calls, for a negative index, a slice bound, a writable view, a spread, an f-string hole, a cancellation point, a broadcast over collections, a nested array literal and a fused dot expression. Lowering finds each through its slot, not by its path, so a hook need not be visible to the code it is lowered into. A hook is not API: each is pub(pkg) in core, and a call written by hand in another package is an error.

Slot nameCalled forStandard library functionRef
spread_len_fnA List / Slice spread f(..xs) checks its lengthcore::index::spread_len2.3
spread_names_fnA Dict spread f(..d) checks its keyscore::index::spread_names2.3
spread_misfit_fnA Dict spread's key for a parameter it cannot fillcore::index::spread_misfit2.3
index_from_end_fnA signed index xs[i], negative from the endcore::index::index_from_end2.3
slice_bound_fnA signed slice bound xs[i:]core::index::slice_bound2.3
slice_range_fnA stepped slice xs[a:b:k]core::index::slice_range2.3
slice_mut_fnxs or xs[a:b] of a list where a SliceMut is expectedcore::index::slice_mut (pub(pkg))2.9
view_live_fneach step of a for ref loop over a list or a view: panics when the view is stalecore::index::view_live (pub(pkg))2.9
fstr_display_fnAn f-string hole {v}core::fmt::fstr_display2.10
fstr_debug_fnAn f-string hole {v:?}core::fmt::fstr_debug2.10
fstr_num_fnAn int or float hole with a speccore::fmt::fstr_num2.10
fstr_pack_fnA hole whose spec is computed, {v:{spec}}core::fmt::fstr_pack2.10
fstr_text_any_fnA computed spec on a value that is not a numbercore::fmt::fstr_text_any2.10
fstr_args_fnAn Arguments f-string: the closure over its piecescore::fmt::fstr_args2.10
fstr_put_str_fnAn Arguments f-string: a literal piece, or a hole made into textcore::fmt::fstr_put_str2.10
fstr_put_display_fnAn Arguments f-string: a hole {v}core::fmt::fstr_put_display2.10
fstr_put_debug_fnAn Arguments f-string: a hole {v:?}core::fmt::fstr_put_debug2.10
cancel_point_fnAn await that polls Pending (cancellation point)core::task::cancel_point2.18
cancel_left_fnAn await whose poll was Readycore::task::cancel_left2.18
cleanup_running_fnA frame left by a cancel enters its cleanupscore::task::cleanup_running2.18
cleanup_done_fnThat frame finished its cleanupscore::task::cleanup_done2.18
broadcast_len_fnA broadcast xs .+ ys checks the lengths agreecore::collections::broadcast::check_len2.6
axis_from_u64_fnAn unsigned position in an axis indexcore::index::axis_from_u642.3
axis_from_i64_fnA wide signed position in an axis indexcore::index::axis_from_i642.3
array_literal_fnA nested list literal in an Array slotcore::array::array_literal2.9.14
fused_shape_fnA fused dot expression: the shape operands stretch tocore::array::fused_shape2.6.6
fused_view_fnA fused dot expression: an operand viewed at that shapecore::array::fused_view2.6.6
fused_alloc_fnA fused dot expression: the fresh result arraycore::array::fused_alloc2.6.6
fused_flat_fnA fused dot expression: a view is contiguouscore::array::fused_flat2.6.6
fused_inner_fnA fused dot expression: the length of a row (the last axis)core::array::fused_inner2.6.6
fused_rows_fnA fused dot expression: the number of rowscore::array::fused_rows2.6.6
fused_row_fnA fused dot expression: the buffer position of a rowcore::array::fused_row2.6.6
fused_step_fnA fused dot expression: the step along the last axiscore::array::fused_step2.6.6
fused_at_fnA fused dot expression: an element of a contiguous runcore::array::fused_at2.6.6
fused_put_fnA fused dot expression: a store into a contiguous runcore::array::fused_put2.6.6
fused_get_fnA fused dot expression: an element of a strided rowcore::array::fused_get2.6.6
fused_set_fnA fused dot expression: a store into a strided rowcore::array::fused_set2.6.6
fused_dest_fnA fused dot expression: an in-place result fits its targetcore::array::fused_dest2.6.6
fused_source_fnA fused dot expression: an in-place source that overlaps the target is copiedcore::array::fused_source2.6.6
fused_list_alloc_fnA fused dot expression over lists: the result list, filled by indexcore::collections::broadcast::fused_list_alloc2.6.6

#Items the tiers share: #[internal]

A few pub items are called by another tier of the toolchain, not by the compiler: std uses them from core, core from bare. They are marked #[internal] (refs-lang 6.2.16): bare, core and std may use them, any other package gets the error "internal to the Nabi toolchain", and the docs and the language server leave them out.

ItemUsed byRef
core::marker::hand_overstd::thread (a thread's result is handed over)2.13
core::marker::Handoff::newstd::thread (a thread's result crosses back to the joiner)2.13
core::marker::viewstd::net (a listener's incoming view)2.13
core::task::wake_iostd::net (waking waiters after a close or shutdown)2.18
core::task::host_enterstd::wit (a component export enters the host loop)2.18
core::task::host_runstd::wit (one turn of the host loop)2.18
core::task::host_leavestd::wit (ends host_enter)2.18
core::task::readable / writablestd::net (waiting until a socket is ready)2.18
core::io::IoError::retoldstd::fs (an error told again for a path)2.23
core::io::IoError::resolverstd::net (a failed name lookup)2.23
core::io::Owned::ofstd::net (TcpListener::into_incoming)2.23
core::io::Read::copy_handle / Write::copy_handlestd fs, net, process and os::unix::net (the OS handle io::copy gives the kernel)2.23
core::num::bigint::Int::from_literal / bigfloat::Float::from_literalstd::nabion (a number literal's digits)2.1
bare::gc::Pinnable::gc_objectcore::marker (a hand-off copying a GcPtr)1.6

#0.4.5. Method slots (1)

Method slots are for methods the compiler calls automatically without the user writing the call. There is only one: disposal when a using binding is released. The ? operator is expanded directly by the compiler for T | none (refs-lang 3.14.10), so it has no method slot. Cloning a value (Clone::clone) is never called automatically (2.13.2), so it is registered as the trait slot clone_trait, not a method slot.

Slot nameMeaningStandard library methodRef
drop_methodCalled where a value is released (using, or its owner leaving scope)core::marker::Drop::drop2.13

#0.4.6. Slot consumers: where the compiler looks up slots

Where the previous sections listed "which slots exist", this section summarizes the reverse: "when the compiler looks up which slot". When tracing which standard library item a line of user syntax resolves to, the following table is the starting point.

Compiler actionSlot looked up
Lowering the none literalnone_type
Literal type of 42 (no expected type)i64_type
Literal type of 3.14 (no expected type)f64_type
A number literal whose expected type is int, float, f16 or bf16, and the f16 / bf16 literal suffixesint_type, float_type, f16_type, bf16_type
Literal type of "hello"str_type
Desugaring for x in xsinto_iterator_trait, iterator_trait, try_iterator_trait
Desugaring arr[i]index_trait
Desugaring arr[i] = vindex_set_trait
Desugaring s[1:3]slice_trait
Desugaring a default f"{x}" holedisplay_trait
Desugaring f"{x:?}"debug_trait
Desugaring await exprfuture_trait
Primitive lowering of arithmetic / bitwise / logical operatorsadd_trait ... logical_or_trait
== / !=, literal pattern matchingeq_trait
< / > / <= / >=, range pattern matchingcmp_trait
Expanding #[derive(Clone / Ord / Hash)]clone_trait, ord_trait, hash_trait
Lowering panic (including try! failure)panic_fn
On OOMoom_fn
Unreachable after match exhaustiveness check of all armsunreachable_fn
A negative index or slice bound, a stepped sliceindex_from_end_fn, slice_bound_fn, slice_range_fn
A list or its range where a SliceMut is expectedslice_mut_fn
Each step of a for ref loop over a list or a viewview_live_fn
A spread f(..xs) / f(..d)spread_len_fn, spread_names_fn, spread_misfit_fn
An f-string holefstr_display_fn ... fstr_text_any_fn
An await, and the cleanups a cancel runscancel_point_fn, cancel_left_fn, cleanup_running_fn, cleanup_done_fn
A broadcast over two or more collectionsbroadcast_len_fn
Releasing a value (a using block ends, or its last owner leaves scope)drop_method
Automatic Send / Sync implementation, + Send checkssend_trait, sync_trait

#0.4.7. Duplicate / missing detection

If two standard library items are attached to the same slot, the compiler rejects it (the duplicate detection rule of refs-lang 6.4.6). Conversely, if a required slot such as iterator_trait is missing, compilation of the features that depend on it (here, for loops) is rejected. Both are devices that force the slot contract to have a single source of truth.

The actual attached items are stated in each chapter of 200-core/. Every trait, method, type and abort-function slot that is attached has its #[lang(...)] attachment site in the chapter indicated by the "Ref" column. The hook _fn slots (spread_len_fn ... fused_list_alloc_fn) are compiler-facing and named only in this table, and the built-in type slots that 0.4.2 leaves unattached have no attachment site. A slot name not in this table is a compile error per refs-lang 6.4.8. For example, Stream has no slot (2.8.10).

#0.4.8. Slot naming policy

Finally, the naming rules to follow when adding a new slot or renaming an existing one. Consistent names let the kind of a slot be guessed just by scanning the table, so the policy is not taken lightly.

Names are written in snake_case: type slots take the _type suffix, trait slots the _trait suffix, function slots the _fn suffix, and method slots the _method suffix (drop_method). A slot designating a whole trait is unified under a single _trait even if the compiler handles several methods or derives of that trait; method slots are limited to cases where the compiler automatically calls one specific method. By this criterion, Clone is registered as clone_trait, not clone_method. The suffix also determines the attachment site: a _trait slot is attached to the trait declaration itself, a _method slot to the corresponding method inside the trait, a _type slot to a type declaration, and a _fn slot to a function declaration; attaching it elsewhere is rejected by the signature check of refs-lang 6.4.7.

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