Skip to main content

yaml_edit/nodes/
mod.rs

1//! AST node types for YAML.
2
3use crate::lex::SyntaxKind;
4
5/// YAML language type for rowan.
6#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
7pub enum Lang {}
8
9impl rowan::Language for Lang {
10    type Kind = SyntaxKind;
11
12    fn kind_from_raw(raw: rowan::SyntaxKind) -> Self::Kind {
13        debug_assert!(
14            raw.0 <= SyntaxKind::EOF as u16,
15            "raw SyntaxKind value {} is out of range (max {})",
16            raw.0,
17            SyntaxKind::EOF as u16,
18        );
19        unsafe { std::mem::transmute::<u16, SyntaxKind>(raw.0) }
20    }
21
22    fn kind_to_raw(kind: Self::Kind) -> rowan::SyntaxKind {
23        kind.into()
24    }
25}
26
27pub type SyntaxNode = rowan::SyntaxNode<Lang>;
28pub type SyntaxToken = rowan::SyntaxToken<Lang>;
29
30/// A macro to create AST node wrappers.
31macro_rules! ast_node {
32    ($ast:ident, $kind:ident, $doc:expr) => {
33        #[doc = $doc]
34        #[doc = ""]
35        #[doc = "**Note:** This type uses interior mutability through the rowan library."]
36        #[doc = "Mutation methods work even when called through `&self`. See the crate-level"]
37        #[doc = "documentation for details on the mutability model."]
38        #[derive(Clone, PartialEq, Eq, Hash)]
39        pub struct $ast(pub(crate) SyntaxNode);
40
41        impl std::fmt::Debug for $ast {
42            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
43                f.debug_struct(stringify!($ast))
44                    .field("syntax", &self.0)
45                    .finish()
46            }
47        }
48
49        impl AstNode for $ast {
50            type Language = Lang;
51
52            fn can_cast(kind: SyntaxKind) -> bool {
53                kind == SyntaxKind::$kind
54            }
55
56            fn cast(syntax: SyntaxNode) -> Option<Self> {
57                if Self::can_cast(syntax.kind()) {
58                    Some(Self(syntax))
59                } else {
60                    None
61                }
62            }
63
64            fn syntax(&self) -> &SyntaxNode {
65                &self.0
66            }
67        }
68
69        impl std::fmt::Display for $ast {
70            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
71                write!(f, "{}", self.0.text())
72            }
73        }
74    };
75}
76
77pub(crate) use ast_node;
78
79// Node modules
80pub mod alias_node;
81pub mod comment;
82pub mod directive;
83pub mod document;
84pub mod mapping;
85pub mod scalar_node;
86pub mod sequence;
87pub mod tagged_node;
88
89// Re-exports
90pub use alias_node::Alias;
91pub use comment::Comment;
92pub use directive::Directive;
93pub use document::Document;
94pub use mapping::{Mapping, MappingEntry};
95pub use scalar_node::{Scalar, ScalarConversionError};
96pub use sequence::Sequence;
97pub use tagged_node::TaggedNode;