Trying to generate doc comments with macros

Hi!
I have a struct called Builder that I use a macro to define setters on.

///Creates a builder function that sets $name.
macro_rules! builder_fn_set {
	{ $name: ident >< $type: ty } => {
		#[allow(dead_code)]
		pub fn $name(mut self, $name: $type) -> Self {
			self.$name = $name;
			self
		}
	};
	{ $name: ident <> $type: ty } => {
		#[allow(dead_code)]
		#[doc="Sets $name of this builder to Some($name)."]
		pub fn $name(mut self, $name: $type) -> Self {
			self.$name = Some($name);
			self
		}
	};
}
pub struct Builder {
	width : Option<u32>,
	height: Option<u32>,
	cells_x: Option<u32>,
	cells_y: Option<u32>,
	wrap: bool
}

///A builder for a Tiler Class.
impl Builder {
	builder_fn_set!{ width   <> u32  }
	builder_fn_set!{ height  <> u32  }
	builder_fn_set!{ cells_x <> u32  }
	builder_fn_set!{ cells_y <> u32  }
	builder_fn_set!{ wrap    >< bool }
        //...
}

My issue is that the docs come out as "Sets $name of this builder to Some($name)." It doesn't parse the $name argument into the doc comment.

A string literal is a string literal; macros don't treat them specially. You can't interpolate directly into a string literal from a declarative macro.

Fortunately, the #[doc] attribute can be repeated, so you can write

		#[doc = "Sets "]
		#[doc = stringify!($name)]
		#[doc = " of this builder to Some("]
		#[doc = stringify!($name)]
		#[doc = ")."]

Playground

Nice! This works well, but I notice it says "Some( u32 )" instead of "Some(u32)". Is it possible to remove the spacing?

You can try and see if concat!() works in attribute context too.

Concat! works well. You still have to use the stringify! macro for idents and tys. Thanks!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.