sml

SML { ❄ }

中文 EN

Chapter 7: Multilingual Use

Chapter 7: Multilingual Use

SML is a format that needs to be parsed by the host language to be “usable”. Each language implementation is decoupled from each other and can be embedded separately (WASM/sandbox/editor are all acceptable). Below are the four most commonly used integration methods.

7.1 Rust(swsml

use sml::parse;
let v = parse("name: John\nage: 27").unwrap();
assert_eq!(v["name"], "John");

Include file:

use sml::parse_file;
let v = parse_file("app.sml")?;

Serde bridging (optional feature):

# Cargo.toml
sml-rs = { version = "0.2", features = ["serde"] }
use sml::{parse, Value};
let v = parse("name: John\nage: 27")?;
let json = serde_json::to_string(&v)?;   // {"name":"John","age":27}

Value handwriting implements Serialize/Deserialize, serialized as natural 27 instead of {"Int":27}. When serde is not enabled, crate has zero dependencies.

7.2 C(sml.c

# include "sml.h"
char err[256] = {0};
sml_value *v = sml_parse("name: John\nage: 27", err, sizeof(err));
/* v->type == SML_STR ("John") ... 用 sml_free(v) 释放 */

The contract system has been 100% aligned with Rust, and the behavior of the four ends of CONFIG_CONTRACT is consistent.

7.3 JavaScript(sml.mjs

Zero dependency ESM, browser/node compatible, including contracts and Playground:

import { parse, stringify } from "./sml.mjs";
const v = parse('name: John\nage: 27');
console.log(stringify(v));

SML ↔ JSON conversion (isomorphic):

const obj = parse(smlText);              // 普通 JS 对象
const json = JSON.stringify(obj);
const sml = stringify(JSON.parse(json));

7.4 Lua / Soup(lib/sml.soup

local sml = require("lib.sml")
local v, err = sml.load(text)   -- 解析
print(sml.dump(v))              -- 序列化
soupx lua/sml.sar config.sml     # 解析并打印

7.5 Other

-* * C++* * (cpp/): header file+single compilation unit, zero third-party dependencies, parsing failure throws sml::ParseError (including row and column positions).

-Python: See py binding outside rust/.

7.6 Which one to choose?

You are writingusing
Rust programs/command-line toolsswsml
Embedded/System LayerC/C++
Front end/Node Servicessml.mjs
Soup Ecology/Scriptlib/sml.soup

Chapter 8: Practical Projects (/book/ch08 project)

Hands on practice

After reading this chapter, directly modify SML in the editor below and click “Run” to immediately see the parsing results or validation errors - having output is necessary for efficient learning.

✍ 动手练习 定义 @contract User { id: str, email: str, role: enum(user,admin,owner) default user },用 @is User 写数据(id=u_1, email=a@b.c),验证 role 自动取默认 user。
💡 提示:同一份契约在 Rust/C/JS/Lua 行为一致——改 role 为 owner 试试。
✍ 自测考题:第 7 章自测:多语言使用 得分 0 / 3
Q1. SML 契约在多种语言里的行为是?
Q2. 判断:同一份 SML 文件,用 Rust 和 Lua 解析,得到的字段名和嵌套结构应完全相同。
Q3. 在 JS 里调用解析器通常用哪个导出?