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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
use crate::analysis::{
build_graph_data, count_entities, determine_race_severity, find_variable_at_position,
find_variable_at_position_enhanced, is_in_goroutine,
};
use crate::types::{Decoration, DecorationType, ProgressNotification, RaceSeverity};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::time::{Duration, SystemTime};
use tokio::sync::Mutex;
use tower_lsp::lsp_types::*;
use tower_lsp::{Client, LanguageServer};
use tree_sitter::{Parser, Tree};
use tree_sitter_go::language;
// Кастомный тип уведомления для статуса индексации
pub struct IndexingStatusNotification;
impl tower_lsp::lsp_types::notification::Notification for IndexingStatusNotification {
// Имя метода для LSP-уведомления
const METHOD: &'static str = "goanalyzer/indexingStatus";
type Params = IndexingStatusParams;
}
// Параметры для уведомления о статусе индексации
#[derive(Serialize, Deserialize)]
pub struct IndexingStatusParams {
// Количество переменных
pub variables: usize,
// Количество функций
pub functions: usize,
// Количество каналов
pub channels: usize,
// Количество горутин
pub goroutines: usize,
}
// Константы для управления кэшами
const MAX_CACHED_TREES: usize = 20;
const MAX_CACHED_DOCUMENTS: usize = 50;
// 5 минут
const CACHE_TTL_SECONDS: u64 = 300;
// Структура для элемента кэша с TTL
#[derive(Clone)]
pub struct CacheEntry<T> {
data: T,
timestamp: SystemTime,
}
impl<T> CacheEntry<T> {
fn new(data: T) -> Self {
Self {
data,
timestamp: SystemTime::now(),
}
}
fn is_expired(&self) -> bool {
self.timestamp.elapsed().unwrap_or(Duration::from_secs(0))
> Duration::from_secs(CACHE_TTL_SECONDS)
}
}
// Основная структура Backend, реализующая сервер LSP
pub struct Backend {
// Клиент LSP для отправки уведомлений и сообщений
pub client: Client,
// Кэш открытых документов с TTL
pub documents: Mutex<HashMap<Url, CacheEntry<String>>>,
// Парсер tree-sitter для Go
pub parser: Mutex<Parser>,
// Кэш синтаксических деревьев с TTL
pub trees: Mutex<HashMap<Url, CacheEntry<Tree>>>,
}
impl Backend {
// Конструктор Backend, инициализация парсера и кэшей
pub fn new(client: Client) -> Self {
let mut parser = Parser::new();
parser.set_language(language()).unwrap_or_else(|e| {
eprintln!("Failed to set Go language: {:?}", e);
std::process::exit(1);
});
Backend {
client,
documents: Mutex::new(HashMap::new()),
parser: Mutex::new(parser),
trees: Mutex::new(HashMap::new()),
}
}
/// Очистить истекшие элементы из кэша
async fn cleanup_expired_cache(&self) {
// Очистка кэша документов
{
let mut docs = self.documents.lock().await;
docs.retain(|_, entry| !entry.is_expired());
}
// Очистка кэша деревьев
{
let mut trees = self.trees.lock().await;
trees.retain(|_, entry| !entry.is_expired());
}
}
/// Принудительно ограничить размер кэша по LRU принципу
async fn enforce_cache_limits(&self) {
// Ограничение размера кэша документов
{
let mut docs = self.documents.lock().await;
if docs.len() > MAX_CACHED_DOCUMENTS {
// Простая LRU: удаляем самые старые элементы
let mut entries: Vec<_> =
docs.iter().map(|(k, v)| (k.clone(), v.timestamp)).collect();
entries.sort_by_key(|(_, timestamp)| *timestamp);
let to_remove = entries.len() - MAX_CACHED_DOCUMENTS;
for (uri, _) in entries.into_iter().take(to_remove) {
docs.remove(&uri);
}
}
}
// Ограничение размера кэша деревьев
{
let mut trees = self.trees.lock().await;
if trees.len() > MAX_CACHED_TREES {
let mut entries: Vec<_> = trees
.iter()
.map(|(k, v)| (k.clone(), v.timestamp))
.collect();
entries.sort_by_key(|(_, timestamp)| *timestamp);
let to_remove = entries.len() - MAX_CACHED_TREES;
for (uri, _) in entries.into_iter().take(to_remove) {
trees.remove(&uri);
}
}
}
}
/// Получить или обновить дерево для документа (с кэшированием)
pub async fn parse_document_with_cache(&self, uri: &Url, code: &str) -> Option<Tree> {
// Периодическая очистка истекших элементов
self.cleanup_expired_cache().await;
let mut parser = self.parser.lock().await;
let mut trees = self.trees.lock().await;
let prev_tree = trees.get(uri).map(|entry| &entry.data);
// Используем инкрементальный парсинг, если есть предыдущее дерево
let new_tree = match if let Some(prev) = prev_tree {
parser.parse(code, Some(prev))
} else {
parser.parse(code, None)
} {
Some(tree) => tree,
None => {
eprintln!("Failed to parse document: {}", uri);
return None;
}
};
// Кэшируем новое дерево с TTL
trees.insert(uri.clone(), CacheEntry::new(new_tree.clone()));
drop(trees);
drop(parser);
// Принудительно ограничиваем размер кэша
self.enforce_cache_limits().await;
Some(new_tree)
}
/// Получить дерево из кэша (если оно есть и не истекло)
pub async fn get_tree_from_cache(&self, uri: &Url) -> Option<Tree> {
let trees = self.trees.lock().await;
if let Some(entry) = trees.get(uri) {
if !entry.is_expired() {
Some(entry.data.clone())
} else {
None // Истекший элемент будет удален при следующей очистке
}
} else {
None
}
}
/// Отправить клиенту статус индексации (количество сущностей в файле)
pub async fn send_indexing_status(&self, uri: &Url) {
let code = {
let docs = self.documents.lock().await;
match docs.get(uri) {
Some(entry) if !entry.is_expired() => entry.data.clone(),
_ => {
eprintln!("Document cache entry expired or missing for: {}", uri);
return;
}
}
}; // docs lock is released here
let tree = match self.parse_document_with_cache(uri, &code).await {
Some(tree) => tree,
None => {
eprintln!("Failed to parse document for indexing status: {}", uri);
return;
}
};
let counts = match std::panic::catch_unwind(|| count_entities(&tree, &code)) {
Ok(counts) => counts,
Err(e) => {
eprintln!("Panic occurred while counting entities: {:?}", e);
return;
}
};
let params = IndexingStatusParams {
variables: counts.variables,
functions: counts.functions,
channels: counts.channels,
goroutines: counts.goroutines,
};
self.client
.send_notification::<IndexingStatusNotification>(params)
.await;
}
}
#[tower_lsp::async_trait]
impl LanguageServer for Backend {
// Инициализация LSP-сервера: объявляем поддерживаемые возможности
async fn initialize(
&self,
_: InitializeParams,
) -> tower_lsp::jsonrpc::Result<InitializeResult> {
Ok(InitializeResult {
capabilities: ServerCapabilities {
hover_provider: Some(HoverProviderCapability::Simple(true)), // поддержка hover
execute_command_provider: Some(ExecuteCommandOptions {
commands: vec![
"goanalyzer/cursor".to_string(),
"goanalyzer/graph".to_string(),
], // поддерживаемые команды
..Default::default()
}),
text_document_sync: Some(TextDocumentSyncCapability::Kind(
TextDocumentSyncKind::FULL,
)),
..Default::default()
},
..Default::default()
})
}
// Обработка события "initialized" — отправляем приветствие и уведомление о прогрессе
async fn initialized(&self, _: InitializedParams) {
self.client
.log_message(MessageType::INFO, "Go Analyzer initialized")
.await;
self.client
.send_notification::<ProgressNotification>("Server initialized".to_string())
.await;
}
// Завершение работы сервера - правильная очистка ресурсов
async fn shutdown(&self) -> tower_lsp::jsonrpc::Result<()> {
self.client
.log_message(MessageType::INFO, "Go Analyzer server shutdown initiated")
.await;
// Очищаем все кэши и освобождаем ресурсы
{
let mut docs = self.documents.lock().await;
let docs_count = docs.len();
docs.clear();
eprintln!("Cleared {} document cache entries", docs_count);
}
{
let mut trees = self.trees.lock().await;
let trees_count = trees.len();
trees.clear();
eprintln!("Cleared {} AST tree cache entries", trees_count);
}
// Освобождаем парсер
{
let _parser = self.parser.lock().await;
eprintln!("Released tree-sitter parser resources");
}
self.client
.log_message(MessageType::INFO, "Go Analyzer server shutdown completed")
.await;
// На Windows добавляем принудительный выход для предотвращения зависших процессов
#[cfg(target_os = "windows")]
{
tokio::spawn(async {
eprintln!("Windows: Initiating graceful shutdown in 100ms...");
tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
eprintln!("Windows: Forcing process exit");
std::process::exit(0);
});
}
Ok(())
}
// Открытие документа: сохраняем текст, парсим дерево, отправляем статус индексации
async fn did_open(&self, params: DidOpenTextDocumentParams) {
let mut docs = self.documents.lock().await;
docs.insert(
params.text_document.uri.clone(),
CacheEntry::new(params.text_document.text.clone()),
);
drop(docs);
// Принудительно ограничиваем размер кэша
self.enforce_cache_limits().await;
// Парсим и кэшируем дерево при открытии
self.parse_document_with_cache(¶ms.text_document.uri, ¶ms.text_document.text)
.await;
self.send_indexing_status(¶ms.text_document.uri).await;
}
// Изменение документа: обновляем текст, парсим дерево, отправляем статус индексации
async fn did_change(&self, params: DidChangeTextDocumentParams) {
let mut docs = self.documents.lock().await;
if let Some(doc) = docs.get_mut(¶ms.text_document.uri) {
if let Some(change) = params.content_changes.into_iter().next_back() {
// Обновляем запись с новым временным штампом
*doc = CacheEntry::new(change.text.clone());
let new_text = change.text.clone();
drop(docs);
// Инкрементальное обновление дерева
self.parse_document_with_cache(¶ms.text_document.uri, &new_text)
.await;
self.send_indexing_status(¶ms.text_document.uri).await;
return;
}
}
drop(docs);
}
// Hover-запрос: ищем переменную под курсором и возвращаем информацию о ней
async fn hover(&self, params: HoverParams) -> tower_lsp::jsonrpc::Result<Option<Hover>> {
let uri = params.text_document_position_params.text_document.uri;
let position = params.text_document_position_params.position;
let docs = self.documents.lock().await;
let code = match docs.get(&uri) {
Some(entry) if !entry.is_expired() => entry.data.clone(),
_ => {
return Ok(None);
}
};
// Освобождаем блокировку раньше
drop(docs);
// Получаем дерево из кэша или парсим заново, если его нет
let tree = match self.get_tree_from_cache(&uri).await {
Some(tree) => tree,
None => match self.parse_document_with_cache(&uri, &code).await {
Some(tree) => tree,
None => {
eprintln!("Failed to parse document for hover: {}", uri);
return Ok(None);
}
},
};
// Ищем переменную под курсором с улучшенным определением позиции
let var_info = match std::panic::catch_unwind(|| {
// Try enhanced detection first, fallback to standard
find_variable_at_position_enhanced(&tree, &code, position)
.or_else(|| find_variable_at_position(&tree, &code, position))
}) {
Ok(Some(var_info)) => var_info,
Ok(None) => return Ok(None),
Err(e) => {
eprintln!("Panic occurred in find_variable_at_position: {:?}", e);
return Ok(None);
}
};
let mut markdown = format!(
"**Variable**: `{}`\n\n**Declared at**: line {}\n**Type**: {}\n**Uses**: {}\n",
var_info.name,
var_info.declaration.start.line + 1,
if var_info.is_pointer {
"Pointer"
} else {
"Value"
},
var_info.uses.len()
);
// Если есть потенциальная гонка данных — добавляем предупреждение
if var_info.potential_race {
markdown.push_str("**Warning**: Potential data race detected!\n");
}
Ok(Some(Hover {
contents: HoverContents::Markup(MarkupContent {
kind: MarkupKind::Markdown,
value: markdown,
}),
range: Some(var_info.declaration),
}))
}
// Обработка команды goanalyzer/cursor: анализ переменной под курсором и отправка декораций
async fn execute_command(
&self,
params: ExecuteCommandParams,
) -> tower_lsp::jsonrpc::Result<Option<serde_json::Value>> {
if params.command == "goanalyzer/cursor" {
self.client
.log_message(MessageType::INFO, "Executing goanalyzer/cursor")
.await;
self.client
.send_notification::<ProgressNotification>("Starting analysis...".to_string())
.await;
// Десериализуем параметры команды (позиция курсора)
if params.arguments.is_empty() {
self.client
.send_notification::<ProgressNotification>("No arguments provided".to_string())
.await;
return Ok(None);
}
let args: TextDocumentPositionParams = match params
.arguments
.first()
.ok_or_else(|| {
tower_lsp::jsonrpc::Error::invalid_params("Missing arguments".to_string())
})
.and_then(|arg| {
serde_json::from_value(arg.clone()).map_err(|e| {
tower_lsp::jsonrpc::Error::invalid_params(format!(
"Invalid arguments: {}",
e
))
})
}) {
Ok(args) => args,
Err(e) => {
self.client
.send_notification::<ProgressNotification>("Invalid arguments".to_string())
.await;
return Err(e);
}
};
let uri = args.text_document.uri;
let position = args.position;
let code = {
let docs = self.documents.lock().await;
match docs.get(&uri) {
Some(entry) if !entry.is_expired() => entry.data.clone(),
_ => {
self.client
.send_notification::<ProgressNotification>(
"No document found or expired".to_string(),
)
.await;
return Ok(None);
}
}
};
// Получаем дерево из кэша или парсим заново
let tree = match self.get_tree_from_cache(&uri).await {
Some(tree) => tree,
None => match self.parse_document_with_cache(&uri, &code).await {
Some(tree) => tree,
None => {
self.client
.send_notification::<ProgressNotification>(
"Failed to parse document".to_string(),
)
.await;
return Ok(None);
}
},
};
// Ищем переменную под курсором с улучшенным определением позиции
let mut var_info = match std::panic::catch_unwind(|| {
// First try the enhanced detection
find_variable_at_position_enhanced(&tree, &code, position).or_else(|| {
// Fallback to standard detection
find_variable_at_position(&tree, &code, position)
})
}) {
Ok(Some(var_info)) => var_info,
Ok(None) => {
self.client
.send_notification::<ProgressNotification>("No variable found".to_string())
.await;
return Ok(None);
}
Err(e) => {
eprintln!("Panic occurred in find_variable_at_position: {:?}", e);
self.client
.send_notification::<ProgressNotification>("Analysis error".to_string())
.await;
return Ok(None);
}
};
let mut decorations = vec![];
// Декорация для объявления переменной
decorations.push(Decoration {
range: var_info.declaration,
kind: DecorationType::Declaration,
hover_text: format!("Declaration of `{}`", var_info.name),
});
// Декорации для всех использований переменной
for use_range in var_info.uses.iter() {
// По умолчанию: обычное использование или указатель
let mut decoration_kind = if var_info.is_pointer {
DecorationType::Pointer
} else {
DecorationType::Use
};
let mut hover_text = format!("Use of `{}`", var_info.name);
// Check for variable reassignment
let is_reassignment = match std::panic::catch_unwind(|| {
crate::analysis::is_variable_reassignment(
&tree,
&var_info.name,
*use_range,
&code,
)
}) {
Ok(result) => result,
Err(e) => {
eprintln!("Panic occurred in is_variable_reassignment: {:?}", e);
// Safe fallback
false
}
};
if is_reassignment {
decoration_kind = DecorationType::AliasReassigned;
hover_text = format!("Reassignment of `{}`", var_info.name);
}
// Check for variable capture in closure/goroutine
else {
let is_captured = match std::panic::catch_unwind(|| {
crate::analysis::is_variable_captured(
&tree,
&var_info.name,
*use_range,
var_info.declaration,
)
}) {
Ok(result) => result,
Err(e) => {
eprintln!("Panic occurred in is_variable_captured: {:?}", e);
// Safe fallback
false
}
};
if is_captured {
decoration_kind = DecorationType::AliasCaptured;
hover_text = format!("Captured `{}` in closure/goroutine", var_info.name);
}
}
// Если использование внутри горутины — определяем приоритет гонки
// Only check for races if it's not already marked as reassignment or capture
if !matches!(
decoration_kind,
DecorationType::AliasReassigned | DecorationType::AliasCaptured
) {
let is_in_goroutine_result =
match std::panic::catch_unwind(|| is_in_goroutine(&tree, *use_range)) {
Ok(result) => result,
Err(e) => {
eprintln!("Panic occurred in is_in_goroutine: {:?}", e);
// Safe fallback
false
}
};
if is_in_goroutine_result {
// Определяем приоритет гонки на основе контекста
let race_severity = match std::panic::catch_unwind(|| {
determine_race_severity(&tree, *use_range, &code)
}) {
Ok(severity) => severity,
Err(e) => {
eprintln!("Panic occurred in determine_race_severity: {:?}", e);
// Safe fallback
RaceSeverity::Medium
}
};
var_info.race_severity = race_severity.clone();
match race_severity {
crate::types::RaceSeverity::High => {
decoration_kind = DecorationType::Race;
hover_text = format!(
"Use of `{}` in goroutine - HIGH PRIORITY data race!",
var_info.name
);
}
crate::types::RaceSeverity::Medium => {
decoration_kind = DecorationType::Race;
hover_text = format!(
"Use of `{}` in goroutine - potential data race",
var_info.name
);
}
crate::types::RaceSeverity::Low => {
decoration_kind = DecorationType::RaceLow;
hover_text = format!(
"Use of `{}` in goroutine - LOW PRIORITY (sync detected)",
var_info.name
);
}
}
var_info.potential_race = true;
}
}
decorations.push(Decoration {
range: *use_range,
kind: decoration_kind,
hover_text,
});
}
// Сериализуем декорации и отправляем клиенту
let value = match serde_json::to_value(&decorations) {
Ok(value) => value,
Err(e) => {
eprintln!("Failed to serialize decorations: {}", e);
self.client
.send_notification::<ProgressNotification>(
"Serialization error".to_string(),
)
.await;
return Err(tower_lsp::jsonrpc::Error::internal_error());
}
};
self.client
.send_notification::<ProgressNotification>("Analysis complete".to_string())
.await;
return Ok(Some(value));
}
// Новый метод: goanalyzer/graph
else if params.command == "goanalyzer/graph" {
self.client
.log_message(MessageType::INFO, "Executing goanalyzer/graph")
.await;
let args: TextDocumentIdentifier = params
.arguments
.first()
.ok_or_else(|| {
tower_lsp::jsonrpc::Error::invalid_params("Missing arguments".to_string())
})
.and_then(|arg| {
serde_json::from_value(arg.clone()).map_err(|e| {
tower_lsp::jsonrpc::Error::invalid_params(format!(
"Invalid arguments: {}",
e
))
})
})?;
let uri = args.uri;
let docs = self.documents.lock().await;
let code = match docs.get(&uri) {
Some(entry) if !entry.is_expired() => entry.data.clone(),
_ => {
self.client
.send_notification::<ProgressNotification>(
"No document found or expired".to_string(),
)
.await;
return Ok(None);
}
};
// Освобождаем блокировку раньше
drop(docs);
let tree = self.get_tree_from_cache(&uri).await.or_else(|| {
futures::executor::block_on(self.parse_document_with_cache(&uri, &code))
});
let tree = match tree {
Some(tree) => tree,
None => {
self.client
.send_notification::<ProgressNotification>(
"Failed to parse document".to_string(),
)
.await;
return Ok(None);
}
};
let graph = build_graph_data(&tree, &code);
let value = serde_json::to_value(&graph)
.map_err(|_| tower_lsp::jsonrpc::Error::internal_error())?;
self.client
.send_notification::<ProgressNotification>("Graph built".to_string())
.await;
return Ok(Some(value));
}
Ok(None)
}
}