有没有办法用宏来算?

问题描述 投票:14回答:3

我想创建一个宏,打印“Hello”一个指定的次数。它的使用,如:

many_greetings!(3);  // expands to three `println!("Hello");` statements

创建宏用简单的方式是:

macro_rules! many_greetings {
    ($times:expr) => {{
        println!("Hello");
        many_greetings!($times - 1);
    }};
    (0) => ();
}

然而,这并不工作,因为编译器不计算表达式; $times - 1不计算,而是供给作为新表达成宏。

macros rust rust-macros
3个回答
7
投票

而普通的宏系统不允许您重复宏扩展了很多次,还有与使用在宏观循环没有问题:

macro_rules! many_greetings {
    ($times:expr) => {{
        for _ in 0..$times {
            println!("Hello");
        }
    }};
}

如果你真的需要重复宏,你不得不考虑程序的宏/ compiler plugins(其为1.4是不稳定的,并且有点难以写)。

编辑:有可能实现这个更好的方式,但我已经花了足够长的时间对这个在今天,所以这里去。 repeat!,实际复制的代码的次数的块的宏:

main.rs

#![feature(plugin)]
#![plugin(repeat)]

fn main() {
    let mut n = 0;
    repeat!{ 4 {
        println!("hello {}", n);
        n += 1;
    }};
}

lib.rs

#![feature(plugin_registrar, rustc_private)]

extern crate syntax;
extern crate rustc;

use syntax::codemap::Span;
use syntax::ast::TokenTree;
use syntax::ext::base::{ExtCtxt, MacResult, MacEager, DummyResult};
use rustc::plugin::Registry;
use syntax::util::small_vector::SmallVector;
use syntax::ast::Lit_;
use std::error::Error;

fn expand_repeat(cx: &mut ExtCtxt, sp: Span, tts: &[TokenTree]) -> Box<MacResult + 'static> {
    let mut parser = cx.new_parser_from_tts(tts);
    let times = match parser.parse_lit() {
        Ok(lit) => match lit.node {
            Lit_::LitInt(n, _) => n,
            _ => {
                cx.span_err(lit.span, "Expected literal integer");
                return DummyResult::any(sp);
            }
        },
        Err(e) => {
            cx.span_err(sp, e.description());
            return DummyResult::any(sp);
        }
    };
    let res = parser.parse_block();

    match res {
        Ok(block) => {
            let mut stmts = SmallVector::many(block.stmts.clone());
            for _ in 1..times {
                let rep_stmts = SmallVector::many(block.stmts.clone());
                stmts.push_all(rep_stmts);
            }
            MacEager::stmts(stmts)
        }
        Err(e) => {
            cx.span_err(sp, e.description());
            DummyResult::any(sp)
        }
    }
}

#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Registry) {
    reg.register_macro("repeat", expand_repeat);
}

added to Cargo.toml

[lib]
name = "repeat"
plugin = true

需要注意的是,如果我们真的不想做循环,但在编译时扩大,我们必须做的事情一样,需要字面数字。毕竟,我们无法评估变量,在编译时参考该计划的其他部分函数调用。


4
投票

据我所知,没有。宏语言是基于模式匹配和变量替换,并且仅评估宏。

现在,你可以实现与评价统计:它只是无聊......看the playpen

macro_rules! many_greetings {
    (3) => {{
        println!("Hello");
        many_greetings!(2);
    }};
    (2) => {{
        println!("Hello");
        many_greetings!(1);
    }};
    (1) => {{
        println!("Hello");
        many_greetings!(0);
    }};
    (0) => ();
}

在此基础上,我敢肯定一个能发明一套宏“计数”,并在每一步(与计)调用各种操作。


3
投票

至于其他的答案已经说了:不,你不能指望像这样用声明宏(macro_rules!)。


但是你可以实现many_greetings!例如,作为程序的宏。宏程序前一阵子被稳定下来,所以定义适用于稳定。然而,我们还不能扩展到宏在稳定的声明 - 这是#![feature(proc_macro_hygiene)]是什么。

这看起来像一个大量的代码,但大多数代码只是错误处理,所以它不是那么复杂!

examples/main.rs

#![feature(proc_macro_hygiene)]

use count_proc_macro::many_greetings;

fn main() {
    many_greetings!(3);
}

Cargo.toml

[package]
name = "count-proc-macro"
version = "0.1.0"
authors = ["me"]
edition = "2018"

[lib]
proc-macro = true

[dependencies]
quote = "0.6"

src/lib.rs

extern crate proc_macro;

use std::iter;
use proc_macro::{Span, TokenStream, TokenTree};
use quote::{quote, quote_spanned};


/// Expands into multiple `println!("Hello");` statements. E.g.
/// `many_greetings!(3);` will expand into three `println`s.
#[proc_macro]
pub fn many_greetings(input: TokenStream) -> TokenStream {
    let tokens = input.into_iter().collect::<Vec<_>>();

    // Make sure at least one token is provided.
    if tokens.is_empty() {
        return err(Span::call_site(), "expected integer, found no input");
    }

    // Make sure we don't have too many tokens.
    if tokens.len() > 1 {
        return err(tokens[1].span(), "unexpected second token");
    }

    // Get the number from our token.
    let count = match &tokens[0] {
        TokenTree::Literal(lit) => {
            // Unfortunately, `Literal` doesn't have nice methods right now, so
            // the easiest way for us to get an integer out of it is to convert
            // it into string and parse it again.
            if let Ok(count) = lit.to_string().parse::<usize>() {
                count
            } else {
                let msg = format!("expected unsigned integer, found `{}`", lit);
                return err(lit.span(), msg);
            }
        }
        other => {
            let msg = format!("expected integer literal, found `{}`", other);
            return err(other.span(), msg);
        }
    };

    // Return multiple `println` statements.
    iter::repeat(quote! { println!("Hello"); })
        .map(TokenStream::from)
        .take(count)
        .collect()
}

/// Report an error with the given `span` and message.
fn err(span: Span, msg: impl Into<String>) -> TokenStream {
    let msg = msg.into();
    quote_spanned!(span.into()=> {
        compile_error!(#msg);
    }).into()
}

运行cargo run --example main打印3“你好” S。

© www.soinside.com 2019 - 2024. All rights reserved.