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>;
28
29/// A macro to create AST node wrappers.
30macro_rules! ast_node {
31    ($ast:ident, $kind:ident, $doc:expr) => {
32        #[doc = $doc]
33        #[doc = ""]
34        #[doc = "**Note:** This type uses interior mutability through the rowan library."]
35        #[doc = "Mutation methods work even when called through `&self`. See the crate-level"]
36        #[doc = "documentation for details on the mutability model."]
37        #[derive(Clone, PartialEq, Eq, Hash)]
38        pub struct $ast(pub(crate) SyntaxNode);
39
40        impl std::fmt::Debug for $ast {
41            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42                f.debug_struct(stringify!($ast))
43                    .field("syntax", &self.0)
44                    .finish()
45            }
46        }
47
48        impl AstNode for $ast {
49            type Language = Lang;
50
51            fn can_cast(kind: SyntaxKind) -> bool {
52                kind == SyntaxKind::$kind
53            }
54
55            fn cast(syntax: SyntaxNode) -> Option<Self> {
56                if Self::can_cast(syntax.kind()) {
57                    Some(Self(syntax))
58                } else {
59                    None
60                }
61            }
62
63            fn syntax(&self) -> &SyntaxNode {
64                &self.0
65            }
66        }
67
68        impl std::fmt::Display for $ast {
69            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
70                write!(f, "{}", self.0.text())
71            }
72        }
73    };
74}
75
76pub(crate) use ast_node;
77
78// Node modules
79pub mod alias_node;
80pub mod directive;
81pub mod document;
82pub mod mapping;
83pub mod scalar_node;
84pub mod sequence;
85pub mod tagged_node;
86
87// Re-exports
88pub use alias_node::Alias;
89pub use directive::Directive;
90pub use document::Document;
91pub use mapping::{Mapping, MappingEntry};
92pub use scalar_node::{Scalar, ScalarConversionError};
93pub use sequence::Sequence;
94pub use tagged_node::TaggedNode;