rubydex 0.4.1 → 0.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +11 -0
  3. data/THIRD_PARTY_LICENSES.html +14 -427
  4. data/ext/rubydex/declaration.c +2 -6
  5. data/ext/rubydex/definition.c +2 -3
  6. data/ext/rubydex/extconf.rb +1 -0
  7. data/ext/rubydex/graph.c +2 -1
  8. data/ext/rubydex/query.c +3 -1
  9. data/ext/rubydex/reference.c +3 -3
  10. data/ext/rubydex/utils.c +13 -0
  11. data/ext/rubydex/utils.h +5 -0
  12. data/lib/rubydex/cli/command/dead_code.rb +59 -0
  13. data/lib/rubydex/mcp_server/tools/codebase_stats_tool.rb +1 -1
  14. data/lib/rubydex/mcp_server/tools/find_constant_references_tool.rb +4 -4
  15. data/lib/rubydex/mcp_server/tools/find_dead_code_candidates_tool.rb +33 -0
  16. data/lib/rubydex/mcp_server/tools/get_declaration_tool.rb +2 -2
  17. data/lib/rubydex/mcp_server/tools/get_descendants_tool.rb +4 -4
  18. data/lib/rubydex/mcp_server/tools/get_file_declarations_tool.rb +2 -2
  19. data/lib/rubydex/mcp_server/tools/search_declarations_tool.rb +6 -6
  20. data/lib/rubydex/mcp_server.rb +24 -12
  21. data/lib/rubydex/version.rb +1 -1
  22. data/rust/Cargo.lock +17 -11
  23. data/rust/Cargo.toml +5 -1
  24. data/rust/rubydex/Cargo.toml +3 -3
  25. data/rust/rubydex/src/compile_assertions.rs +2 -0
  26. data/rust/rubydex/src/config.rs +1 -1
  27. data/rust/rubydex/src/indexing/rbs_indexer.rs +4 -4
  28. data/rust/rubydex/src/indexing/ruby_indexer.rs +26 -18
  29. data/rust/rubydex/src/indexing/ruby_indexer_tests.rs +42 -2
  30. data/rust/rubydex/src/indexing.rs +6 -6
  31. data/rust/rubydex/src/listing.rs +12 -12
  32. data/rust/rubydex/src/model/built_in.rs +1 -1
  33. data/rust/rubydex/src/model/comment.rs +4 -4
  34. data/rust/rubydex/src/model/declaration.rs +25 -17
  35. data/rust/rubydex/src/model/document.rs +11 -11
  36. data/rust/rubydex/src/model/graph.rs +3 -3
  37. data/rust/rubydex/src/offset.rs +1 -13
  38. data/rust/rubydex/src/operation/ruby_builder.rs +29 -19
  39. data/rust/rubydex/src/query.rs +3 -2
  40. data/rust/rubydex/src/test_utils/graph_test.rs +2 -2
  41. data/rust/rubydex/src/test_utils/local_graph_test.rs +13 -6
  42. data/rust/rubydex-sys/Cargo.toml +7 -4
  43. data/rust/rubydex-sys/build.rs +1 -2
  44. data/rust/rubydex-sys/src/cypher_api.rs +8 -8
  45. data/rust/rubydex-sys/src/declaration_api.rs +11 -19
  46. data/rust/rubydex-sys/src/definition_api.rs +10 -17
  47. data/rust/rubydex-sys/src/diagnostic_api.rs +5 -7
  48. data/rust/rubydex-sys/src/graph_api.rs +96 -49
  49. data/rust/rubydex-sys/src/name_api.rs +193 -58
  50. data/rust/rubydex-sys/src/reference_api.rs +7 -10
  51. data/rust/rubydex-sys/src/utils.rs +49 -0
  52. metadata +191 -191
@@ -44,14 +44,14 @@ impl GraphTest {
44
44
  /// Indexes a Ruby source
45
45
  pub fn index_uri(&mut self, uri: &str, source: &str) {
46
46
  let source = normalize_indentation(source);
47
- let local_graph = indexing::build_local_graph(uri.to_string(), &source, &LanguageId::Ruby, self.backend);
47
+ let local_graph = indexing::build_local_graph(uri.into(), &source, &LanguageId::Ruby, self.backend);
48
48
  self.graph.consume_document_changes(local_graph);
49
49
  }
50
50
 
51
51
  /// Indexes an RBS source
52
52
  pub fn index_rbs_uri(&mut self, uri: &str, source: &str) {
53
53
  let source = normalize_indentation(source);
54
- indexing::index_source(&mut self.graph, uri, &source, &LanguageId::Rbs);
54
+ indexing::index_source(&mut self.graph, uri.into(), &source, &LanguageId::Rbs);
55
55
  }
56
56
 
57
57
  pub fn delete_uri(&mut self, uri: &str) {
@@ -24,22 +24,29 @@ impl LocalGraphTest {
24
24
 
25
25
  #[must_use]
26
26
  pub fn new_with_backend(uri: &str, source: &str, backend: IndexerBackend) -> Self {
27
- let uri = uri.to_string();
28
27
  let source = normalize_indentation(source);
29
- let graph = build_local_graph(uri.clone(), &source, &LanguageId::Ruby, backend);
30
- Self { uri, source, graph }
28
+ let graph = build_local_graph(uri.into(), &source, &LanguageId::Ruby, backend);
29
+
30
+ Self {
31
+ uri: uri.to_string(),
32
+ source,
33
+ graph,
34
+ }
31
35
  }
32
36
 
33
37
  #[must_use]
34
38
  pub fn new_rbs(uri: &str, source: &str) -> Self {
35
- let uri = uri.to_string();
36
39
  let source = normalize_indentation(source);
37
40
 
38
- let mut indexer = RBSIndexer::new(uri.clone(), &source);
41
+ let mut indexer = RBSIndexer::new(uri.into(), &source);
39
42
  indexer.index();
40
43
  let graph = indexer.local_graph();
41
44
 
42
- Self { uri, source, graph }
45
+ Self {
46
+ uri: uri.to_string(),
47
+ source,
48
+ graph,
49
+ }
43
50
  }
44
51
 
45
52
  #[must_use]
@@ -1,8 +1,8 @@
1
1
  [package]
2
2
  name = "rubydex-sys"
3
- version = "0.2.6"
3
+ version.workspace = true
4
4
  edition = "2024"
5
- rust-version = "1.89.0"
5
+ rust-version.workspace = true
6
6
  license = "MIT"
7
7
  description = "C FFI bindings for the Rubydex Ruby code indexing engine."
8
8
  homepage = "https://github.com/Shopify/rubydex"
@@ -15,13 +15,16 @@ categories = ["development-tools", "external-ffi-bindings"]
15
15
  crate-type = ["cdylib", "staticlib"]
16
16
 
17
17
  [dependencies]
18
- rubydex = { version = "0.2.6", path = "../rubydex" }
18
+ rubydex = { version = "=0.4.4", path = "../rubydex" }
19
19
  libc = "0.2.174"
20
20
  url = "2.5.4"
21
21
  line-index = "0.1.2"
22
22
 
23
+ [features]
24
+ generate_bindings = ["dep:cbindgen"]
25
+
23
26
  [build-dependencies]
24
- cbindgen = "0.29"
27
+ cbindgen = { version = "0.29", optional = true }
25
28
 
26
29
  [lints]
27
30
  workspace = true
@@ -1,6 +1,5 @@
1
- extern crate cbindgen;
2
-
3
1
  fn main() {
2
+ #[cfg(feature = "generate_bindings")]
4
3
  cbindgen::generate(".")
5
4
  .expect("Unable to generate bindings")
6
5
  .write_to_file("rustbindings.h");
@@ -5,11 +5,13 @@ use crate::declaration_api::CDeclaration;
5
5
  use crate::definition_api::map_definition_to_kind;
6
6
  use crate::graph_api::{GraphPointer, with_graph};
7
7
  use crate::utils;
8
+ use crate::utils::OwnedString;
8
9
  use libc::{c_char, c_void};
9
10
  use rubydex::model::graph::Graph;
10
11
  use rubydex::query::cypher::schema::NodeRef;
11
12
  use rubydex::query::cypher::{self, CypherValue, OutputFormat};
12
13
  use std::ffi::CString;
14
+ use std::mem::ManuallyDrop;
13
15
  use std::ptr;
14
16
 
15
17
  /// Which layer of the Cypher pipeline rejected a call, so callers can raise a matching error class.
@@ -201,14 +203,13 @@ pub struct CMap {
201
203
  /// Payload of a `CCell`. The active field is selected by the cell's `tag`; reading any other field
202
204
  /// is undefined. `Null` carries no payload.
203
205
  #[repr(C)]
204
- #[derive(Clone, Copy)]
205
206
  pub union CCellPayload {
206
207
  /// `Bool`.
207
208
  pub bool_val: bool,
208
209
  /// `Int`.
209
210
  pub int_val: i64,
210
- /// `Str`: owned C string (freed by `rdx_rows_iter_free`).
211
- pub str_val: *const c_char,
211
+ /// `Str`: owned string (freed by `rdx_rows_iter_free`). A union never drops its fields, so `free_cell` drops it.
212
+ pub str_val: ManuallyDrop<OwnedString>,
212
213
  /// `Node`.
213
214
  pub node: CNode,
214
215
  /// `List`.
@@ -306,7 +307,7 @@ fn build_cell(graph: &Graph, value: &CypherValue) -> Result<CCell, String> {
306
307
  CypherValue::Str(s) => Ok(CCell::new(
307
308
  CCellTag::Str,
308
309
  CCellPayload {
309
- str_val: utils::cstring_raw(s),
310
+ str_val: ManuallyDrop::new(OwnedString::new(s)),
310
311
  },
311
312
  )),
312
313
  CypherValue::List(items) => {
@@ -715,10 +716,9 @@ unsafe fn free_cell(cell: &CCell) {
715
716
  match cell.tag {
716
717
  // SAFETY: the tag selects the active union field.
717
718
  CCellTag::Str => {
718
- let str_val = unsafe { cell.payload.str_val };
719
- if !str_val.is_null() {
720
- let _ = unsafe { CString::from_raw(str_val.cast_mut()) };
721
- }
719
+ // The cell is not used after this, so moving the string out of it is sound
720
+ let string = unsafe { ptr::read(&raw const cell.payload.str_val) };
721
+ drop(ManuallyDrop::into_inner(string));
722
722
  }
723
723
  // SAFETY: the tag selects the active union field.
724
724
  CCellTag::List => {
@@ -2,13 +2,13 @@
2
2
 
3
3
  use libc::c_char;
4
4
  use rubydex::model::declaration::{Ancestor, Declaration, Namespace};
5
- use std::ffi::CString;
6
5
  use std::ptr;
7
6
 
8
7
  use crate::definition_api::{DefinitionsIter, rdx_definitions_iter_new_from_ids};
9
8
  use crate::graph_api::{GraphPointer, with_graph};
10
9
  use crate::reference_api::{CConstantReference, CMethodReference, ConstantReferencesIter, MethodReferencesIter};
11
10
  use crate::utils;
11
+ use crate::utils::OwnedString;
12
12
  use rubydex::model::ids::{DeclarationId, StringId, declaration_id_from_lookup_name};
13
13
 
14
14
  #[repr(C)]
@@ -119,24 +119,20 @@ pub unsafe extern "C" fn rdx_graph_declarations_iter_free(iter: *mut Declaration
119
119
  unsafe { DeclarationsIter::free(iter) }
120
120
  }
121
121
 
122
- /// Returns the UTF-8 name string for a declaration id.
123
- /// Caller must free with `free_c_string`.
122
+ /// Returns the UTF-8 name string for a declaration id, or a null string if the declaration cannot be found.
123
+ /// Caller must free with `free_owned_string`.
124
124
  ///
125
125
  /// # Safety
126
126
  ///
127
127
  /// Assumes pointer is valid.
128
- ///
129
- /// # Panics
130
- ///
131
- /// This function will panic if the name pointer is invalid.
132
128
  #[unsafe(no_mangle)]
133
- pub unsafe extern "C" fn rdx_declaration_name(pointer: GraphPointer, name_id: u64) -> *const c_char {
129
+ pub unsafe extern "C" fn rdx_declaration_name(pointer: GraphPointer, name_id: u64) -> OwnedString {
134
130
  with_graph(pointer, |graph| {
135
131
  let name_id = DeclarationId::new(name_id);
136
132
  if let Some(decl) = graph.declarations().get(&name_id) {
137
- CString::new(decl.name()).unwrap().into_raw().cast_const()
133
+ OwnedString::new(decl.name())
138
134
  } else {
139
- ptr::null()
135
+ OwnedString::null()
140
136
  }
141
137
  })
142
138
  }
@@ -213,24 +209,20 @@ pub unsafe extern "C" fn rdx_declaration_find_member(
213
209
  })
214
210
  }
215
211
 
216
- /// Returns the UTF-8 unqualified name string for a declaration id.
217
- /// Caller must free with `free_c_string`.
212
+ /// Returns the UTF-8 unqualified name string for a declaration id, or a null string if the declaration cannot be
213
+ /// found. Caller must free with `free_owned_string`.
218
214
  ///
219
215
  /// # Safety
220
216
  ///
221
217
  /// Assumes pointer is valid.
222
- ///
223
- /// # Panics
224
- ///
225
- /// This function will panic if the name pointer is invalid.
226
218
  #[unsafe(no_mangle)]
227
- pub unsafe extern "C" fn rdx_declaration_unqualified_name(pointer: GraphPointer, name_id: u64) -> *const c_char {
219
+ pub unsafe extern "C" fn rdx_declaration_unqualified_name(pointer: GraphPointer, name_id: u64) -> OwnedString {
228
220
  with_graph(pointer, |graph| {
229
221
  let name_id = DeclarationId::new(name_id);
230
222
  if let Some(decl) = graph.declarations().get(&name_id) {
231
- CString::new(decl.unqualified_name()).unwrap().into_raw().cast_const()
223
+ OwnedString::new(&decl.unqualified_name())
232
224
  } else {
233
- ptr::null()
225
+ OwnedString::null()
234
226
  }
235
227
  })
236
228
  }
@@ -4,6 +4,7 @@ use crate::declaration_api::CDeclaration;
4
4
  use crate::graph_api::{GraphPointer, with_graph};
5
5
  use crate::location_api::{Location, create_location_for_uri_and_offset};
6
6
  use crate::reference_api::CConstantReference;
7
+ use crate::utils::OwnedString;
7
8
  use libc::c_char;
8
9
  use rubydex::model::definitions::{Definition, Mixin};
9
10
  use rubydex::model::graph::Graph;
@@ -84,30 +85,26 @@ pub unsafe extern "C" fn rdx_definition_kind(pointer: GraphPointer, definition_i
84
85
  })
85
86
  }
86
87
 
87
- /// Returns the UTF-8 unqualified name string for a definition id.
88
- /// Caller must free with `free_c_string`.
88
+ /// Returns the UTF-8 unqualified name string for a definition id, or a null string if the definition cannot be found.
89
+ /// Caller must free with `free_owned_string`.
89
90
  ///
90
91
  /// # Safety
91
92
  ///
92
93
  /// Assumes pointer is valid.
93
- ///
94
- /// # Panics
95
- ///
96
- /// This function will panic if the definition cannot be found.
97
94
  #[unsafe(no_mangle)]
98
- pub unsafe extern "C" fn rdx_definition_name(pointer: GraphPointer, definition_id: u64) -> *const c_char {
95
+ pub unsafe extern "C" fn rdx_definition_name(pointer: GraphPointer, definition_id: u64) -> OwnedString {
99
96
  with_graph(pointer, |graph| {
100
97
  let def_id = DefinitionId::new(definition_id);
101
98
  if let Some(defn) = graph.definitions().get(&def_id) {
102
99
  let string_id = graph.definition_string_id(defn);
103
100
 
104
101
  if let Some(name) = graph.strings().get(&string_id) {
105
- CString::new(name.as_str()).unwrap().into_raw().cast_const()
102
+ OwnedString::new(name.as_str())
106
103
  } else {
107
- ptr::null()
104
+ OwnedString::null()
108
105
  }
109
106
  } else {
110
- ptr::null()
107
+ OwnedString::null()
111
108
  }
112
109
  })
113
110
  }
@@ -212,7 +209,7 @@ pub unsafe extern "C" fn rdx_definitions_iter_free(iter: *mut DefinitionsIter) {
212
209
  /// C-compatible struct representing a single comment with its string and location
213
210
  #[repr(C)]
214
211
  pub struct CommentEntry {
215
- pub string: *const c_char,
212
+ pub string: OwnedString,
216
213
  pub location: *mut Location,
217
214
  }
218
215
 
@@ -248,7 +245,7 @@ pub unsafe extern "C" fn rdx_definition_comments(pointer: GraphPointer, definiti
248
245
  .comments()
249
246
  .iter()
250
247
  .map(|c| CommentEntry {
251
- string: CString::new(c.string().as_str()).unwrap().into_raw().cast_const(),
248
+ string: OwnedString::new(c.string()),
252
249
  location: create_location_for_uri_and_offset(graph, document, c.offset()),
253
250
  })
254
251
  .collect::<Vec<CommentEntry>>()
@@ -282,17 +279,13 @@ pub unsafe extern "C" fn rdx_definition_comments_free(ptr: *mut CommentArray) {
282
279
  let mut boxed_slice: Box<[CommentEntry]> = unsafe { Box::from_raw(slice_ptr) };
283
280
 
284
281
  for item in &mut boxed_slice {
285
- if !item.string.is_null() {
286
- // Free the CString allocated for the comment string
287
- let _ = unsafe { CString::from_raw(item.string.cast_mut()) };
288
- }
289
282
  if !item.location.is_null() {
290
283
  unsafe { crate::location_api::rdx_location_free(item.location) };
291
284
  item.location = ptr::null_mut();
292
285
  }
293
286
  }
294
287
 
295
- // boxed_slice is dropped here, freeing the items buffer
288
+ // boxed_slice is dropped here, freeing the items buffer and each item's string
296
289
  }
297
290
  // arr is dropped here
298
291
  }
@@ -2,9 +2,10 @@
2
2
 
3
3
  use crate::graph_api::{GraphPointer, with_graph};
4
4
  use crate::location_api::{Location, create_location_for_uri_and_offset};
5
+ use crate::utils::OwnedString;
5
6
  use libc::c_char;
6
7
  use rubydex::diagnostic::{Rule, Severity};
7
- use std::{ffi::CString, mem, ptr};
8
+ use std::{mem, ptr};
8
9
 
9
10
  /// C-compatible enum representing diagnostic severity levels.
10
11
  #[repr(C)]
@@ -49,7 +50,7 @@ impl From<Rule> for CRule {
49
50
  #[repr(C)]
50
51
  pub struct DiagnosticEntry {
51
52
  pub rule: CRule,
52
- pub message: *const c_char,
53
+ pub message: OwnedString,
53
54
  pub location: *mut Location,
54
55
  }
55
56
 
@@ -91,7 +92,7 @@ pub unsafe extern "C" fn rdx_graph_diagnostics(pointer: GraphPointer) -> *mut Di
91
92
 
92
93
  DiagnosticEntry {
93
94
  rule: CRule::from(*diagnostic.rule()),
94
- message: CString::new(diagnostic.message()).unwrap().into_raw().cast_const(),
95
+ message: OwnedString::new(diagnostic.message()),
95
96
  location,
96
97
  }
97
98
  })
@@ -119,15 +120,12 @@ pub unsafe extern "C" fn rdx_diagnostics_free(ptr: *mut DiagnosticArray) {
119
120
  let mut boxed_slice: Box<[DiagnosticEntry]> = unsafe { Box::from_raw(slice_ptr) };
120
121
 
121
122
  for entry in &mut *boxed_slice {
122
- if !entry.message.is_null() {
123
- let _ = unsafe { CString::from_raw(entry.message.cast_mut()) };
124
- }
125
123
  if !entry.location.is_null() {
126
124
  unsafe { crate::location_api::rdx_location_free(entry.location) };
127
125
  entry.location = ptr::null_mut();
128
126
  }
129
127
  }
130
- // boxed_slice drops here, releasing the buffer
128
+ // boxed_slice drops here, releasing the buffer and each entry's message
131
129
  }
132
130
  // array drops here
133
131
  }
@@ -173,11 +173,11 @@ pub unsafe extern "C" fn rdx_graph_resolve_constant(
173
173
  let nesting: Vec<String> = unsafe { utils::convert_double_pointer_to_vec(nesting, count).unwrap() };
174
174
  let const_name: String = unsafe { utils::convert_char_ptr_to_string(const_name).unwrap() };
175
175
 
176
- let Some((name_id, names_to_untrack)) = name_api::nesting_stack_to_name_id(graph, &const_name, nesting) else {
176
+ let Some(tracked_name) = name_api::name_from_nesting_names(graph, &const_name, nesting) else {
177
177
  return ptr::null();
178
178
  };
179
179
 
180
- resolve_constant_name(graph, name_id, names_to_untrack)
180
+ resolve_constant_name(tracked_name)
181
181
  })
182
182
  }
183
183
 
@@ -225,15 +225,14 @@ pub unsafe extern "C" fn rdx_graph_resolve_constant_from_definition(
225
225
  }
226
226
  };
227
227
 
228
- let Some((name_id, names_to_untrack)) = name_api::name_in_nesting_to_name_id(graph, &const_name, Some(nesting))
229
- else {
228
+ let Some(tracked_name) = name_api::name_from_lexical_nesting(graph, &const_name, Some(nesting)) else {
230
229
  return CDefinitionConstantResolutionResult {
231
230
  status: CDefinitionConstantResolution::NotFound,
232
231
  declaration: ptr::null(),
233
232
  };
234
233
  };
235
234
 
236
- let declaration = resolve_constant_name(graph, name_id, names_to_untrack);
235
+ let declaration = resolve_constant_name(tracked_name);
237
236
  let status = if declaration.is_null() {
238
237
  CDefinitionConstantResolution::NotFound
239
238
  } else {
@@ -260,18 +259,13 @@ fn class_or_module_definition_name_id(
260
259
  }
261
260
  }
262
261
 
263
- fn resolve_constant_name(graph: &mut Graph, name_id: NameId, names_to_untrack: Vec<NameId>) -> *const CDeclaration {
264
- let declaration_id = Resolver::new(graph).resolve_constant(name_id);
265
- let declaration = declaration_id.map_or(ptr::null(), |id| {
266
- let declaration = graph.declarations().get(&id).unwrap();
262
+ fn resolve_constant_name(mut tracked_name: name_api::TrackedName<'_>) -> *const CDeclaration {
263
+ let name_id = tracked_name.name_id();
264
+ let declaration_id = Resolver::new(tracked_name.graph_mut()).resolve_constant(name_id);
265
+ declaration_id.map_or(ptr::null(), |id| {
266
+ let declaration = tracked_name.graph().declarations().get(&id).unwrap();
267
267
  Box::into_raw(Box::new(CDeclaration::from_declaration(id, declaration))).cast_const()
268
- });
269
-
270
- for name_id in names_to_untrack {
271
- graph.untrack_name(name_id);
272
- }
273
-
274
- declaration
268
+ })
275
269
  }
276
270
 
277
271
  /// Adds glob patterns to exclude from file discovery during indexing.
@@ -745,7 +739,7 @@ pub unsafe extern "C" fn rdx_index_source(
745
739
  };
746
740
 
747
741
  with_mut_graph(pointer, |graph| {
748
- indexing::index_source(graph, &uri_str, source_str, &language);
742
+ indexing::index_source(graph, uri_str.into(), source_str, &language);
749
743
  IndexSourceResult::Success
750
744
  })
751
745
  }
@@ -815,19 +809,19 @@ pub unsafe extern "C" fn rdx_completion_candidates_free(ptr: *mut CompletionCand
815
809
  }
816
810
  }
817
811
 
818
- /// Converts the nesting stack into a `NameId`.
819
- /// The last element of the nesting stack is treated as the self type; if the stack is empty, `"Object"` is used.
812
+ /// Converts the nesting names into a tracked name.
813
+ /// The last nesting name is treated as the self type; if the array is empty, `"Object"` is used.
820
814
  ///
821
- /// Returns `Err` if the nesting array contains invalid UTF-8.
815
+ /// Returns `None` if the nesting array contains invalid UTF-8.
822
816
  ///
823
817
  /// # Safety
824
818
  ///
825
819
  /// `nesting` must point to `nesting_count` valid, null-terminated UTF-8 strings.
826
- unsafe fn completion_nesting_name_id(
820
+ unsafe fn completion_nesting_name(
827
821
  graph: &mut Graph,
828
822
  nesting: *const *const c_char,
829
823
  nesting_count: usize,
830
- ) -> Option<(NameId, Vec<NameId>)> {
824
+ ) -> Option<name_api::TrackedName<'_>> {
831
825
  let mut nesting: Vec<String> = unsafe { utils::convert_double_pointer_to_vec(nesting, nesting_count).ok()? };
832
826
 
833
827
  // When serving completion in a bare script, the self (top level) context is Object
@@ -837,7 +831,7 @@ unsafe fn completion_nesting_name_id(
837
831
  nesting.pop().unwrap()
838
832
  };
839
833
 
840
- name_api::nesting_stack_to_name_id(graph, &self_name, nesting)
834
+ name_api::name_from_nesting_names(graph, &self_name, nesting)
841
835
  }
842
836
 
843
837
  /// The result of a completion operation, carrying either a candidate array or an error message.
@@ -866,19 +860,10 @@ impl CompletionResult {
866
860
  }
867
861
 
868
862
  /// Runs completion for the given receiver and returns a structured result with candidates or an error message
869
- fn run_and_finalize_completion(
870
- graph: &mut Graph,
871
- receiver: CompletionReceiver,
872
- names_to_untrack: Vec<NameId>,
873
- ) -> CompletionResult {
863
+ fn run_and_finalize_completion(graph: &Graph, receiver: CompletionReceiver) -> CompletionResult {
874
864
  let candidates = match query::completion_candidates(graph, CompletionContext::new(receiver)) {
875
865
  Ok(candidates) => candidates,
876
- Err(e) => {
877
- for name_id in names_to_untrack {
878
- graph.untrack_name(name_id);
879
- }
880
- return CompletionResult::error(&e.to_string());
881
- }
866
+ Err(e) => return CompletionResult::error(&e.to_string()),
882
867
  };
883
868
 
884
869
  let entries: Vec<CCompletionCandidate> = candidates
@@ -926,10 +911,6 @@ fn run_and_finalize_completion(
926
911
  })
927
912
  .collect();
928
913
 
929
- for name_id in names_to_untrack {
930
- graph.untrack_name(name_id);
931
- }
932
-
933
914
  CompletionResult::success(CompletionCandidateArray::from_vec(entries))
934
915
  }
935
916
 
@@ -950,20 +931,19 @@ pub unsafe extern "C" fn rdx_graph_complete_expression(
950
931
  self_receiver: *const c_char,
951
932
  ) -> CompletionResult {
952
933
  with_mut_graph(pointer, |graph| {
953
- let Some((name_id, names_to_untrack)) = (unsafe { completion_nesting_name_id(graph, nesting, nesting_count) })
954
- else {
934
+ let Some(tracked_name) = (unsafe { completion_nesting_name(graph, nesting, nesting_count) }) else {
955
935
  return CompletionResult::success(ptr::null_mut());
956
936
  };
937
+ let name_id = tracked_name.name_id();
957
938
 
958
939
  let self_decl_id = unsafe { decl_id_from_char_ptr(self_receiver) };
959
940
 
960
941
  run_and_finalize_completion(
961
- graph,
942
+ tracked_name.graph(),
962
943
  CompletionReceiver::Expression {
963
944
  self_decl_id,
964
945
  nesting_name_id: name_id,
965
946
  },
966
- names_to_untrack,
967
947
  )
968
948
  })
969
949
  }
@@ -997,7 +977,6 @@ pub unsafe extern "C" fn rdx_graph_complete_namespace_access(
997
977
  self_decl_id,
998
978
  namespace_decl_id: declaration_id_from_lookup_name(&name_str),
999
979
  },
1000
- Vec::new(),
1001
980
  )
1002
981
  })
1003
982
  }
@@ -1031,7 +1010,6 @@ pub unsafe extern "C" fn rdx_graph_complete_method_call(
1031
1010
  self_decl_id,
1032
1011
  receiver_decl_id: declaration_id_from_lookup_name(&name_str),
1033
1012
  },
1034
- Vec::new(),
1035
1013
  )
1036
1014
  })
1037
1015
  }
@@ -1060,22 +1038,20 @@ pub unsafe extern "C" fn rdx_graph_complete_method_argument(
1060
1038
  };
1061
1039
 
1062
1040
  with_mut_graph(pointer, |graph| {
1063
- let Some((nesting_name_id, names_to_untrack)) =
1064
- (unsafe { completion_nesting_name_id(graph, nesting, nesting_count) })
1065
- else {
1041
+ let Some(tracked_name) = (unsafe { completion_nesting_name(graph, nesting, nesting_count) }) else {
1066
1042
  return CompletionResult::success(ptr::null_mut());
1067
1043
  };
1044
+ let nesting_name_id = tracked_name.name_id();
1068
1045
 
1069
1046
  let self_decl_id = unsafe { decl_id_from_char_ptr(self_receiver) };
1070
1047
 
1071
1048
  run_and_finalize_completion(
1072
- graph,
1049
+ tracked_name.graph(),
1073
1050
  CompletionReceiver::MethodArgument {
1074
1051
  self_decl_id,
1075
1052
  nesting_name_id,
1076
1053
  method_decl_id: declaration_id_from_lookup_name(&name_str),
1077
1054
  },
1078
- names_to_untrack,
1079
1055
  )
1080
1056
  })
1081
1057
  }
@@ -1196,6 +1172,7 @@ pub unsafe extern "C" fn rdx_keyword_free(ptr: *const CKeyword) {
1196
1172
 
1197
1173
  #[cfg(test)]
1198
1174
  mod tests {
1175
+ use crate::declaration_api;
1199
1176
  use rubydex::indexing::ruby_indexer::RubyIndexer;
1200
1177
 
1201
1178
  use super::*;
@@ -1246,7 +1223,9 @@ mod tests {
1246
1223
  nesting_ptrs.as_ptr(),
1247
1224
  nesting_ptrs.len(),
1248
1225
  );
1226
+ assert!(!decl.is_null());
1249
1227
  assert_eq!((*decl).id(), *DeclarationId::from("Foo::BAR"));
1228
+ declaration_api::free_c_declaration(decl);
1250
1229
  };
1251
1230
 
1252
1231
  let graph = unsafe { Box::from_raw(graph_ptr.cast::<RwLock<Graph>>()) };
@@ -1268,4 +1247,72 @@ mod tests {
1268
1247
  .ref_count()
1269
1248
  );
1270
1249
  }
1250
+
1251
+ #[test]
1252
+ fn names_are_untracked_after_completion_error() {
1253
+ let mut indexer = RubyIndexer::new(
1254
+ "file:///foo.rb".into(),
1255
+ "
1256
+ class Foo
1257
+ end
1258
+ ",
1259
+ );
1260
+ indexer.index();
1261
+
1262
+ let mut graph = Graph::new();
1263
+ graph.consume_document_changes(indexer.local_graph());
1264
+ let mut resolver = Resolver::new(&mut graph);
1265
+ resolver.resolve();
1266
+
1267
+ let (foo_name_id, foo_string_id, name_ref_count, string_ref_count) = graph
1268
+ .names()
1269
+ .iter()
1270
+ .find_map(|(name_id, name)| {
1271
+ let string_id = *name.str();
1272
+ if graph.strings().get(&string_id).unwrap().as_str() == "Foo"
1273
+ && name.parent_scope().is_none()
1274
+ && name.nesting().is_none()
1275
+ {
1276
+ Some((
1277
+ *name_id,
1278
+ string_id,
1279
+ name.ref_count(),
1280
+ graph.strings().get(&string_id).unwrap().ref_count(),
1281
+ ))
1282
+ } else {
1283
+ None
1284
+ }
1285
+ })
1286
+ .unwrap();
1287
+ let name_count = graph.names().len();
1288
+ let string_count = graph.strings().len();
1289
+
1290
+ let graph_ptr = Box::into_raw(Box::new(RwLock::new(graph))) as GraphPointer;
1291
+ let nesting_strings = [CString::new("Foo").unwrap()];
1292
+ let nesting_ptrs: Vec<*const c_char> = nesting_strings.iter().map(|s| s.as_ptr()).collect();
1293
+ let self_receiver = CString::new("Nonexistent").unwrap();
1294
+
1295
+ let result = unsafe {
1296
+ rdx_graph_complete_expression(
1297
+ graph_ptr,
1298
+ nesting_ptrs.as_ptr(),
1299
+ nesting_ptrs.len(),
1300
+ self_receiver.as_ptr(),
1301
+ )
1302
+ };
1303
+ assert!(result.candidates.is_null());
1304
+ assert!(!result.error.is_null());
1305
+ utils::free_c_string(result.error);
1306
+
1307
+ let graph = unsafe { Box::from_raw(graph_ptr.cast::<RwLock<Graph>>()) };
1308
+ let graph = graph.read().unwrap();
1309
+
1310
+ assert_eq!(name_count, graph.names().len());
1311
+ assert_eq!(string_count, graph.strings().len());
1312
+ assert_eq!(name_ref_count, graph.names().get(&foo_name_id).unwrap().ref_count());
1313
+ assert_eq!(
1314
+ string_ref_count,
1315
+ graph.strings().get(&foo_string_id).unwrap().ref_count()
1316
+ );
1317
+ }
1271
1318
  }