use crate::{
CppSyntaxNode, DocCommandKind, command_kind, is_documentation_comment,
kind::{CppSyntaxKind, CppTokenKind},
syntax::traits::{CppAstChildren, CppAstNode},
};
use super::{CppDeclaration, CppGeneralToken, CppNameExpr};
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppDocComment {
syntax: CppSyntaxNode,
}
impl CppAstNode for CppDocComment {
fn syntax(&self) -> &CppSyntaxNode {
&self.syntax
}
fn can_cast(kind: CppSyntaxKind) -> bool {
kind == CppSyntaxKind::DocComment
}
fn cast(syntax: CppSyntaxNode) -> Option<Self> {
Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
}
}
impl CppDocComment {
pub fn get_body(&self) -> Option<CppDocCommentBody> {
self.child()
}
pub fn get_commands(&self) -> impl Iterator<Item = CppDocCommand> {
self.descendants()
}
pub fn get_command(&self, name: &str) -> Option<CppDocCommand> {
self.get_commands()
.find(|command| command.get_name().as_deref() == Some(name))
}
pub fn get_commands_of_kind(
&self,
kind: DocCommandKind,
) -> impl Iterator<Item = CppDocCommand> {
self.get_commands()
.filter(move |command| command.get_kind() == Some(kind))
}
pub fn get_items(&self) -> impl Iterator<Item = CppDocItem> {
self.descendants()
}
pub fn get_comment_text(&self) -> String {
let text = self.syntax.text().to_string();
comment_lines(&text, text.trim_start().starts_with("/*")).join("\n")
}
pub fn is_documentation(&self) -> bool {
is_documentation_comment(&self.syntax.text().to_string())
}
pub fn get_owner(&self) -> Option<CppSyntaxNode> {
next_construct(self.syntax())
}
pub fn get_documented_declaration(&self) -> Option<CppDeclaration> {
if self.is_trailing() {
return None;
}
let mut current = next_construct(self.syntax());
while let Some(node) = current {
match CppSyntaxKind::from(node.kind()) {
CppSyntaxKind::Declaration => return CppDeclaration::cast(node),
CppSyntaxKind::UsingDecl => return CppDeclaration::cast(node),
CppSyntaxKind::TemplateDecl => return CppDeclaration::cast(node),
CppSyntaxKind::PreprocessorDirective => current = next_construct(&node),
_ => return None,
}
}
None
}
pub fn is_trailing(&self) -> bool {
let text = self.syntax.text().to_string();
let first = text.lines().next().unwrap_or_default().trim_start();
first.starts_with("///<")
|| first.starts_with("//!<")
|| first.starts_with("/**<")
|| first.starts_with("/*!<")
}
pub fn get_documented_name(&self) -> Option<String> {
let declaration = self.get_documented_declaration()?;
if let Some(name) = declaration.get_name_text() {
return Some(name);
}
super::traits::first_child_of_kind(declaration.syntax(), &[CppSyntaxKind::NameExpr])
.and_then(CppNameExpr::cast)
.and_then(|name| name.get_name_token())
.map(|token| token.get_name_text().to_string())
}
}
fn next_construct(node: &CppSyntaxNode) -> Option<CppSyntaxNode> {
let mut current = node.clone();
loop {
if let Some(sibling) = current
.siblings_with_tokens(rowan::Direction::Next)
.skip(1)
.find_map(|element| element.into_node())
{
return Some(sibling);
}
current = current.parent()?;
}
}
pub fn documentation_of(node: &CppSyntaxNode) -> Option<CppDocComment> {
let mut candidate = previous_construct(node);
while let Some(before) = candidate {
match CppSyntaxKind::from(before.kind()) {
CppSyntaxKind::DocComment => {
let comment = CppDocComment::cast(before)?;
return documents_it(&comment, node).then_some(comment);
}
CppSyntaxKind::PreprocessorDirective => candidate = previous_construct(&before),
_ => {
let comment = last_comment_in(&before)?;
return documents_it(&comment, node).then_some(comment);
}
}
}
None
}
fn previous_construct(node: &CppSyntaxNode) -> Option<CppSyntaxNode> {
let mut current = node.clone();
loop {
if let Some(sibling) = current
.siblings_with_tokens(rowan::Direction::Prev)
.skip(1)
.find_map(|element| element.into_node())
{
return Some(sibling);
}
current = current.parent()?;
}
}
fn last_comment_in(node: &CppSyntaxNode) -> Option<CppDocComment> {
node.descendants().filter_map(CppDocComment::cast).last()
}
fn documents_it(comment: &CppDocComment, node: &CppSyntaxNode) -> bool {
if comment.is_trailing() {
return false;
}
comment.get_owner().is_some_and(|owner| owner == *node)
|| comment
.get_documented_declaration()
.is_some_and(|documented| documented.syntax() == node)
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppDocCommentBody {
syntax: CppSyntaxNode,
}
impl CppAstNode for CppDocCommentBody {
fn syntax(&self) -> &CppSyntaxNode {
&self.syntax
}
fn can_cast(kind: CppSyntaxKind) -> bool {
kind == CppSyntaxKind::DocCommentBody
}
fn cast(syntax: CppSyntaxNode) -> Option<Self> {
Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
}
}
impl CppDocCommentBody {
pub fn get_text(&self) -> String {
self.syntax.text().to_string().trim().to_string()
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppDocCommand {
syntax: CppSyntaxNode,
}
impl CppAstNode for CppDocCommand {
fn syntax(&self) -> &CppSyntaxNode {
&self.syntax
}
fn can_cast(kind: CppSyntaxKind) -> bool {
kind == CppSyntaxKind::DocCommand
}
fn cast(syntax: CppSyntaxNode) -> Option<Self> {
Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
}
}
impl CppDocCommand {
pub fn get_name_token(&self) -> Option<CppGeneralToken> {
self.token_by_kind(CppTokenKind::DocCommandName)
}
pub fn get_name(&self) -> Option<String> {
Some(self.get_name_token()?.get_text().to_string())
}
pub fn get_kind(&self) -> Option<DocCommandKind> {
command_kind(&self.get_name()?)
}
pub fn get_args(&self) -> CppAstChildren<CppDocCommandArg> {
self.children()
}
pub fn get_argument(&self) -> Option<CppDocCommandArg> {
self.get_args().last()
}
pub fn get_argument_text(&self) -> Option<String> {
self.get_argument().map(|argument| argument.get_text())
}
pub fn get_body(&self) -> Option<CppDocCommandBody> {
self.child()
}
pub fn get_body_text(&self) -> Option<String> {
self.get_body().map(|body| body.get_text())
}
pub fn get_code_block(&self) -> Option<CppDocCodeBlock> {
self.descendants()
.next()
.or_else(|| self.syntax().next_sibling().and_then(CppDocCodeBlock::cast))
}
pub fn get_code_text(&self) -> Option<String> {
Some(self.get_code_block()?.get_code_text())
}
pub fn is_callout(&self) -> bool {
self.get_kind() == Some(DocCommandKind::Callout)
}
pub fn is_description(&self) -> bool {
self.get_kind() == Some(DocCommandKind::Description)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppDocCommandBody {
syntax: CppSyntaxNode,
}
impl CppAstNode for CppDocCommandBody {
fn syntax(&self) -> &CppSyntaxNode {
&self.syntax
}
fn can_cast(kind: CppSyntaxKind) -> bool {
kind == CppSyntaxKind::DocCommandBody
}
fn cast(syntax: CppSyntaxNode) -> Option<Self> {
Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
}
}
impl CppDocCommandBody {
pub fn get_text(&self) -> String {
self.syntax.text().to_string().trim().to_string()
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppDocCommandArg {
syntax: CppSyntaxNode,
}
impl CppAstNode for CppDocCommandArg {
fn syntax(&self) -> &CppSyntaxNode {
&self.syntax
}
fn can_cast(kind: CppSyntaxKind) -> bool {
kind == CppSyntaxKind::DocCommandArg
}
fn cast(syntax: CppSyntaxNode) -> Option<Self> {
Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
}
}
impl CppDocCommandArg {
pub fn get_text(&self) -> String {
self.syntax.text().to_string().trim().to_string()
}
pub fn is_direction(&self) -> bool {
self.get_direction().is_some()
}
pub fn get_direction(&self) -> Option<String> {
let text = self.get_text();
let inner = text.strip_prefix('[')?.strip_suffix(']')?.trim();
(!inner.is_empty()).then(|| inner.to_string())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppDocCodeBlock {
syntax: CppSyntaxNode,
}
impl CppAstNode for CppDocCodeBlock {
fn syntax(&self) -> &CppSyntaxNode {
&self.syntax
}
fn can_cast(kind: CppSyntaxKind) -> bool {
kind == CppSyntaxKind::DocCodeBlock
}
fn cast(syntax: CppSyntaxNode) -> Option<Self> {
Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
}
}
impl CppDocCodeBlock {
pub fn get_code_text(&self) -> String {
let mut lines = comment_lines(
&self.syntax.text().to_string(),
is_in_block_comment(&self.syntax),
);
if lines
.last()
.is_some_and(|line| is_block_marker(line, "endcode"))
{
lines.pop();
}
if lines
.first()
.is_some_and(|line| is_block_marker(line, "code"))
{
lines.remove(0);
}
lines.join("\n")
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CppDocInline {
syntax: CppSyntaxNode,
}
impl CppAstNode for CppDocInline {
fn syntax(&self) -> &CppSyntaxNode {
&self.syntax
}
fn can_cast(kind: CppSyntaxKind) -> bool {
kind == CppSyntaxKind::DocInline
}
fn cast(syntax: CppSyntaxNode) -> Option<Self> {
Self::can_cast(syntax.kind().into()).then_some(Self { syntax })
}
}
impl CppDocInline {
pub fn get_text(&self) -> String {
self.syntax.text().to_string().trim().to_string()
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum CppDocItem {
Command(CppDocCommand),
Body(CppDocCommandBody),
Inline(CppDocInline),
CodeBlock(CppDocCodeBlock),
}
impl CppAstNode for CppDocItem {
fn syntax(&self) -> &CppSyntaxNode {
match self {
CppDocItem::Command(node) => node.syntax(),
CppDocItem::Body(node) => node.syntax(),
CppDocItem::Inline(node) => node.syntax(),
CppDocItem::CodeBlock(node) => node.syntax(),
}
}
fn can_cast(kind: CppSyntaxKind) -> bool {
matches!(
kind,
CppSyntaxKind::DocCommand
| CppSyntaxKind::DocCommandBody
| CppSyntaxKind::DocInline
| CppSyntaxKind::DocCodeBlock
)
}
fn cast(syntax: CppSyntaxNode) -> Option<Self> {
match CppSyntaxKind::from(syntax.kind()) {
CppSyntaxKind::DocCommand => CppDocCommand::cast(syntax).map(CppDocItem::Command),
CppSyntaxKind::DocCommandBody => CppDocCommandBody::cast(syntax).map(CppDocItem::Body),
CppSyntaxKind::DocInline => CppDocInline::cast(syntax).map(CppDocItem::Inline),
CppSyntaxKind::DocCodeBlock => CppDocCodeBlock::cast(syntax).map(CppDocItem::CodeBlock),
_ => None,
}
}
}
fn comment_lines(text: &str, block: bool) -> Vec<String> {
let mut lines: Vec<String> = text
.split('\n')
.map(|line| strip_line_furniture(line, block))
.collect();
while lines.first().is_some_and(|line| line.trim().is_empty()) {
lines.remove(0);
}
while lines.last().is_some_and(|line| line.trim().is_empty()) {
lines.pop();
}
lines
}
fn strip_line_furniture(raw: &str, block: bool) -> String {
let mut line = raw.trim_end_matches(['\r', ' ', '\t']);
if block && let Some(rest) = line.strip_suffix("*/") {
line = rest.trim_end_matches([' ', '\t']);
}
let indent = line.len() - line.trim_start_matches([' ', '\t']).len();
let mut rest = &line[indent..];
if let Some(after) = rest.strip_prefix("/*") {
rest = after.trim_start_matches(['*', '!']);
} else if rest.starts_with('/') {
rest = rest.trim_start_matches('/');
rest = rest.strip_prefix('!').unwrap_or(rest);
} else if block && let Some(after) = rest.strip_prefix('*') {
rest = after;
}
rest.strip_prefix(' ')
.unwrap_or(rest)
.trim_end_matches([' ', '\t'])
.to_string()
}
fn is_block_marker(line: &str, marker: &str) -> bool {
let line = line.trim();
line.strip_prefix('@').or_else(|| line.strip_prefix('\\')) == Some(marker)
}
fn is_in_block_comment(node: &CppSyntaxNode) -> bool {
node.ancestors()
.find(|it| CppSyntaxKind::from(it.kind()) == CppSyntaxKind::DocComment)
.is_some_and(|comment| comment.text().to_string().trim_start().starts_with("/*"))
}