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
mod matchcode;
mod names;
mod repr;
mod tokens;
mod trace;
mod visitor;

pub use proc_macro2;

pub use crate::matchcode::compile_input;

use crate::trace::Trace;

use log::trace;
use proc_macro2::TokenStream;
use syn::parse::Parse;
use crate::tokens::MetaContext;
use std::fmt::{Display, Formatter};

#[derive(Debug)]
pub struct Error;

/*/
pub struct Error{
    message: String,
    location: Option<(proc_macro2::LineColumn, proc_macro2::LineColumn)>,
}

impl Error {
    pub fn annotate(&self, src: &str) -> String {
        let start_line = self.location.as_ref().unwrap().0.line;
        let start_col = self.location.as_ref().unwrap().0.column;
        let src = src.lines().nth(start_line).expect("error location within source");
        let pointer = "^";
        format!("{}\n{}\n{:start_col$}", &self.message, &src, pointer, start_col = start_col)
    }
}
*/

pub type Result<T> = std::result::Result<T, Error>;

struct Stmts(Vec<syn::Stmt>);
impl Parse for Stmts {
    fn parse(input: syn::parse::ParseStream) -> syn::parse::Result<Self> {
        Ok(Stmts(input.call(syn::Block::parse_within)?))
    }
}

pub struct PatternDef{ nodes: TokenStream, ids: TokenStream }
impl PatternDef {
    pub fn lex(args: TokenStream, body: TokenStream) -> PatternDef {
        let (nodes, ids) = MetaContext::new(args).apply(body);
        PatternDef{ nodes, ids }
    }

    pub fn parse(self) -> Result<Pattern> {
        trace!("nodes: {}", &self.nodes);
        trace!("ids: {}", &self.ids);
        /*{
            message: e.to_string(),
            location: Some((e.span().start(), e.span().end())),
        }*/
        // parse as a sequence of statements
        let nodes: Stmts = syn::parse2(self.nodes).map_err(|_| Error)?;
        let ids: Stmts = syn::parse2(self.ids).expect("if <nodes> succeeded <ids> must");
        let (mut nodes, mut ids) = (nodes.0, ids.0);
        if nodes.len() == 1 {
            if let syn::Stmt::Expr(_) = nodes[0] {
                if let (syn::Stmt::Expr(nodes), syn::Stmt::Expr(ids)) = (nodes.remove(0), ids.remove(0)) {
                    return Ok(Pattern::Expr{ nodes, ids });
                }
                unreachable!();
            }
        }
        Ok(Pattern::StmtSeq{ nodes, ids })
    }
}

pub enum Pattern {
    StmtSeq { nodes: Vec<syn::Stmt>, ids: Vec<syn::Stmt> },
    Expr { nodes: syn::Expr, ids: syn::Expr },
}

pub enum Ir { 
    StmtSeq { trace: Trace },
    Expr { trace: Trace },
}

enum MatchesInner<'p, 'it> {
    StmtSeq { matches: crate::trace::ToplevelMatches<'p, 'it> },
    Expr { matches: crate::trace::InternalMatches<'p, 'it> },
}

#[derive(Debug)]
pub struct Match {
    pub context: String,
    pub bindings: String,
}

pub struct Matches<'p, 'i, 'it> {
    inner: MatchesInner<'p, 'it>,
    pattern: &'p Trace,
    input: &'i [syn::Stmt],
}

impl Iterator for Matches<'_, '_, '_> {
    type Item = Match;
    fn next(&mut self) -> Option<Self::Item> {
        match &mut self.inner {
            MatchesInner::StmtSeq { matches } => matches.next().map(|m| {
                let mut context = "[".to_owned();
                let mut first = true;
                for s in &self.input[..m] {
                    if !first {
                        context.push_str(",");
                    }
                    first = false;
                    context.push_str(&crate::matchcode::stmt_repr(s));
                }
                if !first { context.push_str(","); }
                context.push_str("\"$1\"");
                for s in &self.input[m+self.pattern.toplevel_len()..] {
                    context.push_str(",");
                    context.push_str(&crate::matchcode::stmt_repr(s));
                }
                context.push_str("]");
                let bindings = crate::matchcode::bind_stmts(self.pattern, &self.input[m..m + self.pattern.toplevel_len()]);
                let bindings = crate::matchcode::bindings_repr(&bindings);
                Match { context, bindings }
            }),
            MatchesInner::Expr { matches } => matches.next().map(|m| {
                let context = crate::matchcode::stmts_tree_repr_of(m.clone(), self.input);
                let extracted = crate::matchcode::bind_expr(crate::trace::ReTracer::new(m), self.input);
                let ex = if let crate::matchcode::Binding::Expr(ex) = extracted.binds[0] {
                    ex
                } else {
                    unreachable!()
                };
                let bindings = crate::matchcode::bind_expr_expr(crate::trace::ReTracer::new(self.pattern.clone()), ex);
                let bindings = crate::matchcode::bindings_repr(&bindings);
                Match { context, bindings }
            }),
        }
    }
}

impl Ir {
    pub fn matches<'p, 'i, 'it>(&'p self, input: &'i [syn::Stmt], input_trace: &'it crate::trace::IndexedTrace) -> Matches<'p, 'i, 'it> {
        let (inner, pattern) = match self {
            Ir::StmtSeq { trace } => {
                (MatchesInner::StmtSeq { matches: trace.toplevel_matches(input_trace) }, trace)
            }
            Ir::Expr { trace } => {
                (MatchesInner::Expr { matches: trace.internal_matches(input_trace) }, trace)
            }
        };
        Matches { inner, pattern, input }
    }
}

pub struct Input { pub stmts: Vec<syn::Stmt> }

impl Input {
    pub fn parse(ts: TokenStream) -> Result<Self> {
        let stmts: Stmts = syn::parse2(ts).map_err(|_| Error)?;
        let stmts = stmts.0;
        Ok(Input { stmts })
    }

    pub fn compile(&self) -> crate::trace::IndexedTrace {
        matchcode::compile_input(&self.stmts)
    }

    pub fn debug_tree_repr(&self) -> String {
        matchcode::stmts_tree_repr_of(matchcode::compile_input(&self.stmts).deindex(), &self.stmts)
    }
}

impl Pattern {
    pub fn compile(&self) -> Ir {
        match self {
            Pattern::StmtSeq { nodes, ids } => Ir::StmtSeq { trace: matchcode::compile_stmts(nodes, ids) },
            Pattern::Expr { nodes, ids } => Ir::Expr { trace: matchcode::compile_expr(nodes, ids) },
        }
    }

    pub fn debug_tree_repr(&self) -> String {
        match self {
            Pattern::StmtSeq { nodes, ids } => matchcode::stmts_tree_repr(nodes, ids),
            Pattern::Expr { nodes, ids } => matchcode::expr_tree_repr(nodes, ids),
        }
    }

    pub fn debug_flat_repr(&self) -> String {
        match self {
            Pattern::StmtSeq { nodes, ids } => matchcode::stmts_flat_repr(nodes, ids),
            Pattern::Expr { nodes, ids } => matchcode::expr_flat_repr(nodes, ids),
        }
    }

    pub fn fragment(&self) -> String {
        match self {
            Pattern::StmtSeq { .. } => "StmtSeq".to_owned(),
            Pattern::Expr { .. } => "Expr".to_owned(),
        }
    }
}

impl Display for PatternDef {
    fn fmt(&self, fmt: &mut Formatter) -> std::fmt::Result {
        write!(fmt, "PatternDef {{ nodes: {}, ids: {} }}", &self.nodes, &self.ids)
    }
}