是否可以在纯 Rust 宏中编写像 `print!` 这样复杂的东西? [英] Is it possible to write something as complex as `print!` in a pure Rust macro?

查看:43
本文介绍了是否可以在纯 Rust 宏中编写像 `print!` 这样复杂的东西?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始学习 Rust 宏,但文档有限.这很好——我想它们是一个专家功能.虽然我可以进行基本的代码生成、特征的实现等,但一些内置宏似乎远远不止这些,例如各种打印宏,它们检查字符串文字并将其用于代码扩展.

I am starting out learning Rust macros, but the documentation is somewhat limited. Which is fine — they're an expert feature, I guess. While I can do basic code generation, implementation of traits, and so on, some of the built-in macros seem well beyond that, such as the various print macros, which examine a string literal and use that for code expansion.

我查看了print! 并调用另一个名为 format_args 的宏.不幸的是,这似乎不是用纯 Rust"构建的,注释只是说内置编译器".

I looked at the source for print! and it calls another macro called format_args. Unfortunately this doesn't seem to be built in "pure Rust" the comment just says "compiler built-in."

是否可以在纯 Rust 宏中编写像 print! 这样复杂的东西?如果是这样,会怎么做?

Is it possible to write something as complex as print! in a pure Rust macro? If so, how would it be done?

我实际上对构建编译时特里"感兴趣——基本上将某些固定字符串识别为在编译时固定的关键字".这将是高性能的(可能),但主要是我只对代码生成感兴趣.

I'm actually interested in building a "compile time trie" -- basically recognizing certain fixed strings as "keywords" fixed at compile time. This would be performant (probably) but mostly I'm just interested in code generation.

推荐答案

format_args 在编译器本身中实现,在 libsyntax_ext crate 中.该名称在 函数,以及处理它的代码在 expand_format_args 函数.

format_args is implemented in the compiler itself, in the libsyntax_ext crate. The name is registered in the register_builtins function, and the code to process it has its entry point in the expand_format_args function.

无法使用macro_rules! 结构定义进行如此详细语法处理的宏.它们可以用 程序宏;但是,此功能目前不稳定(只能与夜间编译器一起使用,并且会受到突然和未宣布的更改的影响)并且文档很少.

Macros that do such detailed syntax processing cannot be defined using the macro_rules! construct. They can be defined with a procedural macro; however, this feature is currently unstable (can only be used with the nightly compiler and is subject to sudden and unannounced changes) and rather sparsely documented.

这篇关于是否可以在纯 Rust 宏中编写像 `print!` 这样复杂的东西?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆