知识卡片
字段类型限定合法输入
解析资源属性时,可以先用 token 类型排除语法形态错误,再用目标值类型约束范围。例如把名称解析为 Ident,把内存和时限解析为 LitInt 后转为 u16。传入 "yes" 会在整数词法层报错,转换成 u16 又会拦住负值或超过 65,535 的数。
服务业务约束应有独立判断。书中示例的消息给出内存和时限的较小上限,但清单 9.8 的实际判断只做整数转换,仍能接收零及其他超出业务范围的可表示值。诊断文字应对应代码真正执行的检查。
相关卡片 [[自定义关键字驱动解析]]。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
- · 解析原始资源语法
原书出处 · 1 处
- Writing an infrastructure DSL 解析原始资源语法 · 查看原书依据
And because memory and time can be larger than 255 (the maximum value of u8), u16 is next in line, which will stop illegal values above 65,535. A further improvement to error handling would be to add additional checks on top of what syn and the compiler are doing for us. For example, in the time branch, we would check that the value is <= 900.
参考来源
- 位置:《Write Powerful Rust Macros》第09章《Writing an infrastructure DSL》(book-source:extracted/Write Powerful Rust Macros/_epub-src/OEBPS/Text/chapter-9.xhtml#p60)
- 结论依据:原书明确区分 u16 的可表示范围与需要额外添加的时限检查,清单 9.8 可以核对实现边界。
- 原始内容:And because memory and time can be larger than 255 (the maximum value of u8), u16 is next in line, which will stop illegal values above 65,535. A further improvement to error handling would be to add additional checks on top of what syn and the compiler are doing for us. For example, in the time branch, we would check that the value is <= 900.