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
use rayon::prelude::*;
use serde::{Deserialize, Serialize};
use tree_sitter::Node;

use crate::{AbstractTree, Error, Result, Statement, Value, VariableMap};

#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq, PartialOrd, Ord)]
pub struct Async {
    statements: Vec<Statement>,
}

impl AbstractTree for Async {
    fn from_syntax_node(source: &str, node: Node) -> Result<Self> {
        debug_assert_eq!("async", node.kind());

        let child_count = node.child_count();
        let mut statements = Vec::with_capacity(child_count);

        for index in 2..child_count - 1 {
            let child = node.child(index).unwrap();

            let statement = match child.kind() {
                "statement" => Statement::from_syntax_node(source, child)?,
                _ => {
                    return Err(Error::UnexpectedSyntaxNode {
                        expected: "comment or statement",
                        actual: child.kind(),
                        location: child.start_position(),
                        relevant_source: source[child.byte_range()].to_string(),
                    })
                }
            };

            statements.push(statement);
        }

        Ok(Async { statements })
    }

    fn run(&self, source: &str, context: &mut VariableMap) -> Result<Value> {
        let statements = &self.statements;

        statements
            .into_par_iter()
            .enumerate()
            .find_map_first(|(index, statement)| {
                let mut context = context.clone();
                let result = statement.run(source, &mut context);

                if result.is_err() {
                    Some(result)
                } else if index == statements.len() - 1 {
                    Some(result)
                } else {
                    None
                }
            })
            .unwrap()
    }
}