summaryrefslogtreecommitdiff
path: root/mlua_derive/src/chunk.rs
blob: ee9b82215bbea70fd5af0cf16f0e574a3c2d56d2 (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
use proc_macro::{TokenStream, TokenTree};

use crate::token::{Pos, Token, Tokens};

#[derive(Debug, Clone)]
pub(crate) struct Capture {
    key: Token,
    rust: TokenTree,
}

impl Capture {
    fn new(key: Token, rust: TokenTree) -> Self {
        Self { key, rust }
    }

    /// Token string inside `chunk!`
    pub(crate) fn key(&self) -> &Token {
        &self.key
    }

    /// As rust variable, e.g. `x`
    pub(crate) fn as_rust(&self) -> &TokenTree {
        &self.rust
    }
}

#[derive(Debug)]
pub(crate) struct Captures(Vec<Capture>);

impl Captures {
    pub(crate) fn new() -> Self {
        Self(Vec::new())
    }

    pub(crate) fn add(&mut self, token: &Token) -> Capture {
        let tt = token.tree();
        let key = token.clone();

        match self.0.iter().find(|arg| arg.key() == &key) {
            Some(arg) => arg.clone(),
            None => {
                let arg = Capture::new(key, tt.clone());
                self.0.push(arg.clone());
                arg
            }
        }
    }

    pub(crate) fn captures(&self) -> &[Capture] {
        &self.0
    }
}

#[derive(Debug)]
pub(crate) struct Chunk {
    source: String,
    caps: Captures,
}

impl Chunk {
    pub(crate) fn new(tokens: TokenStream) -> Self {
        let tokens = Tokens::retokenize(tokens);

        let mut source = String::new();
        let mut caps = Captures::new();

        let mut pos: Option<Pos> = None;
        for t in tokens {
            if t.is_cap() {
                caps.add(&t);
            }

            let (line, col) = (t.start().line, t.start().column);
            let (prev_line, prev_col) = pos
                .take()
                .map(|lc| (lc.line, lc.column))
                .unwrap_or_else(|| (line, col));

            #[allow(clippy::comparison_chain)]
            if line > prev_line {
                source.push('\n');
            } else if line == prev_line {
                for _ in 0..col.saturating_sub(prev_col) {
                    source.push(' ');
                }
            }
            source.push_str(&t.to_string());

            pos = Some(t.end());
        }

        Self {
            source: source.trim_end().to_string(),
            caps,
        }
    }

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

    pub(crate) fn captures(&self) -> &[Capture] {
        self.caps.captures()
    }
}