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
// schema.rs
//
// Copyright (c) 2019  Douglas Lau
//
use crate::common::Define;
use crate::datetime::{Date, DateTime, Time};
use crate::error::ParseError;
use std::str::FromStr;

/// A MuON value
///
/// Warning: this type is not fully implemented.
#[derive(Debug)]
#[allow(dead_code)]
pub enum Value {
    /// Text value
    Text(String),
    /// Boolean value
    Bool(bool),
    // Int(Integer),
    // Number(Number),
    /// Date and time with offset
    DateTime(DateTime),
    /// Date with no time or offset
    Date(Date),
    /// Time with no date or offset
    Time(Time),
    // Record(Map<String, Value>),
    // Dict(Map<Value, Value>),
    // Any(Map<String, Value>),
    /// Optional value
    Optional(Option<Box<Value>>),
    /// List of values
    List(Vec<Value>),
}

/// Type modifier for a schema
#[derive(Debug)]
pub enum Modifier {
    /// Optional values may not be present
    Optional,
    /// List of values
    List,
}

/// Schema Node
#[derive(Debug)]
pub struct Node<'a> {
    /// Indent level
    indent: usize,
    /// Type name
    name: &'a str,
    /// Type modifier
    modifier: Option<Modifier>,
    /// Node type
    node_type: Type,
    /// Default value
    default: Option<Value>,
}

/// Schema Type
#[derive(Debug)]
pub enum Type {
    /// Text is a `String`
    Text,
    /// Boolean is a `bool`
    Bool,
    /// Integer is a signed or unsigned int
    Int,
    /// Number parses into `f64` or `f32`
    Number,
    /// Date-time parses into [DateTime](struct.DateTime.html)
    DateTime,
    /// Date parses into [Date](struct.Date.html)
    Date,
    /// Time parses into [Time](struct.Time.html)
    Time,
    /// Record parses into a struct or
    /// [Value::Record](enum.Value.html#variant.Record)
    Record,
    /// Dictionary parses into [HashMap](struct.HashMap.html)
    Dictionary,
    /// Any type
    Any,
}

/// Full schema
#[derive(Debug)]
pub struct Schema<'a> {
    /// List of all nodes
    nodes: Vec<Node<'a>>,
    /// Flag indicating reading finished
    finished: bool,
}

impl Modifier {
    /// Create a type modifier from start of a string slice
    fn from_str_start(val: &str) -> (Option<Self>, &str) {
        let v: Vec<&str> = val.splitn(2, ' ').collect();
        if v.len() > 1 {
            match v[0] {
                "optional" => (Some(Modifier::Optional), v[1]),
                "list" => (Some(Modifier::List), v[1]),
                _ => (None, v[0]),
            }
        } else {
            (None, v[0])
        }
    }
}

impl FromStr for Type {
    type Err = ParseError;

    fn from_str(val: &str) -> Result<Self, Self::Err> {
        match val {
            "text" => Ok(Type::Text),
            "bool" => Ok(Type::Bool),
            "int" => Ok(Type::Int),
            "number" => Ok(Type::Number),
            "datetime" => Ok(Type::DateTime),
            "date" => Ok(Type::Date),
            "time" => Ok(Type::Time),
            "record" => Ok(Type::Record),
            "dictionary" => Ok(Type::Dictionary),
            "any" => Ok(Type::Any),
            _ => Err(ParseError::InvalidType),
        }
    }
}

impl<'a> Node<'a> {
    /// Create a schema node from a definition
    fn from_define(define: Define<'a>) -> Result<Self, ParseError> {
        let indent = define.indent;
        let name = define.key;
        let value = define.value;
        let (modifier, value) = Modifier::from_str_start(value);
        let v: Vec<&str> = value.splitn(2, ' ').collect();
        if v.len() > 0 {
            let node_type = v[0].parse()?;
            // FIXME: parse default value
            let default = None;
            Ok(Node {
                indent,
                name,
                modifier,
                node_type,
                default,
            })
        } else {
            Err(ParseError::InvalidType)
        }
    }

    /// Check if node indent is valid with previous node
    fn is_indent_valid(&self, prev: Option<&Self>) -> bool {
        match prev {
            None => self.indent == 0,
            Some(prev) => {
                self.indent <= prev.indent
                    || match prev.node_type {
                        Type::Record | Type::Dictionary | Type::Any => {
                            self.indent == prev.indent + 1
                        }
                        _ => false,
                    }
            }
        }
    }
}

impl<'a> Schema<'a> {
    /// Create a new schema
    pub fn new() -> Self {
        let nodes = vec![];
        let finished = false;
        Schema { nodes, finished }
    }

    /// Add node
    fn add_node(&mut self, node: Node<'a>) -> Result<(), ParseError> {
        if node.is_indent_valid(self.nodes.last()) {
            self.nodes.push(node);
            Ok(())
        } else {
            Err(ParseError::InvalidIndent)
        }
    }

    /// Add a define
    pub fn add_define(&mut self, def: Define<'a>) -> Result<bool, ParseError> {
        if self.finished {
            Ok(false)
        } else {
            self.add_node(Node::from_define(def)?)?;
            Ok(true)
        }
    }

    /// Finish the schema
    pub fn finish(&mut self) -> bool {
        if self.finished {
            true
        } else {
            self.finished = true;
            false
        }
    }
}