如何在macro_rules中无元变量实现多层数组类型的递归处理?
解决多层数组类型的宏定义问题
要处理int[][]这类多层数组类型,核心是通过递归宏调用逐层剥离数组标记[],每次将内层类型包裹为数组,直到处理完所有嵌套层级。
修改后的完整宏代码
macro_rules! ty { // 处理任意层数的数组:递归剥离一层[],包裹内层类型后继续处理剩余[] ($inner:tt $([])+) => { $crate::types::expr::Type::Array($crate::types::expr::TypeArray { item: Box::new(ty!($inner $([])*)), }) }; (_ []) => { $crate::types::expr::Type::Array(TypeArray { .. }) }; (int) => { $crate::types::expr::Type::Primitive($crate::types::expr::TypePrimitive::Int) }; (bool) => { $crate::types::expr::Type::Primitive($crate::types::expr::TypePrimitive::Bool) }; (*) => { $crate::types::expr::Type::Any }; (()) => { $crate::types::expr::Type::Unit }; ( { $e: expr } ) => { $e }; }
关键逻辑说明
- 新增的
($inner:tt $([])+)分支匹配至少一个数组标记的情况:$([])+捕获所有连续的[],$([])*保留当前层之外的剩余[]- 递归调用
ty!($inner $([])*),剥离当前层数组标记后继续处理内层类型+剩余数组标记 - 每次递归都会将内层类型包裹为
Type::Array,直到所有[]处理完毕,最终匹配到基础类型分支
示例效果
调用ty!(int[][])时,宏会展开为:
Type::Array(TypeArray { item: Box::new(Type::Array(TypeArray { item: Box::new(Type::Primitive(TypePrimitive::Int)), })), })
内容的提问来源于stack exchange,提问作者laptou
相关产品推荐
相关产品推荐

