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
//! Cursor queries of a JSONA document.

use jsona::{
    dom::{node::DomNode, Keys, Node},
    rowan::{Direction, TextSize, TokenAtOffset},
    syntax::{SyntaxKind, SyntaxNode, SyntaxToken},
};

#[derive(Debug)]
pub struct Query {
    /// The offset the query was made for.
    pub offset: TextSize,
    /// Before the cursor.
    pub before: Option<PositionInfo>,
    /// After the cursor.
    pub after: Option<PositionInfo>,
    /// Scope kind
    pub scope: ScopeKind,
    /// Query node contains offset
    pub node_at_offset: TextSize,
    /// Current property/annotationKey key
    pub key: Option<SyntaxToken>,
    /// Current value
    pub value: Option<SyntaxNode>,
    /// Whether add value for property/annotationKey completion
    pub add_value: bool,
    /// Whether insert separator
    pub add_separator: bool,
}

impl Query {
    pub fn at(root: &Node, offset: TextSize) -> Self {
        let syntax = root.node_syntax().cloned().unwrap().into_node().unwrap();
        let before = offset
            .checked_sub(TextSize::from(1))
            .and_then(|offset| Self::position_info_at(&syntax, offset));

        let mut kind = ScopeKind::Unknown;
        let mut node_at_offset = offset;
        let mut key = None;
        let mut value = None;
        let mut add_separator = false;
        let mut add_value = false;
        if let Some(token) = before
            .as_ref()
            .and_then(|t| Query::prev_none_ws_comment(t.syntax.clone()))
        {
            match token.kind() {
                SyntaxKind::ANNOTATION_KEY => {
                    add_value = !token
                        .siblings_with_tokens(Direction::Next)
                        .any(|v| v.kind() == SyntaxKind::ANNOTATION_VALUE);
                    kind = ScopeKind::AnnotationKey;
                    key = Some(token);
                }
                SyntaxKind::COLON => {
                    node_at_offset = token.text_range().start();
                    kind = ScopeKind::Value;
                    value = token.next_sibling_or_token().and_then(|v| {
                        if v.kind() == SyntaxKind::VALUE {
                            v.as_node()
                                .unwrap()
                                .children()
                                .find(|v| v.kind() == SyntaxKind::SCALAR)
                        } else {
                            None
                        }
                    });
                    add_separator = match value.as_ref() {
                        Some(v) => value_add_separator(v),
                        None => colon_add_separator(token),
                    };
                }
                SyntaxKind::PARENTHESES_START => {
                    kind = ScopeKind::Value;
                    value = token.next_sibling_or_token().and_then(|v| {
                        if v.kind() == SyntaxKind::ANNOTATION_VALUE {
                            v.as_node()
                                .unwrap()
                                .children()
                                .find(|v| v.kind() == SyntaxKind::VALUE)
                                .and_then(|v| v.children().find(|v| v.kind() == SyntaxKind::SCALAR))
                        } else {
                            None
                        }
                    });
                }
                SyntaxKind::BRACE_START => {
                    kind = ScopeKind::Object;
                }
                SyntaxKind::BRACKET_START => {
                    kind = ScopeKind::Array;
                }
                _ => {
                    if let Some(node) = token.parent_ancestors().find(|v| {
                        matches!(
                            v.kind(),
                            SyntaxKind::KEY
                                | SyntaxKind::SCALAR
                                | SyntaxKind::OBJECT
                                | SyntaxKind::ARRAY
                        )
                    }) {
                        node_at_offset = node.text_range().start();
                        match &node.kind() {
                            SyntaxKind::KEY => {
                                key = node
                                    .children_with_tokens()
                                    .find(|v| v.kind().is_key())
                                    .and_then(|v| v.as_token().cloned());
                                add_value = !token
                                    .siblings_with_tokens(Direction::Next)
                                    .any(|v| v.kind() == SyntaxKind::COLON);
                                kind = ScopeKind::PropertyKey
                            }
                            SyntaxKind::SCALAR => {
                                kind = ScopeKind::Value;
                                add_separator = value_add_separator(&node);
                                value = Some(node);
                            }
                            SyntaxKind::OBJECT => kind = ScopeKind::Object,
                            SyntaxKind::ARRAY => kind = ScopeKind::Array,
                            _ => {}
                        };
                    }
                }
            };
        }

        Query {
            offset,
            before,
            after: if offset >= syntax.text_range().end() {
                None
            } else {
                Self::position_info_at(&syntax, offset)
            },
            scope: kind,
            node_at_offset,
            add_value,
            add_separator,
            key,
            value,
        }
    }

    pub fn node_at(root: &Node, offset: TextSize) -> Option<(Keys, Node)> {
        if !root
            .node_text_range()
            .map(|v| v.contains(offset))
            .unwrap_or_default()
        {
            return None;
        }
        node_at_impl(root, offset, Keys::default())
    }

    pub fn index_at(&self) -> Option<usize> {
        self.before
            .as_ref()
            .and_then(|v| {
                v.syntax
                    .parent_ancestors()
                    .find(|v| v.kind() == SyntaxKind::ARRAY)
            })
            .map(|v| {
                let mut index = 0;
                for child in v.children() {
                    if child.kind() == SyntaxKind::VALUE {
                        index += 1;
                        if child.text_range().contains(self.offset) {
                            break;
                        }
                    }
                }
                index
            })
    }

    fn position_info_at(syntax: &SyntaxNode, offset: TextSize) -> Option<PositionInfo> {
        let syntax = match syntax.token_at_offset(offset) {
            TokenAtOffset::None => return None,
            TokenAtOffset::Single(s) => s,
            TokenAtOffset::Between(_, right) => right,
        };

        Some(PositionInfo { syntax })
    }

    fn prev_none_ws_comment(token: SyntaxToken) -> Option<SyntaxToken> {
        if token.kind().is_ws_or_comment() {
            token.prev_token().and_then(Query::prev_none_ws_comment)
        } else {
            Some(token)
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScopeKind {
    Unknown,
    Object,
    Array,
    AnnotationKey,
    PropertyKey,
    Value,
}

#[derive(Debug, Clone)]
pub struct PositionInfo {
    /// The narrowest syntax element that contains the position.
    pub syntax: SyntaxToken,
}

fn node_at_impl(node: &Node, offset: TextSize, keys: Keys) -> Option<(Keys, Node)> {
    if let Some(annotations) = node.annotations() {
        let map = annotations.value().read();
        for (key, value) in map.kv_iter() {
            if map
                .syntax(key)
                .map(|v| v.text_range().contains(offset))
                .unwrap_or_default()
            {
                return node_at_impl(value, offset, keys.join(key.into()));
            }
        }
    }
    match node {
        Node::Array(arr) => {
            for (index, value) in arr.value().read().iter().enumerate() {
                if value
                    .node_syntax()
                    .map(|v| v.text_range().contains(offset))
                    .unwrap_or_default()
                {
                    return node_at_impl(value, offset, keys.join(index.into()));
                }
            }
        }
        Node::Object(obj) => {
            let map = obj.value().read();
            for (key, value) in map.kv_iter() {
                if map
                    .syntax(key)
                    .map(|v| v.text_range().contains(offset))
                    .unwrap_or_default()
                {
                    return node_at_impl(value, offset, keys.join(key.into()));
                }
            }
        }
        _ => {}
    }
    Some((keys, node.clone()))
}

fn value_add_separator(node: &SyntaxNode) -> bool {
    for syntax in node.siblings_with_tokens(Direction::Next) {
        match syntax.kind() {
            SyntaxKind::NEWLINE => return true,
            SyntaxKind::COMMA => return false,
            SyntaxKind::WHITESPACE | SyntaxKind::LINE_COMMENT => {}
            _ => return false,
        }
    }
    false
}

fn colon_add_separator(mut token: SyntaxToken) -> bool {
    loop {
        match token.next_token() {
            Some(tok) => match tok.kind() {
                SyntaxKind::NEWLINE => return true,
                SyntaxKind::COMMA => return false,
                SyntaxKind::WHITESPACE | SyntaxKind::LINE_COMMENT => {
                    token = tok;
                    continue;
                }
                _ => return false,
            },
            None => return false,
        }
    }
}