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
pub trait Node {
    fn node_step(&mut self, runner: NodeRunner) -> String;
}

impl<U> Node for Vec<U> where U: Node {
    fn node_step(&mut self, mut runner: NodeRunner) -> String {
        match runner.step() {
            NodeToken::ChainIndex (index) => {
                let length = self.len();
                match self.get_mut(index) {
                    Some (item) => item.node_step(runner),
                    None      => return format!("Used index {} on a list of size {} (try a value between 0-{}", index, length, length)
                }
            },
            NodeToken::ChainProperty (ref s) if s == "length" => { self.len().node_step(runner) }
            action => { format!("List cannot '{:?}'", action) }
        }
    }
}

macro_rules! int_node {
    ($e:ty) => {
        impl Node for $e {
            fn node_step(&mut self, mut runner: NodeRunner) -> String {
                match runner.step() {
                    NodeToken::Get         => { (*self).to_string() }
                    NodeToken::Set (value) => { *self = value.parse().unwrap(); String::from("") }
                    action                 => { format!("usize cannot '{:?}'", action) }
                }
            }
        }
    }
}

impl Node for bool {
    fn node_step(&mut self, mut runner: NodeRunner) -> String {
        match runner.step() {
            NodeToken::Get         => { if *self { String::from("true") } else { String::from("false") } }
            NodeToken::Set (value) => { *self = value.as_str() == "true"; String::from("") }
            action                 => { format!("bool cannot '{:?}'", action) }
        }
    }
}

impl Node for String {
    fn node_step(&mut self, mut runner: NodeRunner) -> String {
        match runner.step() {
            NodeToken::Get         => { (*self).clone() }
            NodeToken::Set (value) => { *self = value; String::from("") }
            action                 => { format!("String cannot '{:?}'", action) }
        }
    }
}

int_node!(i64);
int_node!(u64);
int_node!(i32);
int_node!(u32);
int_node!(i16);
int_node!(u16);
int_node!(i8);
int_node!(u8);
int_node!(isize);
int_node!(usize);

pub struct NodeRunner {
    tokens: Vec<NodeToken>
}

impl NodeRunner {
    pub fn new(command: &str) -> Result<NodeRunner, String> {
        // add first identifier to token as property
        // get next identifier, could be:
        // *   ChainProperty - starts with '.'
        // *   ChainKey      - starts with '[0-9' ends with ']'
        // *   ChainIndex    - starts with '[a-z' ends with ']'
        // repeat until space found
        // then add identifier as action including any arguments seperated by spaces
        let mut tokens: Vec<NodeToken> = vec!();
        let mut token_progress = NodeTokenProgress::ChainProperty;
        let mut token_begin = 0;

        let chars: Vec<char> = command.chars().collect();
        for (i, c_ref) in chars.iter().enumerate() {
            let c = *c_ref;
            if c == '.' || c == ' ' || c == '[' {
                tokens.push(match token_progress {
                    NodeTokenProgress::ChainProperty => {
                        let token_str = &command[token_begin..i];
                        if token_str.len() == 0 {
                            return Err (String::from("Missing property"));
                        }
                        NodeToken::ChainProperty (token_str.to_string())
                    }

                    NodeTokenProgress::ChainIndex => {
                        let token_str = &command[token_begin..i-1];
                        if token_str.len() == 0 {
                            return Err (String::from("Missing index"));
                        }
                        match command[token_begin..i-1].parse() {
                            Ok (index) => NodeToken::ChainIndex (index),
                            Err (_)    => return Err (String::from("Not a valid index"))
                        }
                    }

                    NodeTokenProgress::ChainKey => {
                        let token_str = &command[token_begin..i-1];
                        if token_str.len() == 0 {
                            return Err (String::from("Missing index"));
                        }
                        NodeToken::ChainKey (token_str.to_string())
                    }
                    NodeTokenProgress::Action => {
                        NodeToken::Get
                    }
                });
                token_begin = i+1;
            }

            match c {
                '.' => {
                    token_progress = NodeTokenProgress::ChainProperty;
                }
                ' ' => {
                    token_progress = NodeTokenProgress::Action;
                    break;
                }
                '[' => {
                    if let Some(next_c) = chars.get(i+1) {
                        if next_c.is_digit(10) {
                            token_progress = NodeTokenProgress::ChainIndex;
                        }
                        else if next_c.is_alphabetic() {
                            token_progress = NodeTokenProgress::ChainKey;
                        }
                        else {
                            return Err (String::from("Not a valid key or index."));
                        }
                    }
                    else {
                        return Err (String::from("Unfinished key or index."));
                    }
                }
                _ => { }
            }
        }

        // add action
        if let NodeTokenProgress::Action = token_progress {
            let mut action = command[token_begin..].split_whitespace();
            tokens.push(match action.next() {
                Some("get") => NodeToken::Get,
                Some("set") => {
                    match action.next() {
                        Some(arg) => NodeToken::Set(arg.to_string()),
                        None => return Err (String::from("No argument given to set action"))
                    }
                }
                Some("copy")  => NodeToken::CopyFrom,
                Some("paste") => NodeToken::PasteTo,
                Some(&_)      => return Err (String::from("Action is invalid")), // TODO: Custom actions
                None          => return Err (String::from("This should be unreachable: No Action"))
            });
        }
        else {
            return Err (String::from("No action"));
        }

        tokens.reverse();
        println!("{:?}", tokens);

        Ok(NodeRunner {
            tokens: tokens
        })
    }

    pub fn step(&mut self) -> NodeToken {
        self.tokens.pop().unwrap()
    }
}

#[derive(Debug)]
pub enum NodeTokenProgress {
    ChainProperty,
    ChainIndex,
    ChainKey,
    Action
}

#[derive(Debug)]
pub enum NodeToken {
    ChainProperty (String),
    ChainIndex (usize),
    ChainKey (String),
    Get,
    Set (String),
    CopyFrom,
    PasteTo,
    Custom (String),
}