dent-parse 0.1.0

Duck's Extensible Notation for Things (DENT) parser
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
mod error;
mod repr;
mod tokenizer;
pub use error::*;
pub use repr::*;
use tokenizer::{Token, Tokenizer};

#[cfg(test)]
mod tests;

use std::{
    collections::HashMap,
    io::Read,
    path::{Path, PathBuf},
    sync::{Arc, Mutex},
};

/// Alias for a trait object that represents a function that can be called from
/// Dent. The function takes a reference to a value and returns a value.
///
/// The function can be called from Dent using the `@` operator, after
/// being registered with `Dent::add_function`.
///
/// A Dent function can only take a single argument, for simplicity.
/// If you need to pass multiple arguments, you can use a list or dictionary.
///
/// # Examples
/// ```
/// use dent_parse::{Dent, Value, Function};
/// use std::collections::HashMap;
///
/// let mut functions: HashMap<String, Box<Function>> = HashMap::new();
/// functions.insert(
///     "sum".to_string(),
///     Box::new(move |value: &Value| -> Value {
///         let mut sum = 0;
///         if let Value::List(values) = value {
///             for value in values.iter() {
///                 if let Value::Int(i) = value {
///                     sum += i;
///                 }
///             }
///             Value::Int(sum)
///         } else if let Value::Int(i) = value {
///             Value::Int(*i)
///         } else {
///             Value::None
///         }
///     }),
/// );
/// let parser = Dent::new(functions);
///
/// assert_eq!(parser.parse("@sum {}"), Ok(Value::None));
/// assert_eq!(parser.parse("@sum 0"), Ok(Value::Int(0)));
/// assert_eq!(parser.parse("@sum [ 1 2 3 ]"), Ok(Value::Int(6)));
/// ```
pub type Function = dyn for<'a> Fn(&Value<'a>) -> Value<'a> + Send + Sync;

/// Main struct for parsing Dent.
///
/// This struct is used to parse Dent files and strings. It can also be used to
/// register functions that can be called from Dent.
///
/// # Examples
/// ```
/// use dent_parse::{Dent, Value};
/// use std::collections::HashMap;
///
/// let parser = Dent::default();
///
/// assert_eq!(parser.parse("foo"), Ok(Value::Str("foo")));
/// assert_eq!(parser.parse("[ 1 2 3 ]"), Ok(Value::List(vec![
///     Value::Int(1),
///     Value::Int(2),
///     Value::Int(3)
/// ])));
/// ```
pub struct Dent {
    internal: Arc<Mutex<DentInternal>>,
}

struct Import {
    src: &'static str,
    value: Value<'static>,
}

impl Drop for Import {
    fn drop(&mut self) {
        unsafe {
            let b = Box::from_raw(self.src as *const str as *mut str);
            std::mem::drop(b);
        }
    }
}

struct DentInternal {
    functions: HashMap<String, Arc<Function>>,
    import_map: HashMap<PathBuf, Import>,
}

struct ParserState<'s> {
    tokenizer: Tokenizer<'s>,
    token: Token<'s>,
}

impl<'s> ParserState<'s> {
    fn new(mut tokenizer: Tokenizer<'s>) -> Result<Self> {
        let token = tokenizer.next()?;
        Ok(ParserState { tokenizer, token })
    }

    fn next(&mut self) -> Result<()> {
        self.token = self.tokenizer.next()?;
        Ok(())
    }
}

impl Dent {
    /// Creates a new Dent parser with the given functions.
    ///
    /// If you want to use the built-in functions, you can use `Dent::default`,
    /// or call `Dent::add_builtins` after creating the parser.
    pub fn new(functions: HashMap<String, Box<Function>>) -> Dent {
        let functions = functions
            .into_iter()
            .map(|(k, v)| (k, Arc::new(v) as Arc<Function>))
            .collect();

        let internal = DentInternal {
            functions,
            import_map: HashMap::new(),
        };

        Dent {
            internal: Arc::new(Mutex::new(internal)),
        }
    }

    /// Adds the built-in functions to the parser.
    ///
    /// This function adds the following functions:
    /// - `import`: Imports a Dent file. Takes a string (file path) as an argument.
    /// - `merge`: Merges a list of lists or a list of dicts into a single list or dict.
    pub fn add_builtins(&mut self) {
        let internal = self.internal.clone();

        let outer_functions = &mut self.internal.lock().unwrap().functions;

        outer_functions.insert(
            "import".to_string(),
            Arc::new(move |value| {
                if let Value::Str(s) = value {
                    let path = Path::new(s);

                    let value = Self::import(internal.clone(), path);

                    match value {
                        Ok(v) => v,
                        Err(_) => Value::None,
                    }
                } else {
                    Value::None
                }
            }),
        );

        outer_functions.insert(
            "merge".to_string(),
            Arc::new(move |value| {
                // we want either a list of dicts or a list of lists
                if let Value::List(values) = value {
                    let mut result = Vec::new();
                    let mut is_dict = None;
                    for value in values.iter() {
                        if let Value::List(values) = value {
                            if is_dict.is_some() && is_dict.unwrap() {
                                return Value::None;
                            }
                            is_dict = Some(false);
                            result.extend(values.clone());
                        } else if let Value::Dict(values) = value {
                            if is_dict.is_some() && !is_dict.unwrap() {
                                return Value::None;
                            }
                            is_dict = Some(true);
                            result.push(Value::Dict(values.clone()));
                        }
                    }

                    match is_dict {
                        Some(true) => Value::Dict(
                            result
                                .into_iter()
                                .flat_map(|v| {
                                    if let Value::Dict(d) = v {
                                        d
                                    } else {
                                        panic!("Expected dict");
                                    }
                                })
                                .collect(),
                        ),
                        Some(false) => Value::List(result),
                        None => Value::None,
                    }
                } else {
                    Value::None
                }
            }),
        );
    }

    /// Adds a function to the parser.
    ///
    /// The function can be called from Dent using the `@` operator.
    /// The function takes a reference to a value and returns a value.
    /// The function can only take a single argument, for simplicity.
    ///
    /// # Examples
    /// ```
    /// use dent_parse::{Dent, Value};
    ///
    /// let mut dent = Dent::default();
    /// dent.add_function("count", Box::new(|value| {
    ///     if let Value::List(values) = value {
    ///         Value::Int(values.len() as i64)
    ///     } else {
    ///         Value::None
    ///     }
    /// }));
    /// assert_eq!(dent.parse("@count [ 1 2 3 ]"), Ok(Value::Int(3)));
    /// ```
    pub fn add_function(&mut self, name: &str, function: Box<Function>) {
        let function = Arc::new(function);

        let outer_functions = &mut self.internal.lock().unwrap().functions;

        outer_functions.insert(name.to_string(), function);
    }

    /// Parses a Dent string.
    ///
    /// The returned value is a zero-copy representation of the parsed Dent
    /// string. This means that the returned value borrows from the input string.
    ///
    /// If you want to parse a file, use `Dent::parse_file` instead.
    ///
    /// # Examples
    /// ```
    /// use dent_parse::{Dent, Value};
    ///
    /// let parser = Dent::default();
    ///
    /// assert_eq!(parser.parse("foo"), Ok(Value::Str("foo")));
    /// assert_eq!(parser.parse("2"), Ok(Value::Int(2)));
    /// assert_eq!(parser.parse("2.0"), Ok(Value::Float(2.0)));
    /// assert_eq!(parser.parse("true"), Ok(Value::Bool(true)));
    /// ```
    pub fn parse<'s>(&self, input: &'s str) -> Result<Value<'s>> {
        let tokenizer = Tokenizer::new(input);

        let mut state = ParserState::new(tokenizer)?;

        Self::parse_value(self.internal.clone(), &mut state)
    }

    /// Parses a Dent file.
    ///
    /// The returned value is a zero-copy representation of the parsed Dent. All strings
    /// in the returned value borrow from the input file.
    ///
    /// The file is read and stored in memory for the lifetime of the program.
    ///
    /// # Examples
    /// ```
    /// use dent_parse::{Dent, Value};
    /// use std::collections::HashMap;
    ///
    /// let parser = Dent::default();
    /// let value = parser.parse_file("examples/dent/dict.dent").unwrap();
    /// assert_eq!(value, Value::Dict(
    ///     vec![
    ///         ("name", Value::Str("Mario")),
    ///         (
    ///             "skills",
    ///             Value::List(vec![Value::Str("jumps"), Value::Str("grows")])
    ///         ),
    ///         ("age", Value::Int(35)),
    ///         ("alive", Value::Bool(true)),
    ///     ].into_iter().collect()
    /// ));
    /// ```
    pub fn parse_file<P: AsRef<Path>>(&self, path: P) -> Result<Value<'static>> {
        Self::import(self.internal.clone(), path)
    }

    fn import<P: AsRef<Path>>(
        internal: Arc<Mutex<DentInternal>>,
        path: P,
    ) -> Result<Value<'static>> {
        let path = if let Ok(path) = path.as_ref().canonicalize() {
            path
        } else {
            return Ok(Value::None);
        };

        let mut ilock = internal.lock().unwrap();
        let import_map = &mut ilock.import_map;
        if let Some(value) = import_map.get(&path) {
            return Ok(value.value.clone());
        }

        import_map.insert(
            path.clone(),
            Import {
                src: "",
                value: Value::None,
            },
        );

        drop(ilock);

        let mut file = std::fs::File::open(&path).unwrap();

        let mut contents = String::new();

        file.read_to_string(&mut contents).unwrap();

        let static_contents = Box::leak(contents.into_boxed_str());

        let tokenizer = Tokenizer::new(static_contents);

        let mut state = ParserState::new(tokenizer).unwrap();

        let value = Self::parse_value(internal.clone(), &mut state);

        let value = match value {
            Ok(v) => v,
            Err(_) => Value::None,
        };

        let mut ilock = internal.lock().unwrap();
        let import_map = &mut ilock.import_map;

        let i = import_map.get_mut(&path).unwrap();
        i.src = static_contents;
        i.value = value.clone();

        Ok(value)
    }

    fn parse_value<'s>(
        internal: Arc<Mutex<DentInternal>>,
        state: &mut ParserState<'s>,
    ) -> Result<Value<'s>> {
        let v = match state.token {
            Token::Eof => Ok(Value::None),
            Token::At => {
                state.next()?;
                if let Token::String(s) = state.token {
                    state.next()?;
                    let function = internal
                        .lock()
                        .unwrap()
                        .functions
                        .get(&s.to_string())
                        .cloned();
                    if let Some(function) = function {
                        let value = Self::parse_value(internal.clone(), state)?;
                        Ok(function(&value))
                    } else {
                        Err(Error::UnknownFunction(s.to_string()))
                    }
                } else {
                    Err(Error::UnexpectedToken(state.token.type_name()))
                }
            }
            Token::String(s) => {
                state.next()?;
                Ok(Value::Str(s))
            }
            Token::OpenBracket => {
                state.next()?;
                let mut values = Vec::new();
                while state.token != Token::CloseBracket {
                    if state.token == Token::Eof {
                        return Err(Error::UnexpectedEof);
                    }
                    values.push(Self::parse_value(internal.clone(), state)?);
                }
                state.next()?;
                Ok(Value::List(values))
            }
            Token::OpenBrace => {
                state.next()?;
                let mut values = HashMap::new();
                while state.token != Token::CloseBrace {
                    if state.token == Token::Eof {
                        return Err(Error::UnexpectedEof);
                    }
                    if let Token::String(s) = state.token {
                        state.next()?;
                        if state.token != Token::Colon {
                            return Err(Error::UnexpectedToken(state.token.type_name()));
                        }
                        state.next()?;
                        values.insert(s, Self::parse_value(internal.clone(), state)?);
                    } else {
                        return Err(Error::UnexpectedToken(state.token.type_name()));
                    }
                }
                state.next()?;
                Ok(Value::Dict(values))
            }
            Token::Number(n) => {
                state.next()?;
                if let Ok(i) = n.parse::<i64>() {
                    Ok(Value::Int(i))
                } else if let Ok(f) = n.parse::<f64>() {
                    Ok(Value::Float(f))
                } else {
                    panic!("Tokenizer returned invalid number: {}", n);
                }
            }
            Token::Bool(b) => {
                state.next()?;
                Ok(Value::Bool(b))
            }
            Token::Comment => {
                state.next()?;
                Self::parse_value(internal, state)
            }
            _ => Err(Error::UnexpectedToken(state.token.type_name())),
        };
        v
    }
}

impl Default for Dent {
    fn default() -> Self {
        let mut s = Self::new(HashMap::new());
        s.add_builtins();
        s
    }
}