num_parser 1.0.2

A math interpreter and evaluator
Documentation
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
use itertools::Itertools;

use crate::{
    objects::Expression,
    out::{ErrorType, EvalResult},
    token::{
        tokentype::{IdentifierType, TokenType},
        Token, TokenStream,
    },
    value::Value,
};

/// An expression is a node in the expression tree.
pub type Node = Expression;

/// A tree needs to be interpreted to determine the requested operation.
#[derive(Debug)]
pub struct Tree(pub Node);

/// Builds an expression tree, effectively parsing the token stream.
pub fn build_tree(stream: TokenStream) -> EvalResult<Tree> {
    check_brackets(&stream)?;
    // Sort by precedence
    let mut sorted_node_tokens = sort_node_tokens(&stream)?;

    Ok(Tree(create_node(
        &mut sorted_node_tokens,
        &stream,
        None,
        (0, stream.len()),
    )?))
}

fn check_brackets(stream: &TokenStream) -> EvalResult<()> {
    let mut depth = 0;
    for token in stream {
        match token.r#type {
            TokenType::OpeningBracket => depth += 1,
            TokenType::ClosingBracket => {
                depth -= 1;
                if depth < 0 {
                    // Also check for invalid brackets
                    return Err(ErrorType::InvalidClosingBracket);
                }
            }
            _ => (),
        }
    }
    match depth {
        0 => Ok(()),
        _ => return Err(ErrorType::MissingClosingBracket),
    }
}

/// Contains the token info inside the token stream.
#[derive(Clone, PartialEq, Debug)]
struct TokenInfo {
    /// The contained token.
    pub token: Token,
    /// The token position inside the stream.
    pub position: usize,
    /// The brackets depth at the token position.
    pub depth: u16,
    /// The token precedence.
    pub precedence: u16,
}

/// Sorts all possible tokens that create nodes.
fn sort_node_tokens(stream: &TokenStream) -> EvalResult<Vec<TokenInfo>> {
    let mut sorted = vec![];
    let mut depth = 0;
    for (position, token) in stream.iter().enumerate() {
        if token.r#type == TokenType::OpeningBracket {
            depth += 1;
        } else if token.r#type == TokenType::ClosingBracket {
            depth -= 1;
        } else if token.r#type.is_expression() {
            let precedence = token.r#type.precedence()?;
            sorted.push(TokenInfo {
                token: token.clone(),
                position,
                depth,
                precedence,
            });
        }
    }
    sorted.sort_by_key(|v| (v.depth, v.precedence, -(v.position as i16)));

    Ok(sorted)
}

/// Consumes the token with the provided stream position and builds a node. It finds
/// eventual required node parameters inside the same vectors within the specified range.
fn create_node(
    sorted_node_tokens: &mut Vec<TokenInfo>,
    stream: &TokenStream,
    position: Option<usize>,
    range: (usize, usize),
) -> EvalResult<Node> {
    let index = match position {
        Some(value) => {
            // Find the node in the sorted ones with the corresponding index
            match sorted_node_tokens.iter().position(|x| x.position == value) {
                Some(position) => position,
                None => {
                    return Err(ErrorType::InternalError {
                        message: String::from("trying to remove non-existing token"),
                    });
                }
            }
        }
        None => 0,
    };

    if sorted_node_tokens.len() == 0 {
        if position == None {
            // First iteration, so input is empty
            return Ok(Node::Literal(Value::Int(0)));
        } else {
            // This is an error
            return Err(ErrorType::InternalError {
                message: String::from("trying to remove non-existing token"),
            });
        }
    }

    let token_info = sorted_node_tokens.remove(index);

    // Get the node type.
    if token_info.token.r#type.is_binary_operator() && token_info.token.r#type.is_unary_operator() {
        // In this case we need to check for both unary and binary
        match build_binary_operator(sorted_node_tokens, stream, &token_info, range) {
            Ok(node) => return Ok(node),
            Err(_) => {
                return Ok(build_unary_operator(
                    sorted_node_tokens,
                    stream,
                    &token_info,
                    range,
                )?)
            }
        }
    } else if token_info.token.r#type.is_binary_operator() {
        // Try just binary
        return Ok(build_binary_operator(
            sorted_node_tokens,
            stream,
            &token_info,
            range,
        )?);
    } else if token_info.token.r#type.is_unary_operator() {
        // Try just unary
        return Ok(build_unary_operator(
            sorted_node_tokens,
            stream,
            &token_info,
            range,
        )?);
    } else if token_info.token.r#type.is_union_operator() {
        return Ok(build_union_operator(
            sorted_node_tokens,
            stream,
            &token_info,
            range,
        )?);
    } else {
        // Match for literals, constants, functions and variables.
        match token_info.token.r#type {
            TokenType::Literal => {
                return Ok(Node::Literal(Value::from_string(token_info.token.value)?))
            }
            TokenType::Identifier(i_type) => {
                let val = &token_info.token.value;
                match i_type {
                    IdentifierType::Var => Ok(Node::Var(val.clone())),
                    IdentifierType::Function => Ok(Node::Func(
                        val.clone(),
                        get_function_parameters(sorted_node_tokens, stream, &token_info)?,
                    )),
                    IdentifierType::Unknown => Err(ErrorType::UnknownToken { token: val.clone() }),
                }
            }
            _ => Err(ErrorType::InternalError {
                message: format!("token `{}` is not a valid node", token_info.token),
            }),
        }
    }
}

/// Builds a unary operator from the provided data.
fn build_unary_operator(
    sorted_node_tokens: &mut Vec<TokenInfo>,
    stream: &TokenStream,
    token_info: &TokenInfo,
    range: (usize, usize),
) -> EvalResult<Node> {
    Ok(Node::Unary(
        token_info.token.r#type,
        Box::new(
            match get_lowest_precedence_node_in_range(
                sorted_node_tokens,
                stream,
                (token_info.position + 1, range.1),
            )? {
                Some(next_node) => next_node,
                None => {
                    return Err(ErrorType::MissingOperatorArgument {
                        token: token_info.token.r#type,
                    })
                }
            },
        ),
    ))
}

/// Builds a binary operator with the provided data.
fn build_binary_operator(
    sorted_node_tokens: &mut Vec<TokenInfo>,
    stream: &TokenStream,
    token_info: &TokenInfo,
    range: (usize, usize),
) -> EvalResult<Node> {
    Ok(Node::Binary(
        Box::new(
            // Previous node
            match get_lowest_precedence_node_in_range(
                sorted_node_tokens,
                stream,
                (range.0, token_info.position),
            )? {
                Some(previous_node) => previous_node,
                None => {
                    return Err(ErrorType::MissingOperatorArgument {
                        token: token_info.token.r#type,
                    })
                }
            },
        ),
        token_info.token.r#type,
        Box::new(
            // Successive node
            match get_lowest_precedence_node_in_range(
                sorted_node_tokens,
                stream,
                (token_info.position + 1, range.1),
            )? {
                Some(next_node) => next_node,
                None => {
                    return Err(ErrorType::MissingOperatorArgument {
                        token: token_info.token.r#type,
                    })
                }
            },
        ),
    ))
}

/// Get the lowest precedence node in the range. The range is start-inclusive, end-exclusive.
fn get_lowest_precedence_node_in_range(
    sorted_node_tokens: &mut Vec<TokenInfo>,
    stream: &TokenStream,
    range: (usize, usize),
) -> EvalResult<Option<Node>> {
    let candidates: Vec<TokenInfo> = sorted_node_tokens
        .iter()
        .filter(|&x| x.position >= range.0 && x.position < range.1)
        .cloned()
        .collect();

    if candidates.len() == 0 {
        Ok(None)
    } else {
        Ok(
            match candidates
                .iter()
                .min_by_key(|&x| (x.depth, x.precedence, -(x.position as i16)))
            {
                Some(value) => {
                    // Create the node
                    Some(create_node(
                        sorted_node_tokens,
                        stream,
                        Some(value.position),
                        range,
                    )?)
                }
                None => return Err(ErrorType::EmptyBrackets),
            },
        )
    }
}

/// Returns the node contained inside the function brackets.
fn get_function_parameters(
    sorted_node_tokens: &mut Vec<TokenInfo>,
    stream: &TokenStream,
    func_token: &TokenInfo,
) -> EvalResult<Vec<Box<Node>>> {
    let func_pos = func_token.position;
    // Check if in range
    let content_node = {
        if func_pos + 1 < stream.len() {
            // Check for bracket
            // Brackets should have all been added during "tokenization" phase.
            if stream[func_pos + 1].r#type == TokenType::OpeningBracket {
                // Builds the node inside the brackets
                match get_lowest_precedence_node_in_range(
                    sorted_node_tokens,
                    stream,
                    (
                        func_pos + 1,
                        get_corresponding_closing_bracket(stream, func_pos + 1)?,
                    ),
                )? {
                    Some(node) => Ok(node),
                    None => {
                        return Err(ErrorType::MissingFunctionParameters {
                            func_name: func_token.token.value.clone(),
                        })
                    }
                }
            } else {
                // No available token
                return Err(ErrorType::MissingFunctionParameters {
                    func_name: func_token.token.value.clone(),
                });
            }
        } else {
            return Err(ErrorType::MissingFunctionParameters {
                func_name: func_token.token.value.clone(),
            });
        }
    }?;

    match content_node {
        Expression::Union(nodes) => Ok(nodes),
        other => Ok(vec![Box::new(other)]),
    }
}

fn get_corresponding_closing_bracket(
    stream: &TokenStream,
    opening_bracket_pos: usize,
) -> EvalResult<usize> {
    let mut index = opening_bracket_pos + 1;
    let mut current_depth = 0;
    while index < stream.len() {
        let token: &Token = &stream[index];

        if token.r#type == TokenType::ClosingBracket {
            if current_depth == 0 {
                return Ok(index.try_into().unwrap());
            }
            current_depth -= 1;
        } else if token.r#type == TokenType::OpeningBracket {
            current_depth += 1;
        }
        index += 1;
    }
    Err(ErrorType::MissingClosingBracket)
}

fn build_union_operator(
    sorted_node_tokens: &mut Vec<TokenInfo>,
    stream: &TokenStream,
    token_info: &TokenInfo,
    range: (usize, usize),
) -> EvalResult<Node> {
    // Check for every other union operators (commas) at the same depth and
    // in the same range.
    let mut union_operators = [vec![token_info.clone()], {
        let vec = sorted_node_tokens
            .iter()
            .filter(|x| {
                x.token.r#type == token_info.token.r#type
                    && x.depth == token_info.depth
                    && x.position >= range.0
                    && x.position < range.1
            })
            .cloned()
            .collect_vec();

        // Remove the found item from the sorted node tokens
        let mut index = 0;
        while index < vec.len() {
            let elem = &vec[index];
            sorted_node_tokens.remove(sorted_node_tokens.iter().position(|x| *x == *elem).unwrap());
            index += 1;
        }

        vec
    }]
    .concat();

    union_operators.sort_by(|a, b| a.position.cmp(&b.position));

    let mut ranges: Vec<(usize, usize)> = vec![];
    let mut pos = range.0;
    // Create ranges for all the nodes to build
    for elem in union_operators {
        ranges.push((pos + 1, elem.position));
        pos = elem.position;
    }
    // Add final range
    ranges.push((pos + 1, range.1));

    let nodes = {
        let mut vec = vec![];
        for r in ranges {
            vec.push(Box::new(
                match get_lowest_precedence_node_in_range(sorted_node_tokens, stream, r)? {
                    Some(node) => node,
                    None => return Err(ErrorType::EmptyUnion),
                },
            ))
        }
        vec
    };

    Ok(Node::Union(nodes))
}