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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
use crate::core::*;
use crate::ide::completion::find_section;
use log::info;
use ropey::Rope;
use std::collections::HashSet;
use tokio::time::Instant;
use tower_lsp::lsp_types::*;
use tree_sitter::{Node, QueryCursor, Tree};
use ustr::Ustr;
/// Syntax highlight happens in here
/// we mainly use tree-sitter queries to extract token and serialize them
/// according to the lsp spec
/// TODO make use of incremental parsing and updates
/// this is fast enough for medium sized files but sinks at huge files

#[derive(Clone, Debug, PartialEq, Eq)]
struct AbsToken {
    range: Range,
    kind: u32,
}
struct FileState {
    state: Vec<SemanticToken>,
}
pub fn token_types() -> Vec<SemanticTokenType> {
    vec![
        SemanticTokenType::KEYWORD,
        SemanticTokenType::OPERATOR,
        SemanticTokenType::NAMESPACE,
        SemanticTokenType::ENUM_MEMBER,
        SemanticTokenType::CLASS,
        SemanticTokenType::COMMENT,
        SemanticTokenType::ENUM,
        SemanticTokenType::INTERFACE,
        SemanticTokenType::FUNCTION,
        SemanticTokenType::MACRO,
        SemanticTokenType::PARAMETER,
        SemanticTokenType::NUMBER,
        SemanticTokenType::STRING,
    ]
}
pub fn modifiers() -> Vec<SemanticTokenModifier> {
    vec![
        SemanticTokenModifier::DEPRECATED,
        SemanticTokenModifier::READONLY,
        SemanticTokenModifier::MODIFICATION,
        SemanticTokenModifier::ASYNC,
        SemanticTokenModifier::STATIC,
        SemanticTokenModifier::ABSTRACT,
        SemanticTokenModifier::ASYNC,
    ]
}
fn token_index(name: &str) -> u32 {
    match name {
        "keyword" => 0,
        "operator" => 1,
        "namespace" => 2,
        "enumMember" => 3,
        "class" => 4,
        "comment" => 5,
        "enum" => 6,
        "interface" => 7,
        "function" => 8,
        "macro" => 9,
        "parameter" => 10,
        "number" => 11,
        "string" => 12,
        _ => 0,
    }
}
fn modifier_bitset(name: &str) -> u32 {
    match name {
        "deprecated" => 0b1,
        "readonly" => 0b10,
        _ => 0,
    }
}

pub enum ColorUpdate {
    File(Tree),
    Root(RootGraph),
}
fn fast_lsp_range(
    node: Node,
    source: &Rope,
    utf16_lines: &HashSet<usize>,
) -> tower_lsp::lsp_types::Range {
    if utf16_lines.contains(&node.start_position().row)
        || utf16_lines.contains(&node.end_position().row)
    {
        node_range(node, source)
    } else {
        tower_lsp::lsp_types::Range {
            start: Position {
                line: node.start_position().row as u32,
                character: node.start_position().column as u32,
            },
            end: Position {
                line: node.end_position().row as u32,
                character: node.end_position().column as u32,
            },
        }
    }
}

impl FileState {
    //calculate the diffrence of two states using a crude single change or all diff algorithm
    fn diff(&self, new: &FileState) -> SemanticTokensFullDeltaResult {
        //TODO use a proper diffing algorithm
        let prefix = self
            .state
            .iter()
            .zip(new.state.iter())
            .take_while(|(i, j)| i == j)
            .count();
        let diff = self.state.len().abs_diff(new.state.len());
        if self.state.len() < new.state.len() {
            if self.state[prefix..]
                .iter()
                .zip(new.state[prefix + diff..].iter())
                .all(|(i, k)| i == k)
            {
                return SemanticTokensFullDeltaResult::TokensDelta(SemanticTokensDelta {
                    result_id: None,
                    edits: vec![SemanticTokensEdit {
                        start: prefix as u32,
                        delete_count: 0,
                        data: Some(new.state[prefix..prefix + diff].to_vec()),
                    }],
                });
            }
        } else if self.state.len() > new.state.len()
            && self.state[prefix + diff..]
                .iter()
                .zip(new.state[prefix..].iter())
                .all(|(i, k)| i == k)
        {
            return SemanticTokensFullDeltaResult::TokensDelta(SemanticTokensDelta {
                result_id: None,
                edits: vec![SemanticTokensEdit {
                    start: prefix as u32,
                    delete_count: diff as u32,
                    data: None,
                }],
            });
        }
        SemanticTokensFullDeltaResult::TokensDelta(SemanticTokensDelta {
            result_id: None,
            edits: vec![SemanticTokensEdit {
                start: prefix as u32,
                delete_count: (self.state.len() - prefix) as u32,
                data: Some(new.state[prefix..].to_vec()),
            }],
        })
    }
    fn color_section(
        origin: Node,
        root: &Snapshot,
        source: &Rope,
        file: &AstDocument,
        utf16_line: &HashSet<usize>,
        token: &mut Vec<AbsToken>,
    ) {
        let _section = find_section(origin);
        let mut cursor = QueryCursor::new();

        let captures = TS.queries.highlight.capture_names();
        for i in cursor.matches(&TS.queries.highlight, origin, node_source(source)) {
            for c in i.captures {
                let path = Self::create_path(c.node, source);
                if c.node.kind() == "path"
                    && path != None
                    && Self::handle_path(root, file, path.unwrap().clone())
                {
                    //document slice gets two colors
                    let kind = captures[7].as_str();
                    let range = node_range(c.node.child(c.node.child_count() - 1).unwrap(), source);
                    token.push(AbsToken {
                        range,
                        kind: token_index(kind),
                    });
                    let feat_kind = captures[c.index as usize].as_str();
                    let mut feat_range = fast_lsp_range(c.node, source, utf16_line);
                    feat_range.end = Position {
                        line: range.start.line,
                        character: range.start.character - 1,
                    };
                    token.push(AbsToken {
                        range: feat_range,
                        kind: token_index(feat_kind),
                    });
                } else {
                    let kind = captures[c.index as usize].as_str();
                    let range = fast_lsp_range(c.node, source, utf16_line);
                    token.push(AbsToken {
                        range,
                        kind: token_index(kind),
                    });
                }
            }
        }
    }
    /**
     * if node is a path create a Path
     */
    fn create_path(node: Node, source: &Rope) -> Option<Path> {
        if node.kind() != "path" {
            return None;
        }
        let mut path = Path::default();
        for i in 0..node.child_count() {
            if let Some(child) = node.child(i) {
                if child.kind() == "name" {
                    if let Some(name) = source.byte_slice(child.byte_range()).as_str() {
                        path.names.push(Ustr::from(name));
                        path.spans.push(child.byte_range());
                    } else {
                        return None;
                    }
                }
            } else {
                return None;
            }
        }
        Some(path)
    }
    /**
     * if it is a attribute path return true
     * otherwise false
     */
    fn handle_path(root: &Snapshot, file: &AstDocument, mut path: Path) -> bool {
        if path.len() == 0 {
            return false;
        } else if path.len() == 1 {
            if file.containe_attribute(path.names.get(0).unwrap().clone()) {
                return true;
            }
        } else if path.len() == 2 {
            // check if path prefix is a feature if not it couldn't be a attribute path
            if file.containe_feature(path.names.remove(0).clone()) {
                let _ = path.spans.remove(0);
                return Self::handle_path(root, file, path);
            }
            return false;
        } else {
            //check if path start with an import or and import alias
            for import in file.imports() {
                //check import alias
                if let Some(alias) = import.clone().alias {
                    if path.names.get(0).unwrap().clone() == alias.name {
                        let _ = path.spans.remove(0);
                        let _ = path.names.remove(0);
                        if let Some(url) =
                            create_new_uvl(file.uri.to_string(), import.path.relative_path())
                        {
                            if let Some(child_ast) = root.file_by_uri(&url) {
                                return Self::handle_path(root, child_ast, path);
                            }
                        }
                        return false;
                    }
                } else {
                    //check normal import
                    let mut same = true;
                    for i in 0..import.path.len() {
                        if let Some(name) = path.names.get(i) {
                            if name != import.path.names.get(i).unwrap() {
                                same = false;
                            }
                        } else {
                            same = false;
                        }
                    }
                    if same {
                        for _ in 0..import.path.len() {
                            let _ = path.spans.remove(0);
                            let _ = path.names.remove(0);
                        }
                        if let Some(url) =
                            create_new_uvl(file.uri.to_string(), import.path.relative_path())
                        {
                            info!("{}", url);
                            if let Some(child_ast) = root.file_by_uri(&url) {
                                return Self::handle_path(root, child_ast, path);
                            }
                        }
                        return false;
                    }
                }
            }
        }
        return false;
    }
    fn new(origin: &Url, tree: Tree, source: &ropey::Rope, root: &Snapshot) -> Self {
        let mut token = vec![];

        let time = Instant::now();
        //Keep track of bad utf16 lines, only perform byte->utf8->utf16 transformation when needed
        //61ms->34ms performance improvment for pure ascii!
        //TODO make a better uniform byte->utf16 provider as ropey is to slow
        //or just use more threads
        let mut utf16_line = HashSet::new();
        for (i, line) in source.lines().enumerate() {
            for c in line.chars() {
                if c.len_utf8() != c.len_utf16() {
                    utf16_line.insert(i);
                }
            }
        }
        let mut sections = tree.walk();
        let file = root.file_by_uri(origin).unwrap();
        //iterate captures and create colors token, we currently allow diffrent color for diffrent
        //sections (currently unsed)
        sections.goto_first_child();
        loop {
            Self::color_section(sections.node(), root, source, file, &utf16_line, &mut token);
            if !sections.goto_next_sibling() {
                break;
            }
        }
        token.sort_by_key(|a| (a.range.start.line, a.range.start.character));
        token.dedup();
        let mut filtered = Vec::new();
        let mut last: Option<AbsToken> = None;
        //translate to relative lsp tokens
        for i in token.iter() {
            if let Some(last) = last.as_ref() {
                if last.range.end.line > i.range.start.line {
                    continue;
                }
                if last.range.end.line == i.range.start.line
                    && last.range.end.character > i.range.start.character
                {
                    continue;
                }
            }
            if i.range.start.line == i.range.end.line {
                let next_col = i.range.start.character;
                let next_line = i.range.start.line;
                let len = i.range.end.character - i.range.start.character;
                if let Some(last) = last.as_ref() {
                    let last_line = last.range.end.line;
                    let last_col = last.range.start.character;
                    filtered.push(SemanticToken {
                        delta_line: next_line - last_line,
                        delta_start: if next_line == last_line {
                            next_col - last_col
                        } else {
                            next_col
                        },
                        length: len,
                        token_type: i.kind,
                        token_modifiers_bitset: 0,
                    })
                } else {
                    filtered.push(SemanticToken {
                        delta_line: next_line,
                        delta_start: next_col,
                        length: len,
                        token_type: i.kind,
                        token_modifiers_bitset: 0,
                    })
                }
            } else {
                let next_col = i.range.start.character;
                let next_line = i.range.start.line;
                if let Some(last) = last.as_ref() {
                    let last_line = last.range.end.line;
                    let last_col = last.range.start.character;
                    filtered.push(SemanticToken {
                        delta_line: next_line - last_line,
                        delta_start: if next_line == last_line {
                            next_col - last_col
                        } else {
                            next_col
                        },
                        length: source.line(i.range.start.line as usize).len_utf16_cu() as u32
                            - next_col,
                        token_type: i.kind,
                        token_modifiers_bitset: 0,
                    })
                } else {
                    filtered.push(SemanticToken {
                        delta_line: next_line,
                        delta_start: next_col,
                        length: source.line(i.range.start.line as usize).len_utf16_cu() as u32
                            - next_col,
                        token_type: i.kind,
                        token_modifiers_bitset: 0,
                    })
                }
                if i.range.end.line - i.range.start.line > 1 {
                    for l in i.range.start.line + 1..i.range.end.line {
                        filtered.push(SemanticToken {
                            delta_line: 1,
                            delta_start: 0,
                            length: source.line(l as usize).len_utf16_cu() as u32,
                            token_type: i.kind,
                            token_modifiers_bitset: 0,
                        })
                    }
                }
                filtered.push(SemanticToken {
                    delta_line: 1,
                    delta_start: 0,
                    length: i.range.end.character,
                    token_type: i.kind,
                    token_modifiers_bitset: 0,
                })
            }
            last = Some(i.clone());
        }

        info!("Semantic highlight took {:?}", time.elapsed());

        FileState { state: filtered }
    }
}
pub struct State {
    files: dashmap::DashMap<Url, FileState>,
}
impl State {
    pub fn new() -> Self {
        State {
            files: Default::default(),
        }
    }
    pub fn remove(&self, uri: &Url) {
        self.files.remove(uri);
    }
    pub fn get(&self, root: Snapshot, uri: Url, tree: Tree, source: ropey::Rope) -> SemanticTokens {
        let state = FileState::new(&uri, tree, &source, &root);
        let out = state.state.clone();
        self.files.insert(uri, state);

        SemanticTokens {
            result_id: None,
            data: out,
        }
    }
    pub fn delta(
        &self,
        root: Snapshot,
        uri: Url,
        tree: Tree,
        source: ropey::Rope,
    ) -> SemanticTokensFullDeltaResult {
        if let Some(old) = self.files.get(&uri) {
            let state = FileState::new(&uri, tree, &source, &root);
            let diff = old.diff(&state);
            self.files.insert(uri.clone(), state);
            diff
        } else {
            info!("Start color");
            let state = FileState::new(&uri, tree, &source, &root);
            let out = state.state.clone();
            self.files.insert(uri.clone(), state);

            info!("End color");
            SemanticTokensFullDeltaResult::Tokens(SemanticTokens {
                result_id: None,
                data: out,
            })
        }
    }
}