#[f]"Hello, {world}" - meet Prefixes, an attribute-like macro suite with prefixes for various literals

68 points sasik520

After discussing string prefixes here, I decided to experiment with attribute-like macros that could do the job. The effect is quite interesting. Although it requires using two nightly features, I find it really decent and promising.

The main advantage is reduced cognitive load - #[f]"foo" is simpler for the brain than format!("foo"), not just because it's shorter (although that helps), but because it doesn't have enclosing parentheses, so it's one less nesting level.

#![feature(stmt_expr_attributes, proc_macro_hygiene)]

use prefixes::{f, ms, P, s};

fn _deep_thought2() -> String {
    let answer_path = #[P]"./answer.txt";
    let answer = if answer_path.exists() {
        std::fs::read_to_string(&answer_path).unwrap()
    } else {
        std::thread::sleep(#[s]6 + #[ms]9);
        #[f]"42"
    };

    #[f]"Answer to the Ultimate Question of Life, the Universe, and Everything = {answer}"
}

As an experiment, I added:

  • #[f] as a shorthand for format!
  • #[ms] as a shorthand for Duration::from_millis
  • #[os] as a shorthand for OsStr::new
  • #[OS] as a shorthand for OsString::from
  • #[p] as a shorthand for Path::new
  • #[P] as a shorthand for PathBuf::from
  • #[re] as a shorthand for Regex::new
  • #[RE] as a shorthand for Regex::new(...).unwrap()
  • #[s] as a shorthand for Duration::from_secs/Duration::from_secs_f32/Duration::from_secs_f64

All ideas and comments are more than welcome; I'm absolutely curious what do you think about this experiment!

GitHub repo
Crates.io
Docs.rs