Doc comments are not real comments

Today, all doc comment formats (//!, ///, /** */ and /*! */) are treated as a syntaxic sugar of !#[doc = "..."] and #[doc = "..."] attributes. However, a direct consequence of this is errors which happen for doc comments in certain code places, while the same errors are not reported when a normal comment is used instead.

Examples of these are Doc comments causing build errors · Issue #83492 · rust-lang/rust · GitHub and Rust Playground

Normally, in most of existing languages, doc comments are not a language feature, and any doc comment is a normal comment first, i.e. ignored by a compiler and only parsed by a special doc parsers. Thus, the above compiler behavior seems weird from a language-design point of view.

My suggestion is to add to doc comment sugaring the automatic translocation of the attribute to the previous/outer language construct which may accept doc attribute. Thus,

pub enum Enum {
    Variant1 /** Some comment */,
    Variant2 /** Another comment */

will be equivalent to

pub enum Enum {
    #[doc = "Some comment"]
    #[doc = "Another comment"]

This was discussed just a couple days ago. Doing this would be a breaking change.


For reference, the prior discussion is here:

1 Like

Note, for better or for worse, that doc comments are visible to proc macros; I could hypothetically write a macro where this:

/// Presto change-o!
fn foo() {}

behaves differently than this:

fn foo() {}

EDIT: And I've been informed that this ability has actually been used in the wild: displaydoc - Rust

So the difference between doc comments and regular comments is rather thoroughly embedded in the language, and doc comments couldn't be made like regular comments without a breaking change.

I don't think it would technically be a breaking change to permit doc comments in places where they are currently errors, but I don't think it would accomplish the goal of making them be more like regular comments. And frankly, I think it's a good thing that invalid doc comments give you an error during routine builds rather than surprising you with an error only when you run rustdoc. The main problem I see here is the unintuitive error messages in that Rust issue.


@elidupree PyO3's proc macros access doc comments as well; they're visible with Python's __doc__ dunder. See Python Modules - PyO3 user guide

1 Like

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