核心库 scoop.core

核心库 scoop:scoop.core:0.1.0 包含语言运行所必需的类型与函数。每个 Cone 都自动依赖它,其公开声明位于根 package 并默认导入(包括 Option 的变体 Some/None),无需任何 import。本页按主题列出核心库的内容,完整签名见 API 文档。

编译期输入函数位于同一 Cone 的 scoop.compiler package,需要显式导入,见编译期输入。

基本类型

声明说明
Any、Nothing顶类型与底类型,没有成员,见类型系统
Boolean、Char、Unit见基本类型
Int8 Int16 Int Long UInt8 UInt16 UInt ULong定宽整数及别名 Byte、Short、Int32、Int64、UByte、UShort、UInt32、UInt64
Float、DoubleIEEE 754 浮点及别名 Float32、Float64;IeeeComparison
Option<T>Some(T) / None,见 Option
IntRange LongRange UIntRange ULongRange整数区间,见区间
CharRange按 Unicode 标量顺序的字符区间,见字符区间

String

String 是不可变的 UTF-8 文本,实现 Equals<String>、Compare<String>、Add<String, String>、Hash、ToString 与 Iterable<Char>。下标与计数都使用 Long。

成员说明
byteLength: LongUTF-8 字节数,O(1)
charLength: LongUnicode 标量的个数,需要扫描
getCharAt(idx: Long): Char第 idx 个标量;越界抛出 IndexOutOfBoundsException
slice(start: Long, endExclusive: Long): String按标量下标取半开区间
iterator(): Iterator<Char>按标量顺序迭代
toCharArray() / toMutableCharArray()独立的字符数组副本
toByteArray() / toMutableByteArray()独立的 UTF-8 字节副本
String.fromChars(chars: List<Char>)由字符序列构造
String.fromUtf8(bytes)严格解码;非法 UTF-8 抛出 CharacterCodingException
String.fromUtf8OrNone(bytes)严格解码;非法时返回 None
String.fromUtf8Lossy(bytes)把每个非法子序列替换为 U+FFFD
String.fromUtf8Unchecked(bytes)@Unsafe:调用方保证字节是合法 UTF-8
withCString、withUtf8Bytes、String.fromCString、String.fromUtf8(pointer, length)@Unsafe 的原生互操作,见借用托管数据的指针

字符串没有 s[i] 下标和 length 属性。查找、分割、修剪、替换、大小写转换、数值解析与格式化等文本操作由 scoop.std 的 scoop.text package 以扩展函数提供。

fun main() {
    val bytes: Array<Byte> = [0x41.toByte(), 0xFF.toByte()]
    println(String.fromUtf8OrNone(bytes) == None)   // true
    println(String.fromUtf8Lossy(bytes))            // A�
    println(String.fromChars(['h', 'i']))           // hi
    println("é".toByteArray().size)                 // 2
}

StringBuilder 与 TextWriter

  • StringBuilder(initialCapacity: Long = 0L):可变的字符串累积器。append 对 String、各整数类型、Char、Boolean 有专门的重载,另有接受任意 T : ToString 的泛型重载;都返回同一个 builder 以便链式调用。toString() 返回当前内容的独立快照,clear() 清空内容并保留容量。f-string 插值的语义与依次 append 相同。
  • TextWriter 是只有 write(text: String) 的文本输出接口;StringWriter 把写入的文本累积为字符串。文件、终端与日志 writer 由相应的库提供。
fun main() {
    val sb = StringBuilder()
    sb.append("x=").append(42).append(' ').append(true)
    println(sb.toString())          // x=42 true
    val w = StringWriter()
    w.write("a")
    w.write("b")
    println(w.toString())           // ab
}

输出与进程

函数说明
print(value) / println(value)写到 stdout;println 追加换行。要求 T : ToString
eprint(value) / eprintln(value)写到 stderr
write(message: String) / writeError(message: String)原样写出字符串的 UTF-8 字节,不追加换行
flushOutput()刷新 stdout 的缓冲
exit(code: Int): Nothing刷新输出后立即结束进程,见退出

输出经过 stdio 缓冲,不保证并发的 println 按行原子输出,也不暴露 I/O 错误。写出的是原始字节:Windows 上标准流以二进制模式打开,不做换行转换,也不改变控制台代码页。文件、进程、环境变量与命令行原始参数等平台功能位于 scoop.platform。

数组与列表

public interface Iterable<T> { public operator fun iterator(): Iterator<T> }
public interface Iterator<T> { public fun next(): Option<T> }
public interface Collection<T> : Iterable<T> { public val size: Long }
public interface List<T> : Collection<T> { public operator fun get(index: Long): T }
public interface MutableList<T> : List<T> {
    public operator fun set(index: Long, value: T): Unit
    public fun add(value: T): Unit
    public fun add(index: Long, value: T): Unit
    public fun removeAt(index: Long): T
    public fun clear(): Unit
}
类型说明
Array<T>定长、只读元素,实现 List<T>,见数组
MutableArray<T>定长、可写元素,实现 List<T> 与 IndexSet<Long, T>(不实现 MutableList)
ArrayList<T>(initialCapacity: Long = 0L)可增长的列表,实现 MutableList<T>;下标读写 O(1),追加摊还 O(1),插入与删除 O(n)
  • List 只是只读访问接口,不保证内容不变:多个引用指向同一个 ArrayList 时,彼此能观察到修改。
  • 下标越界抛出 IndexOutOfBoundsException;按下标插入时允许 index == size。
  • 值类型元素内联存储,不装箱。列表不依赖元素的相等或哈希,因此没有 contains、按值 remove 或列表相等;这些操作由 scoop.collections 在合适的约束下提供。
  • toArray() / toMutableArray() 取得独立的数组快照,对任何 List<T> 都可用。
  • 迭代器在每次 next() 时读取当前大小,不做 fail-fast 检查:遍历期间修改列表可能导致元素被跳过或重复。
fun sum(values: List<Int>): Int {
    var total = 0
    for (v in values) total += v
    return total
}

fun main() {
    val list = ArrayList<Int>()
    list.add(1)
    list.add(3)
    list.add(1L, 2)                 // 插入到下标 1
    println(list.removeAt(0L))      // 1
    list[0] = 10
    println(sum(list))              // 13
    val snapshot = list.toArray()
    list.clear()
    println(snapshot.size)          // 2
}

HashMap、TreeMap、HashSet、ArrayDeque、PriorityQueue、排序与集合变换在 scoop.std 的 scoop.collections 中。

相等、字符串化与运算符接口

异常

Throwable、Exception 以及 UnwrapException、ClassCastException、ArithmeticException、IndexOutOfBoundsException、IllegalArgumentException、IllegalStateException、CharacterCodingException、ResourceUseException、MissingContextException、CancellationException、EncodingException、DecodingException。见异常类型。

资源

Disposable、Closeable 与扩展函数 use(普通与挂起两个版本),见确定性资源释放。

协程

声明说明
Continuation、SuspendTask、SuspendRegistration、startCoroutine、suspendCoroutine协程原语
Job、Deferred、CoroutineScope、coroutineScope、nonCancellableScope、currentJobOrNone、ensureActive结构化并发
CancellableContinuation、suspendCancellableCoroutine可取消的挂起

见协程与并发。事件循环与异步 I/O 在 scoop.asyncio 中。

原子类型

AtomicInt、AtomicLong、AtomicBoolean、AtomicRef<T : ref>、基于锁的 Atomic<T : value> 与 MemoryOrder,见原子类型。线程、互斥锁与条件变量在 scoop.platform.concurrent 中。

编解码、类型描述与调试

声明说明
ValueEncoder<T>、ValueDecoder<T>、Encoder、Decoder 及各种容器接口、Serialize、ValueEncoderFunction、ValueDecoderFunction、encodeList与格式无关的编解码协议,见编解码
typeInfo<T>()、TypeInfo、TypeRef、TypeShape 及各种 …Info/…Ref、annotationKey、findAnnotations静态类型描述,见类型描述
ValueInspector<T>、ValueView、DebugPrinter、DebugOptions、DebugIgnore、DebugRedact值观察与调试输出,见值观察
SourceLocation、currentSourceLocation()源码位置,见源码位置
Target、Repeatable、AnnotationTarget、DocHidden、DocAlias元注解与文档注解,见注解
GenerateWith指定由哪个生成器为所选接口补齐方法,例如为编解码选择 scoop.codec。见代码生成器。

原生互操作与运行时

声明说明
Extern、CallingConvention、NoGC、GCLeaf、Unsafe、Safe、CLayout、Global、ThreadLocal、InteriorMutable核心注解,见原生互操作
Ptr<T>、FunPtr<F>、addressOf、sizeOf、alignOf、withDataPointer原生指针与布局
MaybeUninit<T>可能未初始化的值:uninit() 与 initialized(v) 是安全的,assumeInit() 是 @Unsafe
PinnedPtr、GcHandle、pin/unpin、getGcHandle/releaseGcHandle、ForeignCallback、foreignCallbackScoop ABI 与回调注册,供底层库使用
gcCollect()、gcStats()、gcAdjustPressure(delta)请求完整回收、读取统计、向 GC 提示原生内存压力