2 个版本
| 新 0.1.1 | 2024 年 8 月 18 日 |
|---|---|
| 0.1.0 | 2024 年 8 月 18 日 |
#492 在 Rust 模式
9KB
76 行
Permafrost
该包提供了一个用于将数据嵌入 Rust 代码的进程宏。
示例
use permafrost::embed;
/// Expands to a const item that contains a greeting.
macro_rules! greet {
(
$who:literal
) => {
embed! {
#[allow(dead_code)]
const [< HELLO _ $who:case{upper} >]:concatenate : &str = [< "Hello" " " $who "!" >]:concatenate{string};
}
}
}
greet!("Jonas");
// Recursive expansion of greet! macro
// ====================================
const HELLO_JONAS: &str = r#"Hello Jonas!"#;
用法
将以下内容添加到您的 Cargo.toml
permafrost = "1"
背景
最初,这是作为 paste 包的替代品开始的,该包允许您连接标识符并对它们应用大小写转换。
但是,鉴于 paste 包不再定期更新,而且我需要用于 kebab 案的大小写转换,我决定创建一个更强大、更灵活的替代方案。
结构
所有内容都传递给 embed 宏,它是底层引擎的入口点。最初,只传递一个 token tree 作为任意 transformer chain 中的顶层转换器,然后通过 token stream 进行纯计算。
块
块是 embed 宏的主要构建块,因为它们表示一个具有转换能力的 token stream。
块由方括号定义,并用 < > 标注,因此,[< (..) >] 表示一个块,其中 (..) 是目标 token stream。块也可以有自己的转换器链,它将跟随块。
块语法以 EBNF 给出
token-stream = token-tree | segment;
token-tree = group | ident | literal | punct | ...;
segment = block transformer-chain;
transformer = ident | ident "{" token-stream "}";
transformer-chain = ":" transformer { "," transformer };
block = "[" "<" token-stream { token-stream } ">" "]" [ transformer-chain ];
转换器
所有当前可用的转换器如下
| 转换器 | 描述 | 参数 | 示例 |
|---|---|---|---|
concatenate |
连接目标 token stream |
ident,string,r#ident |
[< (hello[world]):concatenate{ident} >] |
ungroup |
取消分组目标 token stream |
[< (hello[world]):ungroup>] |
|
flatten |
展平目标 token stream |
[< (hello[world]):flatten>] |
|
reverse |
反转目标 token stream |
[< (hello[world]):reverse>] |
|
stringify |
将目标 token stream 字面化 |
[< (hello[world]):stringify>] |
|
unstringify |
取消字面化目标 token stream |
[< "hello world":unstringify>] |
|
case |
将目标 token流 转换为特定的大小写 |
kebab、snake、camel、pascal、upper、lower、title |
[< (hello[world]):case{pascal} >] |
计数 |
计算目标 token流 中元素的数量 |
[< (hello[world]):计数>] |
|
附加 |
将目标 token流 与另一个 token流 附加在一起 |
[< (hello[world]):附加{[!]} >] |
|
前缀 |
将另一个 token流 作为前缀附加到目标 token流 |
[< (hello[world]):前缀{[!]} >] |
如果您认为缺少一个基本转换器,请提交一个issue。
依赖项
~1.2–1.8MB
~33K SLoC