docs

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

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

#0.2. Import policy - the prelude core::prelude

本页内容

This document defines the implicit import policy of the standard libraries. Every user file sees the names of one module, core::prelude, without a use; everything else in core, and all of bare and std, is named by path or imported explicitly.

Nabi implicitly prepends the following single line to every user source file.

nabi
use core::prelude::*;

core::prelude is an ordinary module of pub use re-exports (refs-lang 5.8). Its list is fixed below (0.2.3) and is normative: a name is in the prelude only if this document lists it.

The prelude holds no enum variants. A bare variant name resolves from the type the position expects (refs-lang 2.4.8): let o: Ordering = Less;, x.load(SeqCst), return Ok(v);.

#0.2.1. Core design decision

ModelLanguagesAdopted by Nabi
Explicit use onlyC / C++(verbose)
Every public name of the core librarySwift, Python builtinsRejected
A short, curated prelude moduleRust, Gleam, ElmAdopted

#Why a curated list

An implicit glob over all of core would make every public core item a bare name in every file: about 160 types, 100 traits, 90 functions and every enum variant. Several of them would collide (Map, Filter, Zip in iter and stream; join in task and par; the variant Equal in Ordering and fmt::Alignment), and each new core item would change name resolution in user code.

The prelude keeps what code writes in nearly every file: the collection and core types, the traits written in impl headers and bounds, the printing and panic functions, and the top-level core modules, so task::sleep and par::map stay short. Every name in it is unique in its namespace (a library test checks this on every target), so a bare prelude name is never ambiguous. Because the implicit import has the lowest priority (0.2.4), adding a name to the prelude never breaks a program that defines or imports the same name.

#0.2.2. ** recursive glob

nabi
use foo::bar;            // single item
use foo::{a, b};         // multiple
use foo::*;              // single-level glob (only foo's direct children)
use foo::**;             // recursive glob (foo + all submodules)

The normative definition of the ** syntax is given in refs-lang 5.5 use.

#0.2.3. The prelude list

The names below are exactly the names of core::prelude. Modules, types and traits share one namespace and functions another, as everywhere in Nabi, so channel, panic and print are each a module and a function.

Modules (29). The top-level modules of core, except prelude itself and hash (imported with a use, 2.5.11):

array bench channel cmp collections convert crypto encoding error fmt future hint index io iter marker num ops panic par print range reflect str stream sync task time tuple

Types (36).

GroupNames
CollectionsList Dict Set Deque BinaryHeap Slice SliceMut StrBuf FrozenList FrozenDict FrozenSet
Numbers and rangesRange RangeInclusive Int Float
GeneralResult Ordering Duration Instant
Synchronization and channelsMutex RwLock Atomic Cell Sender Receiver Task
FormattingFormatter FmtError
Core errorsParseError ValueError OverflowError ConversionError TypeError StackOverflowError OutOfMemoryError InternalError

Traits (31).

GroupNames
MarkersClone Copy Drop Default Send Sync
ComparisonPartialEq Eq PartialOrd Ord Hash
Formatting and errorsDebug Display RichDisplay Error
Iteration and asyncIterator IntoIterator FromIterator TryIterator Future IntoFuture
I/ORead Write AsyncRead AsyncWrite
ConversionFrom Into TryFrom TryInto FromStr
ReflectionInspect (also its derive, refs-lang 6.8.11)

The operator traits are not in the prelude: write ops::Add, or use core::ops::Add;. Operators themselves need no name and work everywhere (refs-lang 6.7.8), and so do the methods of every core trait (refs-lang 3.5).

OS extension traits. On the targets that have them, the prelude also names PermissionsExt, CommandExt and ExitStatusExt (unix) and ChildExt and TcpStreamExt (linux), so their methods need no use there (3.10.1). They are not counted above.

Functions (13).

print println eprint eprintln dbg display panic assert assert_eq assert_ne unreachable channel channel_bounded

Variants. None. See refs-lang 2.4.8.

nabi
// user code
fn main() {
    let xs: List<i32> = [1, 2, 3];        // prelude: List
    let total: i32 = xs.iter().sum();      // methods of core traits: no import
    println(f"{total}");                   // prelude: println

    let m = Mutex::new(0);                 // prelude: Mutex
    task::spawn(async { /* ... */ });      // prelude module task
    task::sleep(Duration::ms(10));         // prelude: Duration

    let n = Atomic::new(0);
    n.store(1, SeqCst);                    // variant from the parameter type
}

Everything else in core is named through a prelude module or imported:

nabi
let p: future::Poll<i32> = future::Poll::Pending;
impl ops::Add for V { ... }
use core::sync::LoadOrdering;
let h = encoding::hex::encode("nabi");

A name that is not in scope gets an error that says what to write: the shortest path that works (task::sleep, ops::Add, Ordering::Less), and the use that imports it.

#0.2.4. Name collision policy

The implicit import has the lowest priority: lookup takes the module's own items and its uses first (refs-lang 5.7.1). A user item named like a prelude name shadows it in that module, and the core item stays reachable by path.

nabi
struct List<T> { ... }                  // OK: shadows the prelude's List here
let xs: core::collections::List<i32> = [1, 2];   // the core List, by path

A use path may start with a prelude name: use task::sleep; imports core::task::sleep.

#0.2.5. Tiers not applied implicitly

Only the prelude is implicit. unsafe and std are explicit only.

nabi
use bare::ffi::{CStr, CString};      // unsafe: danger signal
use bare::ptr::{Ptr, ConstPtr};
use std::fs;                         // std: target-dependency signal
use std::time::SystemTime;

This policy matches the following table of the 0.1 Tier model.

TierImplicit importReason
core✓ the prelude (0.2.3)All targets / safe
bare✗Danger signal, explicit only
std✗Target-dep, explicit only

This way, which areas a user is entering is immediately visible from the top of the file.

#0.2.6. Opting out - #![no_implicit_nabi]

In special situations the implicit import itself can be turned off.

nabi
#![no_implicit_nabi]   // top of the file

// no implicit import in this file
use core::prelude::*;   // the same import, written out

Literals are compiler-defined and stay available, and so do operators and the methods of core traits (refs-lang 6.7.8); only bare names are lost.

It is useful in teaching or demo code to show at a glance where each item comes from.

The standard library's own modules do not import the prelude: each tier sees every public item of core by its leaf name (an internal use core::**;), which user code does not get.

#0.2.7. Visibility

The prelude re-exports pub items only. Internal implementation (pub(pkg) / private) never leaks to users: core::collections::raw is pub(pkg), so GcBuf and the buf_* functions are reached only as bare::mem::.. with an explicit use.

Names are not flattened beyond the list; module paths are preserved as they are.

nabi
let m = Mutex::new(0);              // prelude: Mutex
let s = task::spawn(async { /* */ });      // prelude module task; spawn is task::spawn

// both mean the same thing.
core::sync::Mutex::new(0);
Mutex::new(0);

#0.2.8. Comparison with other languages

LanguageImplicit scopeVariants
Ruststd::prelude::rust_20xx, an explicit listSome None Ok Err only
Gothe universe block: about 20 builtins and typesqualified (time.Second)
Swiftevery public declaration of Swift.less from the contextual type
Kotlindefault package importscontext-sensitive resolution (2.2)
Nabicore::prelude, an explicit list (0.2.3)bare, from the expected type (any enum)

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