swsml
SML — SNOWARE Markup Language for Rust: a declarative data/configuration format, an alternative to JSON and YAML. Features: optional quotes, fragments, contracts (schema layer with enums, defaults and composition), include directive, environment-variable inlining, zero dependencies (optional serde).
English below | 中文在上方,English 在下方
包名是
swsml而非sml-rs——后者已被无关项目占用 (Smart Message Language 智能电表协议解析器)。 lib 名仍为sml,因此use sml::{...}不受影响。The crate is named
swsmlbecausesml-rswas taken by an unrelated project (a smart-meter protocol parser). The lib name is stillsml, souse sml::{...}is unaffected.
中文
SML(SNOWARE Markup Language)的 Rust 实现:声明式数据/配置格式,JSON/YAML 的替代品。
Logo:黑花括号 {} 表示语法骨架(块的边界),蓝色雪花 ❄ 表示精确的取值点。
安装
[]
= "0.1"
# 需要 serde 互操作时:
# swsml = { version = "0.1", features = ["serde"] }
快速开始
use ;
let v = parse?;
assert_eq!;
assert_eq!;
// 序列化回 SML(可 round-trip)
println!;
语法一览
@version v1
# 引号可选:裸词即字符串
firstName: John
age: 27
# 块冒号可省:address { } 等价于 address: { }
address {
streetAddress: "21 2nd Street" # 含空格才需要引号
state: NY # 裸词
}
# 数组:逗号可选
phoneNumbers: [ { type: home } { type: office } ]
# 片段:定义 + 以「值」形式引用
@base { region: cn-north-1 }
region: &base
# 环境变量内联
apiKey: $env.RESEND_API_KEY
# 词中 @ 无需转义(仅词首的 @ 才是片段标记)
contact {
to: a@b.c
from: "sal <sal@mail.swebase.cn>"
}
特性
| 特性 | 说明 |
|---|---|
| 引号可选 | 裸词即字符串(state: NY) |
| 块冒号可省 | address { } ≡ address: { } |
| 数组分隔灵活 | [ a b c ]、每行一个、逗号可选 |
| 片段 | @name { } 定义,&name 以值形式引用并展开 |
| 契约 | 可选 schema 层:字段类型、枚举、默认值、区间、组合 |
| include 指令 | 拆分配置,可嵌套、可在块内注入字段 |
| 版本声明 | @version v1,便于将来演进不破坏旧文档 |
| 环境变量内联 | $env.VAR |
| 类型自识别 | true/false/null / 数字 / 字符串 |
数据类型
SML 是纯数据格式,值模型与 JSON 同构,共 7 种:
顶层支持三种形态(与 to_sml 输出对称):键值块、{ ... } 对象块、[ ... ] 数组。
// 对象数组(如「历史记录」这类列表数据)
let v = parse?;
顶层标量(如单独的
42)不可往返——SML 顶层需为容器。
契约(Contract)
SML 本身无类型系统。契约是可选的 schema 层,为块提供结构体约束、枚举、默认值、取值区间。
use parse;
let text = r#"
@contract Server {
host: str # 必填(默认 required)
port: int default 5432 # 缺失时填充
tls: bool default false
tags: [str] optional # 可选,元素须为字符串
status: enum [ active standby retired ]
weight: num min 0 max 100
}
db {
@is Server
host: db1.internal
status: active
weight: 80
}
"#;
let v = parse?;
// port / tls 由 default 填充
assert_eq!;
@contract Name { }定义契约(不进解析结果);@is Name在块内应用- 应用时填充 default,并校验必填、类型、枚举、数值区间、数组元素类型
- 校验发生在解析期,违反即返回错误(而非留到应用侧)
- 契约须在
@is之前定义(顺序依赖) - 不使用契约时行为完全不变 —— 向后兼容
类型:str / int / num / bool / any / [T] / enum [ ... ]
修饰符:required(默认)/ optional / default <值> / min <数> / max <数>
组合(而非继承)
契约之间不共享字段定义,而是「字段的类型是另一个契约」——直接写契约名,可多层嵌套:
@contract Address {
city: str
country: str default CN
}
@contract Server {
host: str
address: Address # 组合:该字段的值须符合 Address 契约
}
db {
@is Server
host: db1.internal
address { city: Beijing } # country 缺 -> 自动填 CN
}
嵌套块会递归校验并回填默认值;被引用契约可在之后定义。
严格模式(默认严格)
未声明字段默认被拒绝(能立即发现 prot 这类拼写错误)。确需放宽须显式写 loose:
@contract Metrics loose { # 允许额外字段
latency: num min 0
}
loose 只放宽「未声明字段」,已声明字段照样校验。
include 指令
# app.sml
app: resender
database {
include "conf.d/db.sml" # 在块内注入一组字段
pool: 16
}
let v = parse_file?;
- 相对路径按被包含文件自身所在目录解析(同 C 预处理器)
- 语义是文本内联而非对象合并,因此可出现在块内部
- 循环引用、文件缺失均返回错误,不静默跳过;嵌套上限 32 层
parse()是纯函数(不做 IO),include 由parse_file()/resolve_includes()处理, 因此在无文件系统的环境(WASM / 沙箱)中仍可安全嵌入parse()。
版本声明
use ;
let = parse_versioned?;
assert_eq!;
- 未声明时默认按当前版本处理,既有文档不受影响
- 声明了不支持的版本会报错,而非静默按错误语法解析
version是保留字,不可作为片段名
serde 支持(可选)
启用 serde feature 后,Value 实现 Serialize/Deserialize,可与任意 serde 后端互操作:
let v = parse?;
let json = to_string?; // {"name":"John","age":27}
let back: Value = from_str?;
采用手写实现而非 #[derive],以保证数据形状自然:
Value::Int(27) 序列化为 27,而非 derive 会产生的 {"Int":27}。
不启用该 feature 时,本 crate 为零依赖。
运行示例
多语言实现
| 语言 | 位置 |
|---|---|
| Soup / Lua | ../lua/(lib/sml.soup) |
| Rust | 本目录 |
| C | ../c/sml.h |
| JavaScript | ../js/sml.mjs |
License
MulanPSL-2.0
English
Rust implementation of SML — SNOWARE Markup Language: a declarative data/configuration format, an alternative to JSON and YAML.
Installation
[]
= "0.1"
# With serde interop:
# swsml = { version = "0.1", features = ["serde"] }
Quick start
use ;
let v = parse?;
assert_eq!;
assert_eq!;
// Serialize back to SML (round-trip safe)
println!;
Syntax at a glance
@version v1
# Quotes optional: bare words are strings
firstName: John
age: 27
# Block colon optional
address {
streetAddress: "21 2nd Street"
state: NY
}
# Arrays: commas optional
phoneNumbers: [ { type: home } { type: office } ]
# Fragment: defined then referenced as a *value*
@base { region: cn-north-1 }
region: &base
# Environment variable inlining
apiKey: $env.RESEND_API_KEY
# `@` inside a word needs no escaping (only a leading `@` is a fragment marker)
contact {
to: a@b.c
from: "sal <sal@mail.swebase.cn>"
}
Features
| Feature | Description |
|---|---|
| Optional quotes | Bare words are strings (state: NY) |
| Optional block colon | address { } ≡ address: { } |
| Flexible array separators | [ a b c ], one per line, commas optional |
| Fragments | @name { } defines, &name references as a value |
| Contracts | Optional schema layer: types, enums, defaults, ranges, composition |
include directive |
Split config files; nestable, injectable inside blocks |
| Version declaration | @version v1 for forward-compatible evolution |
| Env var inlining | $env.VAR |
| Type inference | true/false/null / numbers / strings |
Data types
SML is a pure data format; its value model is isomorphic to JSON with 7 variants:
Three top-level forms are supported (symmetric with to_sml output):
key-value blocks, { ... } object blocks, and [ ... ] arrays.
let v = parse?;
A top-level scalar (e.g. a lone
42) cannot round-trip — the top level must be a container.
Contracts
SML has no type system of its own. Contracts are an optional schema layer providing struct-like constraints, enums, defaults and numeric ranges.
use parse;
let text = r#"
@contract Server {
host: str # required (default)
port: int default 5432 # filled when missing
tls: bool default false
tags: [str] optional # optional, items must be strings
status: enum [ active standby retired ]
weight: num min 0 max 100
}
db {
@is Server
host: db1.internal
status: active
weight: 80
}
"#;
let v = parse?;
// port / tls come from `default`
assert_eq!;
@contract Name { }defines a contract (not included in the parse result);@is Nameapplies it inside a block- Applying one fills defaults and validates required fields, types, enums, numeric ranges and array item types
- Validation happens at parse time — violations return errors immediately
- A contract must be defined before the
@isthat uses it - Without contracts, behaviour is unchanged — fully backward compatible
Types: str / int / num / bool / any / [T] / enum [ ... ]
Modifiers: required (default) / optional / default <value> / min <n> / max <n>
Composition (not inheritance)
Contracts do not share field definitions; instead, a field's type can be another contract. Just write the contract name — nesting works to any depth:
@contract Address {
city: str
country: str default CN
}
@contract Server {
host: str
address: Address # the value must satisfy the Address contract
}
db {
@is Server
host: db1.internal
address { city: Beijing } # country missing -> filled with CN
}
Nested blocks are validated recursively and defaults are filled. A referenced contract may be defined later.
Strict mode (strict by default)
Fields not declared in the contract are rejected by default (this catches
typos like prot). To allow extras, write loose explicitly:
@contract Metrics loose { # allow undeclared fields
latency: num min 0
}
loose only relaxes undeclared fields; declared ones are still validated.
The include directive
# app.sml
app: resender
database {
include "conf.d/db.sml" # injects a set of fields into this block
pool: 16
}
let v = parse_file?;
- Relative paths resolve against the including file's own directory (like the C preprocessor)
- Semantics are text inlining, not object merging, so it works inside blocks
- Cycles and missing files return errors (never silently skipped); depth limit 32
parse()is a pure function (no I/O);includeis handled byparse_file()/resolve_includes(). This makesparse()safe to embed in environments without a filesystem (WASM / sandboxes).
Version declaration
use ;
let = parse_versioned?;
assert_eq!;
- Undeclared documents use the current version — existing documents are unaffected
- An unsupported declared version errors instead of parsing with wrong grammar
versionis a reserved word and cannot be a fragment name
Serde support (optional)
With the serde feature, Value implements Serialize/Deserialize and
interoperates with any serde backend:
let v = parse?;
let json = to_string?; // {"name":"John","age":27}
let back: Value = from_str?;
This uses a hand-written implementation rather than #[derive] to keep the
data shape natural: Value::Int(27) serializes to 27, not {"Int":27}.
Without this feature the crate is dependency-free.
Examples
Other language implementations
| Language | Location |
|---|---|
| Soup / Lua | ../lua/ (lib/sml.soup) |
| Rust | this directory |
| C | ../c/sml.h |
| JavaScript | ../js/sml.mjs |
License
MulanPSL-2.0