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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
use crate::BinaryOp::*;
use crate::_aeon_parser::FnUpdateTemp;
use crate::_aeon_parser::FnUpdateTemp::*;
use std::convert::TryFrom;
use std::iter::Peekable;
use std::str::Chars;

impl TryFrom<&str> for FnUpdateTemp {
    type Error = String;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        let tokens = tokenize_function_group(&mut value.chars().peekable(), true)?;
        Ok(*(parse_update_function(&tokens)?))
    }
}

/// **(internal)** An enum of possible tokens occurring in a string representation of
/// a `FnUpdate`.
#[derive(Debug, Eq, PartialEq)]
enum Token {
    Not,                // '!'
    And,                // '&'
    Or,                 // '|'
    Xor,                // '^'
    Imp,                // '=>'
    Iff,                // '<=>'
    Comma,              // ','
    Name(String),       // 'name'
    Tokens(Vec<Token>), // A block of tokens inside parentheses
}

/// **(internal)** Process a peekable iterator of characters into a vector of `Token`s.
///
/// The outer method always consumes the opening parenthesis and the recursive call consumes the
/// closing parenthesis. Use `top_level` to indicate that there will be no closing parenthesis.
fn tokenize_function_group(
    data: &mut Peekable<Chars>,
    top_level: bool,
) -> Result<Vec<Token>, String> {
    let mut output = Vec::new();
    while let Some(c) = data.next() {
        match c {
            c if c.is_whitespace() => { /* Skip whitespace */ }
            // single char tokens
            '!' => output.push(Token::Not),
            ',' => output.push(Token::Comma),
            '&' => output.push(Token::And),
            '|' => output.push(Token::Or),
            '^' => output.push(Token::Xor),
            '=' => {
                if Some('>') == data.next() {
                    output.push(Token::Imp);
                } else {
                    return Result::Err("Expected '>' after '='.".to_string());
                }
            }
            '<' => {
                if Some('=') == data.next() {
                    if Some('>') == data.next() {
                        output.push(Token::Iff)
                    } else {
                        return Result::Err("Expected '>' after '='.".to_string());
                    }
                } else {
                    return Result::Err("Expected '=' after '<'.".to_string());
                }
            }
            // '>' is invalid as a start of a token
            '>' => return Result::Err("Unexpected '>'.".to_string()),
            ')' => {
                return if !top_level {
                    Result::Ok(output)
                } else {
                    Result::Err("Unexpected ')'.".to_string())
                }
            }
            '(' => {
                // start a nested token group
                let tokens = tokenize_function_group(data, false)?;
                output.push(Token::Tokens(tokens));
            }
            c if is_valid_in_name(c) => {
                // start of a variable name
                let mut name = vec![c];
                while let Some(c) = data.peek() {
                    if c.is_whitespace() || !is_valid_in_name(*c) {
                        break;
                    } else {
                        name.push(*c);
                        data.next(); // advance iterator
                    }
                }
                output.push(Token::Name(name.into_iter().collect()));
            }
            _ => return Result::Err(format!("Unexpected '{}'.", c)),
        }
    }
    if top_level {
        Result::Ok(output)
    } else {
        Result::Err("Expected ')'.".to_string())
    }
}

/// **(internal)** Check if given char can appear in a name.
fn is_valid_in_name(c: char) -> bool {
    c.is_alphanumeric() || c == '_' || c == '{' || c == '}'
}

/// **(internal)** Parse a `FnUpdateTemp` using the recursive steps.
fn parse_update_function(data: &[Token]) -> Result<Box<FnUpdateTemp>, String> {
    iff(data)
}

/// **(internal)** Utility method to find first occurrence of a specific token in the token tree.
fn index_of_first(data: &[Token], token: Token) -> Option<usize> {
    return data.iter().position(|t| *t == token);
}

/// **(internal)** Recursive parsing step 1: extract `<=>` operators.
fn iff(data: &[Token]) -> Result<Box<FnUpdateTemp>, String> {
    let iff_token = index_of_first(data, Token::Iff);
    Ok(if let Some(i) = iff_token {
        Box::new(Binary(Iff, imp(&data[..i])?, iff(&data[(i + 1)..])?))
    } else {
        imp(data)?
    })
}

/// **(internal)** Recursive parsing step 2: extract `=>` operators.
fn imp(data: &[Token]) -> Result<Box<FnUpdateTemp>, String> {
    let imp_token = index_of_first(data, Token::Imp);
    Ok(if let Some(i) = imp_token {
        Box::new(Binary(Imp, or(&data[..i])?, imp(&data[(i + 1)..])?))
    } else {
        or(data)?
    })
}

/// **(internal)** Recursive parsing step 3: extract `|` operators.
fn or(data: &[Token]) -> Result<Box<FnUpdateTemp>, String> {
    let or_token = index_of_first(data, Token::Or);
    Ok(if let Some(i) = or_token {
        Box::new(Binary(Or, and(&data[..i])?, or(&data[(i + 1)..])?))
    } else {
        and(data)?
    })
}

/// **(internal)** Recursive parsing step 4: extract `&` operators.
fn and(data: &[Token]) -> Result<Box<FnUpdateTemp>, String> {
    let and_token = index_of_first(data, Token::And);
    Ok(if let Some(i) = and_token {
        Box::new(Binary(And, xor(&data[..i])?, and(&data[(i + 1)..])?))
    } else {
        xor(data)?
    })
}

/// **(internal)** Recursive parsing step 5: extract `^` operators.
fn xor(data: &[Token]) -> Result<Box<FnUpdateTemp>, String> {
    let xor_token = index_of_first(data, Token::Xor);
    Ok(if let Some(i) = xor_token {
        Box::new(Binary(Xor, terminal(&data[..i])?, xor(&data[(i + 1)..])?))
    } else {
        terminal(data)?
    })
}

/// **(internal)** Recursive parsing step 6: extract terminals and negations.
fn terminal(data: &[Token]) -> Result<Box<FnUpdateTemp>, String> {
    if data.is_empty() {
        Err("Expected formula, found nothing.".to_string())
    } else {
        if data[0] == Token::Not {
            return Ok(Box::new(Not(terminal(&data[1..])?)));
        } else if data.len() == 1 {
            // This should be either a name or a parenthesis group, everything else does not make sense.
            match &data[0] {
                Token::Name(name) => {
                    return if name == "true" {
                        Ok(Box::new(Const(true)))
                    } else if name == "false" {
                        Ok(Box::new(Const(false)))
                    } else {
                        Ok(Box::new(Var(name.clone())))
                    }
                }
                Token::Tokens(inner) => return parse_update_function(inner),
                _ => {} // otherwise, fall through to the error at the end.
            }
        } else if data.len() == 2 {
            // If more tokens remain, it means this should be a parameter (function call).
            // Anything else is invalid.
            if let Token::Name(name) = &data[0] {
                if let Token::Tokens(args) = &data[1] {
                    let args = read_args(args)?;
                    return Ok(Box::new(Param(name.clone(), args)));
                }
            }
        }
        Err(format!("Unexpected: {:?}. Expecting formula.", data))
    }
}

/// **(internal)** Parse a list of function arguments. All arguments must be names separated
/// by commas.
fn read_args(data: &[Token]) -> Result<Vec<String>, String> {
    if data.is_empty() {
        return Ok(Vec::new());
    }
    let mut result = Vec::new();
    let mut i = 0;
    while let Token::Name(name) = &data[i] {
        result.push(name.clone());
        i += 1;
        if data.len() == i {
            return Ok(result);
        }
        if data[i] != Token::Comma {
            return Err(format!("Expected ',', found {:?}.", data[i]));
        }
        i += 1;
        if data.len() == i {
            return Err("Unexpected ',' at the end of an argument list.".to_string());
        }
    }
    Err(format!("Unexpected token {:?} in argument list.", data[i]))
}

#[cfg(test)]
mod tests {
    use crate::_aeon_parser::FnUpdateTemp;
    use std::convert::TryFrom;

    #[test]
    fn parse_update_function_basic() {
        let inputs = vec![
            "var",
            "var1(a, b, c)",
            "!foo(a)",
            "(var(a, b) | x)",
            "(xyz123 & abc)",
            "(a ^ b)",
            "(a => b)",
            "(a <=> b)",
            "(a <=> !(f(a, b) => (c ^ d)))",
        ];
        for str in inputs {
            assert_eq!(str, format!("{}", FnUpdateTemp::try_from(str).unwrap()))
        }
    }

    #[test]
    fn test_invalid_tokens() {
        assert!(FnUpdateTemp::try_from("a = b").is_err());
        assert!(FnUpdateTemp::try_from("a > b").is_err());
        assert!(FnUpdateTemp::try_from("a <= b").is_err());
        assert!(FnUpdateTemp::try_from("a <- b").is_err());
        assert!(FnUpdateTemp::try_from("a ? b").is_err());
    }

    #[test]
    fn test_invalid_parentheses() {
        assert!(FnUpdateTemp::try_from("a & (b <=> c").is_err());
        assert!(FnUpdateTemp::try_from("(f => g))").is_err());
        assert!(FnUpdateTemp::try_from("a <=> (f(a,b ^ g)").is_err());
        assert!(FnUpdateTemp::try_from("a | (f(a,b)) ^ g)").is_err());
    }

    #[test]
    fn test_malformed_args() {
        assert!(FnUpdateTemp::try_from("f(a b c)").is_err());
        assert!(FnUpdateTemp::try_from("f(a, b, c,)").is_err());
        assert!(FnUpdateTemp::try_from("f(a & c)").is_err());
        assert!(FnUpdateTemp::try_from("f(a, & c)").is_err());
        assert!(FnUpdateTemp::try_from("f(a, f(b), c)").is_err());
    }

    #[test]
    fn test_missing_formula() {
        assert!(FnUpdateTemp::try_from("a & | g").is_err());
        assert!(FnUpdateTemp::try_from("a &").is_err());
        assert!(FnUpdateTemp::try_from("a & !").is_err());
        assert!(FnUpdateTemp::try_from("a & | g").is_err());
        assert!(FnUpdateTemp::try_from("a & a b c").is_err());
        assert!(FnUpdateTemp::try_from("a & ^x").is_err());
        assert!(FnUpdateTemp::try_from("a & x^").is_err());
        assert!(FnUpdateTemp::try_from(",").is_err());
        assert!(FnUpdateTemp::try_from(",hello").is_err());
        assert!(FnUpdateTemp::try_from("hello,").is_err());
    }

    #[test]
    fn operator_priority_test() {
        let formula = "a & b | c => d ^ e <=> f";
        let expected = "((((a & b) | c) => (d ^ e)) <=> f)".to_string();
        assert_eq!(
            expected,
            FnUpdateTemp::try_from(formula).unwrap().to_string()
        );
    }
}