triplox-edn 0.1.0-alpha.5

EDN parser used by Triplox; a fork of the parser from Project Mentat.
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
// Copyright 2018 Mozilla
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.

use std::fmt::{Display, Formatter, Write};
use std::str::FromStr;

use crate::namespaceable_name::NamespaceableName;

/// Error returned when a string cannot be parsed as a `Keyword`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum KeywordParseError {
    /// Input did not start with `:`.
    MissingColonPrefix,
    /// The namespace part (before `/`) was empty.
    EmptyNamespace,
    /// The name part was empty.
    EmptyName,
}

impl Display for KeywordParseError {
    fn fmt(&self, f: &mut Formatter) -> ::std::fmt::Result {
        match self {
            KeywordParseError::MissingColonPrefix => {
                write!(f, "keyword must start with ':'")
            }
            KeywordParseError::EmptyNamespace => {
                write!(f, "keyword namespace cannot be empty")
            }
            KeywordParseError::EmptyName => {
                write!(f, "keyword name cannot be empty")
            }
        }
    }
}

impl std::error::Error for KeywordParseError {}

/// Construct a `Keyword` from a Clojure-like literal syntax.
///
/// # Examples
/// ```
/// use edn::kw;
/// // Namespaced keywords
/// let k = kw!(:db/ident);           // :db/ident
/// let k = kw!(:db.type/keyword);    // :db.type/keyword
/// // Plain keywords
/// let k = kw!(:name);               // :name
/// // Hyphenated keywords
/// let k = kw!(:last-name);          // :last-name
/// ```
#[macro_export]
macro_rules! kw {
    // Dotted ns, dotted name: :ns.sub/name.sub
    ( : $ns:ident $(. $nss:ident)+ / $nn:ident $(. $nns:ident)+ ) => {
        $crate::Keyword::namespaced(
            concat!(stringify!($ns) $(, ".", stringify!($nss))*),
            concat!(stringify!($nn) $(, ".", stringify!($nns))*),
        )
    };
    // Dotted ns, simple name: :ns.sub/name
    ( : $ns:ident $(. $nss:ident)+ / $nn:ident ) => {
        $crate::Keyword::namespaced(
            concat!(stringify!($ns) $(, ".", stringify!($nss))*),
            stringify!($nn)
        )
    };
    // Dotted ns, hyphenated name: :ns.sub/name-part
    ( : $ns:ident $(. $nss:ident)+ / $nn:ident $(- $nnh:ident)+ ) => {
        $crate::Keyword::namespaced(
            concat!(stringify!($ns) $(, ".", stringify!($nss))*),
            concat!(stringify!($nn) $(, "-", stringify!($nnh))*)
        )
    };
    // Simple ns, dotted name: :ns/name.sub
    ( : $ns:ident / $nn:ident $(. $nns:ident)+ ) => {
        $crate::Keyword::namespaced(
            stringify!($ns),
            concat!(stringify!($nn) $(, ".", stringify!($nns))*),
        )
    };
    // Simple ns, simple name: :ns/name
    ( : $ns:ident / $nn:ident ) => {
        $crate::Keyword::namespaced(
            stringify!($ns),
            stringify!($nn)
        )
    };
    // Simple ns, hyphenated name: :ns/name-part
    ( : $ns:ident / $nn:ident $(- $nnh:ident)+ ) => {
        $crate::Keyword::namespaced(
            stringify!($ns),
            concat!(stringify!($nn) $(, "-", stringify!($nnh))*)
        )
    };
    // Hyphenated ns, simple name: :ns-part/name
    ( : $ns:ident $(- $nsh:ident)+ / $nn:ident ) => {
        $crate::Keyword::namespaced(
            concat!(stringify!($ns) $(, "-", stringify!($nsh))*),
            stringify!($nn)
        )
    };
    // Plain keyword: :name
    ( : $n:ident ) => {
        $crate::Keyword::plain(
            stringify!($n)
        )
    };
    // Plain hyphenated keyword: :name-part
    ( : $n:ident $(- $nh:ident)+ ) => {
        $crate::Keyword::plain(
            concat!(stringify!($n) $(, "-", stringify!($nh))*)
        )
    };
}

/// A simplification of Clojure's Symbol.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialOrd, PartialEq)]
pub struct PlainSymbol(pub String);

#[derive(Clone, Debug, Eq, Hash, Ord, PartialOrd, PartialEq)]
pub struct NamespacedSymbol(NamespaceableName);

/// A keyword is a symbol, optionally with a namespace, that prints with a leading colon.
/// This concept is imported from Clojure, as it features in EDN and the query
/// syntax that we use.
///
/// Clojure's constraints are looser than ours, allowing empty namespaces or
/// names:
///
/// ```clojure
/// user=> (keyword "" "")
/// :/
/// user=> (keyword "foo" "")
/// :foo/
/// user=> (keyword "" "bar")
/// :/bar
/// ```
///
/// We think that's nonsense, so we only allow keywords like `:bar` and `:foo/bar`,
/// with both namespace and main parts containing no whitespace and no colon or slash:
///
/// ```rust
/// # use edn::symbols::Keyword;
/// let bar     = Keyword::plain("bar");                         // :bar
/// let foo_bar = Keyword::namespaced("foo", "bar");        // :foo/bar
/// assert_eq!("bar", bar.name());
/// assert_eq!(None, bar.namespace());
/// assert_eq!("bar", foo_bar.name());
/// assert_eq!(Some("foo"), foo_bar.namespace());
/// ```
///
/// If you're not sure whether your input is well-formed, you should use a
/// parser or a reader function first to validate. TODO: implement `read`.
///
/// Callers are expected to follow these rules:
/// http://www.clojure.org/reference/reader#_symbols
///
/// Future: fast equality (interning?) for keywords.
///
#[derive(Clone, Debug, Eq, Hash, Ord, PartialOrd, PartialEq)]
#[cfg_attr(
    feature = "serde_support",
    derive(serde::Serialize, serde::Deserialize)
)]
pub struct Keyword(NamespaceableName);

impl PlainSymbol {
    pub fn plain<T>(name: T) -> Self
    where
        T: Into<String>,
    {
        let n = name.into();
        assert!(!n.is_empty(), "Symbols cannot be unnamed.");

        PlainSymbol(n)
    }

    /// Return the name of the symbol without any leading '?' or '$'.
    ///
    /// ```rust
    /// # use edn::symbols::PlainSymbol;
    /// assert_eq!("foo", PlainSymbol::plain("?foo").name());
    /// assert_eq!("foo", PlainSymbol::plain("$foo").name());
    /// assert_eq!("!foo", PlainSymbol::plain("!foo").name());
    /// ```
    pub fn name(&self) -> &str {
        if self.is_src_symbol() || self.is_var_symbol() {
            &self.0[1..]
        } else {
            &self.0
        }
    }

    #[inline]
    pub fn is_var_symbol(&self) -> bool {
        self.0.starts_with('?')
    }

    #[inline]
    pub fn is_src_symbol(&self) -> bool {
        self.0.starts_with('$')
    }
}

impl NamespacedSymbol {
    pub fn namespaced<N, T>(namespace: N, name: T) -> Self
    where
        N: AsRef<str>,
        T: AsRef<str>,
    {
        let r = namespace.as_ref();
        assert!(
            !r.is_empty(),
            "Namespaced symbols cannot have an empty non-null namespace."
        );
        NamespacedSymbol(NamespaceableName::namespaced(r, name))
    }

    #[inline]
    pub fn name(&self) -> &str {
        self.0.name()
    }

    #[inline]
    pub fn namespace(&self) -> &str {
        self.0.namespace().unwrap()
    }

    #[inline]
    pub fn components(&self) -> (&str, &str) {
        self.0.components()
    }
}

impl Keyword {
    pub fn plain<T>(name: T) -> Self
    where
        T: Into<String>,
    {
        Keyword(NamespaceableName::plain(name))
    }
}

impl Keyword {
    /// Creates a new `Keyword`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use edn::symbols::Keyword;
    /// let keyword = Keyword::namespaced("foo", "bar");
    /// assert_eq!(keyword.to_string(), ":foo/bar");
    /// ```
    ///
    /// See also the `kw!` macro in the main `mentat` crate.
    pub fn namespaced<N, T>(namespace: N, name: T) -> Self
    where
        N: AsRef<str>,
        T: AsRef<str>,
    {
        let r = namespace.as_ref();
        assert!(
            !r.is_empty(),
            "Namespaced keywords cannot have an empty non-null namespace."
        );
        Keyword(NamespaceableName::namespaced(r, name))
    }

    #[inline]
    pub fn name(&self) -> &str {
        self.0.name()
    }

    #[inline]
    pub fn namespace(&self) -> Option<&str> {
        self.0.namespace()
    }

    #[inline]
    pub fn components(&self) -> (&str, &str) {
        self.0.components()
    }

    /// Whether this `Keyword` should be interpreted in reverse order. For example,
    /// the two following snippets are identical:
    ///
    /// ```edn
    /// [?y :person/friend ?x]
    /// [?x :person/hired ?y]
    ///
    /// [?y :person/friend ?x]
    /// [?y :person/_hired ?x]
    /// ```
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use edn::symbols::Keyword;
    /// assert!(!Keyword::namespaced("foo", "bar").is_backward());
    /// assert!(Keyword::namespaced("foo", "_bar").is_backward());
    /// ```
    #[inline]
    pub fn is_backward(&self) -> bool {
        self.0.is_backward()
    }

    /// Whether this `Keyword` should be interpreted in forward order.
    /// See `symbols::Keyword::is_backward`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use edn::symbols::Keyword;
    /// assert!(Keyword::namespaced("foo", "bar").is_forward());
    /// assert!(!Keyword::namespaced("foo", "_bar").is_forward());
    /// ```
    #[inline]
    pub fn is_forward(&self) -> bool {
        self.0.is_forward()
    }

    #[inline]
    pub fn is_namespaced(&self) -> bool {
        self.0.is_namespaced()
    }

    /// Returns a `Keyword` with the same namespace and a
    /// 'backward' name. See `symbols::Keyword::is_backward`.
    ///
    /// Returns a forward name if passed a reversed keyword; i.e., this
    /// function is its own inverse.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use edn::symbols::Keyword;
    /// let nsk = Keyword::namespaced("foo", "bar");
    /// assert!(!nsk.is_backward());
    /// assert_eq!(":foo/bar", nsk.to_string());
    ///
    /// let reversed = nsk.to_reversed();
    /// assert!(reversed.is_backward());
    /// assert_eq!(":foo/_bar", reversed.to_string());
    /// ```
    pub fn to_reversed(&self) -> Keyword {
        Keyword(self.0.to_reversed())
    }

    /// If this `Keyword` is 'backward' (see `symbols::Keyword::is_backward`),
    /// return `Some('forward name')`; otherwise, return `None`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use edn::symbols::Keyword;
    /// let nsk = Keyword::namespaced("foo", "bar");
    /// assert_eq!(None, nsk.unreversed());
    ///
    /// let reversed = nsk.to_reversed();
    /// assert_eq!(Some(nsk), reversed.unreversed());
    /// ```
    pub fn unreversed(&self) -> Option<Keyword> {
        if self.is_backward() {
            Some(self.to_reversed())
        } else {
            None
        }
    }
}

//
// Note that we don't currently do any escaping.
//

impl Display for PlainSymbol {
    /// Print the symbol in EDN format.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use edn::symbols::PlainSymbol;
    /// assert_eq!("baz", PlainSymbol::plain("baz").to_string());
    /// ```
    fn fmt(&self, f: &mut Formatter) -> ::std::fmt::Result {
        self.0.fmt(f)
    }
}

impl Display for NamespacedSymbol {
    /// Print the symbol in EDN format.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use edn::symbols::NamespacedSymbol;
    /// assert_eq!("bar/baz", NamespacedSymbol::namespaced("bar", "baz").to_string());
    /// ```
    fn fmt(&self, f: &mut Formatter) -> ::std::fmt::Result {
        self.0.fmt(f)
    }
}

impl FromStr for Keyword {
    type Err = KeywordParseError;

    /// Parse a keyword from its EDN Display form, e.g. `:foo/bar` or `:baz`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use std::str::FromStr;
    /// # use edn::symbols::Keyword;
    /// assert_eq!(Keyword::from_str(":foo/bar").unwrap(), Keyword::namespaced("foo", "bar"));
    /// assert_eq!(Keyword::from_str(":baz").unwrap(), Keyword::plain("baz"));
    /// assert!(Keyword::from_str("foo/bar").is_err());
    /// assert!(Keyword::from_str(":/bar").is_err());
    /// assert!(Keyword::from_str(":foo/").is_err());
    /// ```
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let s = s
            .strip_prefix(':')
            .ok_or(KeywordParseError::MissingColonPrefix)?;
        match s.split_once('/') {
            Some((ns, name)) => {
                if ns.is_empty() {
                    return Err(KeywordParseError::EmptyNamespace);
                }
                if name.is_empty() {
                    return Err(KeywordParseError::EmptyName);
                }
                Ok(Keyword::namespaced(ns, name))
            }
            None => {
                if s.is_empty() {
                    return Err(KeywordParseError::EmptyName);
                }
                Ok(Keyword::plain(s))
            }
        }
    }
}

impl TryFrom<&str> for Keyword {
    type Error = KeywordParseError;

    fn try_from(s: &str) -> Result<Self, Self::Error> {
        Keyword::from_str(s)
    }
}

impl Display for Keyword {
    /// Print the keyword in EDN format.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use edn::symbols::Keyword;
    /// assert_eq!(":baz", Keyword::plain("baz").to_string());
    /// assert_eq!(":bar/baz", Keyword::namespaced("bar", "baz").to_string());
    /// assert_eq!(":bar/_baz", Keyword::namespaced("bar", "baz").to_reversed().to_string());
    /// assert_eq!(":bar/baz", Keyword::namespaced("bar", "baz").to_reversed().to_reversed().to_string());
    /// ```
    fn fmt(&self, f: &mut Formatter) -> ::std::fmt::Result {
        f.write_char(':')?;
        self.0.fmt(f)
    }
}

#[test]
fn test_kw_macro() {
    // Namespaced
    assert_eq!(kw!(:test/name), Keyword::namespaced("test", "name"));
    assert_eq!(kw!(:ns/_name), Keyword::namespaced("ns", "_name"));
    // Dotted namespace
    assert_eq!(
        kw!(:db.type/keyword),
        Keyword::namespaced("db.type", "keyword")
    );
    // Plain
    assert_eq!(kw!(:name), Keyword::plain("name"));
    // Hyphenated
    assert_eq!(kw!(:last-name), Keyword::plain("last-name"));
    assert_eq!(kw!(:foo/bar-baz), Keyword::namespaced("foo", "bar-baz"));
    // Hyphenated namespace
    assert_eq!(kw!(:my-ns/attr), Keyword::namespaced("my-ns", "attr"));
}