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
extern crate xml;

mod trace;

pub use trace::Trace;

//use xml::attribute::{Attribute, OwnedAttribute};

/*
type AnyURI = String;
type ID = String;

struct Ink {
	document_id: Option<AnyURI>,
	
	definitions: Vec<Definition>,
	contexts: Vec<Context>,
	traces: Vec<Trace>,
	trace_groups: Vec<TraceGroup>,
	trace_views: Vec<TraceView>,
	annotations: Vec<Annotation>,
	annotations_xml: Vec<AnnotationXML>,
}
*/

pub type ParseResult<'a, T> = Result<T, ParseError<'a>>;

#[derive(Debug)]
pub enum ParseError<'a> {
    EndOfFile,
    UnexpectedValue(&'a str),
}

/**
value   ::= difference_order?  wsp* "-"? wsp* number | "T" | "F" | "*" | "?"
number  ::= (decimal | double | hex)
double  ::= decimal ("e"|"E") ("+"|"-")? digit+ 
decimal ::= digit+ ("." digit*)? | "." digit+
difference_order ::= ("!" | "'" | '"')
**/

// wsp ::= (#x20 | #x9 | #xD | #xA)
pub fn wsp(c: char) -> bool {
    ['\x20', '\x09', '\x0D', '\x0A'].contains(&c)
}

// digit ::= ("0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9")
fn digit(c: char) -> bool {
    c.is_ascii_digit()
}

// hex ::= "#" (digit | "A" | "B" | "C" | "D" | "E" | "F")+
fn hex(mut input: &str) -> ParseResult<(&str, &str)> {
    let mut end = 0;
    let i = input;
    
    // "#"
    if !input.starts_with('#') {
        return Err(ParseError::UnexpectedValue(input));
    }
    input = &input[1..];
    end += 1;
    
    // (digit | "A" | "B" | "C" | "D" | "E" | "F")
    if !input.starts_with(|c: char| c.is_ascii_hexdigit()) {
        return Err(ParseError::UnexpectedValue(input));
    }
    input = &input[1..];
    end += 1;
    
    // (digit | "A" | "B" | "C" | "D" | "E" | "F")*
    while input.starts_with(|c: char| c.is_ascii_hexdigit()) {
        input = &input[1..];
        end += 1;
    }
    
    Ok((input, &i[..end]))
}


#[derive(Debug, PartialEq)]
pub struct Point(Vec<Value>);

impl Point {
    // point ::= (wsp* value)+ wsp*
    //       ::= wsp* value wsp* (value wsp*)*
    fn parse(mut input: &str) -> ParseResult<(&str, Self)> {
        let mut values = Vec::new();
        
        // wsp*
        input = input.trim_left_matches(wsp);
        
        // value
        let (mut input, value) = Value::parse(input)?;
        values.push(value);
        
        // wsp*
        input = input.trim_left_matches(wsp);
        
        // (value wsp*)*
        loop {
            // value
            match Value::parse(input) {
                Ok((i, value)) => {
                    input = i;
                    values.push(value);
                }
                Err(_) => break
            }
            
            // wsp*
            input = input.trim_left_matches(wsp);
        }
        
        Ok((input, Point(values)))
    }
}

#[cfg(test)]
mod point {
    use super::{Point, Value};
    
    #[test]
    #[should_panic]
    fn empty_string() {
        Point::parse("").unwrap();
    }
    
    #[test]
    fn single() {
        let expect = ("", Point(vec![Value::Inferred]));
        assert_eq!(expect, Point::parse("*").unwrap());
        assert_eq!(expect, Point::parse(" *").unwrap());
        assert_eq!(expect, Point::parse(" \t*\r\n").unwrap());
    }
    
    #[test]
    fn many() {
        let expect = ("", Point(vec![Value::Inferred, Value::Inferred]));
        assert_eq!(expect, Point::parse("**").unwrap());
        assert_eq!(expect, Point::parse("* *").unwrap());
        assert_eq!(expect, Point::parse(" * *").unwrap());
        assert_eq!(expect, Point::parse(" * * ").unwrap());
    }
}



//enum DifferenceOrder { First, Second, Third }

#[derive(Debug, PartialEq)]
pub enum Value {
    Inferred,
    NotGiven,
    Bool(bool),
    //Number {
}

impl Value {
    // value ::= difference_order?  wsp* "-"? wsp* number | "T" | "F" | "*" | "?"
    fn parse(input: &str) -> ParseResult<(&str, Self)> {
        if input.is_empty() {
            return Err(ParseError::EndOfFile)
        }
        
        let value = match &input[..1] {
            // "*"
            "*" => Value::Inferred,
            // "?"
            "?" => Value::NotGiven,
            // "T"
            "T" => Value::Bool(true),
            // "F"
            "F" => Value::Bool(false),
            // TODO
            // difference_order?  wsp* "-"? wsp* number
            _ => return Err(ParseError::UnexpectedValue(input))
        };
        
        Ok((&input[1..], value))
    }
}

#[cfg(test)]
mod value {
    use super::Value;
    
    #[test]
    fn inferred() {
        assert_eq!(("", Value::Inferred), Value::parse("*").unwrap());
    }
    
    #[test]
    fn not_given() {
        assert_eq!(("", Value::NotGiven), Value::parse("?").unwrap());
    }
    
    #[test]
    fn boolean() {
        assert_eq!(("", Value::Bool(true)), Value::parse("T").unwrap());
        assert_eq!(("", Value::Bool(false)), Value::parse("F").unwrap());
    }
}



static TEST_INKML: &str = include_str!("test.inkml");



#[cfg(test)]
mod tests {
    use super::*;
    
    #[test]
    fn open_simple_inkml() {
        use xml::reader::XmlEvent;
        use xml::name::OwnedName;
        
        let stream = xml::EventReader::from_str(TEST_INKML);
        let mut current_path = Vec::new();
        let mut trace = None;
        
        for event in stream {
            match event.unwrap() {
                XmlEvent::StartElement { name: OwnedName { local_name, .. }, .. } => {
                    current_path.push(local_name.clone());
                }
                XmlEvent::EndElement { name: OwnedName { local_name, .. }, .. } => {
                    assert!(*current_path.last().unwrap() == local_name);
                    current_path.pop();
                }
                XmlEvent::Characters(data) => {
                    if current_path.last().unwrap() == "trace" {
                        trace = Some(Trace::parse(&data).unwrap().1);
                    }
                }
                _ => {}
            }
        }
        
        assert_eq!(trace.unwrap(), Trace::new(vec![
            Point(vec![Value::Inferred, Value::Inferred]),
            Point(vec![Value::NotGiven]),
            Point(vec![Value::Bool(false), Value::Bool(true)]),
        ]));
    }
}