注解与编译期能力

Scoop 的注解只在编译期可用。用 @GenerateWith 可以选择生成器为类型实现接口方法,例如用 scoop.codec 生成编解码方法。编译器还提供静态类型描述、调试视图,以及读取源码位置、嵌入文件和读取构建环境的函数。核心注解(@Extern、@NoGC、@Unsafe 等)见原生互操作。

自定义注解

public annotation class Description(val text: String)

@Target([AnnotationTarget.Function])
annotation class Experimental

@Repeatable
annotation class Tag(val name: String)

@Description("Account data")
public struct Account(@Description("Stable identifier") val id: Long, val owner: String)

@Experimental
@Tag("io") @Tag("beta")
fun download() {}

fun main() {
    download()
}
  • annotation class 不能实例化,没有继承、泛型参数、body 或成员函数;参数都是 val,可以有默认值。无参数的注解使用时可以省略括号。
  • 参数类型限于 Boolean、String、Char、整数、浮点、整型枚举、另一个注解类,以及这些类型的一维 Array。
  • 参数值必须是字面量(可带符号)、同类型的 const val、数组字面量 […] 或嵌套注解 Message("text");不能调用函数或构造普通对象。
  • 注解可以标在类型、注解类、enum 变体、字段、属性、函数、构造函数、参数、访问器、接收者和类型别名上。
  • @Target([AnnotationTarget.…]) 限定注解可用的位置,未标注时允许全部位置。AnnotationTarget 的取值有 Class、AnnotationClass、EnumVariant、Field、Property、Function、Constructor、ValueParameter、PropertyGetter、PropertySetter、TypeAlias、Type。
  • 同一目标重复使用同一注解需要该注解标注 @Repeatable,否则是编译错误;重复的应用保留源码顺序。
  • 注解不会从宿主复制到字段、派生类或访问器,也不会被继承。

use-site 目标

一个声明对应多个实体时,用 @target:Name(…) 指定注解属于哪一个:property(逻辑属性)、field(backing field 或值类型字段)、get/set(访问器)、param(构造参数)、setparam(setter 的参数)、receiver(扩展接收者)、delegate(委托存储)。主构造函数中带 val/var 的参数上,未指定目标的注解属于字段/属性;只允许参数目标的注解需要显式写 @param:。

类型使用注解

目标为 AnnotationTarget.Type 的注解可以写在类型的使用位置,包括字段、参数、结果、局部变量的显式类型、类型实参与函数类型的各部分。前缀作用于紧随其后的完整类型:@A T? 标注 Option 本身,(@A T)? 标注元素 T。类型注解不影响类型身份、子类型、重载或布局,只进入静态类型描述。

文档注释

/** … */ 与 /// … 附着于紧随其后的声明,正文使用 Markdown,第一段是摘要。scoop doc 据此生成离线 API 文档站点。

/**
 * Parses a port number from [text].
 *
 * @param text decimal digits without sign
 * @return the port, or `None` when [text] is not a valid port
 * @see Address
 */
public fun parsePort(text: String): Int? = None

/// A network address.
public struct Address(
    /// Host name or literal IP address.
    val host: String,
    val port: Int
)

fun main() {}
标签含义
@param name值参数或类型参数
@property name当前类型的字段或属性
@constructor主构造函数
@receiver扩展的接收者
@return结果
@throws Type可能抛出的异常(只是说明,不是受检异常)
@see target符号或 URL
@since text版本说明

正文中的 [Type]、[Type.member] 与 [label][Type] 链接到符号,在声明处的作用域中解析。核心库注解 @DocHidden 从生成的文档中隐藏声明,@DocAlias("name") 为声明增加搜索关键词;它们不改变可见性或语义。普通编译不检查文档内容。

静态类型描述

typeInfo<T>() 返回编译器为类型 T 生成的描述:字段、变体、属性、构造参数、可见性与注解。描述是普通的不可变值,按需惰性展开;泛型函数中的 T 在单态化时替换为具体类型,不需要 reified。

struct Point(val x: Int, val y: Int)

fun main() {
    val info = typeInfo<Point>()
    println(info.type.displayName)                     // Point
    when (val shape = info.describe().shape) {
        case TypeShape.Struct(val details) -> {
            for (field in details.fields) {
                when (field.name) {
                    case MemberName.Named(val name) -> println(name)
                    case MemberName.Positional(val index) -> println(index)
                }
            }
        }
        case _ -> println("not a struct")
    }
}
  • TypeShape 区分 Struct、Enum、IntegerEnum、Class、Object、Interface、Tuple、Unit、Intrinsic、Function、Pointer。
  • TypeRef 按完整类型身份比较;透明别名与展开后的类型相同。
  • annotationKey<A>() 取得注解声明的键,配合 findAnnotations 在描述中筛选注解。
  • 描述不提供按名称取类型、反射构造或调用,取得私有成员的描述也不会使其值可以访问。

编解码

核心库定义了与数据格式无关的编解码协议:

public interface ValueEncoder<T> {
    public fun encode(value: T, encoder: Encoder): Unit
}

public interface ValueDecoder<T> {
    public fun decode(decoder: Decoder): T
}

要为 User 生成编解码方法,在实际实现接口的 companion 或独立 codec 类型上标注 @GenerateWith。下面的 User.Companion 声明了两个接口,并用 "scoop.codec" 为它们生成 encode 和 decode。只需要一个方向时,只声明并选择对应的接口。

//! dep: scoop:scoop.json:0.1.0

import scoop.json.*

public struct User(
    val name: String,
    @Serialize(rename = "e-mail") val email: String?,
    @Serialize(ignore = true) val cache: Int = 0,
    val tags: Array<String> = []
) {
    @GenerateWith("scoop.codec", ["ValueEncoder<User>", "ValueDecoder<User>"])
    public companion object : ValueEncoder<User>, ValueDecoder<User>
}

fun main() {
    val text = Json.encodeToString(User("Ada", Some("[email protected]"), 5, ["admin"]))
    println(text)       // {"name":"Ada","e-mail":"[email protected]","tags":["admin"]}
    val user = Json.decodeFromString<User>("{\"name\":\"Lin\",\"e-mail\":null}")
    println(f"${user.name} ${user.cache} ${user.tags.size}")      // Lin 0 0
}
  • Json.encodeToString(value) 和 Json.decodeFromString<User>(text) 通过 User 的公开 companion 取得 codec。也可以显式传入一个 codec,例如 Json.encodeToString(value, User.Companion)。见伴生对象约束。
  • 已有的手写、继承或接口默认实现优先,生成器只补齐所选接口缺少的方法。本例若省略 @GenerateWith,编译器会报 E1008,指出 User.Companion 缺少 encode 和 decode 的实现。
  • 默认数据模型:struct 与合格的 class 编码为按声明顺序的键值记录,tuple、数组与 ArrayList 编码为序列,enum 编码为只有一个键(变体名)的记录,Option 的 None 编码为 null,Unit 编码为 null,Char 编码为单字符字符串。
  • 每个字段的 codec 按方向在定义处确定。生成器优先使用 codec 主构造函数中唯一匹配的 val,再依次考虑递归时的自身、核心容器或 tuple 的元素组合,以及字段类型可见且满足接口的 companion。缺少所需能力会在编译时报错。
  • 生成器支持 struct、enum、tuple,以及没有显式 class 基类的普通 final class。为 struct 或 class 生成解码方法时,从 codec 的作用域看,唯一可见的构造函数须是主构造函数。开放的类层级、循环图和多态需要手写 codec。
  • 解码先读取输入并完成容器检查,再调用构造函数。缺少未标记 required 的字段时,优先使用声明的默认值,其次为声明处的 Option 补 None,其余情况报解码错误。显式传入的 JSON null 交给字段的 codec 处理。
  • 编码时,声明为 Option 的字段若没有默认值或默认值直接写作 None,其值为 None 时默认省略。设置 required 或 emitNull 会保留这个键。

实现者上的 @GenerateWith 选择生成器和接口,字段或 enum 变体上的 @Serialize 指定数据映射。scoop.codec 生成方法时读取下列设置。手写方法自行决定如何读写字段。

参数作用
rename = "…"字段或 enum 变体在数据中的名称
required = true解码时要求键存在,编码时总是写出
emitNull = trueNone 也写出(交给字段 codec),只用于声明处为 Option 的字段
ignore = true两个方向都排除该字段,解码时它必须有默认值或是 Option

编码格式由普通库实现 Encoder/Decoder 接口提供。JSON 的具体规则见 scoop.json。

源码位置

currentSourceLocation() 返回所在位置的 SourceLocation(file, line, column, functionName, typeName),在编译期确定,不依赖调试信息。把它用作默认参数时,得到的是调用方的位置:

fun trace(message: String, location: SourceLocation = currentSourceLocation()) {
    println(f"${message} (${location.functionName}:${location.line})")
}

fun warn(message: String, location: SourceLocation = currentSourceLocation()) =
    trace("warning: " + message, location)      // 多层转发需要继续传递 location

fun main() {
    trace("starting")
    warn("low disk")
}

file 是与主机路径无关的逻辑路径,例如 dev.example:app:0.1.0/src/main.scoop。currentSourceLocation 只能直接调用,不能取函数引用。测试库的断言就是这样记录失败位置的。

编译期输入

scoop.compiler package 提供在编译期读取文件与环境的函数。它们不在默认 prelude 中,需要显式导入;实参必须是常量,结果在编译期嵌入程序,没有运行期入口,也不能取函数引用。

函数结果
includeStr(path: String): String文件内容,必须是合法 UTF-8,原样保留
includeBytes(path: String): Array<Byte>文件的原始字节
includeDir(path, include = ["**"], exclude = []): EmbeddedDir目录中按 glob 选中的普通文件,按相对路径排序;dir[path] 查找文件内容
env(name: String): String?编译时宿主环境变量的值;名称必须以 SCOOP_ 开头
import scoop.compiler.*

const val HELP: String = includeStr("assets/help.txt")
val icons = includeDir("assets", include = ["**/*.png"])
val buildTag = env("SCOOP_BUILD_TAG") ?: "dev"

fun main() {
    println(HELP)
    println(f"${icons.files.size} icons, build ${buildTag}")
}
  • 相对路径以所在源文件的目录为基准,而不是当前工作目录。所有路径(包括 symlink 的目标)都必须位于定义它的 Cone 目录之内,越界是编译错误。
  • includeDir 的 glob 匹配完整的相对路径:* 匹配一段中的任意字符,? 匹配一个字符,[…] 是字符组,完整一段的 ** 匹配任意层目录。没有隐式的 .gitignore 或隐藏文件排除。
  • env 只能读取 SCOOP_ 前缀的变量,其他名称是编译错误;变量不存在为 None,存在但为空为 Some("")。交叉编译时读取的是编译机的环境。
  • includeStr 与 env 的结果可以用于 const val;文件或环境变化时,相关代码会重新编译。

值观察与调试输出

ValueInspector<T> 把值转换为只读的结构视图,DebugPrinter 把视图格式化为文本。编译器可以为 struct、enum、tuple 和普通 final class 直接合成 inspect 方法。下面两个类型都在 companion 上声明这个接口。

struct Point(val x: Int, val y: Int) {
    public companion object : ValueInspector<Point>
}

class Credentials(val user: String, @DebugRedact val password: String, @DebugIgnore val cache: Int) {
    public companion object : ValueInspector<Credentials>
}

fun main() {
    println(DebugPrinter.format(Point.inspect(Point(1, 2))))          // Point(x=1, y=2)
    println(DebugPrinter.format(Credentials.inspect(Credentials("ada", "hunter2", 3))))
    // Credentials(user="ada", password="<redacted>")
    println(DebugPrinter.format(Point.inspect(Point(3, 4)), DebugOptions(layout = DebugLayout.Pretty)))
}
  • 视图只在打印时才读取成员,DebugOptions 可以限制深度、元素个数与字符串长度,并检测循环引用。
  • @DebugIgnore 隐藏字段,@DebugRedact 以替代文本显示字段,两者都不会读取该字段。
  • 读取成员遵守定义处的可见性规则。核心类型与容器的 companion 提供现成的 inspector。

代码生成器

核心库注解 @GenerateWith 的第一个参数是生成器名,第二个参数是字符串数组,每项写出实现者已声明或继承的完整接口类型,如 "ValueDecoder<User>"。构建时,生成器返回普通 Scoop 方法体,由编译器在实现者的作用域内检查。

使用工具链自带的生成器时,scoopc 会在自己的目录中自动找到对应的程序。scoop.codec 对应 scoop-codec-generator,用来生成编解码方法。scoop.cli 对应 scoop-cli-generator,为 CliArguments<T> 生成参数布局和绑定方法。见命令行示例和自定义生成器协议。