Skip to main content

oak_toml/ast/
mod.rs

1#![doc = include_str!("readme.md")]
2use core::range::Range;
3
4/// TOML document root node.
5///
6/// Represents the entire TOML document, consisting of a list of top-level items.
7#[derive(Debug, Clone)]
8#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
9pub struct TomlRoot {
10    /// The items in the TOML document.
11    pub items: Vec<TomlItem>,
12    /// Range of the node in the source code.
13    #[cfg_attr(feature = "serde", serde(with = "oak_core::serde_range"))]
14    pub span: Range<usize>,
15}
16
17/// TOML top-level item.
18///
19/// Can be a key-value pair, a standard table, or an array of tables.
20#[derive(Debug, Clone)]
21#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
22pub enum TomlItem {
23    /// A key-value pair.
24    KeyValue(TomlKeyValue),
25    /// A standard table `[table]`.
26    Table(TomlTable),
27    /// An array of tables `[[table]]`.
28    ArrayOfTables(TomlArrayOfTables),
29}
30
31/// TOML key-value pair.
32#[derive(Debug, Clone)]
33#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
34pub struct TomlKeyValue {
35    /// The key part.
36    pub key: TomlKey,
37    /// The value part.
38    pub value: TomlValueNode,
39    /// Range of the key-value pair in the source code.
40    #[cfg_attr(feature = "serde", serde(with = "oak_core::serde_range"))]
41    pub span: Range<usize>,
42}
43
44/// TOML table `[table]`.
45#[derive(Debug, Clone)]
46#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
47pub struct TomlTable {
48    /// Range of the table in the source code.
49    #[cfg_attr(feature = "serde", serde(with = "oak_core::serde_range"))]
50    pub span: Range<usize>,
51    /// Table header.
52    pub header: TomlTableHeader,
53    /// Key-value pairs within the table.
54    pub items: Vec<TomlKeyValue>,
55}
56
57/// TOML table header `[key]`.
58#[derive(Debug, Clone)]
59#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
60pub struct TomlTableHeader {
61    /// Range of the header in the source code.
62    #[cfg_attr(feature = "serde", serde(with = "oak_core::serde_range"))]
63    pub span: Range<usize>,
64    /// The key of the table header.
65    pub key: TomlKey,
66}
67
68/// TOML array of tables `[[table]]`.
69#[derive(Debug, Clone)]
70#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
71pub struct TomlArrayOfTables {
72    /// Range of the array of tables in the source code.
73    #[cfg_attr(feature = "serde", serde(with = "oak_core::serde_range"))]
74    pub span: Range<usize>,
75    /// Header for the array of tables.
76    pub header: TomlArrayOfTablesHeader,
77    /// Key-value pairs within each table entry.
78    pub items: Vec<TomlKeyValue>,
79}
80
81/// TOML array of tables header `[[key]]`.
82#[derive(Debug, Clone)]
83#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
84pub struct TomlArrayOfTablesHeader {
85    /// Range of the header in the source code.
86    #[cfg_attr(feature = "serde", serde(with = "oak_core::serde_range"))]
87    pub span: Range<usize>,
88    /// The key of the array of tables header.
89    pub key: TomlKey,
90}
91
92/// TOML key.
93///
94/// Supports dotted composite keys (e.g., `a.b.c`).
95#[derive(Debug, Clone)]
96#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
97pub struct TomlKey {
98    /// Range of the key in the source code.
99    #[cfg_attr(feature = "serde", serde(with = "oak_core::serde_range"))]
100    pub span: Range<usize>,
101    /// Segments of the key.
102    pub segments: Vec<TomlKeySegment>,
103}
104
105/// TOML key segment.
106#[derive(Debug, Clone)]
107#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
108pub enum TomlKeySegment {
109    /// A bare key (unquoted).
110    Bare(TomlBareKey),
111    /// A quoted key.
112    Quoted(TomlQuotedKey),
113}
114
115/// TOML bare key (unquoted).
116#[derive(Debug, Clone)]
117#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
118pub struct TomlBareKey {
119    /// Range of the key in the source code.
120    #[cfg_attr(feature = "serde", serde(with = "oak_core::serde_range"))]
121    pub span: Range<usize>,
122    /// Name of the key.
123    pub name: String,
124}
125
126/// TOML quoted key.
127#[derive(Debug, Clone)]
128#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
129pub struct TomlQuotedKey {
130    /// Range of the key in the source code.
131    #[cfg_attr(feature = "serde", serde(with = "oak_core::serde_range"))]
132    pub span: Range<usize>,
133    /// Value of the key.
134    pub value: String,
135}
136
137/// TOML value.
138#[derive(Debug, Clone)]
139#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
140pub enum TomlValueNode {
141    /// String value.
142    String(TomlString),
143    /// Integer value.
144    Integer(TomlInteger),
145    /// Floating-point value.
146    Float(TomlFloat),
147    /// Boolean value.
148    Boolean(TomlBoolean),
149    /// Date-time value.
150    DateTime(TomlDateTime),
151    /// Array value.
152    Array(TomlArray),
153    /// Inline table `{ a = 1, b = 2 }`.
154    InlineTable(TomlInlineTable),
155}
156
157/// TOML string.
158#[derive(Debug, Clone)]
159#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
160pub struct TomlString {
161    /// Range of the string in the source code.
162    #[cfg_attr(feature = "serde", serde(with = "oak_core::serde_range"))]
163    pub span: Range<usize>,
164    /// Value of the string.
165    pub value: String,
166    /// Whether it's a multi-line string.
167    pub is_multiline: bool,
168    /// Whether it's a literal string (using single quotes).
169    pub is_literal: bool,
170}
171
172/// TOML integer.
173#[derive(Debug, Clone)]
174#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
175pub struct TomlInteger {
176    /// Range of the integer in the source code.
177    #[cfg_attr(feature = "serde", serde(with = "oak_core::serde_range"))]
178    pub span: Range<usize>,
179    /// Value of the integer.
180    pub value: i64,
181    /// Format of the integer (decimal, hex, etc.).
182    pub format: IntegerFormat,
183}
184
185/// Integer format.
186#[derive(Debug, Clone, Copy)]
187#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
188pub enum IntegerFormat {
189    /// Decimal format.
190    Decimal,
191    /// Hexadecimal format.
192    Hex,
193    /// Octal format.
194    Octal,
195    /// Binary format.
196    Binary,
197}
198
199/// TOML floating-point number.
200#[derive(Debug, Clone)]
201#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
202pub struct TomlFloat {
203    /// Range of the float in the source code.
204    #[cfg_attr(feature = "serde", serde(with = "oak_core::serde_range"))]
205    pub span: Range<usize>,
206    /// Value of the float.
207    pub value: f64,
208}
209
210/// TOML boolean value.
211#[derive(Debug, Clone)]
212#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
213pub struct TomlBoolean {
214    /// Range of the boolean in the source code.
215    #[cfg_attr(feature = "serde", serde(with = "oak_core::serde_range"))]
216    pub span: Range<usize>,
217    /// The boolean value.
218    pub value: bool,
219}
220
221/// TOML date-time.
222#[derive(Debug, Clone)]
223#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
224pub struct TomlDateTime {
225    /// Range of the date-time in the source code.
226    #[cfg_attr(feature = "serde", serde(with = "oak_core::serde_range"))]
227    pub span: Range<usize>,
228    /// String representation of the date-time.
229    pub value: String,
230}
231
232/// TOML array.
233#[derive(Debug, Clone)]
234#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
235pub struct TomlArray {
236    /// Range of the array in the source code.
237    #[cfg_attr(feature = "serde", serde(with = "oak_core::serde_range"))]
238    pub span: Range<usize>,
239    /// List of array items.
240    pub items: Vec<TomlValueNode>,
241}
242
243/// TOML inline table `{ a = 1, b = 2 }`.
244#[derive(Debug, Clone)]
245#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
246pub struct TomlInlineTable {
247    /// Range of the inline table in the source code.
248    #[cfg_attr(feature = "serde", serde(with = "oak_core::serde_range"))]
249    pub span: Range<usize>,
250    /// Key-value pairs in the inline table.
251    pub items: Vec<TomlKeyValue>,
252}
253
254impl TomlTable {
255    /// Creates a new TOML table.
256    pub fn new(span: Range<usize>, header: TomlTableHeader) -> Self {
257        Self { span, header, items: Vec::new() }
258    }
259
260    /// Gets a value from the table by key name.
261    pub fn get(&self, key: &str) -> Option<&TomlValueNode> {
262        for kv in &self.items {
263            if kv.key.to_string() == key {
264                return Some(&kv.value);
265            }
266        }
267        None
268    }
269}
270
271impl TomlKey {
272    /// Converts a composite key to its string representation (e.g., `a.b.c`).
273    pub fn to_string(&self) -> String {
274        self.segments
275            .iter()
276            .map(|s| match s {
277                TomlKeySegment::Bare(b) => b.name.clone(),
278                TomlKeySegment::Quoted(q) => q.value.clone(),
279            })
280            .collect::<Vec<_>>()
281            .join(".")
282    }
283}
284
285impl TomlValueNode {
286    /// Returns the string slice if the value is a string.
287    pub fn as_str(&self) -> Option<&str> {
288        match self {
289            TomlValueNode::String(s) => Some(&s.value),
290            _ => None,
291        }
292    }
293
294    /// Returns the integer value if the value is an integer.
295    pub fn as_integer(&self) -> Option<i64> {
296        match self {
297            TomlValueNode::Integer(i) => Some(i.value),
298            _ => None,
299        }
300    }
301
302    /// Returns the boolean value if the value is a boolean.
303    pub fn as_bool(&self) -> Option<bool> {
304        match self {
305            TomlValueNode::Boolean(b) => Some(b.value),
306            _ => None,
307        }
308    }
309
310    /// Returns a reference to the inline table if the value is an inline table.
311    pub fn as_inline_table(&self) -> Option<&TomlInlineTable> {
312        match self {
313            TomlValueNode::InlineTable(t) => Some(t),
314            _ => None,
315        }
316    }
317
318    /// Returns a reference to the array if the value is an array.
319    pub fn as_array(&self) -> Option<&TomlArray> {
320        match self {
321            TomlValueNode::Array(a) => Some(a),
322            _ => None,
323        }
324    }
325
326    /// Gets the source span of the value.
327    pub fn span(&self) -> Range<usize> {
328        match self {
329            TomlValueNode::String(s) => s.span.clone(),
330            TomlValueNode::Integer(i) => i.span.clone(),
331            TomlValueNode::Float(f) => f.span.clone(),
332            TomlValueNode::Boolean(b) => b.span.clone(),
333            TomlValueNode::DateTime(dt) => dt.span.clone(),
334            TomlValueNode::Array(a) => a.span.clone(),
335            TomlValueNode::InlineTable(t) => t.span.clone(),
336        }
337    }
338}
339
340impl std::fmt::Display for TomlValueNode {
341    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
342        match self {
343            TomlValueNode::String(s) => write!(f, "\"{}\"", s.value),
344            TomlValueNode::Integer(i) => write!(f, "{}", i.value),
345            TomlValueNode::Float(fl) => write!(f, "{}", fl.value),
346            TomlValueNode::Boolean(b) => write!(f, "{}", b.value),
347            TomlValueNode::DateTime(dt) => write!(f, "{}", dt.value),
348            TomlValueNode::Array(a) => {
349                write!(f, "[")?;
350                for (i, item) in a.items.iter().enumerate() {
351                    if i > 0 {
352                        write!(f, ", ")?;
353                    }
354                    write!(f, "{}", item)?;
355                }
356                write!(f, "]")
357            }
358            TomlValueNode::InlineTable(t) => {
359                write!(f, "{{")?;
360                for (i, item) in t.items.iter().enumerate() {
361                    if i > 0 {
362                        write!(f, ", ")?;
363                    }
364                    write!(f, "{} = {}", item.key.to_string(), item.value)?;
365                }
366                write!(f, "}}")
367            }
368        }
369    }
370}
371
372impl TomlRoot {
373    /// Converts the TomlRoot into a TomlValueNode (inline table).
374    pub fn into_value(self) -> TomlValueNode {
375        let mut items = Vec::new();
376
377        // Only include key-value pairs in the root
378        for item in self.items {
379            if let TomlItem::KeyValue(kv) = item {
380                items.push(kv);
381            }
382        }
383
384        TomlValueNode::InlineTable(TomlInlineTable { span: self.span, items })
385    }
386}