mago_syntax/ast/
trivia.rs

1use serde::Deserialize;
2use serde::Serialize;
3use strum::Display;
4
5use mago_interner::StringIdentifier;
6use mago_span::HasSpan;
7use mago_span::Span;
8
9use crate::ast::Sequence;
10
11/// Represents the kind of trivia.
12#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Serialize, Deserialize, PartialOrd, Ord, Display)]
13#[serde(tag = "type", content = "value")]
14pub enum TriviaKind {
15    WhiteSpace,
16    SingleLineComment,
17    MultiLineComment,
18    HashComment,
19    DocBlockComment,
20}
21
22/// Represents a trivia.
23///
24/// A trivia is a piece of information that is not part of the syntax tree,
25/// such as comments and white spaces.
26#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Serialize, Deserialize, PartialOrd, Ord)]
27pub struct Trivia {
28    pub kind: TriviaKind,
29    pub span: Span,
30    pub value: StringIdentifier,
31}
32
33impl TriviaKind {
34    /// Returns `true` if the trivia kind is a comment.
35    #[inline]
36    pub const fn is_comment(&self) -> bool {
37        matches!(
38            self,
39            TriviaKind::SingleLineComment
40                | TriviaKind::MultiLineComment
41                | TriviaKind::HashComment
42                | TriviaKind::DocBlockComment
43        )
44    }
45
46    #[inline]
47    pub const fn is_docblock(&self) -> bool {
48        matches!(self, TriviaKind::DocBlockComment)
49    }
50
51    #[inline]
52    pub const fn is_block_comment(&self) -> bool {
53        matches!(self, TriviaKind::MultiLineComment | TriviaKind::DocBlockComment)
54    }
55
56    #[inline]
57    pub const fn is_single_line_comment(&self) -> bool {
58        matches!(self, TriviaKind::HashComment | TriviaKind::SingleLineComment)
59    }
60}
61
62impl HasSpan for Trivia {
63    fn span(&self) -> Span {
64        self.span
65    }
66}
67
68impl Sequence<Trivia> {
69    /// Returns an iterator over the comments in the sequence.
70    pub fn comments(&self) -> impl Iterator<Item = &Trivia> {
71        self.iter().filter(|trivia| trivia.kind.is_comment())
72    }
73}