注释
词法分析器
LINE_COMMENT
//
(~[/
!
\n
] |//
) ~\n
*
|//
BLOCK_COMMENT
/*
(~[*
!
] |**
| BlockCommentOrDoc) (BlockCommentOrDoc | ~*/
)**/
|/**/
|/***/
INNER_LINE_DOC
//!
~[\n
IsolatedCR]*INNER_BLOCK_DOC
/*!
( BlockCommentOrDoc | ~[*/
IsolatedCR] )**/
OUTER_LINE_DOC
///
(~/
~[\n
IsolatedCR]*)?OUTER_BLOCK_DOC
/**
(~*
| BlockCommentOrDoc ) (BlockCommentOrDoc | ~[*/
IsolatedCR])**/
BlockCommentOrDoc :
BLOCK_COMMENT
| OUTER_BLOCK_DOC
| INNER_BLOCK_DOCIsolatedCR :
\r
非文档注释
注释遵循通用的 C++ 风格的行 (//
) 和块 (/* ... */
) 注释形式。支持嵌套块注释。
非文档注释被解释为空白符的一种形式。
文档注释
以三个斜杠 (///
) 开头的行文档注释和块文档注释 (/** ... */
) 都是外部文档注释,它们被解释为 doc
属性的特殊语法。
也就是说,它们等同于在注释主体周围编写 #[doc="..."]
,例如,/// Foo
变为 #[doc="Foo"]
,而 /** Bar */
变为 #[doc="Bar"]
。 因此,它们必须出现在接受外部属性的事物之前。
以 //!
开头的行注释和块注释 /*! ... */
是应用于注释的父级而不是跟随项的文档注释。
也就是说,它们等同于在注释主体周围编写 #![doc="..."]
。 //!
注释通常用于文档化占据源文件的模块。
字符 U+000D
(CR) 不允许在文档注释中使用。
注意:按照惯例,文档注释应包含 Markdown,正如
rustdoc
所期望的那样。但是,注释语法不遵守任何内部 Markdown。/** `glob = "*/*.rs";` */
会在第一个*/
处终止注释,剩余的代码将导致语法错误。 这稍微限制了块文档注释的内容,与行文档注释相比。
注意:序列
U+000D
(CR) 紧随U+000A
(LF) 之后之前会被转换为单个U+000A
(LF)。
示例
#![allow(unused)] fn main() { //! A doc comment that applies to the implicit anonymous module of this crate pub mod outer_module { //! - Inner line doc //!! - Still an inner line doc (but with a bang at the beginning) /*! - Inner block doc */ /*!! - Still an inner block doc (but with a bang at the beginning) */ // - Only a comment /// - Outer line doc (exactly 3 slashes) //// - Only a comment /* - Only a comment */ /** - Outer block doc (exactly) 2 asterisks */ /*** - Only a comment */ pub mod inner_module {} pub mod nested_comments { /* In Rust /* we can /* nest comments */ */ */ // All three types of block comments can contain or be nested inside // any other type: /* /* */ /** */ /*! */ */ /*! /* */ /** */ /*! */ */ /** /* */ /** */ /*! */ */ pub mod dummy_item {} } pub mod degenerate_cases { // empty inner line doc //! // empty inner block doc /*!*/ // empty line comment // // empty outer line doc /// // empty block comment /**/ pub mod dummy_item {} // empty 2-asterisk block isn't a doc block, it is a block comment /***/ } /* The next one isn't allowed because outer doc comments require an item that will receive the doc */ /// Where is my item? mod boo {} } }