odoo-lsp 0.6.0

Language server for Odoo Python/JS/XML
Documentation
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
//! ## Application flow
//!
//! All LSP requests are implemented here on [`Backend`] via the [`LanguageServer`] trait.
//!
//! As the server handles these requests, it may opt to delegate language-specific tasks
//! to methods in the appropriate modules, for example Python to [`python`], XML to [`xml`] etc.
//!
//! Finally, these modules may also opt to delegate formulation of responses to [`backend`],
//! where most leaf methods live.
//!
//! Here's a rough flowchart of the server:
//! ```txt
//!                      ┌───────────────┐                        
//!        ┌─────────────► src/python.rs ├───────────────┐        
//!        │             └───────────────┘               │        
//!        │             ┌────────────┐                  │        
//!        ├─────────────► src/xml.rs ├──────────────────┤        
//!        │             └────────────┘                  │        
//! ┌──────┴──────┐                             ┌────────▼───────┐
//! │ src/main.rs │                             │ src/backend.rs │
//! └──────┬──────┘                             └────────▲───────┘
//!        │             ┌───────────┐                   │        
//!        ├─────────────► src/js.rs ├───────────────────┤        
//!        │             └───────────┘                   │        
//!        │             ┌──────────────┐                │        
//!        └─────────────► src/index.rs ├────────────────┘        
//!                      └──────────────┘                         
//! ```
//!
//! ## String handling
//!
//! Apart from normal Rust strings, the server uses a few more string-like types
//! for optimizing memory usage and performance:
//!
//! - [`ropey::Rope`] represents full documents, and is also a [data structure] of the same name.
//! - [`Spur`] and [`Symbol`] are [`u32`]-sized tokens representing
//!   [interned strings]. While they are not themselves strings, the
//!   [`interner`] can be used to resolve them into strings as well as intern new strings.
//!   Furthermore, [`Symbol`] is a type-safe wrapper around [`Spur`] to prevent mixing
//!   symbols representing different types.
//! - [`ImStr`](odoo_lsp::str::ImStr) and [`Text`](odoo_lsp::str::Text) are used strategically
//!   to avoid excessive memory usage and copying.
//!
//! ## tree-sitter
//!
//! [tree-sitter] is used to parse and analyze Python and JS code.
//! The entire library is too large to cover here, but the important functions/types used are:
//!
//! - [`tree_sitter::Parser`] creates a generic parser for any language.
//! - [`tree_sitter::Language`] defines the [AST] for each language, in this case
//!   they are provided by [`tree_sitter_python`] and [`tree_sitter_javascript`].
//! - [`tree_sitter::QueryCursor`] is used to extract desired patterns from a [`tree_sitter::Tree`],
//!   which is produced by parsing raw text.
//! - [`ts_macros::query!`] provides a shorthand to manually defining queries
//!   and correctly extracting [captures].
//!
//! XML doesn't use tree-sitter, but instead a low-level [lexer](xmlparser::Tokenizer) which
//! yields a sequence of [tokens](xmlparser::Token).
//!
//! [tree-sitter]: https://tree-sitter.github.io/tree-sitter/
//! [AST]: https://en.wikipedia.org/wiki/Abstract_syntax_tree
//! [data structure]: https://en.wikipedia.org/wiki/Rope_(data_structure)
//! [interned strings]: https://en.wikipedia.org/wiki/String_interning
//! [captures]: https://tree-sitter.github.io/tree-sitter/using-parsers#capturing-nodes
//! [lexer]: quickxml::Reader
//! [`Spur`]: lasso::Spur
//! [`Symbol`]: odoo_lsp::index::Symbol

// #![warn(clippy::cognitive_complexity)]
#![deny(clippy::unused_async)]
#![deny(clippy::await_holding_invalid_type)]

use std::collections::HashSet;
use std::path::Path;
use std::sync::atomic::Ordering::Relaxed;
use std::time::Duration;

use ropey::Rope;
use serde_json::Value;
use tower_lsp_server::jsonrpc::Result;
use tower_lsp_server::lsp_types::notification::{DidChangeConfiguration, Notification};
use tower_lsp_server::lsp_types::*;
use tower_lsp_server::{LanguageServer, LspService, Server};
use tracing::{debug, error, info, instrument, warn};
use tracing_subscriber::fmt::writer::MakeWriterExt;
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
use tracing_subscriber::{fmt as tracing_fmt, EnvFilter};

use odoo_lsp::index::{Interner, _G, _R};
use odoo_lsp::{some, utils::*};

use backend::{Backend, Document, Language, Text};
use catch_panic::CatchPanic;

mod backend;
mod catch_panic;
mod cli;
mod js;
mod python;
mod xml;

#[cfg(test)]
#[path = "../testing/index.rs"]
mod testing;

#[cfg(doc)]
pub use odoo_lsp::*;

#[cfg(unix)]
mod stdio;

fn main() {
	let args = std::env::args().collect::<Vec<_>>();
	let args = parse_args_and_init_logger(&args);

	let mut threads = args.threads.unwrap_or(4);
	match std::thread::available_parallelism() {
		Ok(value) if value.get() <= 4 => {
			threads = 1usize.max(threads / 2);
		}
		_ => {}
	}

	let rt = if threads <= 1 {
		tokio::runtime::Builder::new_current_thread().enable_all().build()
	} else {
		tokio::runtime::Builder::new_multi_thread()
			.worker_threads(threads)
			.enable_all()
			.build()
	}
	.expect("failed to build runtime");
	rt.block_on(async move {
		if cli::run(args).await {
			return;
		}

		#[cfg(unix)]
		let (stdin, stdout) = (
			stdio::PipeStdin::lock_tokio().unwrap(),
			stdio::PipeStdout::lock_tokio().unwrap(),
		);

		#[cfg(not(unix))]
		let (stdin, stdout) = (tokio::io::stdin(), tokio::io::stdout());

		let (service, socket) = LspService::build(Backend::new)
			.custom_method("odoo-lsp/debug/usage", |_: &Backend| async move {
				Ok(Interner::report_usage())
			})
			.custom_method("odoo-lsp/inspect-type", Backend::debug_inspect_type)
			.finish();

		let service = tower::ServiceBuilder::new()
			.layer(tower::timeout::TimeoutLayer::new(Duration::from_secs(30)))
			.layer_fn(CatchPanic)
			.service(service);
		Server::new(stdin, stdout, socket).serve(service).await;
	})
}

fn parse_args_and_init_logger(args: &[String]) -> cli::Args<'_> {
	let args = args.iter().skip(1).map(String::as_str).collect::<Vec<_>>();
	let args = cli::parse_args(&args[..]);

	let outlog = std::env::var("ODOO_LSP_LOG").ok().and_then(|var| {
		let path = match var.as_str() {
			#[cfg(unix)]
			"1" => Path::new("/tmp/odoo_lsp.log"),
			_ => Path::new(&var),
		};
		std::fs::OpenOptions::new().create(true).append(true).open(path).ok()
	});
	let registry = tracing_subscriber::registry().with(EnvFilter::from_default_env());
	let layer = tracing_fmt::layer()
		.without_time()
		.with_writer(std::io::stderr)
		.with_file(true)
		.with_line_number(true)
		.with_target(true);

	match args.log_format {
		cli::LogFormat::Compact => {
			let layer = layer.compact();
			match outlog {
				Some(outlog) => registry.with(layer.map_writer(|stderr| stderr.and(outlog))).init(),
				None => registry.with(layer).init(),
			}
		}
		cli::LogFormat::Json => {
			// both must be specified, ref https://github.com/tokio-rs/tracing/issues/1365#issuecomment-828845393
			let layer = layer
				.event_format(tracing_fmt::format().json())
				.fmt_fields(tracing_fmt::format::JsonFields::new());
			match outlog {
				Some(outlog) => registry.with(layer.map_writer(|stderr| stderr.and(outlog))).init(),
				None => registry.with(layer).init(),
			}
		}
	}

	args
}

impl LanguageServer for Backend {
	#[instrument(skip_all, fields(params), ret)]
	async fn initialize(&self, params: InitializeParams) -> Result<InitializeResult> {
		self.init_workspaces(&params);

		if let Some(WorkspaceClientCapabilities {
			did_change_configuration:
				Some(DynamicRegistrationClientCapabilities {
					dynamic_registration: Some(true),
				}),
			..
		}) = params.capabilities.workspace.as_ref()
		{
			self.capabilities.can_notify_changed_config.store(true, Relaxed);
		}

		if let Some(WorkspaceClientCapabilities {
			did_change_watched_files:
				Some(DidChangeWatchedFilesClientCapabilities {
					dynamic_registration: Some(true),
					..
				}),
			..
		}) = params.capabilities.workspace.as_ref()
		{
			self.capabilities.can_notify_changed_watched_files.store(true, Relaxed);
		}
		if let Some(WorkspaceClientCapabilities {
			workspace_folders: Some(true),
			..
		}) = params.capabilities.workspace.as_ref()
		{
			self.capabilities.workspace_folders.store(true, Relaxed);
		}

		if let Some(TextDocumentClientCapabilities {
			diagnostic: Some(..), ..
		}) = params.capabilities.text_document
		{
			debug!("Client supports pull diagnostics");
			self.capabilities.pull_diagnostics.store(true, Relaxed);
		}

		Ok(InitializeResult {
			server_info: None,
			offset_encoding: None,
			capabilities: ServerCapabilities {
				definition_provider: Some(OneOf::Left(true)),
				hover_provider: Some(HoverProviderCapability::Simple(true)),
				references_provider: Some(OneOf::Left(true)),
				workspace_symbol_provider: Some(OneOf::Left(true)),
				diagnostic_provider: Some(DiagnosticServerCapabilities::Options(Default::default())),
				// XML code actions are done in 1 pass only
				code_action_provider: Some(CodeActionProviderCapability::Simple(true)),
				execute_command_provider: Some(ExecuteCommandOptions {
					commands: vec!["goto_owl".to_string()],
					..Default::default()
				}),
				text_document_sync: Some(TextDocumentSyncCapability::Options(TextDocumentSyncOptions {
					change: Some(TextDocumentSyncKind::INCREMENTAL),
					save: Some(TextDocumentSyncSaveOptions::Supported(true)),
					open_close: Some(true),
					..Default::default()
				})),
				completion_provider: Some(CompletionOptions {
					resolve_provider: Some(true),
					trigger_characters: Some(['"', '\'', '.', '_', ',', ' '].iter().map(char::to_string).collect()),
					all_commit_characters: None,
					completion_item: None,
					work_done_progress_options: Default::default(),
				}),
				workspace: Some(WorkspaceServerCapabilities {
					workspace_folders: Some(WorkspaceFoldersServerCapabilities {
						supported: Some(true),
						change_notifications: Some(OneOf::Left(true)),
					}),
					file_operations: None,
				}),
				..ServerCapabilities::default()
			},
		})
	}
	#[instrument(skip_all)]
	async fn shutdown(&self) -> Result<()> {
		Ok(())
	}
	#[instrument(skip(self))]
	async fn did_close(&self, params: DidCloseTextDocumentParams) {
		let path = params.text_document.uri.path().as_str();
		self.document_map.remove(path);
		self.record_ranges.remove(path);
		self.ast_map.remove(path);

		self.client
			.publish_diagnostics(params.text_document.uri, vec![], None)
			.await;
	}
	#[instrument(skip_all)]
	async fn initialized(&self, _: InitializedParams) {
		let mut registrations = vec![];
		if self.capabilities.can_notify_changed_config.load(Relaxed) {
			registrations.push(Registration {
				id: "odoo-lsp/did-change-config".to_string(),
				method: DidChangeConfiguration::METHOD.to_string(),
				register_options: None,
			});
		}
		if self.capabilities.can_notify_changed_watched_files.load(Relaxed) {
			registrations.push(Registration {
				id: "odoo-lsp/did-change-odoo-lsp".to_string(),
				method: notification::DidChangeWatchedFiles::METHOD.to_string(),
				register_options: Some(
					serde_json::to_value(DidChangeWatchedFilesRegistrationOptions {
						watchers: vec![FileSystemWatcher {
							glob_pattern: GlobPattern::String("**/.odoo_lsp{,.json}".to_string()),
							kind: Some(WatchKind::Create | WatchKind::Change),
						}],
					})
					.unwrap(),
				),
			});
		}

		if !registrations.is_empty() {
			_ = self.client.register_capability(registrations).await;
		}

		let _blocker = self.root_setup.block();
		self.ensure_nonoverlapping_roots();
		info!(workspaces = ?self.workspaces);

		for ws in self.workspaces.iter() {
			match (self.index)
				.add_root(Path::new(ws.key()), Some(self.client.clone()), false)
				.await
			{
				Ok(Some(results)) => {
					info!(
						target: "initialized",
						"{} | {} modules | {} records | {} templates | {} models | {} components | {:.2}s",
						ws.key().display(),
						results.module_count,
						results.record_count,
						results.template_count,
						results.model_count,
						results.component_count,
						results.elapsed.as_secs_f64()
					);
				}
				Err(err) => {
					error!("could not add root {}:\n{err}", ws.key().display());
				}
				_ => {}
			}
		}
		drop(_blocker);
	}
	#[instrument(skip_all, ret, fields(uri=params.text_document.uri.path().as_str()))]
	async fn did_open(&self, params: DidOpenTextDocumentParams) {
		info!("{}", params.text_document.uri.path().as_str());
		let language_id = params.text_document.language_id.as_str();
		let split_uri = params.text_document.uri.path().as_str().rsplit_once('.');
		let language = match (language_id, split_uri) {
			("python", _) | (_, Some((_, "py"))) => Language::Python,
			("javascript", _) | (_, Some((_, "js"))) => Language::Javascript,
			("xml", _) | (_, Some((_, "xml"))) => Language::Xml,
			_ => {
				debug!("Could not determine language, or language not supported:\nlanguage_id={language_id} split_uri={split_uri:?}");
				return;
			}
		};

		let rope = Rope::from_str(&params.text_document.text);
		self.document_map.insert(
			params.text_document.uri.path().as_str().to_string(),
			Document::new(rope.clone()),
		);

		self.root_setup.wait().await;
		let path = params.text_document.uri.to_file_path().unwrap();
		if self.index.module_of_path(&path).is_none() {
			// outside of root?
			debug!("oob: {}", params.text_document.uri.path().as_str());
			let path = params.text_document.uri.to_file_path();
			let mut path = path.as_deref();
			while let Some(path_) = path {
				if tokio::fs::try_exists(path_.with_file_name("__manifest__.py"))
					.await
					.unwrap_or(false)
				{
					if let Some(file_path) = path_.parent().and_then(|p| p.parent()) {
						_ = self
							.index
							.add_root(file_path, Some(self.client.clone()), false)
							.await
							.inspect_err(|err| warn!("failed to add root {}:\n{err}", file_path.display()));
						break;
					}
				}
				path = path_.parent();
			}
		}

		_ = self
			.on_change(backend::TextDocumentItem {
				uri: params.text_document.uri,
				text: Text::Full(params.text_document.text),
				version: params.text_document.version,
				language: Some(language),
				old_rope: None,
				open: true,
			})
			.await
			.inspect_err(|err| warn!("{err}"));
	}
	#[instrument(skip_all)]
	async fn did_change(&self, mut params: DidChangeTextDocumentParams) {
		self.root_setup.wait().await;
		if let [TextDocumentContentChangeEvent {
			range: None,
			range_length: None,
			text,
		}] = params.content_changes.as_mut_slice()
		{
			_ = self
				.on_change(backend::TextDocumentItem {
					uri: params.text_document.uri,
					text: Text::Full(core::mem::take(text)),
					version: params.text_document.version,
					language: None,
					old_rope: None,
					open: false,
				})
				.await
				.inspect_err(|err| warn!("{err}"));
			return;
		}
		let old_rope;
		{
			let mut document = self
				.document_map
				.get_mut(params.text_document.uri.path().as_str())
				.expect("Did not build a document");
			old_rope = document.rope.clone();
			// Update the rope
			// TODO: Refactor into method
			// Per the spec (https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocument_didChange),
			// deltas are applied SEQUENTIALLY so we don't have to do any extra processing.
			for change in &params.content_changes {
				if change.range.is_none() && change.range_length.is_none() {
					document.rope = ropey::Rope::from_str(&change.text);
				} else {
					let range = change.range.expect("LSP change event must have a range");
					let range =
						lsp_range_to_char_range(range, &document.rope).expect("did_change applying delta: no range");
					let rope = &mut document.rope;
					rope.remove(range.erase());
					if !change.text.is_empty() {
						rope.insert(range.start.0, &change.text);
					}
				}
			}
		}
		_ = self
			.on_change(backend::TextDocumentItem {
				uri: params.text_document.uri,
				text: Text::Delta(params.content_changes),
				version: params.text_document.version,
				language: None,
				old_rope: Some(old_rope),
				open: false,
			})
			.await
			.inspect_err(|err| warn!("{err}"));
	}
	#[instrument(skip_all)]
	async fn did_save(&self, params: DidSaveTextDocumentParams) {
		if self.root_setup.should_wait() {
			return;
		}
		_ = self.did_save_impl(params).await.inspect_err(|err| warn!("{err}"));
	}
	#[instrument(skip_all)]
	async fn goto_definition(&self, params: GotoDefinitionParams) -> Result<Option<GotoDefinitionResponse>> {
		if self.root_setup.should_wait() {
			return Ok(None);
		}
		let uri = &params.text_document_position_params.text_document.uri;
		debug!("goto_definition {}", uri.path().as_str());
		let Some((_, ext)) = uri.path().as_str().rsplit_once('.') else {
			debug!("(goto_definition) unsupported: {}", uri.path().as_str());
			return Ok(None);
		};
		let Some(document) = self.document_map.get(uri.path().as_str()) else {
			panic!("Bug: did not build a document for {}", uri.path().as_str());
		};
		let location = match ext {
			"xml" => self.xml_jump_def(params, document.rope.clone()),
			"py" => self.python_jump_def(params, document.rope.clone()),
			"js" => self.js_jump_def(params, &document.rope),
			_ => {
				debug!("(goto_definition) unsupported: {}", uri.path().as_str());
				return Ok(None);
			}
		};

		let location = location
			.map_err(|err| error!("Error retrieving references:\n{err}"))
			.ok()
			.flatten();
		Ok(location.map(GotoDefinitionResponse::Scalar))
	}
	#[instrument(skip_all)]
	async fn references(&self, params: ReferenceParams) -> Result<Option<Vec<Location>>> {
		if self.root_setup.should_wait() {
			return Ok(None);
		}
		let uri = &params.text_document_position.text_document.uri;
		debug!("references {}", uri.path().as_str());

		let Some((_, ext)) = uri.path().as_str().rsplit_once('.') else {
			return Ok(None); // hit a directory, super unlikely
		};
		let Some(document) = self.document_map.get(uri.path().as_str()) else {
			debug!("Bug: did not build a document for {}", uri.path().as_str());
			return Ok(None);
		};
		let refs = match ext {
			"py" => self.python_references(params, document.rope.clone()),
			"xml" => self.xml_references(params, document.rope.clone()),
			"js" => self.js_references(params, &document.rope),
			_ => return Ok(None),
		};

		Ok(refs.inspect_err(|err| warn!("{err}")).ok().flatten())
	}
	#[instrument(skip_all)]
	async fn completion(&self, params: CompletionParams) -> Result<Option<CompletionResponse>> {
		if self.root_setup.should_wait() {
			return Ok(None);
		}
		let uri = &params.text_document_position.text_document.uri;
		debug!("(completion) {}", uri.path().as_str());

		let Some((_, ext)) = uri.path().as_str().rsplit_once('.') else {
			return Ok(None); // hit a directory, super unlikely
		};

		let rope = {
			let Some(document) = self.document_map.get(uri.path().as_str()) else {
				debug!("Bug: did not build a document for {}", uri.path().as_str());
				return Ok(None);
			};
			document.rope.clone()
		};
		if ext == "xml" {
			let completions = self.xml_completions(params, rope).await;
			match completions {
				Ok(ret) => Ok(ret),
				Err(report) => {
					self.client
						.show_message(MessageType::ERROR, format!("error during xml completion:\n{report}"))
						.await;
					Ok(None)
				}
			}
		} else if ext == "py" {
			let ast = {
				let Some(ast) = self.ast_map.get(uri.path().as_str()) else {
					debug!("Bug: did not build AST for {}", uri.path().as_str());
					return Ok(None);
				};
				ast.value().clone()
			};
			let completions = self.python_completions(params, ast, rope).await;
			match completions {
				Ok(ret) => Ok(ret),
				Err(err) => {
					self.client
						.show_message(MessageType::ERROR, format!("error during python completion:\n{err}"))
						.await;
					Ok(None)
				}
			}
		} else {
			debug!("(completion) unsupported {}", uri.path().as_str());
			Ok(None)
		}
	}
	#[instrument(skip_all)]
	async fn completion_resolve(&self, mut completion: CompletionItem) -> Result<CompletionItem> {
		if self.root_setup.should_wait() {
			return Ok(completion);
		}
		'resolve: {
			match &completion.kind {
				Some(CompletionItemKind::CLASS) => {
					let Some(model) = _G(&completion.label) else {
						break 'resolve;
					};
					let Some(mut entry) = self.index.models.get_mut(&model.into()) else {
						break 'resolve;
					};
					if let Err(err) = entry.resolve_details() {
						error!("resolving details: {err}");
					}
					completion.documentation = Some(Documentation::MarkupContent(MarkupContent {
						kind: MarkupKind::Markdown,
						value: self.model_docstring(&entry, None, None),
					}))
				}
				Some(CompletionItemKind::FIELD) => {
					_ = self.completion_resolve_field(&mut completion);
				}
				Some(CompletionItemKind::METHOD) => {
					_ = self.completion_resolve_method(&mut completion);
				}
				_ => {}
			}
		}
		Ok(completion)
	}
	#[instrument(skip_all)]
	async fn hover(&self, params: HoverParams) -> Result<Option<Hover>> {
		if self.root_setup.should_wait() {
			return Ok(None);
		}
		let uri = &params.text_document_position_params.text_document.uri;
		let document = some!(self.document_map.get(uri.path().as_str()));
		let (_, ext) = some!(uri.path().as_str().rsplit_once('.'));
		let hover = match ext {
			"py" => self.python_hover(params, document.rope.clone()),
			"xml" => self.xml_hover(params, document.rope.clone()),
			"js" => self.js_hover(params, document.rope.clone()),
			_ => {
				debug!("(hover) unsupported {}", uri.path().as_str());
				Ok(None)
			}
		};
		match hover {
			Ok(ret) => Ok(ret),
			Err(err) => {
				error!("{err}");
				Ok(None)
			}
		}
	}
	#[instrument(skip_all)]
	async fn did_change_configuration(&self, _: DidChangeConfigurationParams) {
		self.root_setup.wait().await;
		let items = self
			.workspaces
			.iter()
			.map(|entry| {
				let scope_uri = uri_from_file_path(entry.key());
				ConfigurationItem {
					section: Some("odoo-lsp".into()),
					scope_uri,
				}
			})
			.collect();
		let configs = self.client.configuration(items).await.unwrap_or_default();
		let workspace_paths = self.workspaces.iter().map(|ws| ws.key().to_owned()).collect::<Vec<_>>();
		for (config, ws) in configs.into_iter().zip(workspace_paths) {
			match serde_json::from_value(config) {
				Ok(config) => self.on_change_config(config, Some(&ws)),
				Err(err) => error!("Could not parse updated configuration for {}:\n{err}", ws.display()),
			}
		}
		self.ensure_nonoverlapping_roots();

		let workspaces = self
			.workspaces
			.iter()
			.map(|ws| ws.key().to_owned())
			.collect::<HashSet<_>>();
		let roots = self
			.index
			.roots
			.iter()
			.map(|root| root.key().to_owned())
			.collect::<HashSet<_>>();

		for removed in roots.difference(&workspaces) {
			self.index.remove_root(removed);
		}

		self.index.delete_marked_entries();

		for added in workspaces.difference(&roots) {
			if let Err(err) = self.index.add_root(added, None, false).await {
				error!("failed to add root {}:\n{err}", added.display());
			}
		}
	}
	#[instrument(skip_all)]
	async fn did_change_workspace_folders(&self, params: DidChangeWorkspaceFoldersParams) {
		self.root_setup.wait().await;
		for added in params.event.added {
			let Some(file_path) = added.uri.to_file_path() else {
				error!("not a file path: {}", added.uri.as_str());
				continue;
			};
			_ = self
				.index
				.add_root(&file_path, None, false)
				.await
				.inspect_err(|err| warn!("failed to add root {}:\n{err}", file_path.display()));
		}
		for removed in params.event.removed {
			let Some(file_path) = removed.uri.to_file_path() else {
				error!("not a file path: {}", removed.uri.as_str());
				continue;
			};
			self.index.remove_root(&file_path);
		}
		self.index.delete_marked_entries();
	}
	/// For VSCode and capable LSP clients, these events represent changes mostly to configuration files.
	async fn did_change_watched_files(&self, params: DidChangeWatchedFilesParams) {
		for FileEvent { uri, .. } in params.changes {
			let Some(file_path) = uri.to_file_path() else { continue };
			let Some(".odoo_lsp") = file_path.file_stem().and_then(|ostr| ostr.to_str()) else {
				continue;
			};
			if let Some(wspath) = self.workspaces.find_workspace_of(&file_path, |wspath, _| {
				file_path
					.strip_prefix(wspath)
					.is_ok_and(|suffix| {
						suffix.file_stem().unwrap_or(suffix.as_os_str()).to_string_lossy() == ".odoo_lsp"
					})
					.then(|| wspath.to_owned())
			}) {
				let Ok(file) = std::fs::read(&file_path) else {
					break;
				};
				let mut diagnostics = vec![];
				match serde_json::from_slice(&file) {
					Ok(config) => self.on_change_config(config, Some(&wspath)),
					Err(err) => {
						let point = Position {
							line: err.line() as u32 - 1,
							character: err.column() as u32 - 1,
						};
						diagnostics.push(Diagnostic {
							range: Range {
								start: point,
								end: point,
							},
							message: format!("{err}"),
							severity: Some(DiagnosticSeverity::ERROR),
							..Default::default()
						});
					}
				}
				self.client.publish_diagnostics(uri, diagnostics, None).await;
				break;
			}
		}
	}
	#[instrument(skip_all)]
	async fn symbol(&self, params: WorkspaceSymbolParams) -> Result<Option<Vec<SymbolInformation>>> {
		if self.root_setup.should_wait() {
			return Ok(None);
		}
		let query = &params.query;
		let limit = self.project_config.symbols_limit.load(Relaxed);

		let models_by_prefix = self.index.models.by_prefix.read().await;
		let records_by_prefix = self.index.records.by_prefix.read().await;
		let models = models_by_prefix.iter_prefix(query.as_bytes()).flat_map(|(_, key)| {
			self.index.models.get(key).into_iter().flat_map(|entry| {
				#[allow(deprecated)]
				entry.base.as_ref().map(|loc| SymbolInformation {
					name: _R(*entry.key()).to_string(),
					kind: SymbolKind::CONSTANT,
					tags: None,
					deprecated: None,
					location: loc.0.clone().into(),
					container_name: None,
				})
			})
		});
		fn to_symbol_information(record: &odoo_lsp::record::Record) -> SymbolInformation {
			#[allow(deprecated)]
			SymbolInformation {
				name: record.qualified_id(),
				kind: SymbolKind::VARIABLE,
				tags: None,
				deprecated: None,
				location: record.location.clone().into(),
				container_name: None,
			}
		}
		if let Some((module, xml_id_query)) = query.split_once('.') {
			let module = some!(_G(module)).into();
			let records = records_by_prefix
				.iter_prefix(xml_id_query.as_bytes())
				.flat_map(|(_, keys)| {
					keys.iter().flat_map(|key| {
						self.index
							.records
							.get(key)
							.and_then(|record| (record.module == module).then(|| to_symbol_information(&record)))
					})
				});
			Ok(Some(models.chain(records).take(limit).collect()))
		} else {
			let records = records_by_prefix.iter_prefix(query.as_bytes()).flat_map(|(_, keys)| {
				keys.iter()
					.flat_map(|key| self.index.records.get(key).map(|record| to_symbol_information(&record)))
			});
			Ok(Some(models.chain(records).take(limit).collect()))
		}
	}
	#[instrument(skip_all, ret)]
	async fn diagnostic(&self, params: DocumentDiagnosticParams) -> Result<DocumentDiagnosticReportResult> {
		self.root_setup.wait().await;
		let path = params.text_document.uri.path().as_str();
		debug!("{path}");
		let mut diagnostics = vec![];
		if let Some((_, "py")) = path.rsplit_once('.') {
			if let Some(mut document) = self.document_map.get_mut(path) {
				let damage_zone = document.damage_zone.take();
				let rope = &document.rope.clone();
				self.diagnose_python(
					params.text_document.uri.path().as_str(),
					rope,
					damage_zone,
					&mut document.diagnostics_cache,
				);
				diagnostics.clone_from(&document.diagnostics_cache);
			}
		}
		Ok(DocumentDiagnosticReportResult::Report(DocumentDiagnosticReport::Full(
			RelatedFullDocumentDiagnosticReport {
				related_documents: None,
				full_document_diagnostic_report: FullDocumentDiagnosticReport {
					result_id: None,
					items: diagnostics,
				},
			},
		)))
	}
	#[instrument(skip_all)]
	async fn code_action(&self, params: CodeActionParams) -> Result<Option<CodeActionResponse>> {
		if self.root_setup.should_wait() {
			return Ok(None);
		}
		let Some((_, "xml")) = params.text_document.uri.path().as_str().rsplit_once('.') else {
			return Ok(None);
		};

		let document = some!(self.document_map.get(params.text_document.uri.path().as_str()));

		Ok(self
			.xml_code_actions(params, document.rope.clone())
			.inspect_err(|err| {
				error!("(code_lens) {err}");
			})
			.unwrap_or(None))
	}
	#[instrument(skip_all)]
	async fn execute_command(&self, params: ExecuteCommandParams) -> Result<Option<Value>> {
		if self.root_setup.should_wait() {
			return Ok(None);
		}
		if let ("goto_owl", [Value::String(_), Value::String(subcomponent)]) =
			(params.command.as_str(), params.arguments.as_slice())
		{
			// FIXME: Subcomponents should not just depend on the component's name,
			// since users can readjust subcomponents' names at will.
			let component = some!(_G(subcomponent));
			let location = {
				let component = some!(self.index.components.get(&component.into()));
				some!(component.location.clone())
			};
			_ = self
				.client
				.show_document(ShowDocumentParams {
					uri: uri_from_file_path(&location.path.to_path()).unwrap(),
					external: Some(false),
					take_focus: Some(true),
					selection: Some(location.range),
				})
				.await;
		}

		Ok(None)
	}
}