Get module resolution entry point in proc-macros

327 views Asked by At

My question is: Is there a way to get the exact module resolution entry point in the proc-macro stage?

First off some background info on what I'm trying to achieve.

I'm in the process of writing a crate that can automatically implement various traits on a struct, such as PartialEq and Into. This is somewhat special since these traits involve other structs that can theoretically be located anywhere else. I then need to get the actual tokens of that struct, so I can do some crude type checking and automatically map fields that have the same names.

For this reason, I'm doing some crude module resolution of my own by searching the file tree and parsing some files in the current crate.

Such an invocation currently looks like this:

#[derive(InterStruct)]
#[into("crate::into_test::IntoStruct")]
pub struct FromStruct {
...
}

This will now implement

impl From<FromStruct> for crate::into_test::IntoStruct {
    fn from(from: FromStruct) -> Self {
    ...
    }
}

This logic already works, if the module containing the struct is located in the $CARGO_MANIFEST_DIR/src folder.

However, if I would want to run this logic in an integration tests folder, this is where it gets tricky.

I couldn't find a way to detect the actual entry point for module resolution during the proc-macro stage. The only thing that's exposed is the $CARGO_MANIFEST_DIR, but there seems to be now way to detect whether we start at src/main.rs, src/lib.rs or tests/some_test.rs.

This get's even more complicated as I'm currently trying to test compile time errors via compiletest-rs. compiletest-rs (if I understood correctly) creates a temporary directory, copies the file to test to $TEMPDIR/main.rs and directly calls rustc with the exact path to the dependency directories of your project (e.g. '-L target/debug').

Since there's no cargo involved, the rustc call inherits the $CARGO_MANIFEST_DIR environment variable from the parent process. This then points to the actual crate root instead of the $TEMPDIR.

I would really like to properly test the error cases of my crate, but I can't find a way to get the module resolution entry point in the proc-macro stage.

0

There are 0 answers