odoo-lsp 0.6.2

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
use super::*;
use crate::model::ModelProperties;
use pretty_assertions::assert_eq;
use tree_sitter::QueryCursor;

/// Tricky behavior here. The query syntax must match the trailing comma between
/// named arguments, and this test checks that. Furthermore, @help cannot be matched
/// as a `(string)` since that would reify its shape and refuse subsequent matches.
#[test]
fn test_model_fields() {
	let mut parser = Parser::new();
	parser.set_language(&tree_sitter_python::LANGUAGE.into()).unwrap();
	let contents = br#"
class Foo(models.Model):
	foo = fields.Char('asd', help='asd')
	bar = fields.Many2one(comodel_name='asd', help='asd')

	@property
	def foobs(self):
		...

	haha = fields.Many2many('asd')
	what = fields.What(asd)

	def passer(self):
		...

	html = fields.Html(related='asd', foo=123, help='asdf')
"#;
	let ast = parser.parse(&contents[..], None).unwrap();
	let query = ModelProperties::query();
	let mut cursor = QueryCursor::new();
	let expected: &[&[&str]] = &[
		&["foo", "fields", "Char", "'asd'", "help", "'asd'"],
		&["bar", "fields", "Many2one", "comodel_name", "'asd'", "help", "'asd'"],
		&["def foobs(self):\n\t\t...", "foobs"],
		&["haha", "fields", "Many2many", "'asd'"],
		&["what", "fields", "What"],
		&["def passer(self):\n\t\t...", "passer"],
		&[
			"html", "fields", "Html", "related", "'asd'", "foo", "123", "help", "'asdf'",
		],
	];
	let actual = cursor
		.matches(query, ast.root_node(), &contents[..])
		.map(|match_| {
			match_
				.captures
				.iter()
				.map(|capture| String::from_utf8_lossy(&contents[capture.node.byte_range()]))
				.collect::<Vec<_>>()
		})
		.fold_mut(vec![], acc_vec);
	assert_eq!(expected, actual);
}

#[test]
fn test_py_completions() {
	let mut parser = Parser::new();
	parser.set_language(&tree_sitter_python::LANGUAGE.into()).unwrap();
	let contents = br#"
self.env.ref('ref')
env['model']
request.render('template')
foo = fields.Char()
"#;
	let ast = parser.parse(&contents[..], None).unwrap();
	let query = PyCompletions::query();
	let mut cursor = QueryCursor::new();
	let expected = vec![
		(0, vec!["env", "ref", "'ref'"]),
		(1, vec!["env", "'model'"]),
		(0, vec!["request", "render", "'template'"]),
	];
	let actual = cursor
		.matches(query, ast.root_node(), &contents[..])
		.map(|match_| {
			(
				match_.pattern_index,
				match_
					.captures
					.iter()
					.map(|capture| String::from_utf8_lossy(&contents[capture.node.byte_range()]))
					.collect::<Vec<_>>(),
			)
		})
		.fold_mut(vec![], acc_vec);
	let actual = actual
		.iter()
		.map(|(index, captures)| (*index, captures.iter().map(|x| x.as_ref()).collect::<Vec<_>>()))
		.collect::<Vec<_>>();
	assert_eq!(expected, actual);
}

#[test]
fn test_py_completions_class_scoped() {
	let mut parser = Parser::new();
	parser.set_language(&tree_sitter_python::LANGUAGE.into()).unwrap();
	let contents = br#"
class Foo(models.AbstractModel):
	_name = 'foo'
	_inherit = ['inherit_foo', 'inherit_bar']

	foo = fields.Many2one('some.model', 'Field Name', related='related')
	bar = fields.Many2one('positional', string='blah', domain="[('foo', '=', 'bar')]")
	baz = fields.Many2many(comodel_name='named', domain=[('foo', '=', bar)])

	@api.constrains('mapped', 'meh')
	def foo(self):
		what = self.sudo().mapped('ha.ha')

	foo = fields.Foo()

	@api.depends_context('uid')
	@api.depends('mapped2', 'mapped3')
	def another(self):
		pass

	def no_decorators(self):
		pass
"#;
	let ast = parser.parse(contents, None).unwrap();
	let query = PyCompletions::query();
	let mut cursor = QueryCursor::new();
	let expected: &[&[&str]] = &[
		&["_name", "'foo'"],
		&["_inherit", "'inherit_foo'", "'inherit_bar'"],
		&["foo", "fields", "ft:Many2one", "'some.model'", "related"],
		&["bar", "fields", "ft:Many2one", "'positional'", "string", "domain"],
		&["baz", "fields", "ft:Many2many", "comodel_name", "domain"],
		// api.constrains('mapped', 'meh')
		&["api", "constrains", "'mapped'"],
		&["api", "constrains", "'meh'"],
		// scope detection with no .depends
		// note that it goes later
		&["self.sudo()", "mapped", "'ha.ha'"],
		&["api.constrains('mapped', 'meh')", "<scope>"],
		&["foo", "fields", "ft:Foo"],
		// scope detection with both .depends and non-.depends
		// first, each of the original MAPPED rules are triggered
		&["api", "depends", "'mapped2'"],
		&["api", "depends", "'mapped3'"],
		&["api", "depends", "'mapped2'", "'mapped3'", "<scope>"],
		// no decorators
		&["<scope>"],
	];
	let actual = cursor
		.matches(query, ast.root_node(), &contents[..])
		.map(|match_| {
			match_
				.captures
				.iter()
				.map(|capture| match PyCompletions::from(capture.index) {
					Some(PyCompletions::Scope) => Cow::from("<scope>"),
					Some(PyCompletions::FieldType) => Cow::from(format!(
						"ft:{}",
						String::from_utf8_lossy(&contents[capture.node.byte_range()])
					)),
					_ => String::from_utf8_lossy(&contents[capture.node.byte_range()]),
				})
				.collect::<Vec<_>>()
		})
		.fold_mut(vec![], acc_vec);
	assert_eq!(expected, actual);
}

#[test]
fn test_attribute_node_at_offset() {
	let mut parser = Parser::new();
	parser.set_language(&tree_sitter_python::LANGUAGE.into()).unwrap();
	let contents = "foo.mapped(lambda f: f.bar)";
	let offset = contents.find("bar").unwrap();
	let ast = parser.parse(contents, None).unwrap();
	let (object, field, range) = Backend::attribute_node_at_offset(offset, ast.root_node(), contents).unwrap();
	assert_eq!(&contents[object.byte_range()], "f");
	assert_eq!(field, "bar");
	assert_eq!(&contents[range], "bar");
}

#[test]
fn test_attribute_at_offset_2() {
	let mut parser = Parser::new();
	parser.set_language(&tree_sitter_python::LANGUAGE.into()).unwrap();
	let contents = "super().powerful()";
	let offset = contents.find("powerful").unwrap();
	let ast = parser.parse(contents, None).unwrap();
	let (object, field, range) = Backend::attribute_node_at_offset(offset, ast.root_node(), contents).unwrap();
	assert_eq!(&contents[object.byte_range()], "super()");
	assert_eq!(field, "powerful");
	assert_eq!(&contents[range], "powerful");
}

#[test]
fn test_top_level_stmt() {
	let mut parser = Parser::new();
	parser.set_language(&tree_sitter_python::LANGUAGE.into()).unwrap();
	let contents = "class A:\n    pass\n\nclass B:\n    pass\n";
	let offset = contents.find("class B").unwrap() + 6;
	let contents = contents.as_bytes();
	let ast = parser.parse(contents, None).unwrap();
	let node = super::top_level_stmt(ast.root_node(), offset).unwrap();
	assert_eq!(node.kind(), "class_definition");
	assert!(contents[node.byte_range()].starts_with(b"class B"));
}

#[test]
fn test_tag_model() {
	let mut parser = Parser::new();
	parser.set_language(&tree_sitter_python::LANGUAGE.into()).unwrap();
	let contents = "class A(models.Model):\n    _name = 'foo'\n    _inherit = 'bar'\n\nclass B(models.Model):\n    _inherit = 'baz'\n";
	let ast = parser.parse(contents, None).unwrap();
	let query = super::PyCompletions::query();
	let mut cursor = QueryCursor::new();
	let mut this_model = super::ThisModel::default();
	for class_node in ast
		.root_node()
		.named_children(&mut ast.root_node().walk())
		.filter(|n| n.kind() == "class_definition")
	{
		let mut matches = cursor.matches(query, class_node, contents.as_bytes());
		while let Some(match_) = matches.next() {
			for capture in match_.captures {
				if matches!(
					super::PyCompletions::from(capture.index),
					Some(super::PyCompletions::Model)
				) {
					this_model.tag_model(capture.node, match_, class_node.byte_range(), contents);
				}
			}
		}
	}
	assert_eq!(this_model.inner, Some("baz"));
	assert!(matches!(this_model.source, super::ThisModelKind::Inherited));
}

#[test]
fn test_py_completions_broken_syntax_commandlist() {
	// This test demonstrates that completions should work even when syntax is broken
	// (e.g., missing colon after a dictionary key)

	// Simpler test case with just the broken part
	let contents = r#"[(0, 0, {
	'name': 'Test',
	'desc'
})]"#;

	// Find the position after 'desc' where we want completion
	let cursor_pos = contents.find("'desc'").unwrap() + 5; // After 'desc

	let mut parser = tree_sitter::Parser::new();
	parser.set_language(&tree_sitter_python::LANGUAGE.into()).unwrap();
	let tree = parser.parse(contents.as_bytes(), None).unwrap();

	// Find the dictionary node
	fn find_dict(node: tree_sitter::Node) -> Option<tree_sitter::Node> {
		if node.kind() == "dictionary" {
			return Some(node);
		}
		let mut cursor = node.walk();
		for child in node.children(&mut cursor) {
			if let Some(result) = find_dict(child) {
				return Some(result);
			}
		}
		None
	}

	let dict_node = find_dict(tree.root_node());

	if let Some(dict) = dict_node {
		let mut cursor = dict.walk();
		for child in dict.children(&mut cursor) {
			let child_text = if child.byte_range().end <= contents.len() {
				&contents[child.byte_range()]
			} else {
				"<out of bounds>"
			};

			if child.kind() == "ERROR" && child_text == "'desc'" {
				// Verify we can extract the needle
				let error_start = child.start_byte();
				if cursor_pos > error_start + 1 {
					let needle_bytes = &contents.as_bytes()[error_start + 1..cursor_pos];
					let needle = std::str::from_utf8(needle_bytes).unwrap();
					assert_eq!(needle, "desc", "Should extract 'desc' as the needle");
				}

				return;
			}
		}
	}

	panic!("Did not find expected ERROR node for broken syntax");
}

#[test]
fn test_broken_syntax_string_detection() {
	// Test case: dictionary with missing colon after key
	let contents = r#"
class TestModel(models.Model):
	_name = 'test.model'
	
	field_ids = fields.One2many('related.model', 'parent_id', string='Fields')
	
	def test_method(self):
		self.write({
			'field_ids': [(0, 0, {
				'name': 'Test',
				'description'
			})]
		})
"#;

	// Parse the Python code
	let mut parser = tree_sitter::Parser::new();
	parser.set_language(&tree_sitter_python::LANGUAGE.into()).unwrap();
	let tree = parser.parse(contents.as_bytes(), None).unwrap();

	// Find position after 'description' (missing colon)
	let cursor_pos = contents.find("'description'").unwrap() + "'description".len();

	// Find the node at cursor position
	let node_at_cursor = tree.root_node().descendant_for_byte_range(cursor_pos, cursor_pos);
	assert!(node_at_cursor.is_some(), "Should find node at cursor position");

	// We should be able to find a string node without a following colon
	let mut found_broken_string = false;
	if let Some(node) = node_at_cursor {
		// Look for a string node
		let string_node = match node.kind() {
			"string_content" | "string_end" => node.parent().filter(|&p| p.kind() == "string"),
			"string" | "ERROR" => Some(node),
			_ => node.parent().filter(|&parent| parent.kind() == "ERROR"),
		};

		if let Some(string_node) = string_node {
			// Check if this node looks like a string (starts with quote)
			let node_text = &contents[string_node.byte_range()];
			if node_text.starts_with("'") || node_text.starts_with("\"") {
				// Check if this string is followed by a colon
				if let Some(next_sibling) = string_node.next_sibling() {
					if next_sibling.kind() != ":" {
						found_broken_string = true;
					}
				} else {
					// No next sibling means it's incomplete
					found_broken_string = true;
				}
			}
		}
	}

	assert!(found_broken_string, "Should find broken syntax string node");
}

#[test]
fn test_proper_syntax_string_detection() {
	// Test case: properly formatted dictionary (should not be broken)
	let contents = r#"
class TestModel(models.Model):
	def test_method(self):
		self.write({
			'field_ids': [(0, 0, {
				'name': 'Test',
				'description': 'Proper syntax'
			})]
		})
"#;

	let mut parser = tree_sitter::Parser::new();
	parser.set_language(&tree_sitter_python::LANGUAGE.into()).unwrap();
	let tree = parser.parse(contents.as_bytes(), None).unwrap();

	// Find position in the middle of 'description' key
	let cursor_pos = contents.find("'description'").unwrap() + 5;

	// Find the node at cursor position
	let node_at_cursor = tree.root_node().descendant_for_byte_range(cursor_pos, cursor_pos);
	assert!(node_at_cursor.is_some(), "Should find node at cursor position");

	// Check that this is NOT broken syntax
	let mut has_proper_syntax = false;
	if let Some(node) = node_at_cursor {
		let string_node = if node.kind() == "string" {
			node
		} else if let Some(parent) = node.parent() {
			if parent.kind() == "string" { parent } else { node }
		} else {
			node
		};

		// Check if followed by colon
		if let Some(next) = string_node.next_sibling()
			&& next.kind() == ":"
		{
			has_proper_syntax = true;
		}
	}

	assert!(has_proper_syntax, "Should detect proper syntax (has colon)");
}

#[test]
fn test_gather_commandlist_with_broken_syntax() {
	use tree_sitter::QueryCursor;

	// Test case: commandlist with incomplete field at the end
	let contents = r#"
class TestModel(models.Model):
	_name = 'test.model'
	
	def test_method(self):
		records = self.mapped('partner_ids.name')
		values = self.mapped('field_ids.desc
"#;

	// Parse the Python code
	let mut parser = tree_sitter::Parser::new();
	parser.set_language(&tree_sitter_python::LANGUAGE.into()).unwrap();
	let tree = parser.parse(contents.as_bytes(), None).unwrap();

	// Test 1: Complete field access should work
	let _cursor_pos1 = contents.find("'partner_ids.name'").unwrap() + "'partner_ids.na".len();
	let root = tree.root_node();

	// Find the commandlist node for the first case
	let mut cursor = QueryCursor::new();
	let query = tree_sitter::Query::new(
		&tree_sitter_python::LANGUAGE.into(),
		r#"(call
			function: (attribute
				object: (_)
				attribute: (identifier) @method)
			arguments: (argument_list
				(string) @cmdlist)
			(#eq? @method "mapped"))"#,
	)
	.unwrap();

	let mut matches = cursor.matches(&query, root, contents.as_bytes());
	assert!(matches.next().is_some(), "Should find mapped calls");

	// Test 2: Incomplete field access (broken syntax)
	let cursor_pos2 = contents.find("'field_ids.desc").unwrap() + "'field_ids.desc".len();

	// The incomplete string at the end should cause a parse error
	// Check that the tree has errors
	assert!(
		tree.root_node().has_error(),
		"Tree should have parse errors due to incomplete string"
	);

	// Check that we can find a node at the position where completion would be triggered
	let node_at_pos = root.descendant_for_byte_range(cursor_pos2 - 1, cursor_pos2 - 1);
	assert!(node_at_pos.is_some(), "Should find node at cursor position");

	// The important thing is that the parser recognizes this as broken syntax
	// and that our completion logic can handle it
	// The exact tree structure may vary, but there should be an ERROR somewhere
	let mut has_error_ancestor = false;
	if let Some(mut node) = node_at_pos {
		loop {
			if node.kind() == "ERROR" {
				has_error_ancestor = true;
				break;
			}
			if let Some(parent) = node.parent() {
				node = parent;
			} else {
				break;
			}
		}
	}

	// Either the node itself is an ERROR or the tree has errors
	assert!(
		has_error_ancestor || tree.root_node().has_error(),
		"Should detect broken syntax through ERROR nodes or tree errors"
	);
}

#[test]
fn test_extract_comodel_name() {
	let mut parser = Parser::new();
	parser.set_language(&tree_sitter_python::LANGUAGE.into()).unwrap();

	let contents = r#"
		class What(models.Model):
			foo = fields.One2many('foob')
			bar = fields.One2many(comodel_name='foob')
	"#;
	let ast = parser.parse(contents.as_bytes(), None).unwrap();
	let query = PyCompletions::query();
	let mut cursor = QueryCursor::new();
	let mut matches = cursor.matches(query, ast.root_node(), contents.as_bytes());
	let mut matched = 0;
	while let Some(match_) = matches.next() {
		for cap in match_.captures {
			let Some(PyCompletions::Prop) = PyCompletions::from(cap.index) else {
				continue;
			};
			match &contents[cap.node.byte_range()] {
				"foo" => {
					let comodel = extract_comodel_name(match_.captures, contents).unwrap();
					assert_eq!(&contents[comodel.byte_range()], "'foob'");
					matched += 1;
				}
				"bar" => {
					let comodel = extract_comodel_name(match_.captures, contents).unwrap();
					assert_eq!(&contents[comodel.byte_range()], "'foob'");
					matched += 1;
				}
				_ => unreachable!(),
			}
		}
	}
	assert_eq!(matched, 2);
}