summaryrefslogtreecommitdiff
path: root/graph_macro/src/lib.rs
blob: 3b7742ac3fbb9a7d6125bcad9b383f911d4fbb6c (plain)
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
671
672
673
674
675
//! This file provides a macro to delegate the implementation of a
//! type that wraps a graph.  More precisely, the macro helps the
//! wrapper type implement the various Graph-related traits.
//!
//! See the macro [`graph_derive`].

use proc_macro::{Delimiter, Group, Ident, Literal, Punct, Spacing, Span, TokenStream, TokenTree};

use std::{collections::HashMap, iter::Peekable};

/// A visibility modifer is either "pub", "pub(restriction)", or
/// "Private".
#[derive(Debug, Default)]
enum VisibilityMod {
    /// Simple pub visibility.
    Pub,
    /// The pub visibility with restrictions.
    ///
    /// Since the restrictions can be given in a variety of ways, and
    /// since it does not matter to us, we just keep them as a
    /// tokentree.
    PubRes(TokenTree),
    #[default]
    Private,
}

#[derive(Debug)]
struct Generic {
    name: Ident,
    type_stream: TokenStream,
}

impl Generic {
    fn new(name: Ident, type_stream: TokenStream) -> Self {
        Self { name, type_stream }
    }
}

/// The content of the struct
#[derive(Debug)]
struct GraphInfo {
    name: TokenStream,
    generics: Vec<Generic>,
    field_name: String,
    field_type: TokenStream,
}

impl GraphInfo {
    fn new(
        name: TokenStream,
        generics: Vec<Generic>,
        field_name: String,
        field_type: TokenStream,
    ) -> Self {
        Self {
            name,
            generics,
            field_name,
            field_type,
        }
    }
}

/// For custom compiler errors
#[derive(Debug)]
struct CompileError {
    mes: String,
    span: Span,
}

impl CompileError {
    fn new(mes: impl ToString, span: Span) -> Self {
        Self {
            mes: mes.to_string(),
            span,
        }
    }

    /// Produce a token stream that will trigger compiler errors.
    ///
    /// The point is that the span of the token trees will be set to
    /// the desired locations, and hence produce the effect we want.
    fn emit(self) -> TokenStream {
        // I cannot use the parse method of the type TokenStream, as
        // that will not set the spans properly.

        let compile_error_ident = TokenTree::Ident(Ident::new("compile_error", self.span));
        let mut exclamation_punct = TokenTree::Punct(Punct::new('!', Spacing::Alone));

        exclamation_punct.set_span(self.span);

        let mut arg_mes_literal = TokenTree::Literal(Literal::string(&self.mes));

        arg_mes_literal.set_span(self.span);

        let arg_mes_stream = [arg_mes_literal].into_iter().collect();

        let mut arg_group = TokenTree::Group(Group::new(Delimiter::Parenthesis, arg_mes_stream));

        arg_group.set_span(self.span);

        let mut semi_colon_punct = TokenTree::Punct(Punct::new(';', Spacing::Alone));

        semi_colon_punct.set_span(self.span);

        [
            compile_error_ident,
            exclamation_punct,
            arg_group,
            semi_colon_punct,
        ]
        .into_iter()
        .collect()
    }
}

macro_rules! unwrap_or_emit {
    ($value:ident) => {
        if let Err(err) = $value {
            return err.emit();
        }

        let $value = $value.unwrap();
    };
}

#[allow(unused)]
macro_rules! mytodo {
    () => {
        Err(CompileError::new("not umplemented yet", Span::mixed_site()))
    };
}

macro_rules! myerror {
    ($mes:tt, $input:ident) => {
        Err(CompileError::new($mes, $input.peek().unwrap().span()))
    };
}

#[proc_macro_derive(Graph, attributes(graph))]
pub fn graph_derive(input: TokenStream) -> TokenStream {
    let mut input = input.into_iter().peekable();

    while move_attributes(&mut input).is_ok() {}

    let _ = get_visibility_mod(&mut input);

    let info = get_info(&mut input);

    unwrap_or_emit!(info);

    let name = info.name;
    let generics = info.generics;
    let field_name = info.field_name;
    let field_type = info.field_type;

    let generics_impl_string = {
        let mut result = String::new();

        if !generics.is_empty() {
            result.push('<');
        }

        for generic in generics.iter() {
            result.push_str(&format!("{}:{},", generic.name, generic.type_stream));
        }

        if !generics.is_empty() {
            result.push('>');
        }

        result
    };

    let generic_struct_string = {
        let mut result = String::new();

        if !generics.is_empty() {
            result.push('<');
        }

        for generic in generics.iter() {
            result.push_str(&format!("{},", generic.name));
        }

        if !generics.is_empty() {
            result.push('>');
        }

        result
    };

    let generic_where_string = {
        let mut result = String::new();

        if !generics.is_empty() {
            result.push_str("\nwhere\n");
        }

        for generic in generics.iter() {
            result.push_str(&format!("{}: 'a,\n", generic.name));
        }

        result
    };

    let result =     format!(
        "
#[automatically_derived]
impl{generics_impl_string} graph::Graph for {name}{generic_struct_string} {{
type Iter<'a> = <{field_type} as graph::Graph>::Iter<'a>{generic_where_string};

#[inline]
fn is_empty(&self) -> bool {{self.{field_name}.is_empty()}}

#[inline]
fn nodes_len(&self) -> usize {{ self.{field_name}.nodes_len() }}

#[inline]
fn children_of(&self, node: usize) -> Result<<Self as graph::Graph>::Iter<'_>, graph::error::Error> {{
self.{field_name}.children_of(node)
}}

#[inline]
fn degree(&self, node: usize) -> Result<usize, graph::error::Error> {{ self.{field_name}.degree(node) }}

#[inline]
fn is_empty_node(&self, node: usize) -> Result<bool, graph::error::Error> {{ self.{field_name}.is_empty_node(node) }}

#[inline]
fn has_edge(&self, nodea: usize, nodeb: usize) -> Result<bool, graph::error::Error> {{
self.{field_name}.has_edge(nodea, nodeb)
}}

#[inline]
fn replace_by_builder(&mut self, _builder: impl graph::builder::Builder<Result = Self>) {{
unimplemented!()
}}

#[inline]
fn print_viz(&self, filename: &str) -> Result<(), std::io::Error> {{
self.{field_name}.print_viz(filename)
}}
}}"
    );

    result.parse().unwrap()
}

fn get_visibility_mod(
    input: &mut Peekable<impl Iterator<Item = TokenTree>>,
) -> Result<VisibilityMod, CompileError> {
    if let Some(TokenTree::Ident(id)) = input.peek() {
        if id.to_string() == "pub" {
            input.next();

            if let Some(TokenTree::Group(g)) = input.peek() {
                let delimiter = g.delimiter();

                if delimiter != Delimiter::Parenthesis {
                    return Err(CompileError::new("invalid bracket", g.span()));
                }

                let tree = TokenTree::Group(g.clone());

                input.next();

                return Ok(VisibilityMod::PubRes(tree));
            } else {
                return Ok(VisibilityMod::Pub);
            }
        }
    }

    Ok(Default::default())
}

fn get_info(
    input: &mut Peekable<impl Iterator<Item = TokenTree>>,
) -> Result<GraphInfo, CompileError> {
    if let Some(TokenTree::Ident(id)) = input.peek() {
        if id.to_string() != "struct" {
            let span = input.next().unwrap().span();
            return Err(CompileError::new("Only struct is supported", span));
        }

        input.next();

        let struct_name = get_until(
            input,
            |tree| match tree {
                TokenTree::Group(g)
                    if g.delimiter() == Delimiter::Brace
                        || g.delimiter() == Delimiter::Parenthesis =>
                {
                    true
                }
                TokenTree::Punct(p) if p.as_char() == ';' || p.as_char() == '<' => true,
                _ => false,
            },
            false,
            false,
        )?;

        // We are not at the end as guaranteed by `get_until`.
        let peek = input.peek().unwrap();

        if matches!(peek, TokenTree::Punct(p) if p.as_char()  == ';') {
            // unit struct

            return myerror!("Cannot derive graph for unit structs", input);
        }

        let mut generics = Vec::new();

        if matches!(peek, TokenTree::Punct(p) if p.as_char() == '<') {
            // Extract generics

            input.next();

            generics = get_generics(input)?;

            // println!("generics: {generics:?}");
        }

        let (graph_field_name, graph_field_type) = get_graph_field_name_type(input)?;

        Ok(GraphInfo::new(
            struct_name,
            generics,
            graph_field_name,
            graph_field_type,
        ))
    } else {
        myerror!("unexpected token", input)
    }
}

fn get_graph_field_name_type(
    input: &mut Peekable<impl Iterator<Item = TokenTree>>,
) -> Result<(String, TokenStream), CompileError> {
    let end_of_input = Err(CompileError::new(
        "unexpected end of input",
        Span::mixed_site(),
    ));

    match input.peek() {
        Some(TokenTree::Group(g)) => {
            let delimiter = g.delimiter();

            if delimiter != Delimiter::Parenthesis && delimiter != Delimiter::Brace {
                return myerror!(
                    "expected a group enclosed in curly brackets or parentheses",
                    input
                );
            }

            if delimiter == Delimiter::Parenthesis {
                // a named tuple

                // in this case only a tuple with one field is
                // supported

                let mut body = g.stream().into_iter().peekable();

                while let Some(tree) = body.peek() {
                    if matches!(tree, TokenTree::Punct(p) if p.as_char() == ',') {
                        return myerror!(
                            "Among named tuples, only those with one field are supported",
                            input
                        );
                    }

                    body.next();
                }

                let mut body = g.stream().into_iter().peekable();

                let _vis = get_visibility_mod(&mut body)?;

                return Ok(("0".to_string(), body.collect()));
            }

            let mut body = g.stream().into_iter().peekable();

            if body.peek().is_none() {
                return end_of_input;
            }

            get_visibility_mod(&mut body)?;

            let mut cloned_body = body.clone();

            while move_attributes(&mut cloned_body).is_ok() {}

            let _ = get_visibility_mod(&mut cloned_body)?;

            let mut result_name = get_first_ident(&mut cloned_body, g.span())?.to_string();

            move_punct(&mut cloned_body, ':')?;

            if cloned_body.peek().is_none() {
                return end_of_input;
            }

            let mut result_type = get_until(
                &mut cloned_body,
                |tree| matches!(tree, TokenTree::Punct(p) if p.as_char() == ','),
                true,
                true,
            )?;

            let mut result = (result_name, result_type);

            'search: while let Some(tree) = body.next() {
                match tree {
                    TokenTree::Punct(p) if p.as_char() == '#' => match body.peek() {
                        Some(TokenTree::Group(g)) if g.delimiter() == Delimiter::Bracket => {
                            let mut attr_stream = g.stream().into_iter().peekable();

                            let mut found_attribute = false;

                            while let Some(TokenTree::Ident(id)) = attr_stream.next() {
                                if id.to_string() == "graph" {
                                    found_attribute = true;

                                    break;
                                }

                                get_until(
                                    &mut attr_stream,
                                    |tree| matches!(tree, TokenTree::Punct(p) if p.as_char() == ','),
                                    true,
                                    true,
                                )?;
                            }

                            body.next();

                            if found_attribute {
                                while move_attributes(&mut body).is_ok() {}

                                get_visibility_mod(&mut body)?;

                                result_name = get_ident(&mut body)?.to_string();

                                move_punct(&mut body, ':')?;

                                result_type = get_until(
                                    &mut body,
                                    |tree| matches!(tree, TokenTree::Punct(p) if p.as_char() == ','),
                                    true,
                                    true,
                                )?;

                                result = (result_name, result_type);

                                break 'search;
                            }
                        }
                        Some(_) => {
                            return myerror!("expected a group enclosed in square brackets", body);
                        }
                        None => {
                            return end_of_input;
                        }
                    },
                    _ => {}
                }
            }

            Ok(result)
        }
        Some(_) => myerror!("expected a group or a semicolon", input),

        _ => end_of_input,
    }
}

fn get_generics(
    input: &mut Peekable<impl Iterator<Item = TokenTree>>,
) -> Result<Vec<Generic>, CompileError> {
    // Assume the starting '<' punct has already been consumed.

    let mut generic_map: HashMap<String, TokenStream> = Default::default();

    let mut result: Vec<Generic> = Vec::new();

    while !matches!(input.peek(), Some(TokenTree::Punct(p)) if p.as_char() == '>') {
        let ident = get_ident(input)?.to_string();

        let mut stream = TokenStream::new();

        if matches!(input.peek(), Some(TokenTree::Punct(p)) if p.as_char() == ':') {
            input.next();
            stream = get_until(
                input,
                |tree| matches!(tree, TokenTree::Punct(p) if p.as_char() == ',' || p.as_char() == '>'),
                false,
                false,
            )?;
        }

        generic_map.insert(ident, stream);

        let _ = move_punct(input, ',');
    }

    assert!(matches!(input.next(), Some(TokenTree::Punct(p)) if p.as_char() == '>'));

    if matches!(input.peek(), Some(TokenTree::Ident(id)) if id.to_string() == "where") {
        // where clauses

        input.next();

        while !matches!(input.peek(), Some(TokenTree::Group(g)) if g.delimiter() == Delimiter::Brace)
        {
            let ident = get_ident(input)?.to_string();

            move_punct(input, ':')?;

            let stream = get_until(
                input,
                |tree| match tree {
                    TokenTree::Punct(p) if p.as_char() == ',' => true,
                    TokenTree::Group(g) if g.delimiter() == Delimiter::Brace => true,
                    _ => false,
                },
                false,
                false,
            )?;

            generic_map.insert(ident, stream);

            let _ = move_punct(input, ',');
        }
    }

    if generic_map.is_empty() {
        // this is not valid syntax anyways
        return myerror!("empty generics section?", input);
    }

    for (k, v) in generic_map {
        result.push(Generic::new(Ident::new(k.as_str(), Span::mixed_site()), v));
    }

    Ok(result)
}

fn get_ident(input: &mut Peekable<impl Iterator<Item = TokenTree>>) -> Result<Ident, CompileError> {
    match input.peek() {
        Some(TokenTree::Ident(id)) => {
            let id = id.clone();

            input.next();

            Ok(id)
        }
        Some(next_tree) => {
            let span = next_tree.span();

            Err(CompileError::new("expected an identifier", span))
        }
        _ => Err(CompileError::new(
            "unexpected end of input",
            Span::mixed_site(),
        )),
    }
}

fn get_first_ident(
    input: &mut Peekable<impl Iterator<Item = TokenTree>>,
    span: Span,
) -> Result<Ident, CompileError> {
    for tree in input {
        if let TokenTree::Ident(id) = tree {
            return Ok(id);
        }
    }

    Err(CompileError::new("expect at least one identifier", span))
}

fn get_until(
    input: &mut Peekable<impl Iterator<Item = TokenTree>>,
    predicate: impl Fn(&TokenTree) -> bool,
    accept_end: bool,
    consume_boundary: bool,
) -> Result<TokenStream, CompileError> {
    let mut trees: Vec<TokenTree> = Vec::new();

    let mut found_predicate = false;

    if consume_boundary {
        for tree in input.by_ref() {
            if predicate(&tree) {
                found_predicate = true;
                break;
            }

            trees.push(tree);
        }
    } else {
        while let Some(tree) = input.peek() {
            if predicate(tree) {
                found_predicate = true;
                break;
            }

            let tree = input.next().unwrap();

            trees.push(tree);
        }
    }

    if found_predicate || accept_end {
        Ok(trees.into_iter().collect())
    } else {
        Err(CompileError::new(
            "unexpected end of input",
            Span::mixed_site(),
        ))
    }
}

fn move_punct(
    input: &mut Peekable<impl Iterator<Item = TokenTree>>,
    punct: char,
) -> Result<(), CompileError> {
    let error_mes = format!("expect punctuation {punct}");

    match input.peek() {
        Some(TokenTree::Punct(p)) if p.as_char() == punct => {
            input.next();

            Ok(())
        }
        Some(_) => myerror!(error_mes, input),
        _ => Err(CompileError::new(
            "unexpected end of input",
            Span::mixed_site(),
        )),
    }
}

fn move_attributes(
    input: &mut Peekable<impl Iterator<Item = TokenTree>>,
) -> Result<(), CompileError> {
    let error_mes = "expect attributes";
    let end_of_input = Err(CompileError::new(
        "unexpected end of input",
        Span::mixed_site(),
    ));

    match input.peek() {
        Some(TokenTree::Punct(p)) if p.as_char() == '#' => {
            input.next();

            match input.peek() {
                Some(TokenTree::Group(g)) if g.delimiter() == Delimiter::Bracket => {
                    input.next();

                    Ok(())
                }
                Some(_) => {
                    myerror!("expected a group in square brackets", input)
                }
                _ => end_of_input,
            }
        }
        Some(_) => myerror!(error_mes, input),
        _ => end_of_input,
    }
}