Search code examples
rustrust-macrosmacro-rules

How to use unicode in a rust macro argument?


This is rougly what I want to use:

enum DashNumber<N> {
    NegInfinity,
    Number(N),
    Infinity,
}
macro_rules! dn {
    (-∞) => {
        DashNumber::NegInfinity
    };
    (∞) => {
        DashNumber::Infinity
    };
    ($e:expr) => {
        DashNumber::Number($e)
    };
}

however I get the following errors:

error: unknown start of token: \u{221e}
  --> src/main.rs:13:7
   |
13 |     (-∞) => {
   |       ^

error: unknown start of token: \u{221e}
  --> src/main.rs:16:6
   |
16 |     (∞) => {
   |      ^

What is wrong with this macro?


Solution

  • Macro arguments cannot be arbitrary text. They still have to be valid Rust tokens, and all types of brackets must be balanced; see MacroMatcher here.

    The character could only be possibly parsed as an identifier. However, identifiers can only start with characters from the XID_Start Unicode set, which contains "letter-like" characters, or with _. Unfortunately, ∞ is not in that set, so it can't be used as a macro argument.

    You'll have to use some alternate syntax, like quoting the symbol ("∞") or using letters (INF).