Raw identifiers don't work for all identifiers

The 2018 edition saw the introduction of raw identifiers.

However, it doesn’t work for the Self identifier/keyword:

enum Foo {
    Self // Error: expected identifier, got keyword `Self`
}
enum Bar {
    r#Self // Error: r#Self is not currently supported
}

Could support for this be implemented in the next Rust release?

I don’t know why this restriction exists, but in case this helps someone else answer: here is the list of keywords that are not supported in r#.

  • r#super
  • r#self
  • r#Self
  • r#extern
  • r#crate
5 Likes

cc @petrochenkov

These are identifiers that can be used in paths, and therefore can go through name resolution.
https://github.com/rust-lang/rust/issues/48589 has some discussion about this.

The “rawness” property belongs to the token world and is lost after tokens are parsed into something semantic (by design, I’d say).
So r#Self would be treated exactly like Self during name resolution and later, so if you create a type named Self you won’t be able to refer to it. That’s confusing and that’s why Self was made a keyword in the first place (https://github.com/rust-lang/rfcs/pull/593).

To support raw path segment identifiers we either need to rework resolve (and perhaps type checking, due to Self parameters) to work in the world where Self/crate/super can be both reserved names with special meaning and regular item names (e.g. introduce some priorities).

Or we can prohibit defining items (and other names to which paths may resolve, like type parameters) with same names as path segment keywords.

Or we can keep the rawness property until resolve/type-check and consider Self and r#Self different names (that would be bad ideologically and also messy from implementation point of view).

Or we can just keep the restriction on raw identifiers.

4 Likes

r#_ is also prohibited for similar reasons.

1 Like

For now I solved it (quite hackily IMO) by renaming the variant SelfKw, which meant I needed to write custom from_str() and to_str() methods to keep it translatable from/to the self string literal.

The Display impl for the enum then uses the to_str() method.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.