All Questions
554
questions
79
votes
3
answers
12k
views
How to allow optional trailing commas in macros?
Here's a synthetic example of what I want:
macro_rules! define_enum {
($Name:ident { $($Variant:ident),* }) => {
pub enum $Name {
None,
$($Variant),*,
}
...
59
votes
3
answers
43k
views
Can I convert a string to enum without macros in Rust?
For example, if I have code like:
enum Foo {
Bar,
Baz,
Bat,
Quux
}
impl Foo {
from(input: &str) -> Foo {
Foo::input
}
}
This will obviously fail because input ...
49
votes
6
answers
16k
views
Equivalent of __func__ or __FUNCTION__ in Rust?
In C and C++ you can get the name of the currently executing function through the __func__ macro with C99 & C++11 and ___FUNCTION___ for MSVC.
Is there an equivalent of this in Rust?
Example of ...
47
votes
1
answer
13k
views
Generating documentation in macros
I have a couple of macros to reduce boilerplate when defining certain tuple-structs of the form:
macro_rules! new_type (($name:ident, $bytes:expr) => (
pub struct $name(pub [u8; $bytes]);
/...
43
votes
1
answer
13k
views
What does the tt metavariable type mean in Rust macros?
I'm reading a book about Rust, and start playing with Rust macros. All metavariable types are explained there and have examples, except the last one – tt. According to the book, it is a “a single ...
41
votes
3
answers
20k
views
How to prefix/suffix identifiers within a macro? [duplicate]
When using a macro that defines a function, is it possible to add a prefix to the function?
macro_rules! my_test {
($id:ident, $arg:expr) => {
#[test]
fn $id() {
...
33
votes
3
answers
21k
views
How do I match the type of an expression in a Rust macro?
This is just pseudocode:
macro_rules! attribute {
$e: expr<f32> => { /* magical float stuff */ };
$e: expr<i64> => { /* mystical int stuff */ };
};
I would like to have a ...
33
votes
4
answers
11k
views
Is it possible to declare variables procedurally using Rust macros?
Basically, there are two parts to this question:
Can you pass an unknown identifier to a macro in Rust?
Can you combine strings to generate new variable names in a Rust macro?
For example, something ...
31
votes
5
answers
7k
views
Using $crate in Rust's procedural macros?
I know what the $crate variable is, but as far as I can tell, it can't be used inside procedural macros. Is there another way to achieve a similar effect?
I have an example that roughly requires me ...
25
votes
1
answer
27k
views
How do I create a Rust macro with optional parameters using repetitions?
I'm currently looking into Rust macros and I can not find any detailed documentation on repetitions. I would like to create macros with optional parameters. This would be my idea:
macro_rules! ...
23
votes
4
answers
18k
views
Is there a way to get the field names of a struct in a macro?
Consider the following example:
struct S {
a: String,
b: String,
}
I have a macro which is called like this:
my_macro!(S);
I want to access the field names of the struct in the macro like ...
22
votes
5
answers
14k
views
How can I use the format! macro in a no_std environment?
How could I implement the following example without using std?
let text = format!("example {:.1} test {:x} words {}", num1, num2, num3);
text has type &str and num1, num2 and num3 have any ...
22
votes
3
answers
23k
views
How to import macros in Rust?
I'm struggling with how to import macros from an external crate. In my main.rs I'm importing the Glium crate:
#![macro_use]
extern crate glium;
pub use glium::*;
// where my actual main function ...
22
votes
1
answer
4k
views
Is there a way to alias multiple derives as a single one?
When using the newtype pattern I often have lengthy derives:
extern crate derive_more;
use derive_more::*;
#[derive(Add, Sub, Mul, Div, ..., Copy, Clone, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]...
21
votes
3
answers
16k
views
Rust macro accepting type with generic parameters
I have a macro that implements a trait, impl_Trait!(). Right now, it works for types without generic parameters, but I'm not sure how to add the type parameters to the impl keyword.
macro_rules! ...
19
votes
4
answers
11k
views
Can a Rust macro create new identifiers?
I'd like to create a setter/getter pair of functions where the names are automatically generated based on a shared component, but I couldn't find any example of macro rules generating a new name.
Is ...
18
votes
4
answers
10k
views
Is there a way to count with macros?
I want to create a macro that prints "Hello" a specified number of times. It's used like:
many_greetings!(3); // expands to three `println!("Hello");` statements
The naive way to create that macro ...
18
votes
1
answer
4k
views
Why do we call the vec macro using square brackets instead of the parenthesis it is defined with?
I am learning Rust macros and am confused about the syntax while using vec. The source code implementing vec!:
macro_rules! vec {
($elem:expr; $n:expr) => (
$crate::vec::from_elem($...
18
votes
1
answer
19k
views
Fixing "no rules expected the token" macro error
I'm trying to write a macro for destructuring BSON data which looks like this:
let bson: Document = ...;
let (id, hash, name, path, modification_time, size, metadata, commit_data) = bson_destructure! ...
18
votes
1
answer
734
views
Is there a way to enforce correct spelling of features?
Let's assume I have the following feature defined in Cargo.toml:
[features]
my_feature = []
And the following code lives in src/lib.rs:
#[cfg(feature = "my_feature")]
fn f() { /* ... */ }
#...
17
votes
3
answers
7k
views
Is it possible for a macro to turn an identifier lowercase? [duplicate]
Is it possible to generate a symbol or identifier in a Rust macro
from a string? Or to perform string-like operations on a identifier?
I wanted to generate a method given a symbol, but need to ...
17
votes
1
answer
13k
views
Can Rust macros create compile-time strings?
Macro variables are escaped in Rust macros by default. Is there any way to have them not escaped?
macro_rules! some {
( $var:expr ) => ( "$var" );
}
some!(1) // returns "$var", not "1"
This ...
16
votes
2
answers
5k
views
How do I use C preprocessor macros with Rust's FFI?
I'm writing some code that interfaces an existing library written in C. In my Rust code I'd like to be able to use values from CPP macros. If I have a C include.h that looks like this:
#define ...
16
votes
2
answers
3k
views
How do I write a wrapper for a macro without repeating the rules?
I am trying to make a wrapper for a macro. The trouble is that I don't want to repeat the same rules in both macro. Is there a way to do that?
Here is what I tried:
macro_rules! inner {
($test:...
16
votes
1
answer
3k
views
Why can I not access a variable declared in a macro unless I pass in the name of the variable?
I have this macro:
macro_rules! set_vars {
( $($x:ident),* ) => {
let outer = 42;
$( let $x = outer; )*
}
} ...
16
votes
1
answer
3k
views
Is it possible to "namespace" Rust macros?
I've been writing a lot of macros in a recent project. I was just thinking about how incredibly useful Rust's module system is for managing "namespaces", and I began to wonder:
Why was it decided ...
15
votes
1
answer
7k
views
How to disable the unused macros warning?
This code:
#[allow(dead_code)]
macro_rules! test {
($x:expr) => {{}}
}
fn main() {
println!("Results:")
}
produces the following warning about unused macro definition:
warning: unused ...
15
votes
1
answer
9k
views
Is it possible to write a Rust macro that will expand into a function/method signature?
I would love to be able to something like the following:
macro_rules! impl_a_method(
($obj:ident, $body:block) => (
fn a_method(foo: Foo, bar: Bar, baz: Baz) -> $obj $body
)
)
/...
14
votes
2
answers
2k
views
How to embed a Rust macro variable into documentation?
I'd like to use a macro variable in the macro-generated documentation:
macro_rules! impl_foo {
($name:ident) => {
/// Returns a new `$name`.
fn myfoo() -> $name {
}
...
14
votes
1
answer
6k
views
How do I create a Rust macro to define a String variable with the value of its own identifier?
I want to write a macro to define something like below:
let FOO: String = "FOO".to_string();
It is possible for me to have a macro:
macro_rules! my_macro {
($name: ident, $val: expr) => {
...
14
votes
2
answers
2k
views
Is there a way to hide a macro pattern from docs?
As of Rust 1.6.0, the generated documentation hides the implementation of each macro pattern:
Is there a way to hide some of the patterns from the Cargo-generated docs?
macro_rules! mc {
// ...
14
votes
2
answers
7k
views
Use output of macro as parameter for another macro
I am trying to implement a generic Point<T> type for small dimensions.
To achieve that, I wrote a macro that takes the name of the new type and the dimension of the point (since, as far as I ...
13
votes
1
answer
3k
views
Can I create a macro that unrolls loops?
I'm trying to write some fast matrix code in Rust and to do this needs to ensure that loops are unrolled. Is there a way to create a compile-time for-loop? E.g: I want
unroll_loop!(f, a, 3);
to ...
12
votes
1
answer
4k
views
How to match Rust's `if` expressions in a macro?
I'm trying to write a macro that will rewrite certain Rust control flow, but I'm having difficulty matching an if expression. The problem is that the predicate is an expression, but an expr is not ...
11
votes
2
answers
4k
views
Can a procedural macro derive on a struct add other derives?
Is it possible for a procedural macro derive to add derives from other crates to the struct that it is derived upon?
lib.rs
#[derive(Combined)]
struct Foo;
derive_combined.rs
#[macro_use] extern ...
11
votes
2
answers
2k
views
Is it possible for the assert_eq macro to show a diff when two strings aren't equal?
I'm writing some tests for a language tokenizer and I'm comparing a JSON-serialized version of the tokenization produced by the tokenizer with a serialization of a known-good tokenization. So I have ...
11
votes
1
answer
4k
views
Is there a way to reference a local variable within a Rust macro?
I would like to use macros to generate the body of a function, but to do so they need to access variables in the local scope:
macro_rules! generate_func {
($name:ident) => {
fn $name(...
11
votes
2
answers
6k
views
How to use variadic macros to call nested constructors?
I'm trying to create a macro in Rust that lets me write
make_list!(1, 2, 3)
instead of
Node::new(1, Node::new(2, Node::new(3, None)))
which should work for an arbitrary number of "parameters" ...
11
votes
1
answer
4k
views
How to use a macro from one crate in another?
I'm struggling to make macros from my rust lib available to other rust projects.
Here's an example of how I'm trying to get this work at the moment.
lib.rs:
#![crate_name = "dsp"]
#![feature(...
10
votes
1
answer
642
views
What types of Macros/Syntax Extensions/Compiler Plugins are there?
I am very confused by the many terms used for several macro-like things in the Rust ecosystem. Could someone clarify what macros/syntax extensions/compiler plugins there are as well as explain the ...
10
votes
1
answer
4k
views
How to get index of macro repetition single element
I need to get index of macro repetition element to write next code:
struct A {
data: [i32; 3]
}
macro_rules! tst {
( $( $n:ident ),* ) => {
impl A {
$(
...
10
votes
1
answer
7k
views
Macro that declare variables in Rust?
In C its possible to write a macro that declares variables, as follows:
#define VARS(a, b, c) \
int a, b, c;
Of course this isn't something you'd typically want to do.
In the actual example I'm ...
10
votes
1
answer
7k
views
error: variable 'x' is still repeating at this depth
I'm trying to write a macro to time how long various functions are executing.
macro_rules! timer {
($( $x: expr ),+ ) => {
let now = SystemTime::now();
let val = $x;
...
9
votes
2
answers
4k
views
Is it possible to modify the case of a token inside of a macro?
I am writing a macro which creates a struct managing user input. I am using the crates bitflags and sdl2. Return is an example for the key Return.
This macro takes a list of all possible inputs and ...
9
votes
3
answers
3k
views
What is a macro for concatenating an arbitrary number of components to build a path in Rust?
In Python, a function called os.path.join() allows concatenating multiple strings into one path using the path separator of the operating system. In Rust, there is only a function join() that appends ...
9
votes
3
answers
9k
views
Counting length of repetition in macro
I'm trying to implement a macro to allow MATLAB-esque matrix creation. I've got a basic working macro but I still have a long way to go.
I want to be able to enforce the right structure (same number ...
9
votes
1
answer
1k
views
Why do I need angle brackets in <$a> when implementing macro based on type?
I can implement a macro taking a type like this:
trait Boundable<A> {
fn max_value() -> A;
}
impl Boundable<u8> for u8 {
fn max_value() -> u8 { u8::MAX }
}
When I turn the ...
9
votes
2
answers
4k
views
How can I create hygienic identifiers in code generated by procedural macros?
When writing a declarative (macro_rules!) macro, we automatically get macro hygiene. In this example, I declare a variable named f in the macro and pass in an identifier f which becomes a local ...
9
votes
1
answer
2k
views
Is there any way to use private functions in public macros in Rust?
There is a variadic C function that I cannot call outside of a macro. This macro is public which it should be, but the C function with variadic arguments should not be visible.
Is there any way to ...
9
votes
1
answer
5k
views
How to set a compile time condition in macros
I want to set the compile-time condition in macros when it generates code outside the functions. I need something like that:
macro_rules! cond {
( $cond_el:expr ) => {
#[if $cond_el ==...