lispexp 0.1.1

A pure-Rust reader (lexer + parser) for S-expression syntax across many Lisp dialects
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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
//! Dialect-configurable reader/lexer settings.
//!
//! [`Options`] is the orthogonal, individually-toggleable syntax configuration
//! the Lexer and Reader share (ADR-0003). A [`Dialect`] is just a named preset
//! constructor. Scheme, Clojure, Common Lisp, Emacs Lisp, Racket, Janet, Hy,
//! AutoLISP, Guile, Phel, Fennel, LFE, and ISLisp are all implemented.

use crate::datum::Prefix;

/// The role of a bracket pair `[]` or `{}` in a dialect.
///
/// The reader records delimiter *shape* (`Delim`), not meaning, so for the tree
/// only the `Ordinary` distinction (is it a delimiter at all?) affects parsing;
/// `List`/`Vector`/`Map` all mean "an active delimiter" and differ only in the
/// meaning a consumer assigns.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DelimRole {
    /// An alternate list delimiter (Scheme `[]`).
    List,
    /// A vector literal (Emacs Lisp `[]`).
    Vector,
    /// A map literal (Clojure `{}`).
    Map,
    /// Not a delimiter — an ordinary symbol-constituent character (e.g. ISLisp).
    Ordinary,
}

impl DelimRole {
    /// Whether this role makes the bracket an active delimiter (not `Ordinary`).
    pub fn is_delimiter(self) -> bool {
        self != DelimRole::Ordinary
    }
}

/// A block-comment delimiter pair (ADR-0007).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BlockComment {
    /// The opening delimiter (e.g. `#|`).
    pub open: &'static str,
    /// The closing delimiter (e.g. `|#`).
    pub close: &'static str,
    /// Whether the pair nests.
    pub nestable: bool,
}

/// How character literals are introduced.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CharSyntax {
    /// `#\a`, `#\space` (Scheme, Common Lisp).
    HashBackslash,
    /// `\a`, `\newline` (Clojure).
    Backslash,
    /// `?a`, `?\n`, `?\C-x` (Emacs Lisp).
    Question,
}

/// What `#(` means in a dialect.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HashParen {
    /// `#(...)` is a vector literal (data) — Scheme.
    Vector,
    /// `#(...)` is an anonymous-function reader macro (code) — Clojure/Phel.
    HashFn,
    /// `#(` is not special.
    None,
}

/// A named dialect. Presets are constructed via [`Options`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Dialect {
    /// R7RS-small Scheme.
    Scheme,
    /// Clojure.
    Clojure,
    /// ANSI Common Lisp.
    CommonLisp,
    /// Emacs Lisp.
    EmacsLisp,
    /// Racket.
    Racket,
    /// Janet.
    Janet,
    /// Hy.
    Hy,
    /// AutoLISP.
    AutoLisp,
    /// Guile Scheme.
    Guile,
    /// Phel.
    Phel,
    /// Fennel.
    Fennel,
    /// LFE (Lisp Flavoured Erlang).
    Lfe,
    /// ISLisp.
    Islisp,
}

/// Reader/lexer configuration. Construct via a preset such as
/// [`Options::scheme`] or [`Options::clojure`], then adjust fields if needed.
#[derive(Debug, Clone)]
pub struct Options {
    /// Character that starts a line comment (`;` for most; `#` for Janet).
    pub line_comment: char,
    /// Whether a comma is whitespace (Clojure/Phel).
    pub comma_is_whitespace: bool,
    /// Block-comment delimiters, if any.
    pub block_comment: Option<BlockComment>,
    /// Whether `#;` discards the next datum (Scheme).
    pub datum_comment: bool,
    /// Whether `#_` discards the next datum (Clojure/Phel).
    pub discard_underscore: bool,
    /// Whether `#` introduces reader syntax (`#t`, `#\`, `#(`, ...).
    pub hash_syntax: bool,
    /// Role of `[` `]`.
    pub square: DelimRole,
    /// Role of `{` `}`.
    pub curly: DelimRole,
    /// Whether `#{` opens a set literal.
    pub set_literal: bool,
    /// Whether `#"..."` is a regex literal (lexed as a string leaf).
    pub regex_literal: bool,
    /// Whether `#tag <form>` is a tagged literal (Clojure `#inst`, `#uuid`, ...).
    pub tagged_literals: bool,
    /// The prefix `#'` maps to, if any (Clojure `VarQuote`, Common Lisp
    /// `FunctionQuote`).
    pub hash_apostrophe: Option<Prefix>,
    /// Whether `#?`/`#?@` are reader conditionals wrapping the next list (Clojure).
    pub reader_conditional: bool,
    /// Whether `#+`/`#-` are feature conditionals: a feature test followed by a
    /// guarded form (Common Lisp). The reader reads two data.
    pub feature_conditional: bool,
    /// Whether `#.` is a read-time-eval prefix (Common Lisp).
    pub read_eval: bool,
    /// Whether `\` escapes the next character inside a symbol (Common Lisp).
    pub symbol_escape: bool,
    /// Whether `#t`/`#f`/`#true`/`#false` are booleans.
    pub booleans: bool,
    /// How character literals are written, if the dialect has them.
    pub char_syntax: Option<CharSyntax>,
    /// What `#(` means.
    pub hash_paren: HashParen,
    /// Whether `:foo` is a keyword.
    pub keyword_colon: bool,
    /// Whether `#:foo` is a keyword (Racket, Guile).
    pub hash_keyword: bool,
    /// Whether a leading `#lang <name>` line is captured (Racket).
    pub lang_line: bool,
    /// Whether a leading `#!`-line is a shebang comment (Racket scripts).
    pub shebang_line: bool,
    /// Whether `|...|` is a piped symbol.
    pub piped_symbols: bool,
    /// Whether `#n=` / `#n#` datum labels are recognized.
    pub datum_labels: bool,
    /// Whether a lone `.` inside a list marks a dotted/improper tail `(a . b)`.
    /// False for Clojure, where `.` is an ordinary interop symbol.
    pub dotted_pairs: bool,
    /// Glyph for `quote` shorthand, if any.
    pub quote: Option<char>,
    /// Glyph for `quasiquote` shorthand, if any.
    pub quasiquote: Option<char>,
    /// Glyph for `unquote` shorthand, if any.
    pub unquote: Option<char>,
    /// Suffix that turns `unquote` into `unquote-splicing` (e.g. `,` + `@`).
    pub splicing_suffix: char,
    /// Glyph for a deref prefix (Clojure `@`), if any.
    pub deref: Option<char>,
    /// Glyph for a metadata prefix (Clojure `^`), if any.
    pub meta: Option<char>,
    /// Glyph for a splice prefix (Janet `;`), if any.
    pub splice: Option<char>,
    /// Glyph for a mutable-marker prefix (Janet `@`), if any.
    pub mutable: Option<char>,
    /// Glyph for a bare short-function prefix (Janet `|`), if any.
    pub short_fn: Option<char>,
    /// Whether a run of backticks delimits a long string (Janet).
    pub long_string_backtick: bool,
    /// Whether `#[DELIM[...]DELIM]` is a bracket string (Hy).
    pub bracket_string: bool,
}

impl Options {
    /// R7RS-small Scheme (the first implemented dialect).
    pub fn scheme() -> Self {
        Options {
            line_comment: ';',
            comma_is_whitespace: false,
            block_comment: Some(BlockComment {
                open: "#|",
                close: "|#",
                nestable: true,
            }),
            datum_comment: true,
            discard_underscore: false,
            hash_syntax: true,
            square: DelimRole::List,
            // R7RS reserves `{` `}` for future use; treat as ordinary so the
            // reader neither errors nor invents a meaning.
            curly: DelimRole::Ordinary,
            set_literal: false,
            regex_literal: false,
            tagged_literals: false,
            hash_apostrophe: None,
            reader_conditional: false,
            feature_conditional: false,
            read_eval: false,
            symbol_escape: false,
            booleans: true,
            char_syntax: Some(CharSyntax::HashBackslash),
            hash_paren: HashParen::Vector,
            keyword_colon: false,
            piped_symbols: true,
            datum_labels: true,
            dotted_pairs: true,
            hash_keyword: false,
            lang_line: false,
            shebang_line: false,
            quote: Some('\''),
            quasiquote: Some('`'),
            unquote: Some(','),
            splicing_suffix: '@',
            deref: None,
            meta: None,
            splice: None,
            mutable: None,
            short_fn: None,
            long_string_backtick: false,
            bracket_string: false,
        }
    }

    /// Clojure.
    pub fn clojure() -> Self {
        Options {
            line_comment: ';',
            comma_is_whitespace: true,
            block_comment: None,
            datum_comment: false,
            discard_underscore: true,
            hash_syntax: true,
            square: DelimRole::Vector,
            curly: DelimRole::Map,
            set_literal: true,
            regex_literal: true,
            tagged_literals: true,
            hash_apostrophe: Some(Prefix::VarQuote),
            reader_conditional: true,
            feature_conditional: false,
            read_eval: false,
            symbol_escape: false,
            booleans: false, // true/false/nil are ordinary symbols
            char_syntax: Some(CharSyntax::Backslash),
            hash_paren: HashParen::HashFn,
            keyword_colon: true,
            piped_symbols: false,
            datum_labels: false,
            dotted_pairs: false,
            hash_keyword: false,
            lang_line: false,
            shebang_line: false,
            quote: Some('\''),
            quasiquote: Some('`'),
            unquote: Some('~'),
            splicing_suffix: '@',
            deref: Some('@'),
            meta: Some('^'),
            splice: None,
            mutable: None,
            short_fn: None,
            long_string_backtick: false,
            bracket_string: false,
        }
    }

    /// Common Lisp (ANSI).
    pub fn common_lisp() -> Self {
        Options {
            line_comment: ';',
            comma_is_whitespace: false,
            block_comment: Some(BlockComment {
                open: "#|",
                close: "|#",
                nestable: true,
            }),
            datum_comment: false,
            discard_underscore: false,
            hash_syntax: true,
            // `[` `]` `{` `}` are not standard delimiters in CL.
            square: DelimRole::Ordinary,
            curly: DelimRole::Ordinary,
            set_literal: false,
            regex_literal: false,
            tagged_literals: false,
            hash_apostrophe: Some(Prefix::FunctionQuote), // #'fn
            reader_conditional: false,
            feature_conditional: true, // #+/#-
            read_eval: true,           // #.
            symbol_escape: true,       // foo\ bar
            booleans: false,           // t / nil are ordinary symbols
            char_syntax: Some(CharSyntax::HashBackslash),
            hash_paren: HashParen::Vector, // #(...)
            keyword_colon: true,           // :keyword
            piped_symbols: true,           // |foo bar|
            datum_labels: true,            // #n= / #n#
            dotted_pairs: true,
            hash_keyword: false,
            lang_line: false,
            shebang_line: false,
            quote: Some('\''),
            quasiquote: Some('`'),
            unquote: Some(','),
            splicing_suffix: '@',
            deref: None,
            meta: None,
            splice: None,
            mutable: None,
            short_fn: None,
            long_string_backtick: false,
            bracket_string: false,
        }
    }

    /// Emacs Lisp.
    pub fn emacs_lisp() -> Self {
        Options {
            line_comment: ';',
            comma_is_whitespace: false,
            block_comment: None, // `;` line comments only
            datum_comment: false,
            discard_underscore: false,
            hash_syntax: true,
            square: DelimRole::Vector, // `[...]` is a data vector
            curly: DelimRole::Ordinary,
            set_literal: false,
            regex_literal: false,
            tagged_literals: false,
            hash_apostrophe: Some(Prefix::FunctionQuote), // #'fn
            reader_conditional: false,
            feature_conditional: false,
            read_eval: false,
            symbol_escape: true,
            booleans: false,                         // t / nil are ordinary symbols
            char_syntax: Some(CharSyntax::Question), // ?a, ?\n, ?\C-x
            hash_paren: HashParen::Vector,           // #("propertized" ...) string
            keyword_colon: true,                     // :keyword
            piped_symbols: false,
            datum_labels: true, // #1= / #1# circular structure
            dotted_pairs: true,
            hash_keyword: false,
            lang_line: false,
            shebang_line: false,
            quote: Some('\''),
            quasiquote: Some('`'),
            unquote: Some(','),
            splicing_suffix: '@',
            deref: None,
            meta: None,
            splice: None,
            mutable: None,
            short_fn: None,
            long_string_backtick: false,
            bracket_string: false,
        }
    }

    /// Racket. Layers on the Scheme surface with `#lang`, `#:` keywords, `[]`/`{}`
    /// as code lists, `#'` syntax, and `#[`/`#{` vectors.
    pub fn racket() -> Self {
        Options {
            square: DelimRole::List,
            curly: DelimRole::List, // `[]` and `{}` are interchangeable with `()`
            hash_apostrophe: Some(Prefix::VarQuote), // #'syntax
            symbol_escape: true,
            keyword_colon: false, // Racket keywords are `#:foo`, not `:foo`
            hash_keyword: true,
            lang_line: true,
            shebang_line: true,
            ..Options::scheme()
        }
    }

    /// Janet. Note: `#` is the line comment, `;` is splice, `~` is quasiquote.
    pub fn janet() -> Self {
        Options {
            line_comment: '#',
            block_comment: None,
            datum_comment: false,
            hash_syntax: false,      // `#` is the comment char, not reader syntax
            square: DelimRole::List, // `[...]` bracketed tuple
            curly: DelimRole::Map,   // `{...}` struct
            booleans: false,
            char_syntax: None,
            hash_paren: HashParen::None,
            keyword_colon: true,
            piped_symbols: false,
            datum_labels: false,
            dotted_pairs: false,
            quasiquote: Some('~'),
            unquote: Some(','),
            splice: Some(';'),
            mutable: Some('@'), // `@[]` array, `@{}` table, `@"..."` buffer
            short_fn: Some('|'),
            long_string_backtick: true, // `` `...` ``
            ..Options::scheme()
        }
    }

    /// Hy (a Lisp that compiles to Python).
    pub fn hy() -> Self {
        Options {
            block_comment: None,
            datum_comment: false,
            discard_underscore: true, // #_
            square: DelimRole::List,  // `[...]` list
            curly: DelimRole::Map,    // `{...}` dict
            set_literal: true,        // #{}
            tagged_literals: true,    // #foo reader macros, #* #**
            booleans: false,          // True/False/None are symbols
            char_syntax: None,
            hash_paren: HashParen::None,
            keyword_colon: true,
            piped_symbols: false,
            datum_labels: false,
            dotted_pairs: false,  // `.` is attribute access
            unquote: Some('~'),   // Clojure-style unquote
            bracket_string: true, // #[[...]] / #[DELIM[...]DELIM]
            ..Options::scheme()
        }
    }

    /// AutoLISP (AutoCAD). Minimal: `'` quote only, `;|...|;` block comments,
    /// no character literals, no reader syntax.
    pub fn autolisp() -> Self {
        Options {
            block_comment: Some(BlockComment {
                open: ";|",
                close: "|;",
                nestable: false,
            }),
            datum_comment: false,
            hash_syntax: false,
            square: DelimRole::Ordinary,
            booleans: false, // T / nil are symbols
            char_syntax: None,
            hash_paren: HashParen::None,
            piped_symbols: false,
            datum_labels: false,
            quasiquote: None, // no backquote/unquote in AutoLISP
            unquote: None,
            ..Options::scheme()
        }
    }

    /// Guile (a Scheme implementation with extensions).
    pub fn guile() -> Self {
        Options {
            hash_keyword: true,                      // #:kw keywords
            hash_apostrophe: Some(Prefix::VarQuote), // #'syntax
            ..Options::scheme()
        }
    }

    /// Phel (a Clojure-like Lisp that compiles to PHP).
    pub fn phel() -> Self {
        // Phel's reader is essentially Clojure's; #php tagged literals are
        // already covered by tagged_literals.
        Options::clojure()
    }

    /// Fennel (a Lisp that compiles to Lua).
    pub fn fennel() -> Self {
        Options {
            block_comment: None,
            datum_comment: false,
            square: DelimRole::List, // [...] sequence
            curly: DelimRole::Map,   // {...} table
            booleans: false,         // true/false/nil are symbols
            char_syntax: None,
            hash_paren: HashParen::HashFn, // #(...) hashfn
            keyword_colon: false,          // :foo is a string; kept as a symbol leaf
            piped_symbols: false,
            datum_labels: false,
            dotted_pairs: false, // `.` is multi-symbol / method access
            ..Options::scheme()
        }
    }

    /// LFE (Lisp Flavoured Erlang).
    pub fn lfe() -> Self {
        Options {
            block_comment: Some(BlockComment {
                open: "#|",
                close: "|#",
                nestable: false, // LFE block comments do not nest
            }),
            regex_literal: true, // #"..." binary strings, lexed as a Str leaf
            hash_apostrophe: Some(Prefix::FunctionQuote), // #'name/arity
            booleans: false,     // 'true / 'false atoms
            datum_labels: false,
            ..Options::scheme()
        }
    }

    /// ISLisp (ISO/IEC 13816).
    pub fn islisp() -> Self {
        Options {
            square: DelimRole::Ordinary, // [] {} are ordinary symbol chars
            keyword_colon: true,         // :keyword
            hash_apostrophe: Some(Prefix::FunctionQuote), // #'fn
            booleans: false,             // t / nil are symbols
            datum_labels: false,
            ..Options::scheme()
        }
    }

    /// Options for a named [`Dialect`].
    pub fn for_dialect(dialect: Dialect) -> Self {
        match dialect {
            Dialect::Scheme => Options::scheme(),
            Dialect::Clojure => Options::clojure(),
            Dialect::CommonLisp => Options::common_lisp(),
            Dialect::EmacsLisp => Options::emacs_lisp(),
            Dialect::Racket => Options::racket(),
            Dialect::Janet => Options::janet(),
            Dialect::Hy => Options::hy(),
            Dialect::AutoLisp => Options::autolisp(),
            Dialect::Guile => Options::guile(),
            Dialect::Phel => Options::phel(),
            Dialect::Fennel => Options::fennel(),
            Dialect::Lfe => Options::lfe(),
            Dialect::Islisp => Options::islisp(),
        }
    }
}

impl Default for Options {
    fn default() -> Self {
        Options::scheme()
    }
}