Macro undefined when test module is moved to a separate file - testing

I am writing a test for a macro I want to export. The test works as long as I keep my tests in a single file, but as soon as I put the tests module in a separate file, I get an error.
export/src/lib.rs
pub mod my_mod {
#[macro_export]
macro_rules! my_macro {
( $x:expr ) => { $x + 1 };
}
pub fn my_func(x: isize) -> isize {
my_macro!(x)
}
}
export/tests/lib.rs
#[macro_use]
extern crate export;
mod my_test_mod {
use export::my_mod;
#[test]
fn test_func() {
assert_eq!(my_mod::my_func(1), 2);
}
#[test]
fn test_macro() {
assert_eq!(my_macro!(1), 2);
}
}
Running cargo test indicates that both tests passed. If I extract my_test_mod to a file it no longer compiles.
export/src/lib.rs
Unchanged
export/tests/lib.rs
#[macro_use]
extern crate export;
mod my_test_mod;
export/tests/my_test_mod.rs
use export::my_mod;
#[test]
fn test_func() {
assert_eq!(my_mod::my_func(1), 2);
}
#[test]
fn test_macro() {
assert_eq!(my_macro!(1), 2); // error: macro undefined: 'my_macro!'
}
This gives me an error that the macro is undefined.

The problem here is that you aren't compiling what you think you are compiling. Check it out:
$ cargo test --verbose
Compiling export v0.1.0 (file:///private/tmp/export)
Running `rustc --crate-name my_test_mod tests/my_test_mod.rs ...`
When you run cargo test, it assumes that every .rs file is a test to be run. It doesn't know that my_test_mod.rs should only be compiled as part of another test!
The easiest solution is to move your module to the other valid module location, in a separate directory: tests/my_test_mod/mod.rs. Cargo will not recursively look inside the directory for test files.

Related

How to generate documentation for modules that are behind #[cfg(test)]?

In a Rust project there is a module with utilities to support testing, packed in a module test_utils:
#[cfg(test)]
pub mod test_utils;
Is there a way to make cargo doc generate also the documentation for test_utils module and the things inside?
There are probably multiple ways of generating documentation for tests, but I think the easier approach is to generate the documentation with cargo rustdoc and pass the --cfg test flag through:
cargo rustdoc -- --cfg test
I just found that this works too:
#[cfg(any(test, doc))]
pub mod test_utils;
While documentation is generated with regular
cargo doc
I think #[cfg(any(test, doc))] is probably not enough, it will generate doc with no function information.
/// The module should work
#[cfg(any(test, doc))]
pub mod test_utils {
/// The function about test1
#[test]
fn test1() {
assert!(true);
}
}
In order to doc with utilities to support testing, perhaps [cfg_attr(not(doc), test)] is necessary.
/// The module should work
#[cfg(any(test, doc))]
pub mod test_utils {
/// The function about test1
#[cfg_attr(not(doc), test)]
fn test1() {
assert!(true);
}
}
After added [cfg_attr(not(doc), test)] above test cases:

How to dynamically call a function in a shared library?

I have a Rust project, set as an executable. I am trying to call an external shared library, also written in Rust, dynamically. I have the external library compiled on release, and I have tried both crate types cdylib and dylib.
I am using the crate libloading, which claims to be able to dynamically load shared library functions, as long as they only use primitive arguments. I keep getting this error when I try to run my code using this crate.
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: GetProcAddress { source: Os { code: 127, kind: Other, message: "The specified procedure could not be found." } }', src\main.rs:14:68
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
main.rs/main():
let now = Instant::now();
unsafe {
let lib = libloading::Library::new(
"externtest.dll").unwrap();
let foo3: Symbol<extern fn(i32) -> i32> = lib.get(b"foo").unwrap();
println!("{}", foo(1));
}
let elapsed = now.elapsed();
println!("Elapsed: {:?}", elapsed);
lib.rs:
pub extern "C" fn foo3(i:i32) -> i32{
i
}
First, your library function is called "foo3", but you're trying to load the symbol "foo".
Second, the library function's symbol may not match it's name due to mangling. You need to tell the compiler not to do that with the #[no_mangle] attribute:
#[no_mangle]
pub extern "C" fn foo(i: i32) -> i32 {
i
}
Third, this is mostly a stylistic choice, but I'd specify the ABI extern "C" when defining your symbol. Even though extern with no epecified ABI uses the "C" ABI, I've found it better to be explicit.
use libloading::{Library, Symbol};
fn main() {
unsafe {
let lib = Library::new("externtest.dll").unwrap();
let foo = lib
.get::<Symbol<extern "C" fn(i32) -> i32>>(b"foo")
.unwrap();
println!("{}", foo(1));
}
}
The above should work without issue.

How to access the function in main.rs which has been written in a file in different directory in rust in same package [duplicate]

This question already has answers here:
How can I include a module from another file from the same project?
(6 answers)
How do I "use" or import a local Rust file? [duplicate]
(1 answer)
Closed 3 years ago.
I want to call a function inside a main.rs file. I have made one directory name "library" inside the same src folder as main.rs exist.
src/main.rs
mod library;
fn main() {
println!("{}", library::name1::name(4));
}
src/library/file.rs
pub mod name1 {
pub fn name(a: i32) -> i32 {
println!("from diff file {}", a);
a * a
}
}
when I call this function name in main.rs, compiler throws an error:
error[E0583]: file not found for module library
I think I am missing something. What is the correct way to do this? Keep in mind that the library directory is just an ordinary directory not a cargo package
You can fix this issue in 2 different ways:
1 ) Using Module
2 ) Using Library
Using Module
Simply create a file next to main.rs in src directory and name it name1.rs
name1.rs will look like:
//no need to specify "pub mod name1;" explicitly
pub fn name(a: i32) -> i32 {
println!("from diff file {}", a);
a * a
}
main.rs will look like:
//name of the second file will be treated as module here
pub mod name1;
fn main() {
println!("{}", name1::name(4));
}
Using Library
a) create a library, standing in main project directory (i.e. parent of src directory) and run the command below:
//In your case library name "file"
$ cargo new --lib file
This command will create another directory of name file same as your main project.
b) Add this library(file) in the dependency section of Cargo.toml file of main project
[package]
name = "test_project"
version = "0.1.0"
authors = ["mohammadrajabraza <mohammadrajabraza#gmail.com>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
file = {path ="file"}
c) A file under main_project>file(library)>src>lib.rs will be created, once you created library using command above.
lib.rs will be look like:
pub fn name(a: i32) -> i32 {
println!("from diff file {}", a);
a * a
}
d) and finally your main.rs will be:
//importing library in thescope
use file;
fn main() {
println!("{}", file::name(4));
}
Create a file in src directory named as library.rs and than in library.rs write the following code:
pub mod file;
Than access the same function from your main file as you are doing right now.Than it will work properly.
You can follow this method too
https://github.com/Abdul-sid/PIAIC-IOT-RUST-CLASS/tree/master/13th-Oct-chapter-7-part-2/dir-mod-bin/src
You can use the concept of library which rust have in it.
Simply making a library project having the --lib flag.
cargo build library --lib
After doing it. You will write this in your dependency section in Cargo.toml.
library = {path = "./src/library"}
You can even use the absolute path of your directory.
library = {path = "C:/Users/Admin/Desktop/Rust/jawwad/src/library"}
Then write your library code in lib.rs file.
pub mod name1 {
pub fn name(a: i32) -> i32 {
println!("from diff file {}", a);
a * a
}
}
Here is the main.rs file.
use library;
fn main() {
println!("{}", library::name1::name(4));
}

"macro undefined" when reading u8 using scan!()

I read about reading integer input in How to read an integer input from the user in Rust 1.0?, but I noticed that all the solutions first take a string as input and then convert it to integer. I wonder if there's a way to read an integer directly.
This page mentions scan!() macro but for some reason it doesn't seem to run when I compile the following program using rustc main.rc.
extern crate text_io;
fn main() {
let mut a: u8;
let mut b: u8;
scan!("{},{}", a, b);
print!("{} {}", a, b);
}
This produces the error:
error: macro undefined: 'scan!'
scan!("{},{}",a,b);
You have to explicitly say that you want to import macros from this crate:
#[macro_use] extern crate text_io;
This is written at the very top of the readme, you must have missed it.
To use crates from crates.io, you need to add them to your Cargo.toml, for example by adding the following lines to that file:
[dependencies]
text_io = "0.1"

How do I use a macro across module files?

I have two modules in separate files within the same crate, where the crate has macro_rules enabled. I want to use the macros defined in one module in another module.
// macros.rs
#[macro_export] // or not? is ineffectual for this, afaik
macro_rules! my_macro(...)
// something.rs
use macros;
// use macros::my_macro; <-- unresolved import (for obvious reasons)
my_macro!() // <-- how?
I currently hit the compiler error "macro undefined: 'my_macro'"... which makes sense; the macro system runs before the module system. How do I work around that?
Macros within the same crate
New method (since Rust 1.32, 2019-01-17)
foo::bar!(); // works
mod foo {
macro_rules! bar {
() => ()
}
pub(crate) use bar; // <-- the trick
}
foo::bar!(); // works
With the pub use, the macro can be used and imported like any other item. And unlike the older method, this does not rely on source code order, so you can use the macro before (source code order) it has been defined.
Old method
bar!(); // Does not work! Relies on source code order!
#[macro_use]
mod foo {
macro_rules! bar {
() => ()
}
}
bar!(); // works
If you want to use the macro in the same crate, the module your macro is defined in needs the attribute #[macro_use]. Note that macros can only be used after they have been defined!
Macros across crates
Crate util
#[macro_export]
macro_rules! foo {
() => ()
}
Crate user
use util::foo;
foo!();
Note that with this method, macros always live at the top-level of a crate! So even if foo would be inside a mod bar {}, the user crate would still have to write use util::foo; and not use util::bar::foo;. By using pub use, you can export a macro from a module of your crate (in addition to it being exported at the root).
Before Rust 2018, you had to import macro from other crates by adding the attribute #[macro_use] to the extern crate util; statement. That would import all macros from util. This syntax should not be necessary anymore.
Alternative approach as of 1.32.0 (2018 edition)
Note that while the instructions from #lukas-kalbertodt are still up to date and work well, the idea of having to remember special namespacing rules for macros can be annoying for some people.
EDIT: it turns out their answer has been updated to include my suggestion, with no credit mention whatsoever ๐Ÿ˜•
On the 2018 edition and onwards, since the version 1.32.0 of Rust, there is another approach which works as well, and which has the benefit, imho, of making it easier to teach (e.g., it renders #[macro_use] obsolete). The key idea is the following:
A re-exported macro behaves as any other item (function, type, constant, etc.): it is namespaced within the module where the re-export occurs.
It can then be referred to with a fully qualified path.
It can also be locally used / brought into scope so as to refer to it in an unqualified fashion.
Example
macro_rules! macro_name { ... }
pub(crate) use macro_name; // Now classic paths Just Workโ„ข
And that's it. Quite simple, huh?
Feel free to keep reading, but only if you are not scared of information overload ;) I'll try to detail why, how and when exactly does this work.
More detailed explanation
In order to re-export (pub(...) use ...) a macro, we need to refer to it! That's where the rules from the original answer are useful: a macro can always be named within the very module where the macro definition occurs, but only after that definition.
macro_rules! my_macro { ... }
my_macro!(...); // OK
// Not OK
my_macro!(...); /* Error, no `my_macro` in scope! */
macro_rules! my_macro { ... }
Based on that, we can re-export a macro after the definition; the re-exported name, then, in and of itself, is location agnostic, as all the other global items in Rust ๐Ÿ™‚
In the same fashion that we can do:
struct Foo {}
fn main() {
let _: Foo;
}
We can also do:
fn main() {
let _: A;
}
struct Foo {}
use Foo as A;
The same applies to other items, such as functions, but also to macros!
fn main() {
a!();
}
macro_rules! foo { ... } // foo is only nameable *from now on*
use foo as a; // but `a` is now visible all around the module scope!
And it turns out that we can write use foo as foo;, or the common use foo; shorthand, and it still works.
The only question remaining is: pub(crate) or pub?
For #[macro_export]-ed macros, you can use whatever privacy you want; usually pub.
For the other macro_rules! macros, you cannot go above pub(crate).
Detailed examples
For a non-#[macro_export]ed macro
mod foo {
use super::example::my_macro;
my_macro!(...); // OK
}
mod example {
macro_rules! my_macro { ... }
pub(crate) use my_macro;
}
example::my_macro!(...); // OK
For a #[macro_export]-ed macro
Applying #[macro_export] on a macro definition makes it visible after the very module where it is defined (so as to be consistent with the behavior of non-#[macro_export]ed macros), but it also puts the macro at the root of the crate (where the macro is defined), in an absolute path fashion.
This means that a pub use macro_name; right after the macro definition, or a pub use crate::macro_name; in any module of that crate will work.
Note: in order for the re-export not to collide with the "exported at the root of the crate" mechanic, it cannot be done at the root of the crate itself.
pub mod example {
#[macro_export] // macro nameable at `crate::my_macro`
macro_rules! my_macro { ... }
pub use my_macro; // macro nameable at `crate::example::my_macro`
}
pub mod foo {
pub use crate::my_macro; // macro nameable at `crate::foo::my_macro`
}
When using the pub / pub(crate) use macro_name;, be aware that given how namespaces work in Rust, you may also be re-exporting constants / functions or types / modules. This also causes problems with globally available macros such as #[test], #[allow(...)], #[warn(...)], etc.
In order to solve these issues, remember you can rename an item when re-exporting it:
macro_rules! __test__ { ... }
pub(crate) use __test__ as test; // OK
macro_rules! __warn__ { ... }
pub(crate) use __warn__ as warn; // OK
Also, some false positive lints may fire:
from the trigger-happy clippy tool, when this trick is done in any fashion;
from rustc itself, when this is done on a macro_rules! definition that happens inside a function's body: https://github.com/rust-lang/rust/issues/78894
This answer is outdated as of Rust 1.1.0-stable.
You need to add #![macro_escape] at the top of macros.rs and include it using mod macros; as mentioned in the Macros Guide.
$ cat macros.rs
#![macro_escape]
#[macro_export]
macro_rules! my_macro {
() => { println!("hi"); }
}
$ cat something.rs
#![feature(macro_rules)]
mod macros;
fn main() {
my_macro!();
}
$ rustc something.rs
$ ./something
hi
For future reference,
$ rustc -v
rustc 0.13.0-dev (2790505c1 2014-11-03 14:17:26 +0000)
Adding #![macro_use] to the top of your file containing macros will cause all macros to be pulled into main.rs.
For example, let's assume this file is called node.rs:
#![macro_use]
macro_rules! test {
() => { println!("Nuts"); }
}
macro_rules! best {
() => { println!("Run"); }
}
pub fn fun_times() {
println!("Is it really?");
}
Your main.rs would look sometime like the following:
mod node; //We're using node.rs
mod toad; //Also using toad.rs
fn main() {
test!();
best!();
toad::a_thing();
}
Finally let's say you have a file called toad.rs that also requires these macros:
use node; //Notice this is 'use' not 'mod'
pub fn a_thing() {
test!();
node::fun_times();
}
Notice that once files are pulled into main.rs with mod, the rest of your files have access to them through the use keyword.
I have came across the same problem in Rust 1.44.1, and this solution works for later versions (known working for Rust 1.7).
Say you have a new project as:
src/
main.rs
memory.rs
chunk.rs
In main.rs, you need to annotate that you are importing macros from the source, otherwise, it will not do for you.
#[macro_use]
mod memory;
mod chunk;
fn main() {
println!("Hello, world!");
}
So in memory.rs you can define the macros, and you don't need annotations:
macro_rules! grow_capacity {
( $x:expr ) => {
{
if $x < 8 { 8 } else { $x * 2 }
}
};
}
Finally you can use it in chunk.rs, and you don't need to include the macro here, because it's done in main.rs:
grow_capacity!(8);
The upvoted answer caused confusion for me, with this doc by example, it would be helpful too.
Note: This solution does work, but do note as #ineiti highlighted in the comments, the order u declare the mods in the main.rs/lib.rs matters, all mods declared after the macros mod declaration try to invoke the macro will fail.