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
use std::collections::HashMap;
use serde::{Deserialize, Serialize};
#[derive(Clone, Eq, PartialEq, Serialize, Deserialize, Debug)]
struct Node {
    #[serde(rename(deserialize = "type", serialize = "type"))]
    ty: String,
    named: bool,
    #[serde(default)] children: Children,
    #[serde(default)] fields: HashMap<String, Field>,
    #[serde(default)] subtypes: Vec<Subtype>,
}
#[derive(Default, Clone, Eq, PartialEq, Serialize, Deserialize, Debug)]
struct Children {
    multiple: bool,
    required: bool,
    types: Vec<Subtype>,
}
#[derive(Clone, Eq, PartialEq, Serialize, Deserialize, Debug)]
struct Field {
    multiple: bool,
    required: bool,
    types: Vec<Subtype>,
}
#[derive(Clone, Eq, PartialEq, Serialize, Deserialize, Debug)]
struct Subtype {
    #[serde(rename(deserialize = "type", serialize = "type"))]
    ty: String,
    named: bool,
}
#[derive(Clone, Debug)]
pub struct FieldInfo {
    parent_ty: String,
    multiple: bool,
    required: bool,
}
#[derive(Clone, Debug)]
pub struct NodeTypes {
    children: HashMap<String, Children>,
    subtypes: HashMap<String, Vec<String>>,
    reverse_fields: HashMap<String, Vec<FieldInfo>>,
}
fn subtypes(name: &str, nodes: &Vec<Node>) -> Vec<String> {
    let mut r = vec![name.to_string()];
    for n in nodes {
        if n.ty == name {
            for subty in &n.subtypes {
                r.push(subty.ty.clone());
                r.extend(subtypes(&subty.ty, nodes));
            }
        }
    }
    r
}
impl NodeTypes {
    pub fn new(node_types_json_str: &str) -> Result<Self, serde_json::Error> {
        let nodes: Vec<Node> = serde_json::from_str(node_types_json_str)?;
        let subtypes: HashMap<_, _> = nodes
            .iter()
            .map(|n| (n.ty.clone(), subtypes(&n.ty, &nodes)))
            .collect();
        let mut reverse_fields = HashMap::new();
        for node in &nodes {
            for (_field_name, field) in node.fields.iter() {
                for subtype in &field.types {
                    for subsubty in subtypes.get(&subtype.ty).unwrap_or(&Vec::new()) {
                        let entry = reverse_fields.entry(subsubty.clone());
                        entry
                            .and_modify(|v: &mut Vec<FieldInfo>| {
                                v.push(FieldInfo {
                                    parent_ty: node.ty.clone(),
                                    multiple: field.multiple,
                                    required: field.required,
                                });
                            })
                            .or_insert_with(|| {
                                vec![FieldInfo {
                                    parent_ty: node.ty.clone(),
                                    multiple: field.multiple,
                                    required: field.required,
                                }]
                            });
                    }
                }
            }
        }
        Ok(NodeTypes {
            children: nodes
                .iter()
                .map(|n| (n.ty.clone(), n.children.clone()))
                .collect(),
            subtypes,
            reverse_fields,
        })
    }
    fn optional(&self, node_kind: &str, parent_kind: &str) -> bool {
        if let Some(flds) = self.reverse_fields.get(node_kind) {
            for fi in flds {
                if parent_kind == fi.parent_ty && (!fi.multiple || fi.required) {
                    return false;
                }
            }
        }
        true
    }
    pub fn optional_node(&self, node: &tree_sitter::Node) -> bool {
        if let Some(p) = node.parent() {
            self.optional(node.kind(), p.kind())
        } else {
            true
        }
    }
    pub fn list_types(&self, node: &tree_sitter::Node) -> Vec<String> {
        let mut kinds = Vec::new();
        if let Some(children) = self.children.get(node.kind()) {
            if children.multiple && !children.required {
                for child in &children.types {
                    kinds.push(child.ty.clone());
                }
            }
        }
        kinds
    }
    pub fn subtypes(&self, kind: &String) -> &[String] {
        self.subtypes.get(kind).expect("Invalid node kind")
    }
}
#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn test_optional() {
        let nt = NodeTypes::new(tree_sitter_c::NODE_TYPES).unwrap();
        assert!(nt.optional("_expression", "return_statement"));
        assert!(!nt.optional("compound_statement", "function_definition"));
    }
}