How can I add and use doc comments with a macro invocation?
macro_rules! foo {
(
$(#[$outer:meta])*
$name:ident
) => {
pub mod $name {
$(#[$outer])*
pub const THE_ANSWER: i32 = 42;
}
}
}
/// doc for macro created module
foo!(bar);
fn main() {
println!("{}", bar::THE_ANSWER);
}
Playground Link
I seem to be doing what's recommended by this question but I still get the warning.
warning: unused doc comment
--> src/main.rs:13:1
|
13 | /// doc for macro created module
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ rustdoc does not generate documentation for macro invocations
|
= note: `#[warn(unused_doc_comments)]` on by default
= help: to document an item produced by a macro, the macro must produce the documentation as part of its expansion
Related
Is it possible to export a function and a macro with the same name from a module?
Example lib.rs
mod log;
fn foo() {
log::info!("");
log::info("");
}
In log.rs:
Using pub(crate) use info; conflicts with pub fn info() { .. }
Using #[macro_export] and #[macro_use] doesn't allow namespaces
Macros and functions belong to different namespaces so two with the same name should happily coexist. This compiles (playground):
macro_rules! info {
($v:expr) => {}
}
fn info(v: &str) { }
However, trouble seems to arise when when trying to make them public from within a module. Exporting the macro as shown in How do I use a macro across module files? seems to conflict somehow with the function declaration (playground):
mod log {
macro_rules! info {
($v:expr) => {}
}
pub(crate) use info;
pub fn info(v: &str) { }
}
error[E0255]: the name `info` is defined multiple times
--> src/lib.rs:8:5
|
6 | pub(crate) use info;
| ---- previous import of the value `info` here
7 |
8 | pub fn info(v: &str) { }
| ^^^^^^^^^^^^^^^^^^^^ `info` redefined here
|
= note: `info` must be defined only once in the value namespace of this module
help: you can use `as` to change the binding name of the import
|
6 | pub(crate) use info as other_info;
| ~~~~~~~~~~~~~~~~~~
I do not know if this is a bug or intended behavior. Either way it is confusing.
A workaround that I found was to declare the function in a separate module and then re-export it by wildcard in the original module (playground):
mod log {
mod imp {
pub fn info(v: &str) { }
}
pub use imp::*;
macro_rules! info {
($v:expr) => { }
}
pub(crate) use info;
}
You can do it the other way (i.e. putting the macro in a separate module) but the compiler strangely yields a warning that it didn't re-export anything even when it did (playground).
I'm building a wrapper around a DLL. This DLL gives me access to a database engine which implements an OOP design pattern. This requires me to create multiple overlapping traits that cover all the functionality:
pub trait CursorStatement { /* ... */ }
pub trait CursorTable { /* ... */ }
pub trait CursorStatementTable { /* ... */ }
...
I want to be able to bring these traits in scope so that I can call the functions without having to list every trait. Right now I'm doing:
mod traittest;
use traittest::*;
fn test() -> Result<(), AceError> {
let t = traittest::Table::new(3, "ORDERS")?;
let c = traittest::Cursor { handle: 42 };
println!("t.fields={}", t.fields());
println!("c.fields={}", c.fields());
Ok(())
}
fn main() {
test().expect("success");
}
The problem with use foo::* is that it puts everything from the module into my namespace, which I don't want.
In the example above, I don't have to type traittest::Table or traittest::Cursor, I just have to type Table or Cursor. However, I want to have to prefix those objects with the module name so when I'm reading the code I know where the objects came from. I might want to create a Table object in my local file that is distinguished from the one coming from the module.
I also don't want to have to do the following because if I later have to add a new trait I will have to update a bunch of other source files that depend on this module:
mod traittest;
use traittest::{CursorStatement, CursorStatementTable, CursorTable, /* ... */};
I tried creating a Traits supertrait that would inherit all other traits as shown in Is there any way to create a type alias for multiple traits?, but it doesn't work because I can't implement the trait for anything because there's nothing that would be an implementation of every trait in the file:
pub trait Traits: CursorStatement, CursorTable, CursorStatementHandle, /* ... */ {}
If I could create a named scope for all the traits, that would work, but I can't figure out how to make Rust happy with this idea:
let traits = {
pub trait CursorTable { /* ... */ }
}
It looks like this trait_group macro might do the trick but it's not obvious to me how I could use it to solve my problem.
Here's my entire program
mod traittest {
#[derive(Debug)]
pub struct AceError {
code: u32,
description: String,
}
pub trait CursorTable {
fn get_handle(&self) -> u32; // impl's must write this function
fn fields(&self) -> String {
return format!("(get_handle() -> {})", self.get_handle());
}
}
pub struct Table {
pub handle: u32,
pub table_name: String,
}
pub struct Cursor {
pub handle: u32,
}
impl Table {
pub fn new(handle: u32, table_name: &str) -> Result<Table, AceError> {
let table = Table {
handle: handle,
table_name: table_name.to_string(),
};
return Ok(table);
}
}
impl CursorTable for Table {
fn get_handle(&self) -> u32 {
return self.handle;
}
}
impl CursorTable for Cursor {
fn get_handle(&self) -> u32 {
return self.handle;
}
}
pub trait Traits: CursorTable {} /* super trait to bring all other traits in scope */
}
use traittest::Traits;
fn test() -> Result<(), traittest::AceError> {
let t = traittest::Table::new(3, "ORDERS")?;
let c = traittest::Cursor { handle: 42 };
println!("t.fields={}", t.fields());
println!("c.fields={}", c.fields());
Ok(())
}
fn main() {
test().expect("success");
}
and here's the error I get:
warning: unused import: `traittest::Traits`
--> src/main.rs:49:5
|
49 | use traittest::Traits;
| ^^^^^^^^^^^^^^^^^
|
= note: `#[warn(unused_imports)]` on by default
error[E0599]: no method named `fields` found for struct `traittest::Table` in the current scope
--> src/main.rs:54:31
|
10 | fn fields(&self) -> String {
| ------
| |
| the method is available for `std::boxed::Box<traittest::Table>` here
| the method is available for `std::sync::Arc<traittest::Table>` here
| the method is available for `std::rc::Rc<traittest::Table>` here
...
15 | pub struct Table {
| ---------------- method `fields` not found for this
...
54 | println!("t.fields={}", t.fields());
| ^^^^^^ method not found in `traittest::Table`
|
= help: items from traits can only be used if the trait is in scope
help: the following trait is implemented but not in scope; perhaps add a `use` for it:
|
49 | use crate::traittest::CursorTable;
|
error[E0599]: no method named `fields` found for struct `traittest::Cursor` in the current scope
--> src/main.rs:55:31
|
10 | fn fields(&self) -> String {
| ------
| |
| the method is available for `std::boxed::Box<traittest::Cursor>` here
| the method is available for `std::sync::Arc<traittest::Cursor>` here
| the method is available for `std::rc::Rc<traittest::Cursor>` here
...
20 | pub struct Cursor {
| ----------------- method `fields` not found for this
...
55 | println!("c.fields={}", c.fields());
| ^^^^^^ method not found in `traittest::Cursor`
|
= help: items from traits can only be used if the trait is in scope
help: the following trait is implemented but not in scope; perhaps add a `use` for it:
|
49 | use crate::traittest::CursorTable;
|
I finally figured out a solution I can live with, in case anybody else is looking for a solution to this problem.
In your module where you define your traits, create a sub-module with all the traits, like so:
pub mod Traits
{
pub trait CursorTrait
{
fn get_handle ( &self ) -> u32; // impl's must write this function
fn fields ( &self ) -> String
{
return format! ( "(get_handle() -> {})", self.get_handle() );
}
}
}
Now in your other modules, if you want to bring the traits in scope without bringing in the entire module, you can just bring in the submodule, like so:
mod foo; use foo::Traits::*;
macro_rules! call_on_self {
($F:ident) => {
self.$F()
}
}
struct F;
impl F {
fn dummy(&self) {}
fn test(&self) {
call_on_self!(dummy);
}
}
The above doesn't work (Playground):
error[E0424]: expected value, found module `self`
--> src/lib.rs:3:9
|
3 | self.$F()
| ^^^^ `self` value is a keyword only available in methods with `self` parameter
...
11 | call_on_self!(dummy);
| --------------------- in this macro invocation
I don't understand why this is not working: the macro is invoked in the method where self is available! Is this somehow possible? Should I pass self into the macro because otherwise the macro cannot resolve self?
I'm using rustc 1.19.0-nightly.
Rust macros are not just text replacement. Instead, there are a couple of important differences, one of which is "macro hygiene". With this, identifiers inside the macro don't interfere with identifiers outside which does prevent a couple of bugs that commonly happen with macro systems like C's.
As a consequence, a macro can only access identifiers that are:
passed explicitly, or
are in scope when the macro is defined.
While it might seem like an unnecessary restriction at first, it actually helps with the readability of code. Otherwise, it's "spooky action at a distance". It's more or less the same reasoning why passing references to a variable into a function is done via some_fn(&mut foo) in Rust and is not implicit like in C++ (some_fn(foo)): it's clearer how a variable is used by a function at the call site.
This means we have two ways to fix your problem. The standard solution is to pass in self to the macro:
macro_rules! call_on_self {
($self:ident, $F:ident) => {
$self.$F()
};
}
struct F;
impl F {
fn dummy(&self) {}
fn test(&self) {
call_on_self!(self, dummy);
}
}
If you only need to use the macro inside the test method, you can define the macro inside that method. Then, self is already in scope when the macro is defined, so it works without passing self:
struct F;
impl F {
fn dummy(&self) {}
fn test(&self) {
macro_rules! call_on_self {
($F:ident) => {
self.$F()
};
}
call_on_self!(dummy);
}
}
There's also fun combinations of the two, like defining a macro that takes self explicitly and another macro defined inside the function to capture self:
macro_rules! call_on_self_outer {
($self:ident, $F:ident) => {
$self.$F()
};
}
struct F;
impl F {
fn dummy(&self) {}
fn test(&self) {
macro_rules! call_on_self {
($F:ident) => {
call_on_self_outer!(self, $F);
};
}
call_on_self!(dummy);
}
}
`
I started grouping code for one of my projects into module files. I encountered a lot of warnings about unused code for functions in those modules, but the functions are actually used (privately within the module).
An example from my project:
// ...
// Line 46:
fn calc_p(word: &str, dict: &Dictionary) -> f32
{
if !dict.contains_key(word) {
return 0.0;
}
let total: u32 = dict.values().sum();
dict[word] as f32 / total as f32
}
...
But at line 13 in the same file, same module the function is clearly used:
// ...
pub fn suggest_corrections(to_be_corrected: &str, dict: &Dictionary) -> Vec<(f32, String)>
{
let candidates = create_candidates(to_be_corrected, dict);
let mut weighted_candidates = candidates
.into_iter()
.map(|w| (calc_p(&w, dict), w)) // Line 13 - calc_p used here
.collect::<Vec<_>>();
weighted_candidates.sort_by(|a, b| b.partial_cmp(a).unwrap());
weighted_candidates
}
// ...
Yet I get the compiler warning:
warning: function is never used: `calc_p`, #[warn(dead_code)] on by default
--> src/spellcheck/corrections.rs:46:1
|
46 | fn calc_p(word: &str, dict: &Dictionary) -> f32
| _^ starting here...
47 | | {
48 | | if !dict.contains_key(word) {
49 | | return 0.0;
50 | | }
51 | |
52 | | let total: u32 = dict.values().sum();
53 | | dict[word] as f32 / total as f32
54 | | }
| |_^ ...ending here
I thought maybe it's because the module corrections is not public, but I also marked the module as public and still get the same warning.
I tried to reproduce the behaviour using the playground, but if the module is defined in the same file it seems to work. The warnings also happen for me during a TravisCI build.
Why is the function marked as unused although it's actually used in the same file in the same module?
I'm using Rust 1.15 / 1.16.
Why is the function marked as unused although it's actually used in the same file in the same module?
Because unused code is a transitive calculation, and the code that calls that function cannot be called from outside the crate. The compiler is correct here.
The first error I see is:
warning: static item is never used: `ALPHABET`, #[warn(dead_code)] on by default
--> src/spellcheck/edits.rs:3:1
That's defined as:
src/spellcheck/edits.rs
static ALPHABET : &'static str = "abcdefghijklmnopqrstuvwxyz";
So it's not public, and can only be used from inside the module.
It's called from replaces and inserts. Both of those are used from edits1, a public function. Is the module containing it (edits) public?
src/spellcheck/mod.rs
mod edits;
pub mod corrections;
pub mod dictionary;
Nope, it is not. So where is edits1 called from? kodecheck_spellcheck::spellcheck::corrections::create_candidates, a non-public function. This is called by suggest_corrections, a public function, inside the public module corrections.
Let's look up the tree...
src/lib-spellcheck.rs
// #FIXME do we really need this here or move to sub-modules?
#[macro_use]
extern crate nom;
extern crate regex;
mod spellcheck;
Ah. For whatever reason, you've decided to introduce a completely nested private module spellcheck inside the crate (which is why the full path earlier is kodecheck_spellcheck::spellcheck::corrections::create_candidates).
From this, we can see that kodecheck_spellcheck::spellcheck cannot be accessed from outside the crate; it's not pub.
Let's create an example that uses the crate. This the the best way to see if it's true and would have been easy for you to test yourself:
examples/foo.rs
extern crate kodecheck_spellcheck;
fn main() {
kodecheck_spellcheck::spellcheck::corrections::create_candidates();
}
Compiling this has the error:
error: module `spellcheck` is private
--> examples/foo.rs:4:5
|
4 | kodecheck_spellcheck::spellcheck::corrections::create_candidates();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
We could also create a MCVE:
mod spellcheck {
mod edits {
static ALPHABET: &'static str = "";
pub fn edits1() {
println!("{}", ALPHABET);
}
}
pub mod corrections {
pub fn create_candidates() {
::spellcheck::edits::edits1();
}
}
}
fn main() {}
Note that this differs from your example because main is empty. Your library crate doesn't have a mainmethod that calls anything. You could also explicitly specify that it's a library crate, but this is less well-known:
#![crate_type="lib"]
mod spellcheck {
mod edits {
static ALPHABET: &'static str = "";
pub fn edits1() {
println!("{}", ALPHABET);
}
}
pub mod corrections {
pub fn create_candidates() {
::spellcheck::edits::edits1();
}
}
}
Because there's a private module where all the code is, nothing outside this crate can call anything inside the crate. Therefore every method is unreachable.
To fix it, I'd suggest combining src/spellcheck/mod.rs into src/lib-spellcheck.rs. You could also just make the module public, but I see no reason to have the extra module.
I also see no reason to rename src/lib.rs to src/lib-spellcheck.rs; it's far more idiomatic to just leave it lib.rs.
Additionally, you should go ahead and become comfortable with Rust style. Braces go on the same line as the signature:
fn calc_p(word: &str, dict: &Dictionary) -> f32 {
// ...
Tools like rustfmt will help you apply the proper style.
I want to write a macro that prints "OK" then returns self in a method. It's my first macro, so I tried this, thinking it will just make something like a text replacement, but it fails:
macro_rules! print_ok_and_return_self {
() => {
println!("OK");
self
}
}
fn main() {
let a = A{};
a.a().a();
}
struct A {}
impl A {
fn a(self) -> Self {
print_ok_and_return_self!()
}
}
Error:
error: macro expansion ignores token `self` and any following
--> src/main.rs:4:13
|
4 | self
| ^^^^
|
note: caused by the macro expansion here; the usage of `print_ok_and_return_self!` is likely invalid in expression context
--> src/main.rs:17:13
|
17| print_ok_and_return_self!()
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^
After a quick look at the documentation, I know it's not just text replacement, but I still don't know how to make it work.
There are two errors in a row, let's fix the first one.
The syntax for a macro arm is:
(...) => {
...
}
which means that what your macro expands to is:
println!("OK");
self
which is not OK (two statements).
Instead, it should expand to an expression (in this case), which you get by enclosing it within {}:
macro_rules! print_ok_and_return_self {
() => {
{
println!("OK");
self
}
}
}
This leads to the second error:
error[E0424]: `self` is not available in a static method
--> <anon>:4:9
|
4 | self
| ^^^^ not available in static method
...
17 | print_ok_and_return_self!()
| --------------------------- in this macro invocation
|
= note: maybe a `self` argument is missing?
A macro cannot assume the existence of a variable in its scope, so you need to pass self as an argument:
macro_rules! print_ok_and_return_value {
($v:expr) => {{
println!("OK");
$v
}}
}
and the invocation becomes:
impl A {
fn a(self) -> Self {
print_ok_and_return_value!(self)
}
}