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
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
// Copyright (C) 2024 Jelmer Vernooij <jelmer@samba.org>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Pyright LSP integration for type inference
//!
//! This module provides type querying capabilities using pyright language server.
use anyhow::{anyhow, Result};
/// Trait for pyright-like LSP clients that can be used in TypeIntrospectionContext
pub trait PyrightLspClientTrait {
fn open_file(&mut self, file_path: &str, content: &str) -> Result<()>;
fn update_file(&mut self, file_path: &str, content: &str, version: i32) -> Result<()>;
fn query_type(
&mut self,
file_path: &str,
content: &str,
line: u32,
column: u32,
) -> Result<Option<String>>;
fn shutdown(&mut self) -> Result<()>;
}
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::io::{BufRead, BufReader, Read, Write};
use std::process::{Child, Command, Stdio};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
/// LSP request message
#[derive(Debug, Serialize)]
struct LspRequest {
jsonrpc: &'static str,
id: u64,
method: String,
params: Value,
}
/// LSP notification message
#[derive(Debug, Serialize)]
struct LspNotification {
jsonrpc: &'static str,
method: String,
params: Value,
}
/// LSP response message
#[derive(Debug, Deserialize)]
struct LspResponse {
#[allow(dead_code)]
jsonrpc: String,
id: Option<u64>,
result: Option<Value>,
error: Option<LspError>,
}
/// LSP error
#[derive(Debug, Deserialize)]
struct LspError {
#[allow(dead_code)]
code: i32,
message: String,
#[allow(dead_code)]
data: Option<Value>,
}
/// Position in a text document
#[derive(Debug, Serialize)]
struct Position {
line: u32,
character: u32,
}
/// Text document identifier
#[derive(Debug, Serialize)]
struct TextDocumentIdentifier {
uri: String,
}
/// Text document item
#[derive(Debug, Serialize)]
#[allow(dead_code)]
struct TextDocumentItem {
uri: String,
#[serde(rename = "languageId")]
language_id: String,
version: i32,
text: String,
}
/// Hover params
#[derive(Debug, Serialize)]
struct HoverParams {
#[serde(rename = "textDocument")]
text_document: TextDocumentIdentifier,
position: Position,
}
/// Type definition params (same structure as hover params)
#[derive(Debug, Serialize)]
struct TypeDefinitionParams {
#[serde(rename = "textDocument")]
text_document: TextDocumentIdentifier,
position: Position,
}
/// Pyright LSP client
pub struct PyrightLspClient {
process: Arc<Mutex<Child>>,
request_id: AtomicU64,
reader: Arc<Mutex<BufReader<std::process::ChildStdout>>>,
is_shutdown: Arc<Mutex<bool>>,
}
impl PyrightLspClient {
/// Create and start a new pyright LSP client
pub fn new(workspace_root: Option<&str>) -> Result<Self> {
tracing::debug!("Starting PyrightLspClient::new()");
// Try to find pyright executable
let pyright_cmd = if Command::new("pyright-langserver")
.arg("--version")
.output()
.is_ok()
{
"pyright-langserver"
} else if Command::new("pyright").arg("--version").output().is_ok() {
// Some installations use 'pyright' directly
"pyright"
} else {
return Err(anyhow!(
"pyright not found. Please install pyright: pip install pyright"
));
};
// Start pyright in LSP mode
tracing::debug!("Starting pyright process with command: {}", pyright_cmd);
let mut process = Command::new(pyright_cmd)
.args(["--stdio"])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.map_err(|e| anyhow!("Failed to start pyright: {}", e))?;
let stdout = process.stdout.take().ok_or_else(|| anyhow!("No stdout"))?;
let reader = BufReader::new(stdout);
let mut client = Self {
process: Arc::new(Mutex::new(process)),
request_id: AtomicU64::new(0),
reader: Arc::new(Mutex::new(reader)),
is_shutdown: Arc::new(Mutex::new(false)),
};
// Initialize the LSP connection
client.initialize(workspace_root)?;
Ok(client)
}
/// Initialize the LSP connection
fn initialize(&mut self, workspace_root: Option<&str>) -> Result<()> {
// Use provided workspace root or fall back to current directory
let workspace_root = if let Some(root) = workspace_root {
std::path::Path::new(root).to_path_buf()
} else {
std::env::current_dir()?
};
let workspace_uri = format!("file://{}", workspace_root.display());
tracing::debug!(
"Initializing pyright with workspace: {}",
workspace_root.display()
);
let init_params = json!({
"processId": std::process::id(),
"clientInfo": {
"name": "dissolve",
"version": "0.1.0"
},
"locale": "en",
"rootPath": workspace_root.to_str(),
"rootUri": workspace_uri,
"capabilities": {
"textDocument": {
"hover": {
"contentFormat": ["plaintext", "markdown"]
},
"typeDefinition": {
"dynamicRegistration": false
}
}
},
"trace": "off",
"workspaceFolders": [{
"uri": workspace_uri,
"name": "test_workspace"
}],
"initializationOptions": {
"autoSearchPaths": true,
"useLibraryCodeForTypes": true,
"typeCheckingMode": "basic",
"python": {
"analysis": {
"extraPaths": []
}
}
}
});
// Use timeout for initialization
let _response =
self.send_request_with_timeout("initialize", init_params, Duration::from_secs(10))?;
// Send initialized notification
self.send_notification("initialized", json!({}))?;
Ok(())
}
/// Send a request to the language server
fn send_request(&mut self, method: &str, params: Value) -> Result<Value> {
// Use timeout for all requests, not just initialization
self.send_request_with_timeout(method, params, Duration::from_secs(5))
}
/// Send a request to the language server with timeout
fn send_request_with_timeout(
&mut self,
method: &str,
params: Value,
timeout: Duration,
) -> Result<Value> {
let id = self.request_id.fetch_add(1, Ordering::SeqCst);
let request = LspRequest {
jsonrpc: "2.0",
id,
method: method.to_string(),
params,
};
self.send_message(&request)?;
// Read response with timeout
self.read_response_with_timeout(id, timeout)
}
/// Send a notification to the language server
fn send_notification(&mut self, method: &str, params: Value) -> Result<()> {
let notification = LspNotification {
jsonrpc: "2.0",
method: method.to_string(),
params,
};
self.send_message(¬ification)
}
/// Send a message to the language server
fn send_message<T: Serialize>(&mut self, message: &T) -> Result<()> {
let content = serde_json::to_string(message)?;
let header = format!("Content-Length: {}\r\n\r\n", content.len());
let mut process = self.process.lock().unwrap();
let stdin = process.stdin.as_mut().ok_or_else(|| anyhow!("No stdin"))?;
stdin.write_all(header.as_bytes())?;
stdin.write_all(content.as_bytes())?;
stdin.flush()?;
Ok(())
}
/// Read a response from the language server
#[allow(dead_code)]
fn read_response(&self, expected_id: u64) -> Result<Value> {
let mut reader = self.reader.lock().unwrap();
loop {
// Read headers
let mut headers = Vec::new();
loop {
let mut line = String::new();
reader.read_line(&mut line)?;
if line == "\r\n" || line == "\n" {
break;
}
headers.push(line);
}
// Parse Content-Length header
let content_length = headers
.iter()
.find(|h| h.starts_with("Content-Length:"))
.and_then(|h| h.split(':').nth(1))
.and_then(|v| v.trim().parse::<usize>().ok())
.ok_or_else(|| anyhow!("Missing or invalid Content-Length header"))?;
// Read content
let mut content = vec![0u8; content_length];
reader.read_exact(&mut content)?;
// Parse JSON
let response: LspResponse = serde_json::from_slice(&content)?;
// Skip notifications
if response.id.is_none() {
continue;
}
// Check if this is our response
if response.id == Some(expected_id) {
if let Some(error) = response.error {
return Err(anyhow!("LSP error: {}", error.message));
}
return response
.result
.ok_or_else(|| anyhow!("No result in response"));
}
}
}
/// Read a response from the language server with timeout
fn read_response_with_timeout(&self, expected_id: u64, timeout: Duration) -> Result<Value> {
use std::time::Instant;
let start = Instant::now();
let mut reader = self.reader.lock().unwrap();
// Poll for response with timeout
while start.elapsed() < timeout {
// Try to read with a small timeout to avoid blocking indefinitely
std::thread::sleep(Duration::from_millis(10));
// Check if the process is still alive
{
let mut process = self.process.lock().unwrap();
match process.try_wait() {
Ok(Some(_)) => return Err(anyhow!("Pyright process has exited")),
Ok(None) => {} // Still running
Err(e) => return Err(anyhow!("Failed to check process status: {}", e)),
}
}
// Try to read response
loop {
// Read headers
let mut headers = Vec::new();
loop {
let mut line = String::new();
match reader.read_line(&mut line) {
Ok(0) => return Err(anyhow!("Connection closed")),
Ok(_) => {
if line == "\r\n" || line == "\n" {
break;
}
headers.push(line);
}
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
// No data available yet, continue outer loop
break;
}
Err(e) => return Err(anyhow!("Failed to read line: {}", e)),
}
}
if headers.is_empty() {
break; // No data available, continue with timeout loop
}
// Parse Content-Length header
let content_length = headers
.iter()
.find(|h| h.starts_with("Content-Length:"))
.and_then(|h| h.split(':').nth(1))
.and_then(|v| v.trim().parse::<usize>().ok())
.ok_or_else(|| anyhow!("Missing or invalid Content-Length header"))?;
// Read content
let mut content = vec![0u8; content_length];
reader.read_exact(&mut content)?;
// Parse JSON
let response: LspResponse = serde_json::from_slice(&content)?;
// Skip notifications
if response.id.is_none() {
continue;
}
// Check if this is our response
if response.id == Some(expected_id) {
if let Some(error) = response.error {
return Err(anyhow!("LSP error: {}", error.message));
}
return response
.result
.ok_or_else(|| anyhow!("No result in response"));
}
}
}
Err(anyhow!(
"Timeout waiting for LSP response ({}s)",
timeout.as_secs()
))
}
/// Open a file in the language server
pub fn open_file(&mut self, file_path: &str, content: &str) -> Result<()> {
// Convert to absolute path if relative
let abs_path = if std::path::Path::new(file_path).is_relative() {
std::env::current_dir()?.join(file_path)
} else {
std::path::PathBuf::from(file_path)
};
let uri = format!("file://{}", abs_path.display());
let params = json!({
"textDocument": {
"uri": uri,
"languageId": "python",
"version": 1,
"text": content
}
});
self.send_notification("textDocument/didOpen", params)?;
// Give pyright time to analyze the file
std::thread::sleep(Duration::from_millis(100));
Ok(())
}
/// Update file content in the language server
pub fn update_file(&mut self, file_path: &str, content: &str, version: i32) -> Result<()> {
tracing::debug!(
"Updating file in pyright LSP: {} (version {})",
file_path,
version
);
// Convert to absolute path if relative
let abs_path = if std::path::Path::new(file_path).is_relative() {
std::env::current_dir()?.join(file_path)
} else {
std::path::PathBuf::from(file_path)
};
let uri = format!("file://{}", abs_path.display());
let params = json!({
"textDocument": {
"uri": uri,
"version": version
},
"contentChanges": [{
"text": content
}]
});
self.send_notification("textDocument/didChange", params)?;
// Give pyright time to analyze the changes
std::thread::sleep(Duration::from_millis(100));
Ok(())
}
/// Get hover information (type) at a specific position
pub fn get_hover(&mut self, file_path: &str, line: u32, column: u32) -> Result<Option<String>> {
// Convert to absolute path if relative
let abs_path = if std::path::Path::new(file_path).is_relative() {
std::env::current_dir()?.join(file_path)
} else {
std::path::PathBuf::from(file_path)
};
let uri = format!("file://{}", abs_path.display());
let params = HoverParams {
text_document: TextDocumentIdentifier { uri },
position: Position {
line: line - 1, // Convert to 0-based
character: column,
},
};
let response = self.send_request("textDocument/hover", serde_json::to_value(params)?)?;
// Extract type information from hover response
if let Some(hover) = response.as_object() {
if let Some(contents) = hover.get("contents") {
let type_info = match contents {
Value::String(s) => s.clone(),
Value::Object(obj) => {
if let Some(Value::String(s)) = obj.get("value") {
s.clone()
} else {
return Ok(None);
}
}
_ => return Ok(None),
};
// Parse pyright's hover format
// Examples:
// "(variable) repo: Repo"
// "(module) porcelain\n..."
// eprintln!("DEBUG HOVER: Raw hover response: '{}'", type_info);
tracing::debug!("Pyright hover response: {}", type_info);
// Check for module format first
if type_info.starts_with("(module) ") {
// Extract module name - it's between "(module) " and the first newline or end of string
let module_start = "(module) ".len();
let module_end = type_info[module_start..]
.find('\n')
.map(|pos| module_start + pos)
.unwrap_or(type_info.len());
let module_name = type_info[module_start..module_end].trim();
tracing::debug!("Extracted module type: {}", module_name);
return Ok(Some(module_name.to_string()));
}
// Check for class format
if type_info.starts_with("(class) ") {
// Extract class name - it's between "(class) " and the first newline or end of string
let class_start = "(class) ".len();
let class_end = type_info[class_start..]
.find('\n')
.map(|pos| class_start + pos)
.unwrap_or(type_info.len());
let class_name = type_info[class_start..class_end].trim();
tracing::debug!("Extracted class type: {}", class_name);
return Ok(Some(class_name.to_string()));
}
// Otherwise look for colon format for variables
if let Some(colon_pos) = type_info.find(':') {
let type_part = type_info[colon_pos + 1..].trim();
tracing::debug!("Extracted type: {}", type_part);
// Check if pyright returned "Unknown" - treat as no type info
if type_part == "Unknown" {
tracing::warn!(
"Pyright returned 'Unknown' type at {}:{}:{}",
file_path,
line,
column
);
return Ok(None);
}
return Ok(Some(type_part.to_string()));
}
}
}
Ok(None)
}
/// Get type definition location
pub fn get_type_definition(
&mut self,
file_path: &str,
line: u32,
column: u32,
) -> Result<Option<String>> {
// Convert to absolute path if relative
let abs_path = if std::path::Path::new(file_path).is_relative() {
std::env::current_dir()?.join(file_path)
} else {
std::path::PathBuf::from(file_path)
};
let uri = format!("file://{}", abs_path.display());
let params = TypeDefinitionParams {
text_document: TextDocumentIdentifier { uri: uri.clone() },
position: Position {
line: line - 1, // Convert to 0-based
character: column,
},
};
let response =
self.send_request("textDocument/typeDefinition", serde_json::to_value(params)?)?;
// Parse the response to get the location
if let Some(locations) = response.as_array() {
if let Some(first_location) = locations.first() {
if let Some(target_uri) = first_location.get("uri").and_then(|u| u.as_str()) {
// The URI contains the file path which might have the module information
if let Some(target_range) = first_location.get("range") {
// We have the location of the type definition
// Now we need to read that location to get the type name
tracing::debug!(
"Type definition location: {} at {:?}",
target_uri,
target_range
);
// For now, just extract the filename which might give us module info
if let Some(path) = target_uri.strip_prefix("file://") {
if let Some(module_name) = path
.strip_suffix(".py")
.and_then(|p| p.split('/').next_back())
{
// This is a simple heuristic - the file name is often the module name
return Ok(Some(module_name.to_string()));
}
}
}
}
}
}
Ok(None)
}
/// Query type at a specific location
pub fn query_type(
&mut self,
file_path: &str,
_content: &str,
line: u32,
column: u32,
) -> Result<Option<String>> {
// Note: we assume the file is already open to avoid redundant open calls
// First try hover for immediate type info
let hover_result = self.get_hover(file_path, line, column);
// Debug output
match &hover_result {
Ok(Some(type_str)) => {
// eprintln!("DEBUG PYRIGHT: Querying {}:{} returned type: {}", line, column, type_str);
tracing::debug!("Pyright hover returned type: {}", type_str);
// If we get a simple type name, try to get more info from type definition
if !type_str.contains('.') {
if let Ok(Some(type_def_info)) =
self.get_type_definition(file_path, line, column)
{
tracing::debug!("Type definition info: {}", type_def_info);
// For now, still return the hover result
// In the future we could combine this info
}
}
return Ok(Some(type_str.clone()));
}
Ok(None) => {
tracing::debug!("Pyright returned no type information");
}
Err(e) => {
tracing::debug!("Pyright error: {}", e);
}
}
hover_result
}
/// Shutdown the language server
pub fn shutdown(&mut self) -> Result<()> {
{
let mut is_shutdown = self.is_shutdown.lock().unwrap();
if *is_shutdown {
return Ok(());
}
*is_shutdown = true;
}
// For shutdown, we expect a null result, so we need special handling
let id = self.request_id.fetch_add(1, Ordering::SeqCst);
let request = LspRequest {
jsonrpc: "2.0",
id,
method: "shutdown".to_string(),
params: json!({}),
};
self.send_message(&request)?;
// Read shutdown response - expect null result
self.read_shutdown_response(id)?;
self.send_notification("exit", json!({}))?;
Ok(())
}
/// Read shutdown response that expects null result
fn read_shutdown_response(&self, expected_id: u64) -> Result<()> {
let mut reader = self.reader.lock().unwrap();
loop {
// Read headers
let mut headers = Vec::new();
loop {
let mut line = String::new();
reader.read_line(&mut line)?;
if line == "\r\n" || line == "\n" {
break;
}
headers.push(line);
}
// Parse Content-Length header
let content_length = headers
.iter()
.find(|h| h.starts_with("Content-Length:"))
.and_then(|h| h.split(':').nth(1))
.and_then(|v| v.trim().parse::<usize>().ok())
.ok_or_else(|| anyhow!("Missing or invalid Content-Length header"))?;
// Read content
let mut content = vec![0u8; content_length];
reader.read_exact(&mut content)?;
// Parse JSON
let response: LspResponse = serde_json::from_slice(&content)?;
// Skip notifications
if response.id.is_none() {
continue;
}
// Check if this is our response
if response.id == Some(expected_id) {
if let Some(error) = response.error {
return Err(anyhow!("LSP error: {}", error.message));
}
// For shutdown, result is null - this is expected and valid
return Ok(());
}
}
}
}
impl Drop for PyrightLspClient {
fn drop(&mut self) {
// Try to shutdown gracefully
let _ = self.shutdown();
// Kill the process if it's still running
if let Ok(mut process) = self.process.lock() {
let _ = process.kill();
let _ = process.wait();
}
}
}
impl PyrightLspClientTrait for PyrightLspClient {
fn open_file(&mut self, file_path: &str, content: &str) -> Result<()> {
self.open_file(file_path, content)
}
fn update_file(&mut self, file_path: &str, content: &str, version: i32) -> Result<()> {
self.update_file(file_path, content, version)
}
fn query_type(
&mut self,
file_path: &str,
content: &str,
line: u32,
column: u32,
) -> Result<Option<String>> {
self.query_type(file_path, content, line, column)
}
fn shutdown(&mut self) -> Result<()> {
self.shutdown()
}
}
/// Get type for a variable at a specific location using pyright
pub fn get_type_with_pyright(
file_path: &str,
content: &str,
line: u32,
column: u32,
) -> Result<Option<String>> {
let mut client = PyrightLspClient::new(None)?;
client.query_type(file_path, content, line, column)
}
#[cfg(test)]
pub mod tests {
use super::*;
use std::collections::HashMap;
use std::fs;
use std::sync::{Arc, Mutex, OnceLock};
/// Pool of concurrent pyright clients for tests - one per workspace to avoid cross-test pollution
/// Uses message-passing with request IDs to distribute responses to correct threads
static CONCURRENT_CLIENT_POOL: OnceLock<
Arc<Mutex<HashMap<String, Arc<crate::concurrent_lsp::SyncConcurrentPyrightClient>>>>,
> = OnceLock::new();
/// Get or create a concurrent pyright client for a specific workspace
/// This enables TRUE PARALLELISM while maintaining test isolation by using separate clients per workspace
pub fn get_workspace_concurrent_client(
workspace_root: Option<&str>,
) -> Arc<crate::concurrent_lsp::SyncConcurrentPyrightClient> {
let pool = CONCURRENT_CLIENT_POOL.get_or_init(|| Arc::new(Mutex::new(HashMap::new())));
let workspace_key = workspace_root
.map(|s| s.to_string())
.unwrap_or_else(|| "default".to_string());
let mut clients = pool.lock().unwrap();
if let Some(client) = clients.get(&workspace_key) {
client.clone()
} else {
let client = crate::concurrent_lsp::SyncConcurrentPyrightClient::new(workspace_root)
.expect("Failed to create concurrent pyright client for tests");
let arc_client = Arc::new(client);
clients.insert(workspace_key, arc_client.clone());
arc_client
}
}
/// Clear the client pool to force creation of fresh clients (for test isolation)
pub fn clear_client_pool() {
if let Some(pool) = CONCURRENT_CLIENT_POOL.get() {
if let Ok(mut clients) = pool.lock() {
// Shutdown existing clients gracefully
for (workspace, client) in clients.iter() {
tracing::debug!("Shutting down pyright client for workspace: {}", workspace);
let _ = client.shutdown();
}
clients.clear();
tracing::debug!("Cleared pyright client pool for test isolation");
}
}
}
/// Cleanup function to be called at the end of test runs
/// This ensures all pyright processes are terminated
pub fn cleanup_all_pyright_processes() {
clear_client_pool();
tracing::info!("Cleaned up all pyright processes");
}
/// A wrapper around the concurrent PyrightLspClient that implements the same interface
/// but uses the new message-passing concurrent client instead of mutex-based locking.
/// This removes the serialization bottleneck and enables true parallelism in tests!
pub struct ConcurrentPyrightClientWrapper {
concurrent: Arc<crate::concurrent_lsp::SyncConcurrentPyrightClient>,
}
impl ConcurrentPyrightClientWrapper {
pub fn new() -> Self {
Self {
concurrent: get_workspace_concurrent_client(None),
}
}
pub fn new_with_workspace(workspace_root: Option<&str>) -> Self {
Self {
concurrent: get_workspace_concurrent_client(workspace_root),
}
}
/// Open a file - handled automatically by concurrent client on first query
pub fn open_file(&self, _file_path: &str, _content: &str) -> Result<()> {
// The concurrent client handles file opening automatically when queries are made
Ok(())
}
/// Update a file - not needed for concurrent client
pub fn update_file(&self, _file_path: &str, _content: &str, _version: i32) -> Result<()> {
// The concurrent client doesn't need explicit file updates for our use case
Ok(())
}
/// Query type using the concurrent client - THIS IS THE PERFORMANCE WIN!
/// Multiple threads can call this simultaneously without blocking each other
pub fn query_type(
&self,
file_path: &str,
content: &str,
line: u32,
column: u32,
) -> Result<Option<String>> {
self.concurrent
.query_type_concurrent(file_path, content, line, column)
}
/// Shutdown the client - for the concurrent wrapper we don't shutdown the shared client
/// but we could trigger cleanup if needed
pub fn shutdown(&mut self) -> Result<()> {
// Note: We don't shut down the shared client here because it's shared across tests
// The shared clients are cleaned up via clear_client_pool() when needed
Ok(())
}
}
impl super::PyrightLspClientTrait for ConcurrentPyrightClientWrapper {
fn open_file(&mut self, file_path: &str, content: &str) -> Result<()> {
ConcurrentPyrightClientWrapper::open_file(self, file_path, content)
}
fn update_file(&mut self, file_path: &str, content: &str, version: i32) -> Result<()> {
ConcurrentPyrightClientWrapper::update_file(self, file_path, content, version)
}
fn query_type(
&mut self,
file_path: &str,
content: &str,
line: u32,
column: u32,
) -> Result<Option<String>> {
ConcurrentPyrightClientWrapper::query_type(self, file_path, content, line, column)
}
fn shutdown(&mut self) -> Result<()> {
ConcurrentPyrightClientWrapper::shutdown(self)
}
}
use tempfile::NamedTempFile;
#[test]
#[ignore] // Ignore by default as it requires pyright to be installed
fn test_pyright_type_inference() {
let code = r#"
class Repo:
@staticmethod
def init(path):
return Repo()
def test():
repo = Repo.init(".")
"#;
let temp_file = NamedTempFile::new().unwrap();
fs::write(&temp_file, code).unwrap();
let result = get_type_with_pyright(
temp_file.path().to_str().unwrap(),
code,
8, // Line with 'repo' variable
4, // Column of 'repo'
);
match result {
Ok(Some(type_str)) => {
assert!(
type_str.contains("Repo"),
"Expected Repo type, got: {}",
type_str
);
}
Ok(None) => panic!("No type information returned"),
Err(e) => panic!("Error: {}", e),
}
}
}