I wonder how to use a conditionally compiled module under cfg! macro. I am trying this:
pub fn f() { ... }
#[cfg(feature = "x")]
pub mod xmodule {
pub fn f() { ... }
}
pub fn test() {
if cfg!(feature = "x") {
xmodule::f();
} else {
f();
};
}
It works fine when I compile it with cargo check --features x, but if I don't enable the feature it fails with the following error:
use of undeclared type or module `xmodule`
Am I doing something wrong or the compilation is not smart enough to understand that the module should not be used if the feature is not set?
While the #[cfg] attribute will conditionally compile code, cfg! is gives the equivalent boolean value (e.g. true if a feature is enabled, false otherwise). So your code essentially compiles into:
pub fn test() {
if false { // assuming "x" feature is not set
xmodule::f();
} else {
f();
};
}
Therefore both branches must still contain valid code, even if only one is ever run.
To get actual conditional compilation, you may do something like this:
pub fn test() {
#[cfg(feature = "x")]
fn inner() {
xmodule::f()
}
#[cfg(not(feature = "x"))]
fn inner() {
f()
}
inner();
}
Playground example
Or you can use a third-party macro like cfg-if:
use cfg_if::cfg_if;
pub fn test() {
cfg_if! {
if #[cfg(feature = "x")] {
xmodule::f();
} else {
f();
}
}
}
Playground example
Related
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, currently, my code looks something like this:
// "/my_derive/lib.rs"
// inside a derive macro function
let tokens = quote! {
struct MyDeriveMacroInternalStruct {
variant: #ident_name,
// other stuff ...
}
impl #ident_name {
pub fn something() -> Vec<MyDeriveMacroInternalStruct> {
vec![MyDeriveMacroInternalStruct { variant: #ident_name::#variant_name, /*...*/ }, /*...*/]
}
}
};
tokens.into()
The usage of my code would look something like this:
use my_derive::MyDerive;
#[derive(MyDerive)]
enum Something {
A,
B,
C,
}
fn process_data() -> Vec<MyDeriveMacroInternalStruct> { // having to write that struct name that came out of nowhere bothers me
Something::something()
}
fn main() {
let result = process_data();
// do stuff...
}
This is a condensed version of my actual code (process_data is in another file). To reiterate my question in light of the example, how can I access the struct without having it randomly appear out of nowhere (due to macro expansion)? To me the code unchanged is hard to understand, read, and change.
I would like to be able to do something like this:
use my_derive::{MyDerive, MyDeriveStruct};
#[derive(MyDerive)]
enum Something {
A,
B,
C,
}
fn process_data() -> Vec<MyDeriveStruct> { // importing the struct instead of magically appearing
Something::something()
}
fn main() {
let result = process_data();
// do stuff...
}
Obviously the idea seems quite stupid, but there has to be a way around it (an arbitrary struct definition). If what I imagined isn't possible, is there some way to be more clear about where the random struct came from?
Actually I thought of something better. Your derive should probably be associated with a trait of the same name.
Add an associated type to your trait:
trait MyDerive {
type Output;
...
}
Then set the associated type when you impl the trait:
struct MyDeriveMacroInternalStruct {
variant: #ident_name,
// other stuff ...
}
impl MyDerive for #ident_name {
type Output = MyDeriveMacroInternalStruct;
pub fn something() -> Vec<MyDeriveMacroInternalStruct> {
vec![MyDeriveMacroInternalStruct { variant: #ident_name::#variant_name, /*...*/ }, /*...*/]
}
}
Then you can refer to that associated type in return position or wherever:
use my_derive::MyDerive;
#[derive(MyDerive)]
enum Something {
A,
B,
C,
}
fn process_data() -> Vec<<Something as MyDerive>::Output> {
Something::something()
}
fn main() {
let result = process_data();
// do stuff...
}
Note: the convention is for #[derive(Trait)] to correspond to an impl for the given Trait, but your proc macro crate can't export a trait directly for importing in your library code.
So generally the solution is to have two crates:
my-trait is the "library" crate which contains the MyTrait trait definition
my-trait-derive is the proc-macro crate which contains the derive macro code
my-trait has my-trait-derive as a direct dependency, and re-exports the proc macro from it:
// my-trait lib.rs
pub use my_trait_derive::MyTrait;
// macro and trait names can overlap as they're
// treated as different item kinds
pub trait MyTrait {
type Output;
fn something();
}
see how clap does it here (they also re-export the whole clap_derive)
Then a user can use your proc macro + trait like this:
use my_trait::MyTrait;
#[derive(MyTrait)]
enum Something {}
fn process_data() -> Vec<<Something as MyTrait>::Output> {
Something::something()
}
Older Answer
What I would do is create a trait MyDeriveOutput or something with whatever stuff you want exposed from MyDeriveMacroInternalStruct:
trait MyDeriveOutput {
fn variant() ...
}
And then generate an impl for each internal struct you create:
struct MyDeriveMacroInternalStruct {
variant: #ident_name,
// other stuff ...
}
impl MyDeriveOutput for MyDeriveMacroInternalStruct {
// whatever
}
Then you can expose the trait and require it to be imported and used with impl Trait in return position:
use my_derive::{MyDerive, MyDeriveOutput};
#[derive(MyDerive)]
enum Something {
A,
B,
C,
}
fn process_data() -> Vec<impl MyDeriveOutput> {
Something::something()
}
fn main() {
let result = process_data();
// do stuff...
}
I have defined a few structs in my code and if a certain feature is enabled on the crate, I would like to generate Python bindings for those structs as well. Right now I am not able to get it correctly. Let's say I have a struct MyStruct for which I want to optionally generate Python Bindings.
I have tried something like the following
cfg_if! {
if #[cfg(feature = "python-bindings")] {
#[pyclass]
}
else {
}
}
struct MyStruct{
value: i32
}
I would like to only add #[pyclass] if feature python-bindings is enabled and not otherwise.
This works fine if python-bindings is not enabled. But if I compile with --features python-bindings, I get the following error.
error: expected item after attributes
As far as possible I do not want to duplicate the code. like
cfg_if! {
if #[cfg(feature = "python-bindings")] {
#[pyclass]
struct MyStruct{
value: i32
}
}
else {
struct MyStruct{
value: i32
}
}
}
Is there a way of doing it without duplicating the code?
Yes, with #[cfg_attr]:
#[cfg_attr(feature = "python-bindings", pyclass)]
struct MyStruct {
value: i32
}
I have the following structure:
Inside queues.rs I have a #[macro_export],
#[macro_export]
macro_rules! queue {...}
but I am not sure how to import it in lib.rs.
What I have looks like this:
use crate::utils::queues::*;
// use it here
let mut service_queue: Queue<isize> = queue![];
This throws an error
error: cannot find macro `queue` in this scope
--> src/broker.rs:54:51
|
54 | let mut service_queue: Queue<isize> = queue![];
| ^^^^^
|
= note: consider importing this macro:
crate::queue
= help: have you added the `#[macro_use]` on the module/import?
What is the correct way to type #[macro_use] here, and import my custom macros from utils?
You can use the queue! macro from lib.rs using the #[macro_use] attribute (playground):
#[macro_use]
mod utils {
#[macro_use]
mod queues {
macro_rules! queue {
() => { vec![] };
}
}
}
pub fn foo() {
let _service_queue: Vec<isize> = queue![];
}
In your existing code you are using #[macro_export] which means it is declared in the crate root scope and not in the utils::queues module. In your error message you can see the compile is suggesting to consider importing this macro: crate::queue.
To access it in this case (playground):
mod utils {
mod queues {
#[macro_export]
macro_rules! queue {
() => { vec![] };
}
}
}
pub fn foo() {
let _service_queue: Vec<isize> = queue![];
}
Note that in either case the use crate::utils::queues::*; statement does not help, in fact you'll get an unused_imports warning (unless you happen to have other items declared in that module).
There is also this trick (playground):
pub mod utils {
pub mod queues {
macro_rules! queue {
() => { vec![] };
}
pub(crate) use queue;
}
}
pub fn foo() {
let _service_queue: Vec<isize> = crate::utils::queues::queue![];
}
Aside: if you plan to use the macro in other crates and you wish to retain the module hierarchy (i.e. access from my_crate::utils::queues::queue! from my_other_crate) there is a (convoluted) way to do that.
Rust has support for both pub and pub(super). pub makes it so the parent module can access an item... and pub(super) seems to also do exactly the same thing. I've tried playing with the example below, and swapping pub and pub(super) seems to have no effect:
#![allow(dead_code)]
mod outer {
pub(super) fn outer_foo() { inner::inner_foo(); }
mod inner {
pub(super) fn inner_foo() { println!("hello world!"); }
}
}
fn top_level_foo() { outer::outer_foo(); }
Why would you ever use one over the other?
Playground link.
In your example, if you change your inner module to be public, then the difference would become clear.
For example, this works because outer::inner::inner_foo is visible from the main module:
#![allow(dead_code)]
mod outer {
pub(super) fn outer_foo() { inner::inner_foo(); }
pub mod inner {
pub fn inner_foo() { println!("hello world!"); }
}
}
fn top_level_foo() { outer::outer_foo(); }
fn main() {
outer::inner::inner_foo();
}
If you kept inner_foo as pub(super) it would've been only visible from the outer module (because super refers to the super-module, outer in the case of something inside inner), hence the above code wouldn't compile and you would see this error:
|
13 | outer::inner::inner_foo();
| ^^^^^^^^^ private function
|
note: the function `inner_foo` is defined here
Notice that pub can also take crate as an argument, making the function public within the crate itself, but not to other crates.
In the code below, removing the second line will result in a compilation error saying:
type `std::io::net::tcp::TcpListener` does not implement any method in scope named `listen`
Since I am nowhere directly using Listener (even though std uses it internally), why do I need to specify it?
use std::io::{TcpListener, TcpStream};
use std::io::{Acceptor, Listener};
fn handle_client(mut stream: TcpStream) {
// ...
}
fn main() {
let args = std::os::args();
println!("{}", args);
let listener = TcpListener::bind("127.0.0.1", 80).unwrap();
let mut acceptor = listener.listen().unwrap();
for stream in acceptor.incoming() {
spawn(proc() {
handle_client(stream.unwrap());
});
}
}
It was a design decision of the language to require explicit use of traits that implement methods. For example in the following code:
use my::A;
use my::B;
mod my {
pub trait A {
fn foo(&self);
}
pub struct B;
impl B {
pub fn bar(&self) {
println!("Called `bar`.");
}
}
impl A for B {
fn foo(&self) {
println!("Called `foo`.");
}
}
}
fn main() {
// Requires "use my::B".
let b = B;
b.bar();
// Requires "use my::A".
b.foo();
}
I believe the motivation for this is heavily due to the fact that currently there is no seamless way to support multiple traits with the same method name. There is a lot of work being done to traits atm however https://github.com/rust-lang/rfcs/blob/master/active/0024-traits.md.
Listener is a trait, and your code uses its listen method, implemented by TcpListener
http://static.rust-lang.org/doc/master/std/io/trait.Listener.html