toml_edit/parser/
inline_table.rs

1use winnow::combinator::cut_err;
2use winnow::combinator::delimited;
3use winnow::combinator::separated;
4use winnow::combinator::trace;
5use winnow::token::one_of;
6
7use crate::key::Key;
8use crate::parser::error::CustomError;
9use crate::parser::key::key;
10use crate::parser::prelude::*;
11use crate::parser::trivia::ws;
12use crate::parser::value::value;
13use crate::{InlineTable, Item, RawString, Value};
14
15use indexmap::map::Entry;
16
17// ;; Inline Table
18
19// inline-table = inline-table-open inline-table-keyvals inline-table-close
20pub(crate) fn inline_table<'i>(input: &mut Input<'i>) -> ModalResult<InlineTable> {
21    trace("inline-table", move |input: &mut Input<'i>| {
22        delimited(
23            INLINE_TABLE_OPEN,
24            cut_err(inline_table_keyvals.try_map(|(kv, p)| table_from_pairs(kv, p))),
25            cut_err(INLINE_TABLE_CLOSE)
26                .context(StrContext::Label("inline table"))
27                .context(StrContext::Expected(StrContextValue::CharLiteral('}'))),
28        )
29        .parse_next(input)
30    })
31    .parse_next(input)
32}
33
34fn table_from_pairs(
35    v: Vec<(Vec<Key>, (Key, Item))>,
36    preamble: RawString,
37) -> Result<InlineTable, CustomError> {
38    let mut root = InlineTable::new();
39    root.set_preamble(preamble);
40    // Assuming almost all pairs will be directly in `root`
41    root.items.reserve(v.len());
42
43    for (path, (key, value)) in v {
44        let table = descend_path(&mut root, &path)?;
45
46        // "Likewise, using dotted keys to redefine tables already defined in [table] form is not allowed"
47        let mixed_table_types = table.is_dotted() == path.is_empty();
48        if mixed_table_types {
49            return Err(CustomError::DuplicateKey {
50                key: key.get().into(),
51                table: None,
52            });
53        }
54
55        match table.items.entry(key) {
56            Entry::Vacant(o) => {
57                o.insert(value);
58            }
59            Entry::Occupied(o) => {
60                return Err(CustomError::DuplicateKey {
61                    key: o.key().get().into(),
62                    table: None,
63                });
64            }
65        }
66    }
67    Ok(root)
68}
69
70fn descend_path<'a>(
71    mut table: &'a mut InlineTable,
72    path: &'a [Key],
73) -> Result<&'a mut InlineTable, CustomError> {
74    let dotted = !path.is_empty();
75    for (i, key) in path.iter().enumerate() {
76        let entry = table.entry_format(key).or_insert_with(|| {
77            let mut new_table = InlineTable::new();
78            new_table.set_implicit(dotted);
79            new_table.set_dotted(dotted);
80
81            Value::InlineTable(new_table)
82        });
83        match *entry {
84            Value::InlineTable(ref mut sweet_child_of_mine) => {
85                // Since tables cannot be defined more than once, redefining such tables using a
86                // [table] header is not allowed. Likewise, using dotted keys to redefine tables
87                // already defined in [table] form is not allowed.
88                if dotted && !sweet_child_of_mine.is_implicit() {
89                    return Err(CustomError::DuplicateKey {
90                        key: key.get().into(),
91                        table: None,
92                    });
93                }
94                table = sweet_child_of_mine;
95            }
96            ref v => {
97                return Err(CustomError::extend_wrong_type(path, i, v.type_name()));
98            }
99        }
100    }
101    Ok(table)
102}
103
104// inline-table-open  = %x7B ws     ; {
105pub(crate) const INLINE_TABLE_OPEN: u8 = b'{';
106// inline-table-close = ws %x7D     ; }
107const INLINE_TABLE_CLOSE: u8 = b'}';
108// inline-table-sep   = ws %x2C ws  ; , Comma
109const INLINE_TABLE_SEP: u8 = b',';
110// keyval-sep = ws %x3D ws ; =
111pub(crate) const KEYVAL_SEP: u8 = b'=';
112
113// inline-table-keyvals = [ inline-table-keyvals-non-empty ]
114// inline-table-keyvals-non-empty =
115// ( key keyval-sep val inline-table-sep inline-table-keyvals-non-empty ) /
116// ( key keyval-sep val )
117
118fn inline_table_keyvals(
119    input: &mut Input<'_>,
120) -> ModalResult<(Vec<(Vec<Key>, (Key, Item))>, RawString)> {
121    (
122        separated(0.., keyval, INLINE_TABLE_SEP),
123        ws.span().map(RawString::with_span),
124    )
125        .parse_next(input)
126}
127
128fn keyval(input: &mut Input<'_>) -> ModalResult<(Vec<Key>, (Key, Item))> {
129    (
130        key,
131        cut_err((
132            one_of(KEYVAL_SEP)
133                .context(StrContext::Expected(StrContextValue::CharLiteral('.')))
134                .context(StrContext::Expected(StrContextValue::CharLiteral('='))),
135            (ws.span(), value, ws.span()),
136        )),
137    )
138        .map(|(key, (_, v))| {
139            let mut path = key;
140            let key = path.pop().expect("grammar ensures at least 1");
141
142            let (pre, v, suf) = v;
143            let pre = RawString::with_span(pre);
144            let suf = RawString::with_span(suf);
145            let v = v.decorated(pre, suf);
146            (path, (key, Item::Value(v)))
147        })
148        .parse_next(input)
149}
150
151#[cfg(test)]
152#[cfg(feature = "parse")]
153#[cfg(feature = "display")]
154mod test {
155    use super::*;
156
157    #[test]
158    fn inline_tables() {
159        let inputs = [
160            r#"{}"#,
161            r#"{   }"#,
162            r#"{a = 1e165}"#,
163            r#"{ hello = "world", a = 1}"#,
164            r#"{ hello.world = "a" }"#,
165        ];
166        for input in inputs {
167            dbg!(input);
168            let mut parsed = inline_table.parse(new_input(input));
169            if let Ok(parsed) = &mut parsed {
170                parsed.despan(input);
171            }
172            assert_eq!(parsed.map(|a| a.to_string()), Ok(input.to_owned()));
173        }
174    }
175
176    #[test]
177    fn invalid_inline_tables() {
178        let invalid_inputs = [r#"{a = 1e165"#, r#"{ hello = "world", a = 2, hello = 1}"#];
179        for input in invalid_inputs {
180            dbg!(input);
181            let mut parsed = inline_table.parse(new_input(input));
182            if let Ok(parsed) = &mut parsed {
183                parsed.despan(input);
184            }
185            assert!(parsed.is_err());
186        }
187    }
188}