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
#![feature(proc_macro_span)]

extern crate petgraph;
extern crate proc_macro;

#[cfg(test)]
mod tests;

use petgraph::graphmap::UnGraphMap;
use std::cmp::Ordering;
use std::ops::{Deref, DerefMut};
use std::str::FromStr;
use unicode_normalization::char::is_combining_mark;

#[derive(Debug)]
pub enum Error {
    TODO,
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct LineColumn {
    line: usize,
    column: usize,
}

#[derive(Debug, Copy, Clone)]
pub enum Brush {
    NorthSouth(char),
    EastWest(char),
    NorthEastSouthWest(char),
    NorthWestSouthEast(char),
}

#[derive(Debug, Copy, Clone)]
pub struct Edge(Option<char>, Brush, Option<char>);

#[derive(Debug)]
struct Graph(UnGraphMap<LineColumn, Edge>);

/*
"  ┌──
 ─╲┼╱┐
  │╳ │
  └──┘
   ┏━━
 ━╲╋╱┓
  ┃╳ ┃
  ┗━━┛
   +--
 -\+/+
  |X |
  +--+
   ╔══
 ═╲╬╱╗
  ║╳ ║
  ╚══╝
   ╱╲
   ╲╱
"
*/

impl From<proc_macro::LineColumn> for LineColumn {
    fn from(loc: proc_macro::LineColumn) -> Self {
        let proc_macro::LineColumn { line, column } = loc;
        LineColumn { line, column }
    }
}

/*
impl From<char> for Brush {
    fn from(c: char) -> Option<Self> {
        match c {
            '│' | '║' | '┃' | '┊' | '┋' | '┆' | '┇' | '╎' | '╏' | '|' => Some(Brush::NorthSouth(c)),
            '─' | '═' | '━' | '┈' | '┉' | '┄' | '┅' | '╌' | '╍' | '-' => Some(Brush::EastWest(c)),
            '╱' | '/' => Some(Brush::NorthEastSouthWest(c)),
            '╲' | '\\' => Some(Brush::NorthWestSouthEast(c)),
            _ => None,
        }
    }
}
*/

impl Ord for LineColumn {
    fn cmp(&self, other: &Self) -> Ordering {
        match self.line.cmp(&other.line) {
            Ordering::Equal => self.column.cmp(&other.column),
            o => o,
        }
    }
}

impl PartialOrd for LineColumn {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Deref for Graph {
    type Target = UnGraphMap<LineColumn, Edge>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl DerefMut for Graph {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

#[derive(Debug, Copy, Clone)]
enum Tx {
    Initial,
    Build { start: LineColumn, edge: Edge },
}

struct State {
    graph: UnGraphMap<LineColumn, Edge>,
    ports: Vec<(LineColumn, LineColumn, LineColumn, Edge)>,
    source_location: LineColumn,
    visible_location: LineColumn,
    tx: Tx,
}

impl State {
    fn next(&mut self, c: char) {
        let LineColumn { line, column } = self.visible_location;
        let ports = self.ports.to_owned();
        self.ports = Vec::with_capacity(ports.len() + 1);
        for (mut location, start, end, edge) in ports {
            let brush = edge.1;
            if location.line + 1 == line {
                if match brush {
                    Brush::NorthSouth(brush) => {
                        if location.column == column {
                            brush == c
                        } else {
                            false
                        }
                    }
                    Brush::EastWest(_) => false,
                    Brush::NorthEastSouthWest(brush) => {
                        if location.column + 1 == column {
                            brush == c
                        } else {
                            false
                        }
                    }
                    Brush::NorthWestSouthEast(brush) => {
                        if location.column == column + 1 {
                            brush == c
                        } else {
                            false
                        }
                    }
                } {
                    location.line = line;
                    location.column = column;
                    self.ports
                        .push((location, start, self.source_location, edge));
                } else {
                    self.ports.push((location, start, end, edge));
                }
            } else {
                self.graph.add_edge(start, end, edge);
            }
        }

        self.tx = match self.tx {
            Tx::Initial => match c {
                '─' | '═' | '━' | '┈' | '┉' | '┄' | '┅' | '╌' | '╍' | '-'
                | '=' => {
                    let start = self.graph.add_node(self.source_location.clone());
                    let edge = Edge(None, Brush::EastWest(c), None);
                    Tx::Build { start, edge }
                }
                '│' | '║' | '┃' | '┊' | '┋' | '┆' | '┇' | '╎' | '╏' | '|' => {
                    let start = self.graph.add_node(self.source_location.clone());
                    self.ports.push((
                        self.visible_location,
                        start,
                        self.source_location,
                        Edge(None, Brush::NorthSouth(c), None),
                    ));
                    Tx::Initial
                }
                _ => Tx::Initial,
            },
            Tx::Build { start, edge } => match edge.1 {
                Brush::EastWest(chr) if c == chr => self.tx,
                _ => {
                    let mut source_location = self.source_location.clone();
                    source_location.column -= 1;
                    let end = self.graph.add_node(source_location);
                    self.graph.add_edge(start, end, edge);
                    Tx::Initial
                }
            },
        }
    }

    fn finish(&mut self) {
        match self.tx {
            Tx::Initial => (),
            _ => self.next('\n'),
        }
    }
}

impl FromStr for Graph {
    type Err = Error;

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        let mut state = &mut State {
            graph: UnGraphMap::new(),
            ports: Vec::new(),
            source_location: LineColumn { line: 1, column: 0 },
            visible_location: LineColumn { line: 1, column: 0 },
            tx: Tx::Initial,
        };

        for c in input.chars() {
            if !is_combining_mark(c) {
                state.next(c);

                state.visible_location.column += 1;
            }

            // TODO drop unreachable ports

            if c == '\n' {
                state.visible_location.line += 1;
                state.visible_location.column = 0;
                state.source_location.line += 1;
                state.source_location.column = 0;
            } else {
                state.source_location.column += 1;
            }
        }
        state.finish();

        Ok(Graph(state.graph.to_owned()))
    }
}