Unresolved import; can't find crate/modules in macro no matter what I do


#1

I’m trying to use the unicode-segmentation crate in some macros I’m writing. I’ve added “unicode-segmentation” = "version = “^0.1.2” to my Cargo.toml file. Then I added “extern crate unicode_segmentation” and “use unicode_segmentation::UnicodeSegmentation” all over the place. I put it in lib.rs, I put it in the file I use it in, I put it in the test module (it only complains when I run cargo test), I even put it directly in the macro definition (which actually helped with the same problem I had trying to use HashSets), but to no avail. I just get more error: can't find crate for unicode_segmentation and error: unresolved import unicode_segmentation::*. Did you mean self::unicode_segmentation? and error: unresolved name UnicodeSegmentation::grapheme_indices errors. I’ve also tried pub use everywhere too.

I’m not going to show you all the different places I try to declare it, but here’s one attempt:

#[macro_export]
macro_rules! take_till_s (
  ($input:expr, $submac:ident!( $($args:tt)* )) => (
    {
      extern crate unicode_segmentation;
      use unicode_segmentation::*;
      let mut offset = $input.len();
      for (o, s) in UnicodeSegmentation::grapheme_indices($input, true) {
        if $submac!(s, $($args)*) {
            offset = o;
            break;
        }
      }
      if offset < $input.len() {
        $crate::IResult::Done(&$input[offset..], &$input[..offset])
      } else {
        $crate::IResult::Done("", $input)
      }
    }
  );
  ($input:expr, $f:expr) => (
    take_till_s!($input, call!($f));
  );
);

I have other macros where declaring HashMap inside the macro finally got the compiler to recognize the import, but no such luck in this case. What could I possibly do to use the unicode_segmentation crate in my macros?


#2

It’s not going to work like this. use cannot be used to access names defined inside a function. You should just be able to use unicode_segmentation::UnicodeSegmentation instead.

However, this would be a bad idea because it requires any crate that uses this macro to also explicitly depend on unicode_segmentation. No, it’s worse: depend on a semver compatible version of unicode_segmentation that the macro was written against.

It’s far simpler to link to unicode_segmentation in your crate, publicly re-export it (either the whole crate, or just the things you need), and then access those names via $crate.