Skip to content

Doc comments can be passed to macros as literals #61001

Open
@petrochenkov

Description

@petrochenkov

Doc comments are the only tokens that cannot be passed to macros precisely, they are converted into a #[doc = "text"] form instead, which is a pretty big hack.
This conversion may change escaping in the text irrecoverably and can also change semantics in corner cases (e.g. doc starts going through name resolution).
Also, this is the single reason why doc comments may need a conversion at all (#60935).

Lexically doc comments are raw string literals with weird quotes (/** + */ and /// + \n).
Syntactically they certainly can be interpreted as attribute literals, similarly to how strings or integers are expression literals, and how ! would be a type literal if it wasn't a punctuation lexically.
We can use this intuition for fixing the situation with passing doc comments to macros.

Declarative macros

The recently introduced literal matcher can start matching doc comments.

macro m($doc: literal) {
    $doc
    struct S;
}

m!(/** text */);

I don't think there are going to be any implementation issues with that.

Proc macros

We cannot add a new variant to TokenTree backward compatibly, but the content of TokenTree::Literal is only available through to_string() and is open for additions.

So, literal.to_string() can start returning things like /// Text.
Of course, syn and friends must be ready to get a result like this from stringifying a literal token.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-frontendArea: Compiler frontend (errors, parsing and HIR)A-macrosArea: All kinds of macros (custom derive, macro_rules!, proc macros, ..)C-enhancementCategory: An issue proposing an enhancement or a PR with one.T-langRelevant to the language team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions