是否有办法在运行时获取 struct 跟 enum 的字段信息?

跟 Rust 中 serde_json 或者 argh - Rust 的场景对应, 比如这个例子定中作为类库作者, 我希望用户定义 struct 结束之后, 我在类库当中的就能实现好如何做 parse 跟 format, 大幅降低用户使用时的成本,

#[derive(FromArgs)]
/// Reach new heights.
#[argh(help_triggers("-h", "--help", "help"))]
struct GoUp {
    /// an optional nickname for the pilot
    #[argh(option)]
    pilot_nickname: Option<String>,

    /// an optional height
    #[argh(option, default = "default_height()")]
    height: usize,

    /// an optional direction which is "up" by default
    #[argh(option, default = "String::from(\"only up\")")]
    direction: String,
}

只要定义好这个 struct 加上标注, 后续就直接能用 parser 了, 不用额外写中间的逻辑.

看已有的语言通过反射做这个比较多, 然后 Rust 是通过 macro 在编译时产生相关的代码. MoonBit 有什么推荐的方案吗?

目前编译器还没稳定到能提供这些自定义标注的程度吧,否则首先受益的应该是官方的 trait Default/ToJson。

我感觉短期内只能先用moon test/moon bench 来做替代。

比如:


///| Reach new heights.
struct GoUp {
  /// an optional nickname for the pilot
  pilot_nickname : String?
  /// an optional height
  height : UInt
  /// an optional direction which is "up" by default
  direction : String
} derive(Default, ToJson)

///|
fn[T : ToJson] toParseAble(
  defaultIns : T,
  ///| 一些标注信息
  deriveConfig? : Array[String],
  defaultsConfig? : Map[String, String]
) -> Unit {
  // 基于 json 获得结构信息
  let ins_json = defaultIns.to_json()
  // 最终输出到 target/xxx/ 下
  // @fs.write_string_to_file
  
  // 然后执行一些额外的脚本,将 target/xxx/ 下的元数据拿出来,继续生成对应的 *.gen.mbt 文件
}

///|
test "gen" {
  toParseAble(GoUp::default(), deriveConfig=["FromArgs"], defaultsConfig={
    "height": "default_height()",
    "direction": "String::from(\"only up\"))",
  })
}