m2-syn 0.1.0

Typed syntax trees, traversal, and parser adapters for Macaulay2
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
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
use std::{
    fmt::{Display, Formatter, Result},
    vec::IntoIter,
};

use crate::{SourceId, Span, Spanned};
use delim::{Delimiter, DelimiterKind};

pub mod delim;
mod punct;
pub use punct::Punct;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum LiteralKind {
    String,
    RawString,
    Integer,
    Float,
}

#[derive(Debug, Clone, PartialEq, Eq, Spanned)]
pub struct Literal {
    pub kind: LiteralKind,
    text: String,
    span: Span,
}

impl Display for Literal {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> Result {
        formatter.write_str(&self.text)
    }
}

impl Literal {
    pub fn new(kind: LiteralKind, text: String, span: Span) -> Self {
        Self { kind, text, span }
    }

    pub fn text(&self) -> &str {
        &self.text
    }
}
impl ToTokens for Literal {
    fn to_tokens(&self, output: &mut TokenStream) {
        output.push_literal(self.clone());
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Spanned)]
pub struct IdentToken {
    text: String,
    span: Span,
}

impl IdentToken {
    pub fn new(text: impl Into<String>, span: Span) -> Self {
        Self {
            text: text.into(),
            span,
        }
    }

    pub fn text(&self) -> &str {
        &self.text
    }
}

impl Display for IdentToken {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> Result {
        formatter.write_str(&self.text)
    }
}
impl ToTokens for IdentToken {
    fn to_tokens(&self, output: &mut TokenStream) {
        output.push_ident(self.clone());
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Spanned)]
pub struct Group {
    delimiter: Delimiter,
    stream: TokenStream,
}

impl Group {
    pub fn new(delimiter: Delimiter, stream: TokenStream) -> Self {
        Self { delimiter, stream }
    }

    pub fn delimiter(&self) -> &Delimiter {
        &self.delimiter
    }

    pub fn delim_kind(&self) -> DelimiterKind {
        self.delimiter.kind
    }

    pub fn stream(&self) -> &TokenStream {
        &self.stream
    }

    pub fn into_stream(self) -> TokenStream {
        self.stream
    }
}

impl Display for Group {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> Result {
        formatter.write_str(self.delim_kind().opening())?;
        self.stream.fmt(formatter)?;
        formatter.write_str(self.delim_kind().closing())
    }
}
impl ToTokens for Group {
    fn to_tokens(&self, output: &mut TokenStream) {
        output.push_group(self.clone());
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TriviaKind {
    Whitespace,
    CarriageReturn,
    LineBreak,
    LineComment,
    BlockComment,
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Spanned)]
pub struct Trivia {
    kind: TriviaKind,
    text: String,
    span: Span,
}

impl Trivia {
    pub fn new(kind: TriviaKind, text: impl Into<String>, span: Span) -> Self {
        Self {
            kind,
            text: text.into(),
            span,
        }
    }

    pub fn kind(&self) -> TriviaKind {
        self.kind
    }

    pub fn text(&self) -> &str {
        &self.text
    }

    pub fn contains_line_break(&self) -> bool {
        self.text.contains('\n')
    }
}

impl Display for Trivia {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> Result {
        formatter.write_str(&self.text)
    }
}
impl ToTokens for Trivia {
    fn to_tokens(&self, output: &mut TokenStream) {
        output.push_trivia(self.clone());
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Spanned)]
/// One top-level token sequence together with its terminating delimiter.
///
/// An ordinary cell has [`DelimiterKind::Empty`]. A muted cell has
/// [`DelimiterKind::Semicolon`], and its semicolon is held by the delimiter
/// rather than repeated in `stream`.
pub struct CellBlock {
    delimiter: Delimiter,
    stream: TokenStream,
}

impl CellBlock {
    /// Creates a cell from its delimiter and interior token stream.
    pub fn new(delimiter: Delimiter, stream: TokenStream) -> Self {
        Self { delimiter, stream }
    }

    /// Returns the type-erased cell delimiter and its boundary spans.
    pub fn delimiter(&self) -> &Delimiter {
        &self.delimiter
    }

    /// Returns whether this is an ordinary or semicolon-terminated cell.
    pub fn delim_kind(&self) -> DelimiterKind {
        self.delimiter.kind
    }

    /// Borrows the tokens inside the cell delimiter.
    pub fn stream(&self) -> &TokenStream {
        &self.stream
    }

    /// Consumes the cell and returns the tokens inside its delimiter.
    pub fn into_stream(self) -> TokenStream {
        self.stream
    }
}

impl Display for CellBlock {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> Result {
        formatter.write_str(self.delim_kind().opening())?;
        self.stream.fmt(formatter)?;
        formatter.write_str(self.delim_kind().closing())
    }
}

impl ToTokens for CellBlock {
    fn to_tokens(&self, output: &mut TokenStream) {
        self.delimiter.surround(output, self.stream.clone());
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Spanned)]
pub enum TokenTree {
    Group(Group),
    Literal(Literal),
    Punct(Punct),
    Ident(IdentToken),
    Trivia(Trivia),
    #[doc(hidden)]
    Eof(Span),
}

impl TokenTree {
    pub fn spelling(&self) -> Option<&str> {
        match self {
            Self::Literal(token) => Some(token.text()),
            Self::Punct(token) => Some(token.text()),
            Self::Ident(token) => Some(token.text()),
            Self::Group(_) | Self::Trivia(_) | Self::Eof(_) => None,
        }
    }
}
impl ToTokens for TokenTree {
    fn to_tokens(&self, output: &mut TokenStream) {
        if !matches!(self, Self::Eof(_)) {
            output.push(self.clone());
        }
    }
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Spanned)]
pub struct TokenStream(Vec<TokenTree>);

impl TokenStream {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn iter(&self) -> impl Iterator<Item = &TokenTree> {
        self.0.iter()
    }

    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    pub(crate) fn len(&self) -> usize {
        self.0.len()
    }

    pub(crate) fn get(&self, position: usize) -> Option<&TokenTree> {
        self.0.get(position)
    }

    pub(crate) fn last(&self) -> Option<&TokenTree> {
        self.0.last()
    }

    pub(crate) fn push_eof(&mut self, span: Span) {
        self.0.push(TokenTree::Eof(span));
    }

    pub fn starts_with_whitespace(&self) -> bool {
        matches!(self.0.first(), Some(TokenTree::Trivia(_)))
    }

    pub fn ends_with_whitespace(&self) -> bool {
        matches!(self.0.last(), Some(TokenTree::Trivia(_)))
    }

    fn ends_with_line_break(&self) -> bool {
        matches!(self.0.last(), Some(TokenTree::Trivia(trivia)) if trivia.contains_line_break())
    }

    fn starts_with_line_break(&self) -> bool {
        matches!(self.0.first(), Some(TokenTree::Trivia(trivia)) if trivia.contains_line_break())
    }

    fn remove_leading_line_break(&mut self) {
        if self.starts_with_line_break() {
            self.0.remove(0);
        }
    }

    pub fn push_ident(&mut self, ident: IdentToken) {
        self.0.push(TokenTree::Ident(ident));
    }

    pub fn push_literal(&mut self, literal: Literal) {
        self.0.push(TokenTree::Literal(literal));
    }

    pub fn push_punct(&mut self, punct: Punct) {
        self.0.push(TokenTree::Punct(punct));
    }

    pub fn push_trivia(&mut self, trivia: Trivia) {
        self.0.push(TokenTree::Trivia(trivia));
    }

    pub fn push_group(&mut self, group: Group) {
        self.0.push(TokenTree::Group(group));
    }

    pub fn push(&mut self, tree: TokenTree) {
        self.0.push(tree);
    }

    /// Appends one emitted syntax fragment with any separator required to keep
    /// adjacent word-like fragments lexically distinct.
    ///
    /// This is the composition operation used by [`crate::quote_m2!`]. The
    /// fragment retains all of its internal token structure and trivia; a
    /// detached space is inserted only when the last existing token and first
    /// appended token would otherwise be rendered as adjacent words.
    #[doc(hidden)]
    pub fn append_fragment<T: ToTokens + ?Sized>(&mut self, fragment: &T) {
        let fragment = fragment.to_token_stream();
        if self.last().is_some_and(is_wordlike) && fragment.iter().next().is_some_and(is_wordlike) {
            self.push_trivia(Trivia::new(TriviaKind::Whitespace, " ", Span::detached()));
        }
        self.extend([fragment]);
    }

    /// Removes and returns the final token tree, if any.
    pub fn pop(&mut self) -> Option<TokenTree> {
        self.0.pop()
    }
}

fn is_wordlike(tree: &TokenTree) -> bool {
    matches!(
        tree,
        TokenTree::Ident(_) | TokenTree::Literal(_) | TokenTree::Group(_)
    )
}

impl Display for TokenStream {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> Result {
        for tree in &self.0 {
            match tree {
                TokenTree::Group(group) => group.fmt(formatter)?,
                TokenTree::Literal(literal) => literal.fmt(formatter)?,
                TokenTree::Punct(punct) => punct.fmt(formatter)?,
                TokenTree::Ident(ident) => ident.fmt(formatter)?,
                TokenTree::Trivia(trivia) => trivia.fmt(formatter)?,
                TokenTree::Eof(_) => {}
            }
        }
        Ok(())
    }
}

impl Extend<TokenStream> for TokenStream {
    fn extend<T: IntoIterator<Item = TokenStream>>(&mut self, iter: T) {
        self.0.extend(iter.into_iter().flat_map(|stream| stream.0));
    }
}
impl Extend<TokenTree> for TokenStream {
    fn extend<T: IntoIterator<Item = TokenTree>>(&mut self, iter: T) {
        self.0.extend(iter);
    }
}

impl FromIterator<TokenTree> for TokenStream {
    fn from_iter<T: IntoIterator<Item = TokenTree>>(iter: T) -> Self {
        Self(iter.into_iter().collect())
    }
}

impl IntoIterator for TokenStream {
    type Item = TokenTree;
    type IntoIter = IntoIter<TokenTree>;
    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

impl ToTokens for TokenStream {
    fn to_tokens(&self, output: &mut TokenStream) {
        output.0.extend(self.0.iter().cloned());
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CellStream {
    cells: Vec<CellBlock>,
    source_id: SourceId,
}

impl CellStream {
    pub fn new(cells: Vec<CellBlock>, source_id: SourceId) -> Self {
        Self { cells, source_id }
    }

    pub fn iter(&self) -> impl Iterator<Item = &CellBlock> {
        self.cells.iter()
    }

    pub fn cells(&self) -> &[CellBlock] {
        &self.cells
    }

    pub fn into_cells(self) -> Vec<CellBlock> {
        self.cells
    }

    pub fn is_empty(&self) -> bool {
        self.cells.is_empty()
    }

    pub fn source_id(&self) -> SourceId {
        self.source_id
    }

    /// Appends one global cell.
    pub fn push(&mut self, mut cell: CellBlock) {
        if self.cells.last().is_some_and(|previous| {
            !previous.stream().ends_with_line_break() && !cell.stream().starts_with_line_break()
        }) {
            let mut separated = TokenStream::new();
            separated.push_trivia(Trivia::new(TriviaKind::LineBreak, "\n", Span::detached()));
            separated.extend([cell.stream]);
            cell.stream = separated;
        }
        self.cells.push(cell);
    }

    fn push_unseparated(&mut self, cell: CellBlock) {
        self.cells.push(cell);
    }
}

impl Display for CellStream {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> Result {
        for cell in &self.cells {
            cell.fmt(formatter)?;
        }
        Ok(())
    }
}

impl IntoIterator for CellStream {
    type Item = CellBlock;
    type IntoIter = IntoIter<CellBlock>;

    fn into_iter(self) -> Self::IntoIter {
        self.cells.into_iter()
    }
}

impl Extend<CellBlock> for CellStream {
    fn extend<T: IntoIterator<Item = CellBlock>>(&mut self, iter: T) {
        for cell in iter {
            self.push(cell);
        }
    }
}

impl ToTokens for CellStream {
    fn to_tokens(&self, output: &mut TokenStream) {
        for (index, cell) in self.cells.iter().enumerate() {
            let mut stream = cell.stream.clone();
            if index != 0 && self.cells[index - 1].delim_kind() == DelimiterKind::Semicolon {
                stream.remove_leading_line_break();
            }
            cell.delimiter.surround(output, stream);
        }
    }
}

pub trait ToTokens {
    fn to_tokens(&self, output: &mut TokenStream);

    fn to_token_stream(&self) -> TokenStream {
        let mut output = TokenStream::new();
        self.to_tokens(&mut output);
        output
    }

    fn to_m2(&self) -> String {
        self.to_token_stream().to_string()
    }

    fn to_code(&self) -> String {
        self.to_m2()
    }
}

impl<T: ToTokens + ?Sized> ToTokens for &T {
    fn to_tokens(&self, output: &mut TokenStream) {
        (*self).to_tokens(output);
    }
}

impl<T: ToTokens + ?Sized> ToTokens for Box<T> {
    fn to_tokens(&self, output: &mut TokenStream) {
        self.as_ref().to_tokens(output);
    }
}

impl<T: ToTokens> ToTokens for Option<T> {
    fn to_tokens(&self, output: &mut TokenStream) {
        if let Some(value) = self {
            value.to_tokens(output);
        }
    }
}

impl<T: ToTokens> ToTokens for [T] {
    fn to_tokens(&self, output: &mut TokenStream) {
        for token in self {
            token.to_tokens(output);
        }
    }
}

impl<T: ToTokens> ToTokens for Vec<T> {
    fn to_tokens(&self, output: &mut TokenStream) {
        self.as_slice().to_tokens(output);
    }
}

/// Emits syntax as the linear sequence of cells evaluated at global scope.
///
/// This is the global-scope counterpart of [`ToTokens`]. Implementations append
/// to an existing stream so independently produced cell fragments compose
/// without intermediate allocation.
pub trait ToCells {
    /// Appends this value's global cells to `output`.
    fn to_cells(&self, output: &mut CellStream);

    /// Emits this value into a fresh cell stream with the requested identity.
    fn to_cell_stream(&self, source_id: SourceId) -> CellStream {
        let mut output = CellStream::new(Vec::new(), source_id);
        self.to_cells(&mut output);
        output
    }
}

impl<T: ToCells + ?Sized> ToCells for &T {
    fn to_cells(&self, output: &mut CellStream) {
        (*self).to_cells(output);
    }
}

impl<T: ToCells + ?Sized> ToCells for Box<T> {
    fn to_cells(&self, output: &mut CellStream) {
        self.as_ref().to_cells(output);
    }
}

impl<T: ToCells> ToCells for Option<T> {
    fn to_cells(&self, output: &mut CellStream) {
        if let Some(value) = self {
            value.to_cells(output);
        }
    }
}

impl<T: ToCells> ToCells for [T] {
    fn to_cells(&self, output: &mut CellStream) {
        for value in self {
            value.to_cells(output);
        }
    }
}

impl<T: ToCells> ToCells for Vec<T> {
    fn to_cells(&self, output: &mut CellStream) {
        self.as_slice().to_cells(output);
    }
}

impl ToCells for CellBlock {
    fn to_cells(&self, output: &mut CellStream) {
        output.push(self.clone());
    }
}

impl ToCells for CellStream {
    fn to_cells(&self, output: &mut CellStream) {
        output.extend(self.cells.iter().cloned());
    }
}

impl ToCells for TokenStream {
    fn to_cells(&self, output: &mut CellStream) {
        append_promoted_cells(self, output);
    }
}

impl ToCells for Group {
    fn to_cells(&self, output: &mut CellStream) {
        self.stream.to_cells(output);
    }
}

fn append_promoted_cells(tokens: &TokenStream, output: &mut CellStream) {
    let mut current = TokenStream::new();
    let mut first = true;
    for token in tokens.iter() {
        if matches!(token, TokenTree::Eof(_)) {
            continue;
        }
        if matches!(token, TokenTree::Punct(punct) if punct.text() == ";") {
            let span = current.span().join(token.span());
            push_promoted_cell(
                output,
                &mut first,
                CellBlock::new(
                    Delimiter::new(DelimiterKind::Semicolon, span),
                    std::mem::take(&mut current),
                ),
            );
            continue;
        }

        current.push(token.clone());
        if matches!(token, TokenTree::Trivia(trivia) if trivia.kind() == TriviaKind::LineBreak)
            && crate::lexer::newline_ends_cell(&current)
        {
            let span = current.span();
            push_promoted_cell(
                output,
                &mut first,
                CellBlock::new(
                    Delimiter::new(DelimiterKind::Empty, span),
                    std::mem::take(&mut current),
                ),
            );
        }
    }

    if !current.is_empty() {
        let span = current.span();
        push_promoted_cell(
            output,
            &mut first,
            CellBlock::new(Delimiter::new(DelimiterKind::Empty, span), current),
        );
    }
}

fn push_promoted_cell(output: &mut CellStream, first: &mut bool, cell: CellBlock) {
    if std::mem::take(first) {
        output.push(cell);
    } else {
        output.push_unseparated(cell);
    }
}