Questions tagged [rust-macros]

Rust macros are a powerful tool to map a certain input sequence to an output sequence according to a defined procedure.

Filter by
Sorted by
Tagged with
1 vote
0 answers
48 views

Idiomatic way to write tests in an inner scope

I understand that I can test top-level functions like so: #[test] fn test() { assert_eq!(1 + 2, 3); } However, this does not work for inner functions, i.e. like so: fn outer() { #[test] ...
  • 237
0 votes
1 answer
26 views

macro_rules presume type about arguments

tl;dr I think I want a macro declaration to infer type (how do I create this macro?) This macro fails to compile (rust playground) macro_rules! debug_assert_none { ($($arg:tt),+) => { $(...
0 votes
1 answer
22 views

How to use unicode in a rust macro argument?

This is rougly what I want to use: enum DashNumber<N> { NegInfinity, Number(N), Infinity, } macro_rules! dn { (-∞) => { DashNumber::NegInfinity }; (∞) => { ...
  • 1,778
2 votes
1 answer
34 views

Rustlang Macro $operator= seen as syntax error

So I wrote this macro in Rustlang to allow me to create multiple functions fast that accepts a bunch of values and then perform an arithmetic operation (or may be other operations, hence the need for ...
0 votes
0 answers
31 views

Use procedural macros to make a modified copy of external code

Say I have some external library code (that is also generated from a procedural macro itself): struct Type1; struct Type2<'a> (&'a str); struct Type3<'a> (&'a str); // Expanded ...
  • 838
-1 votes
1 answer
48 views

Rust macro to generate a macro

I'm writing some macros that are all really similar (MWE the actual ones are much larger): macro_rules! var1 { () => {some_func(some_enum::Var1, vec![])}; ($($e:expr),*) => {some_func(...
  • 231
0 votes
1 answer
22 views

macro_rules repeatition does not yield the expected token type

I am trying to match user-provided lists in a macro, but the repeat-pattern does not match the same branches depending on whether I call the macro on single items directly, or whether I call it from a ...
  • 327
0 votes
1 answer
55 views

how to read a "mut" keyword in a macro call on some identifiers?

I'm making a macro to iterate over any tuple of components in my ECS. In the main lines, here is how it goes : for (pos: &Position, vel: &Velocity) in iterate_over_components!(components; ...
0 votes
0 answers
34 views

Fully-qualified macro is undefined [duplicate]

I'm just experimenting with macros. I've this: src/entry.rs #[macro_export] macro_rules! initialize { ($lambda_exp:expr) => { fn main() { $lambda_exp(); } }; } ...
0 votes
1 answer
45 views

Is there any way to "early return" in a declarative macro iterations?

I'm new to Rust's macros. I'd like to find a way to achieve a behaviour like this: early return in iterations I learned I can generate tuples using a declarative macro like this one: fn function(input)...
  • 3
0 votes
1 answer
35 views

Indexing a tuple using a macro in Rust unexpected token [duplicate]

I am trying to create a macro to perform a certain action for every element in a tuple in order to compensate for not being able to iterate over them. I wrote some code that replicates my issue: fn ...
2 votes
1 answer
55 views

How do I set a 'private' property for the default parameter in rust declarative macros

I want to write a declarative macros: log!("{} {} {}", private!(1), public!(2), 3); out : <private>2<private> parameter is printed as "" if parameter is not add "...
  • 21
0 votes
1 answer
48 views

Trying to implement trait to `std::io::Read` and `std::fs::DirEntry`

I am trying to implement my custom trait for both impl std::io::Read and std::fs::DirEntry - the idea is to implement trait both for directores as well as files, buffers and so on. use std::fs::...
  • 2,762
0 votes
1 answer
51 views

Double vs single bracket in rust macros

I've been looking at rust macros recently and have found conflicting examples of macros using brackets (as laid out below). I'd like to know what the difference between each of these are and which one ...
  • 113
1 vote
1 answer
48 views

Rust: using derive inside macro

i have a question on rust macros... i created a custom trait, and i made it derivable... but now if i try to derive the trait inside a macro it doesn't work (but if i write it manually it does work) ...
  • 45
1 vote
1 answer
43 views

How to make sure that a Rust attribute proc macro runs before the compiler tries parsing the item?

I'm trying to make a macro that adds some extra syntax to struct type declarations. For simplicity, here's a toy example: a macro that replaces "function call"-style type declarations with ...
  • 934
1 vote
2 answers
55 views

Construct ident from string/int in declarative macro

I have a dozen crates all with two functions part1() and part2(). For each of those, I want to print the return value of both functions. To not repeat myself, I wrote a little macro, so my main crate'...
  • 63
2 votes
1 answer
80 views

Is there a way to automatically register trait implementors?

I'm trying to load JSON files that refer to structs implementing a trait. When the JSON files are loaded, the struct is grabbed from a hashmap. The problem is, I'll probably have to have a lot of ...
  • 947
1 vote
1 answer
75 views

Automatically create enum variants

I want macros that automatically add structures with attribute macros to the enum. For example #[add_enum(AutoEnum)] struct A(usize); #[add_enum(AutoEnum)] struct B(i32); #[auto_enum] enum AutoEnum{} ...
0 votes
1 answer
41 views

How to expand a type alias (speifically a typle type) in Rust declarative macros?

I'm trying to adapt a macro that takes a variable number of type arguments, to a macro that takes a (possibly aliased) tuple type as its last argument: macro_rules! serialize_individually2 { ($ecs:...
  • 11.1k
0 votes
0 answers
16 views

How to store a list of types using a Rust macro?

I am using some macros that look like this: macro_rules! deserialize_individually { ($ecs:expr, $de_ser:expr, $data:expr, $( $type:ty),*) => { $( // *** omitted *** )* }; }...
  • 11.1k
3 votes
2 answers
90 views

Why is "-x" trying to parse as a literal and failing in declarative macros?

I have a little macro I wrote to help me explore what things are parsed as. With a few arms lopped off, it looks like: macro_rules! show_me{ ($l : literal $($tail : tt)*) => { println!(&...
0 votes
0 answers
40 views

Why can't macros see variables in scope? [duplicate]

I apparently don't understand how scoping works with regards to macros. I'm trying to write a macro using the TT muncher pattern. I think I need to have an initial matching arm which declares a ...
6 votes
1 answer
63 views

"unnecessary parens" warning in macro call that needs the parens - is this a bad way to write macros?

This is an extremely minor issue and I know how to do disable the warning, but reading up on it I suspect it might indicate that I might be doing something incorrect with my macro. Anyway, I have a ...
1 vote
1 answer
76 views

How can a macro match any token tree except comma

macro_rules! foo { ( $( $( $tok:tt )* ,)* ) => { [ bar!( $( $tok )* ,)* ] } } Produces error: local ambiguity when calling macro 'foo'. Because the comma ',' is of type :tt. I ...
  • 1,161
0 votes
1 answer
32 views

Can I specify an operator or other syntactic literal within a macro input?

First, I know this is not a good use of macros but I'm learning what I can do. I have a struct Rational: pub struct Rational{ pub n: i128, pub d : i128 } I have a macro that builds these: ...
1 vote
1 answer
84 views

Tuple, array or vector of vectors as argument of a function

I want to be able to provide vectors as arguments from an array of vectors to a macro iproduct!, which accepts varying numbers of arguments (all arguments must be Iterator element type). Most ...
1 vote
2 answers
65 views

How to make rust macro optional token produce code when not present?

Here is the classic situation : macro_rules! foo { ($a:tt $(b:tt)?) => { do_something_with_a($a); $(do_something_with_b($b);)? } } But what if you want this: macro_rules! ...
  • 1,161
1 vote
2 answers
140 views

How to split an ident into letters in Rust macro?

I need to write an multiply macro which converts ident into single letter idents and multiply them. let a = 4; let b = 7; println!("{}", multiply!(abbabbb)); // println!("{}", (a * ...
1 vote
0 answers
35 views

How to add optional comma support in Rust? [duplicate]

I started learning macros in Rust. I decided to practice a little and write a simple macro for hashmap. If call the macro this way, then everything works let hashmap = hashmap!{ 1 => String::from(&...
  • 11
3 votes
1 answer
178 views

Escape $ dollar sign in macro_rules

How can I escape a dollar sign for a macro like this? macro_rules! test { ($ $name:ident) => { println!(stringify!($name)); }; } fn main() { test!($abc); } I want to get abc. ...
  • 1,853
0 votes
0 answers
86 views

How can I write a Rust macro and what type should I use?

I have an implementation for a struct that needs to be implemented on multiple structs with an argument for every struct. My impl statement is as follows: #[rocket::async_trait] impl<'r> ...
0 votes
1 answer
204 views

Rust macro with dots in token trees

I'm trying to create a Rust macro that generates endpoints like "/api/v2/stats/<token>". I thought it would be cool to make it like warp path does it: warp::path!("sum" / u32 ...
  • 2,955
2 votes
0 answers
164 views

Rust equivalent of #Define?

I have a trait that has functions which need to return constantly sized arrays. Since generic array currenly does not support generic expressions within a constant generic, I have had to change ...
0 votes
1 answer
76 views

Some explanation needed regarding custom multiplications in Rust

1.) I have made a big knot in my code it seems. I defined my own structs e.g. struct State { // some float values } and require them be multiplied by f64 + Complex64 and added together member-wise. ...
  • 375
0 votes
0 answers
143 views

Rust Procedural Macro - macro expansion ignores token `,` [duplicate]

I have the following trivial procedural macro in one crate (it was more than this, but I distilled it to be as simple as possible while still causing the issue to occur) #[proc_macro] pub fn the_macro(...
  • 1
0 votes
1 answer
120 views

Macros, How to generate enum variant from str literal?

I have an enum with over 100 variants. and I have to get each of its variants from a string. Something like this. enum VeryLongEnum { A, B, C, D, E, } impl From<&'static ...
  • 520
0 votes
0 answers
39 views

Expanding function type in rust macro

I'm trying to write a small program that hooks IAT entries. Inside the hook, for now I want to just print the arguments and invoke orginal function (whose address I stored beforehand in a static ...
  • 71
0 votes
1 answer
87 views

How to import required types inside of a custom derive macro?

I have a custom derive macro which generates some code for a struct it is applied to. That code uses few types (bytes::Buf, ect) that need to be imported. #[derive(MyMacro)] struct S { ... } What is ...
  • 2,971
1 vote
1 answer
104 views

Can a macro access the field names and types of a remote struct from its path?

I am trying to create a macro that can copy the fields of some external struct into the struct where the macro is applied. So something like: // external_crate.rs pub struct ExternalStruct { foo: ...
  • 2,967
1 vote
3 answers
201 views

Can a struct be inspected in a proc-macro?

I'd like to create a proc-macro that is able to inspect the structure of its arguments. For example, I may have a struct Foo and then my user calls my macro with something like frobulate!(Foo). This ...
  • 9,348
1 vote
1 answer
202 views

"no rules expected the token" when using macro to implement methods [closed]

I previously used C/C++ and recently started using Rust. I'm experiencing difficulties on writing simple macro_rules! to automatically implement some helper methods. Originally, I had Scanner struct, ...
1 vote
1 answer
81 views

How can I add 'unsafe extern "C"' to a fn type in a declarative macro?

I would like to be able to pass a fn type as argument into macro_rules, and then generate code that adds unsafe extern "C" to the type. For example, I would like: define_ext_fn_type!(fn(i32),...
  • 14.7k
0 votes
1 answer
148 views

Expose struct generated from quote macro without appearing out of nowhere

How can I expose a struct generated from the quote macro in my derive macro without having to introduce a struct name out of the blue in my usage file (due to macro expansion)? To illustrate the point,...
  • 5,037
1 vote
1 answer
62 views

Rust macro accept call to member function

I'm trying to replace a bunch of snippets like if let Some(thing) = some_t { thing.doSomething(); } with a macro, resulting in something like if_some(some_t, doSomething()); so basically ...
  • 1,337
2 votes
1 answer
95 views

Are all Rust attributes Macros?

Are all attributes in Rust implemented as Macros? Or some native attributes are created specially by the compiler/language and does not use the Macros mechanism? If there are attributes not created ...
  • 2,526
1 vote
1 answer
138 views

Directly parse data on nested proc macro

Suppose this: #[route(base_path="/api")] pub struct Type; impl Type { #[route(path="/v1/handler")] pub fn handler() {} #[route(path="/v1/handler2")] pub ...
  • 1,744
0 votes
1 answer
257 views

How to implement a Rust macro using module paths as a macro function parameter?

As asked by @isaactfa, PS C:\...> rustc --version rustc 1.62.1 (e092d0b6b 2022-07-16) // Cargo.toml [dependencies] diesel = { version = "1.4.5", features = ["postgres", "...
1 vote
1 answer
38 views

Why does tt in declarative macros not expect the token "::"?

I have written the following macro: macro_rules! foo { ($bar:tt) => { fn baz() { $tt } } } I am using it like this: foo! { String::new(); } This produces the ...
  • 23
2 votes
0 answers
66 views

Design choice of default trait implementation vs. derive macro in Rust

After reading quite a bit I haven't found much in the way how to decide whether to implement functionality as a trait with a default implementation or as a derive macro. It appears that the ...
  • 1,201

1
2 3 4 5 6