-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraph_api.rs
More file actions
668 lines (585 loc) · 21.3 KB
/
graph_api.rs
File metadata and controls
668 lines (585 loc) · 21.3 KB
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
//! This file provides the C API for the Graph object
use crate::declaration_api::CDeclaration;
use crate::declaration_api::DeclarationsIter;
use crate::reference_api::{CReference, ReferenceKind, ReferencesIter};
use crate::{name_api, utils};
use libc::{c_char, c_void};
use rubydex::indexing::LanguageId;
use rubydex::model::encoding::Encoding;
use rubydex::model::graph::Graph;
use rubydex::model::ids::DeclarationId;
use rubydex::resolution::Resolver;
use rubydex::{indexing, integrity, listing, query};
use std::ffi::CString;
use std::path::PathBuf;
use std::{mem, ptr};
pub type GraphPointer = *mut c_void;
/// Creates a new graph within a mutex. This is meant to be used when creating new Graph objects in Ruby
#[unsafe(no_mangle)]
pub extern "C" fn rdx_graph_new() -> GraphPointer {
Box::into_raw(Box::new(Graph::new())) as GraphPointer
}
/// Frees a Graph through its pointer
#[unsafe(no_mangle)]
pub extern "C" fn rdx_graph_free(pointer: GraphPointer) {
unsafe {
let _ = Box::from_raw(pointer.cast::<Graph>());
}
}
pub fn with_graph<F, T>(pointer: GraphPointer, action: F) -> T
where
F: FnOnce(&Graph) -> T,
{
let mut graph = unsafe { Box::from_raw(pointer.cast::<Graph>()) };
let result = action(&mut graph);
mem::forget(graph);
result
}
fn with_mut_graph<F, T>(pointer: GraphPointer, action: F) -> T
where
F: FnOnce(&mut Graph) -> T,
{
let mut graph = unsafe { Box::from_raw(pointer.cast::<Graph>()) };
let result = action(&mut graph);
mem::forget(graph);
result
}
/// Searches the graph based on query and returns all declarations that match
///
/// # Safety
///
/// Expects both the graph and the query pointers to be valid
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdx_graph_declarations_search(
pointer: GraphPointer,
c_query: *const c_char,
) -> *mut DeclarationsIter {
let Ok(query) = (unsafe { utils::convert_char_ptr_to_string(c_query) }) else {
return ptr::null_mut();
};
let entries = with_graph(pointer, |graph| {
query::declaration_search(graph, &query)
.into_iter()
.filter_map(|id| {
let decl = graph.declarations().get(&id)?;
Some(CDeclaration::from_declaration(id, decl))
})
.collect::<Vec<CDeclaration>>()
.into_boxed_slice()
});
Box::into_raw(Box::new(DeclarationsIter::new(entries)))
}
/// # Panics
///
/// Will panic if the nesting cannot be transformed into a vector of strings
///
/// # Safety
///
/// Assumes that the `const_name` and `nesting` pointer are valid
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdx_graph_resolve_constant(
pointer: GraphPointer,
const_name: *const c_char,
nesting: *const *const c_char,
count: usize,
) -> *const CDeclaration {
with_mut_graph(pointer, |graph| {
let nesting: Vec<String> = unsafe { utils::convert_double_pointer_to_vec(nesting, count).unwrap() };
let const_name: String = unsafe { utils::convert_char_ptr_to_string(const_name).unwrap() };
let (name_id, names_to_untrack) = name_api::nesting_stack_to_name_id(graph, &const_name, nesting);
let mut resolver = Resolver::new(graph);
let declaration = match resolver.resolve_constant(name_id) {
Some(id) => {
let decl = graph.declarations().get(&id).unwrap();
Box::into_raw(Box::new(CDeclaration::from_declaration(id, decl))).cast_const()
}
None => ptr::null(),
};
for name_id in names_to_untrack {
graph.untrack_name(name_id);
}
declaration
})
}
/// Indexes all given file paths in parallel using the provided Graph pointer.
/// Returns an array of error message strings and writes the count to `out_error_count`.
/// Returns NULL if there are no errors. Caller must free with `free_c_string_array`.
///
/// # Panics
///
/// Will panic if the given array of C string file paths cannot be converted to a Vec<String>
///
/// # Safety
///
/// This function is unsafe because it dereferences raw pointers coming from C. The caller has to ensure that the Ruby
/// VM will not free the pointers related to the string array while they are in use by Rust
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdx_index_all(
pointer: GraphPointer,
file_paths: *const *const c_char,
count: usize,
out_error_count: *mut usize,
) -> *const *const c_char {
let file_paths: Vec<String> = unsafe { utils::convert_double_pointer_to_vec(file_paths, count).unwrap() };
let (file_paths, listing_errors) = listing::collect_file_paths(file_paths);
with_mut_graph(pointer, |graph| {
let indexing_errors = indexing::index_files(graph, file_paths);
let all_errors: Vec<String> = listing_errors
.into_iter()
.chain(indexing_errors)
.map(|e| e.to_string())
.collect();
if all_errors.is_empty() {
unsafe { *out_error_count = 0 };
return ptr::null();
}
let c_strings: Vec<*const c_char> = all_errors
.into_iter()
.filter_map(|string| {
CString::new(string)
.ok()
.map(|c_string| c_string.into_raw().cast_const())
})
.collect();
unsafe { *out_error_count = c_strings.len() };
let boxed = c_strings.into_boxed_slice();
Box::into_raw(boxed).cast::<*const c_char>()
})
}
/// Deletes a document and all of its definitions from the graph.
/// Returns a pointer to the URI ID if the document was found and removed, or NULL if it didn't exist.
/// Caller must free the returned pointer with `free_u64`.
///
/// # Safety
///
/// Expects both the graph pointer and uri string pointer to be valid
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdx_graph_delete_document(pointer: GraphPointer, uri: *const c_char) -> *const u64 {
let Ok(uri_str) = (unsafe { utils::convert_char_ptr_to_string(uri) }) else {
return ptr::null();
};
with_mut_graph(pointer, |graph| match graph.delete_document(&uri_str) {
Some(uri_id) => Box::into_raw(Box::new(*uri_id)),
None => ptr::null(),
})
}
/// Runs the resolver to compute declarations, ownership and related structures
#[unsafe(no_mangle)]
pub extern "C" fn rdx_graph_resolve(pointer: GraphPointer) {
with_mut_graph(pointer, |graph| {
let mut resolver = Resolver::new(graph);
resolver.resolve_all();
});
}
/// Checks the integrity of the graph and returns an array of error message strings. Returns NULL if there are no
/// errors. Caller must free with `free_c_string_array`.
///
/// # Safety
///
/// - `pointer` must be a valid `GraphPointer` previously returned by this crate.
/// - `out_error_count` must be a valid, writable pointer.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdx_check_integrity(
pointer: GraphPointer,
out_error_count: *mut usize,
) -> *const *const c_char {
with_graph(pointer, |graph| {
let errors = integrity::check_integrity(graph);
if errors.is_empty() {
unsafe { *out_error_count = 0 };
return ptr::null();
}
let c_strings: Vec<*const c_char> = errors
.into_iter()
.filter_map(|error| {
CString::new(error.to_string())
.ok()
.map(|c_string| c_string.into_raw().cast_const())
})
.collect();
unsafe { *out_error_count = c_strings.len() };
let boxed = c_strings.into_boxed_slice();
Box::into_raw(boxed).cast::<*const c_char>()
})
}
/// # Safety
///
/// Expects both the graph pointer and encoding string pointer to be valid
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdx_graph_set_encoding(pointer: GraphPointer, encoding_str: *const c_char) -> bool {
let Ok(encoding) = (unsafe { utils::convert_char_ptr_to_string(encoding_str) }) else {
return false;
};
let encoding_variant = match encoding.as_str() {
"utf8" => Encoding::Utf8,
"utf16" => Encoding::Utf16,
"utf32" => Encoding::Utf32,
_ => {
return false;
}
};
with_mut_graph(pointer, |graph| {
graph.set_encoding(encoding_variant);
});
true
}
/// Creates a new iterator over declaration IDs by snapshotting the current set of IDs.
///
/// # Safety
///
/// - `pointer` must be a valid `GraphPointer` previously returned by this crate.
/// - The returned pointer must be freed with `rdx_graph_declarations_iter_free`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdx_graph_declarations_iter_new(pointer: GraphPointer) -> *mut DeclarationsIter {
// Snapshot the declarations at iterator creation to avoid borrowing across FFI calls
let entries = with_graph(pointer, |graph| {
graph
.declarations()
.iter()
.map(|(id, decl)| CDeclaration::from_declaration(*id, decl))
.collect::<Vec<CDeclaration>>()
.into_boxed_slice()
});
Box::into_raw(Box::new(DeclarationsIter::new(entries)))
}
/// Returns the total number of IDs in the iterator snapshot.
///
/// # Safety
///
/// - `iter` must be a valid pointer previously returned by `rdx_graph_declarations_iter_new`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdx_graph_declarations_iter_len(iter: *const DeclarationsIter) -> usize {
if iter.is_null() {
return 0;
}
unsafe { (&*iter).len() }
}
/// Advances the iterator and writes the next declaration into `out_decl`.
/// Returns `true` if a declaration was written, or `false` if the iterator is exhausted or inputs are invalid.
///
/// # Safety
///
/// - `iter` must be a valid pointer previously returned by `rdx_graph_declarations_iter_new`.
/// - `out_decl` must be a valid, writable pointer.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdx_graph_declarations_iter_next(
iter: *mut DeclarationsIter,
out_decl: *mut CDeclaration,
) -> bool {
if iter.is_null() || out_decl.is_null() {
return false;
}
unsafe {
let it = &mut *iter;
it.next(out_decl)
}
}
/// Frees an iterator created by `rdx_graph_declarations_iter_new`.
///
/// # Safety
///
/// - `iter` must be a pointer previously returned by `rdx_graph_declarations_iter_new`.
/// - `iter` must not be used after being freed.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdx_graph_declarations_iter_free(iter: *mut DeclarationsIter) {
if iter.is_null() {
return;
}
unsafe {
let _ = Box::from_raw(iter);
}
}
/// An iterator over document (URI) IDs
///
/// We snapshot the IDs at iterator creation so if the graph is modified, the iterator will not see the changes
#[derive(Debug)]
pub struct DocumentsIter {
/// The snapshot of document (URI) IDs
ids: Box<[u64]>,
/// The current index of the iterator
index: usize,
}
/// Creates a new iterator over document (URI) IDs by snapshotting the current set of IDs.
///
/// # Safety
///
/// - `pointer` must be a valid `GraphPointer` previously returned by this crate.
/// - The returned pointer must be freed with `rdx_graph_documents_iter_free`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdx_graph_documents_iter_new(pointer: GraphPointer) -> *mut DocumentsIter {
// Snapshot the IDs at iterator creation to avoid borrowing across FFI calls
let ids = with_graph(pointer, |graph| {
graph
.documents()
.keys()
.map(|uri_id| **uri_id)
.collect::<Vec<_>>()
.into_boxed_slice()
});
Box::into_raw(Box::new(DocumentsIter { ids, index: 0 }))
}
/// Returns the total number of IDs in the iterator snapshot.
///
/// # Safety
///
/// - `iter` must be a valid pointer previously returned by `rdx_graph_documents_iter_new`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdx_graph_documents_iter_len(iter: *const DocumentsIter) -> usize {
if iter.is_null() {
return 0;
}
unsafe { (&*iter).ids.len() }
}
/// Advances the iterator and writes the next ID into `out_id`.
/// Returns `true` if an ID was written, or `false` if the iterator is exhausted or inputs are invalid.
///
/// # Safety
///
/// - `iter` must be a valid pointer previously returned by `rdx_graph_documents_iter_new`.
/// - `out_id` must be a valid, writable pointer.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdx_graph_documents_iter_next(iter: *mut DocumentsIter, out_id: *mut u64) -> bool {
if iter.is_null() || out_id.is_null() {
return false;
}
let it = unsafe { &mut *iter };
if it.index >= it.ids.len() {
return false;
}
let id = it.ids[it.index];
it.index += 1;
unsafe { *out_id = id };
true
}
/// Frees an iterator created by `rdx_graph_documents_iter_new`.
///
/// # Safety
///
/// - `iter` must be a pointer previously returned by `rdx_graph_documents_iter_new`.
/// - `iter` must not be used after being freed.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdx_graph_documents_iter_free(iter: *mut DocumentsIter) {
if iter.is_null() {
return;
}
unsafe {
let _ = Box::from_raw(iter);
}
}
/// Attempts to resolve a declaration from a fully-qualified name string.
/// Returns a `CDeclaration` pointer if it exists, or NULL if it does not.
///
/// # Safety
/// - `pointer` must be a valid `GraphPointer`
/// - `name` must be a valid, null-terminated UTF-8 string
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdx_graph_get_declaration(pointer: GraphPointer, name: *const c_char) -> *const CDeclaration {
let Ok(name_str) = (unsafe { utils::convert_char_ptr_to_string(name) }) else {
return ptr::null();
};
with_graph(pointer, |graph| {
let decl_id = DeclarationId::from(name_str.as_str());
if let Some(decl) = graph.declarations().get(&decl_id) {
Box::into_raw(Box::new(CDeclaration::from_declaration(decl_id, decl))).cast_const()
} else {
ptr::null()
}
})
}
/// Creates a new iterator over constant references by snapshotting the current set of (id, kind) pairs.
///
/// # Safety
/// - `pointer` must be a valid `GraphPointer` previously returned by this crate.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdx_graph_constant_references_iter_new(pointer: GraphPointer) -> *mut ReferencesIter {
with_graph(pointer, |graph| {
let refs: Vec<_> = graph
.constant_references()
.keys()
.map(|id| CReference::new(**id, ReferenceKind::Constant))
.collect();
ReferencesIter::new(refs.into_boxed_slice())
})
}
/// Creates a new iterator over method references by snapshotting the current set of (id, kind) pairs.
///
/// # Safety
/// - `pointer` must be a valid `GraphPointer` previously returned by this crate.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdx_graph_method_references_iter_new(pointer: GraphPointer) -> *mut ReferencesIter {
with_graph(pointer, |graph| {
let refs: Vec<_> = graph
.method_references()
.keys()
.map(|id| CReference::new(**id, ReferenceKind::Method))
.collect();
ReferencesIter::new(refs.into_boxed_slice())
})
}
/// Resolves a require path to its document URI ID.
/// Returns a pointer to the URI ID if found, or NULL if not found.
/// Caller must free with the returned pointer.
///
/// # Safety
/// - `pointer` must be a valid `GraphPointer` previously returned by this crate.
/// - `require_path` must be a valid, null-terminated UTF-8 string.
/// - `load_paths` must be an array of `load_paths_count` valid, null-terminated UTF-8 strings.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdx_resolve_require_path(
pointer: GraphPointer,
require_path: *const c_char,
load_paths: *const *const c_char,
load_paths_count: usize,
) -> *const u64 {
let Ok(path_str) = (unsafe { utils::convert_char_ptr_to_string(require_path) }) else {
return ptr::null();
};
let Ok(paths_vec) = (unsafe { utils::convert_double_pointer_to_vec(load_paths, load_paths_count) }) else {
return ptr::null();
};
let paths_vec = paths_vec.into_iter().map(PathBuf::from).collect::<Vec<_>>();
with_graph(pointer, |graph| {
query::resolve_require_path(graph, &path_str, &paths_vec).map_or(ptr::null(), |id| Box::into_raw(Box::new(*id)))
})
}
/// Returns all require paths for completion.
/// Returns array of C strings and writes count to `out_count`.
/// Returns null if `load_path` contain invalid UTF-8.
/// Caller must free with `free_c_string_array`.
///
/// # Safety
/// - `pointer` must be a valid `GraphPointer` previously returned by this crate.
/// - `load_path` must be an array of `load_path_count` valid, null-terminated UTF-8 strings.
/// - `out_count` must be a valid, writable pointer.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdx_require_paths(
pointer: GraphPointer,
load_path: *const *const c_char,
load_path_count: usize,
out_count: *mut usize,
) -> *const *const c_char {
let Ok(paths_vec) = (unsafe { utils::convert_double_pointer_to_vec(load_path, load_path_count) }) else {
return ptr::null_mut();
};
let paths_vec = paths_vec.into_iter().map(PathBuf::from).collect::<Vec<_>>();
let results = with_graph(pointer, |graph| query::require_paths(graph, &paths_vec));
let c_strings: Vec<*const c_char> = results
.into_iter()
.filter_map(|string| {
CString::new(string)
.ok()
.map(|c_string| c_string.into_raw().cast_const())
})
.collect();
unsafe { *out_count = c_strings.len() };
let boxed = c_strings.into_boxed_slice();
Box::into_raw(boxed).cast::<*const c_char>()
}
#[repr(C)]
pub enum IndexSourceResult {
Success = 0,
InvalidUri = 1,
InvalidSource = 2,
InvalidLanguageId = 3,
UnsupportedLanguageId = 4,
}
/// Indexes source code from memory using the specified language. Returns `IndexSourceResult::Success` on success
/// or a specific error variant if string conversion or language lookup fails.
///
/// # Safety
///
/// - `pointer` must be a valid `GraphPointer` previously returned by this crate.
/// - `uri` and `language_id` must be valid, null-terminated UTF-8 strings.
/// - `source` must point to a valid UTF-8 byte buffer of at least `source_len` bytes.
/// It may contain null bytes.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdx_index_source(
pointer: GraphPointer,
uri: *const c_char,
source: *const c_char,
source_len: usize,
language_id: *const c_char,
) -> IndexSourceResult {
let Ok(uri_str) = (unsafe { utils::convert_char_ptr_to_string(uri) }) else {
return IndexSourceResult::InvalidUri;
};
let source_bytes = unsafe { std::slice::from_raw_parts(source.cast::<u8>(), source_len) };
let Ok(source_str) = std::str::from_utf8(source_bytes) else {
return IndexSourceResult::InvalidSource;
};
let Ok(language_id_str) = (unsafe { utils::convert_char_ptr_to_string(language_id) }) else {
return IndexSourceResult::InvalidLanguageId;
};
let Ok(language) = LanguageId::from_language_id(&language_id_str) else {
return IndexSourceResult::UnsupportedLanguageId;
};
with_mut_graph(pointer, |graph| {
indexing::index_source(graph, &uri_str, source_str, &language);
IndexSourceResult::Success
})
}
#[cfg(test)]
mod tests {
use rubydex::indexing::ruby_indexer::RubyIndexer;
use super::*;
#[test]
fn names_are_untracked_after_resolving_constant() {
let mut indexer = RubyIndexer::new(
"file:///foo.rb".into(),
"
class Foo
BAR = 1
end
",
);
indexer.index();
let mut graph = Graph::new();
graph.consume_document_changes(indexer.local_graph());
let mut resolver = Resolver::new(&mut graph);
resolver.resolve_all();
assert_eq!(
1,
graph
.names()
.iter()
.find_map(|(_, name)| {
if graph.strings().get(name.str()).unwrap().as_str() == "BAR" {
Some(name)
} else {
None
}
})
.unwrap()
.ref_count()
);
let graph_ptr = Box::into_raw(Box::new(graph)) as GraphPointer;
// Build the nesting array: ["Foo"] since BAR is inside class Foo
let nesting_strings = [CString::new("Foo").unwrap()];
let nesting_ptrs: Vec<*const c_char> = nesting_strings.iter().map(|s| s.as_ptr()).collect();
unsafe {
let decl = rdx_graph_resolve_constant(
graph_ptr,
CString::new("BAR").unwrap().as_ptr(),
nesting_ptrs.as_ptr(),
nesting_ptrs.len(),
);
assert_eq!((*decl).id(), *DeclarationId::from("Foo::BAR"));
};
let graph = unsafe { Box::from_raw(graph_ptr.cast::<Graph>()) };
assert_eq!(
1,
graph
.names()
.iter()
.find_map(|(_, name)| {
if graph.strings().get(name.str()).unwrap().as_str() == "BAR" {
Some(name)
} else {
None
}
})
.unwrap()
.ref_count()
);
}
}