Skip to main content

r_dcf_syntax/
ast.rs

1//! Typed transient AST wrappers.
2
3use std::fmt;
4
5use crate::{SourceSpan, SyntaxKind, SyntaxNode};
6
7/// Typed document root.
8#[derive(Debug, Clone, PartialEq, Eq, Hash)]
9pub struct Root {
10    syntax: SyntaxNode,
11}
12
13impl Root {
14    pub(crate) fn new(syntax: SyntaxNode) -> Self {
15        debug_assert_eq!(syntax.kind(), SyntaxKind::Root);
16        Self { syntax }
17    }
18
19    /// Returns the underlying Rowan node.
20    pub fn syntax(&self) -> &SyntaxNode {
21        &self.syntax
22    }
23
24    /// Iterates over records in source order.
25    pub fn records(&self) -> impl Iterator<Item = Record> + '_ {
26        self.syntax.children().filter_map(Record::cast)
27    }
28
29    /// Returns the complete source range.
30    pub fn source_range(&self) -> SourceSpan {
31        SourceSpan::from_text_range(self.syntax.text_range())
32    }
33}
34
35impl fmt::Display for Root {
36    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
37        fmt::Display::fmt(&self.syntax, formatter)
38    }
39}
40
41/// Typed DCF record.
42#[derive(Debug, Clone, PartialEq, Eq, Hash)]
43pub struct Record {
44    syntax: SyntaxNode,
45}
46
47impl Record {
48    pub(crate) fn cast(syntax: SyntaxNode) -> Option<Self> {
49        (syntax.kind() == SyntaxKind::Record).then_some(Self { syntax })
50    }
51
52    /// Returns the underlying Rowan node.
53    pub fn syntax(&self) -> &SyntaxNode {
54        &self.syntax
55    }
56
57    /// Iterates over every valid field, including duplicates.
58    pub fn fields(&self) -> impl Iterator<Item = Field> + '_ {
59        self.syntax.children().filter_map(Field::cast)
60    }
61
62    /// Iterates over fields whose names exactly equal `name`.
63    pub fn fields_named<'a>(&'a self, name: &'a str) -> impl Iterator<Item = Field> + 'a {
64        self.fields()
65            .filter(move |field| field.name().as_deref() == Some(name))
66    }
67
68    /// Returns the first field whose name exactly equals `name`.
69    pub fn field(&self, name: &str) -> Option<Field> {
70        self.fields_named(name).next()
71    }
72
73    /// Returns the last field whose name exactly equals `name`.
74    pub fn last_field(&self, name: &str) -> Option<Field> {
75        self.fields_named(name).last()
76    }
77
78    /// Returns the record's source range.
79    pub fn source_range(&self) -> SourceSpan {
80        SourceSpan::from_text_range(self.syntax.text_range())
81    }
82
83    /// Returns the exact record text.
84    pub fn raw_text(&self) -> String {
85        self.syntax.to_string()
86    }
87}
88
89impl fmt::Display for Record {
90    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
91        fmt::Display::fmt(&self.syntax, formatter)
92    }
93}
94
95/// Typed valid DCF field.
96#[derive(Debug, Clone, PartialEq, Eq, Hash)]
97pub struct Field {
98    syntax: SyntaxNode,
99}
100
101impl Field {
102    pub(crate) fn cast(syntax: SyntaxNode) -> Option<Self> {
103        (syntax.kind() == SyntaxKind::Field).then_some(Self { syntax })
104    }
105
106    /// Returns the underlying Rowan node.
107    pub fn syntax(&self) -> &SyntaxNode {
108        &self.syntax
109    }
110
111    /// Returns the case-sensitive field name.
112    pub fn name(&self) -> Option<String> {
113        self.syntax
114            .children_with_tokens()
115            .filter_map(rowan::NodeOrToken::into_token)
116            .find(|token| token.kind() == SyntaxKind::Name)
117            .map(|token| token.text().to_owned())
118    }
119
120    /// Returns the unfolded logical value and its enclosing source range.
121    pub fn value(&self) -> ValueText {
122        let raw = self.raw_text();
123        let tokens: Vec<_> = self
124            .syntax
125            .children_with_tokens()
126            .filter_map(rowan::NodeOrToken::into_token)
127            .collect();
128        let value_start = tokens
129            .iter()
130            .find(|token| token.kind() == SyntaxKind::Colon)
131            .map_or(self.syntax.text_range().start(), |token| {
132                token.text_range().end()
133            });
134        let value_end = tokens
135            .iter()
136            .rev()
137            .find(|token| token.kind() != SyntaxKind::LineEnding)
138            .map_or(value_start, |token| token.text_range().end());
139        let range = SourceSpan::from_text_range(rowan::TextRange::new(value_start, value_end));
140        let mut logical = Vec::new();
141        for (index, line) in split_bodies(&raw).into_iter().enumerate() {
142            let content = if index == 0 {
143                line.split_once(':').map_or("", |(_, value)| value)
144            } else {
145                line.trim_start_matches([' ', '\t'])
146            };
147            let content = content.trim_matches([' ', '\t']);
148            logical.push(if index > 0 && content == "." {
149                ""
150            } else {
151                content
152            });
153        }
154        ValueText {
155            text: logical.join("\n"),
156            range,
157        }
158    }
159
160    /// Returns the field's source range, including its final line ending.
161    pub fn source_range(&self) -> SourceSpan {
162        SourceSpan::from_text_range(self.syntax.text_range())
163    }
164
165    /// Returns the exact physical field text.
166    pub fn raw_text(&self) -> String {
167        self.syntax.to_string()
168    }
169}
170
171impl fmt::Display for Field {
172    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
173        fmt::Display::fmt(&self.syntax, formatter)
174    }
175}
176
177/// Owned unfolded field text and the enclosing physical source range.
178#[derive(Debug, Clone, PartialEq, Eq, Hash)]
179pub struct ValueText {
180    text: String,
181    range: SourceSpan,
182}
183
184impl ValueText {
185    /// Returns the logical unfolded text.
186    pub fn as_str(&self) -> &str {
187        &self.text
188    }
189
190    /// Returns the contiguous physical value range.
191    ///
192    /// For continued values this includes intervening line endings and
193    /// indentation, but excludes the field name, colon, and final line ending.
194    pub const fn source_range(&self) -> SourceSpan {
195        self.range
196    }
197
198    /// Consumes this value and returns its text.
199    pub fn into_string(self) -> String {
200        self.text
201    }
202}
203
204impl fmt::Display for ValueText {
205    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
206        formatter.write_str(&self.text)
207    }
208}
209
210fn split_bodies(text: &str) -> Vec<&str> {
211    let bytes = text.as_bytes();
212    let mut result = Vec::new();
213    let mut start = 0;
214    let mut cursor = 0;
215    while cursor < bytes.len() {
216        if matches!(bytes[cursor], b'\r' | b'\n') {
217            result.push(&text[start..cursor]);
218            if bytes[cursor] == b'\r' && bytes.get(cursor + 1) == Some(&b'\n') {
219                cursor += 1;
220            }
221            cursor += 1;
222            start = cursor;
223        } else {
224            cursor += 1;
225        }
226    }
227    if start < text.len() {
228        result.push(&text[start..]);
229    }
230    result
231}