rubydex-sys 0.2.5

C FFI bindings for the Rubydex Ruby code indexing engine.
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
//! This file provides the C API for Definition accessors

use crate::declaration_api::CDeclaration;
use crate::graph_api::{GraphPointer, with_graph};
use crate::location_api::{Location, create_location_for_uri_and_offset};
use crate::reference_api::CConstantReference;
use libc::c_char;
use rubydex::model::definitions::{Definition, Mixin};
use rubydex::model::ids::DefinitionId;
use std::ffi::CString;
use std::ptr;

/// C-compatible enum representing the kind of a definition.
#[repr(C)]
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum DefinitionKind {
    Class = 0,
    SingletonClass = 1,
    Module = 2,
    Constant = 3,
    ConstantAlias = 4,
    ConstantVisibility = 5,
    MethodVisibility = 6,
    Method = 7,
    AttrAccessor = 8,
    AttrReader = 9,
    AttrWriter = 10,
    GlobalVariable = 11,
    InstanceVariable = 12,
    ClassVariable = 13,
    MethodAlias = 14,
    GlobalVariableAlias = 15,
}

#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct CDefinition {
    pub id: u64,
    pub kind: DefinitionKind,
}

pub(crate) fn map_definition_to_kind(defn: &Definition) -> DefinitionKind {
    match defn {
        Definition::Class(_) => DefinitionKind::Class,
        Definition::SingletonClass(_) => DefinitionKind::SingletonClass,
        Definition::Module(_) => DefinitionKind::Module,
        Definition::Constant(_) => DefinitionKind::Constant,
        Definition::ConstantAlias(_) => DefinitionKind::ConstantAlias,
        Definition::ConstantVisibility(_) => DefinitionKind::ConstantVisibility,
        Definition::MethodVisibility(_) => DefinitionKind::MethodVisibility,
        Definition::Method(_) => DefinitionKind::Method,
        Definition::AttrAccessor(_) => DefinitionKind::AttrAccessor,
        Definition::AttrReader(_) => DefinitionKind::AttrReader,
        Definition::AttrWriter(_) => DefinitionKind::AttrWriter,
        Definition::GlobalVariable(_) => DefinitionKind::GlobalVariable,
        Definition::InstanceVariable(_) => DefinitionKind::InstanceVariable,
        Definition::ClassVariable(_) => DefinitionKind::ClassVariable,
        Definition::MethodAlias(_) => DefinitionKind::MethodAlias,
        Definition::GlobalVariableAlias(_) => DefinitionKind::GlobalVariableAlias,
    }
}

/// Returns the enum kind for a definition id (e.g. Class, Module).
///
/// # Safety
///
/// Assumes pointer is valid.
///
/// # Panics
///
/// This function will panic if the definition cannot be found.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdx_definition_kind(pointer: GraphPointer, definition_id: u64) -> DefinitionKind {
    with_graph(pointer, |graph| {
        let definition_id = DefinitionId::new(definition_id);
        if let Some(defn) = graph.definitions().get(&definition_id) {
            map_definition_to_kind(defn)
        } else {
            panic!("Definition not found: {definition_id:?}");
        }
    })
}

/// Returns the UTF-8 unqualified name string for a definition id.
/// Caller must free with `free_c_string`.
///
/// # Safety
///
/// Assumes pointer is valid.
///
/// # Panics
///
/// This function will panic if the definition cannot be found.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdx_definition_name(pointer: GraphPointer, definition_id: u64) -> *const c_char {
    with_graph(pointer, |graph| {
        let def_id = DefinitionId::new(definition_id);
        if let Some(defn) = graph.definitions().get(&def_id) {
            let string_id = graph.definition_string_id(defn);

            if let Some(name) = graph.strings().get(&string_id) {
                CString::new(name.as_str()).unwrap().into_raw().cast_const()
            } else {
                ptr::null()
            }
        } else {
            ptr::null()
        }
    })
}

/// Shared iterator over definition (id, kind) pairs
#[derive(Debug)]
pub struct DefinitionsIter {
    entries: Box<[CDefinition]>,
    index: usize,
}

iterator!(DefinitionsIter, entries: CDefinition);

/// # Safety
/// `iter` must be a valid pointer previously returned by `DefinitionsIter::new`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdx_definitions_iter_len(iter: *const DefinitionsIter) -> usize {
    unsafe { DefinitionsIter::len(iter) }
}

/// # Safety
/// - `iter` must be a valid pointer previously returned by `DefinitionsIter::new`.
/// - `out` must be a valid, writable pointer.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdx_definitions_iter_next(iter: *mut DefinitionsIter, out: *mut CDefinition) -> bool {
    unsafe { DefinitionsIter::next(iter, out) }
}

/// # Safety
/// - `iter` must be a pointer previously returned by `DefinitionsIter::new`.
/// - `iter` must not be used after being freed.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdx_definitions_iter_free(iter: *mut DefinitionsIter) {
    unsafe { DefinitionsIter::free(iter) }
}

/// C-compatible struct representing a single comment with its string and location
#[repr(C)]
pub struct CommentEntry {
    pub string: *const c_char,
    pub location: *mut Location,
}

/// C-compatible array of comments
#[repr(C)]
pub struct CommentArray {
    pub items: *mut CommentEntry,
    pub len: usize,
}

/// Returns a newly allocated array of comments (string and location) for the given definition id.
/// Caller must free the returned pointer with `rdx_definition_comments_free` and each inner string with `free_c_string` if needed.
///
/// # Safety
/// - `pointer` must be a valid pointer previously returned by `rdx_graph_new`.
/// - `definition_id` must be a valid definition id.
///
/// # Panics
/// This function will panic if a definition or document cannot be found.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdx_definition_comments(pointer: GraphPointer, definition_id: u64) -> *mut CommentArray {
    with_graph(pointer, |graph| {
        let def_id = DefinitionId::new(definition_id);
        let Some(defn) = graph.definitions().get(&def_id) else {
            panic!("Definition not found: {definition_id:?}");
        };

        let uri_id = *defn.uri_id();
        let document = graph.documents().get(&uri_id).expect("document should exist");

        let mut entries = defn
            .comments()
            .iter()
            .map(|c| CommentEntry {
                string: CString::new(c.string().as_str()).unwrap().into_raw().cast_const(),
                location: create_location_for_uri_and_offset(graph, document, c.offset()),
            })
            .collect::<Vec<CommentEntry>>()
            .into_boxed_slice();

        let len = entries.len();
        let items_ptr = entries.as_mut_ptr();
        std::mem::forget(entries);

        Box::into_raw(Box::new(CommentArray { items: items_ptr, len }))
    })
}

/// Frees a `CommentArray` previously returned by `rdx_definition_comments`.
///
/// # Safety
/// - `ptr` must be a valid pointer previously returned by `rdx_definition_comments`.
/// - `ptr` must not be used after being freed.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdx_definition_comments_free(ptr: *mut CommentArray) {
    if ptr.is_null() {
        return;
    }

    // Take ownership of the CommentArray
    let arr = unsafe { Box::from_raw(ptr) };

    if !arr.items.is_null() && arr.len > 0 {
        // Reconstruct the boxed slice so we can drop it after freeing inner allocations
        let slice_ptr = ptr::slice_from_raw_parts_mut(arr.items, arr.len);
        let mut boxed_slice: Box<[CommentEntry]> = unsafe { Box::from_raw(slice_ptr) };

        for item in &mut boxed_slice {
            if !item.string.is_null() {
                // Free the CString allocated for the comment string
                let _ = unsafe { CString::from_raw(item.string.cast_mut()) };
            }
            if !item.location.is_null() {
                unsafe { crate::location_api::rdx_location_free(item.location) };
                item.location = ptr::null_mut();
            }
        }

        // boxed_slice is dropped here, freeing the items buffer
    }
    // arr is dropped here
}

/// Returns a newly allocated `Location` for the given definition id.
/// Caller must free the returned pointer with `rdx_location_free`.
///
/// # Safety
/// - `pointer` must be a valid pointer previously returned by `rdx_graph_new`.
/// - `definition_id` must be a valid definition id.
///
/// # Panics
///
/// This function will panic if a definition or document cannot be found.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdx_definition_location(pointer: GraphPointer, definition_id: u64) -> *mut Location {
    with_graph(pointer, |graph| {
        let def_id = DefinitionId::new(definition_id);
        let Some(defn) = graph.definitions().get(&def_id) else {
            panic!("Definition not found: {definition_id:?}");
        };

        let document = graph.documents().get(defn.uri_id()).expect("document should exist");
        create_location_for_uri_and_offset(graph, document, defn.offset())
    })
}

/// Returns the declaration that the given definition belongs to. Returns NULL when the definition has no associated
/// declaration (for example, before resolution has run or when the declaration cannot be located). Caller must free
/// with `free_c_declaration`.
///
/// # Safety
/// - `pointer` must be a valid pointer previously returned by `rdx_graph_new`.
/// - `definition_id` must be a valid definition id.
///
/// # Panics
/// This function will panic if the definition cannot be found.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdx_definition_declaration(pointer: GraphPointer, definition_id: u64) -> *const CDeclaration {
    with_graph(pointer, |graph| {
        let def_id = DefinitionId::new(definition_id);
        let Some(decl_id) = graph.definition_id_to_declaration_id(def_id) else {
            return ptr::null();
        };
        let Some(decl) = graph.declarations().get(decl_id) else {
            return ptr::null();
        };

        Box::into_raw(Box::new(CDeclaration::from_declaration(*decl_id, decl))).cast_const()
    })
}

/// Returns the lexical nesting definition id for the given definition, or NULL if there is no lexical nesting.
/// Caller must free the returned pointer with `free_u64`.
///
/// # Safety
/// - `pointer` must be a valid pointer previously returned by `rdx_graph_new`.
/// - `definition_id` must be a valid definition id.
///
/// # Panics
/// This function will panic if the definition cannot be found.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdx_definition_lexical_nesting_id(pointer: GraphPointer, definition_id: u64) -> *const u64 {
    with_graph(pointer, |graph| {
        let def_id = DefinitionId::new(definition_id);
        let Some(defn) = graph.definitions().get(&def_id) else {
            panic!("Definition not found: {definition_id:?}");
        };

        match defn.lexical_nesting_id() {
            Some(lexical_nesting_id) => Box::into_raw(Box::new(**lexical_nesting_id)).cast_const(),
            None => ptr::null(),
        }
    })
}

/// Creates a new iterator over definition IDs for a given declaration by snapshotting the current set of IDs.
///
/// # Panics
///
/// This function will panic if a definition cannot be found.
pub(crate) fn rdx_definitions_iter_new_from_ids<'a, I>(
    graph: &rubydex::model::graph::Graph,
    ids: I,
) -> *mut DefinitionsIter
where
    I: IntoIterator<Item = &'a DefinitionId>,
{
    let entries = ids
        .into_iter()
        .map(|def_id| {
            let id = **def_id;
            let kind = graph
                .definitions()
                .get(&DefinitionId::new(id))
                .map_or_else(|| panic!("Definition not found: {id:?}"), map_definition_to_kind);
            CDefinition { id, kind }
        })
        .collect::<Vec<_>>()
        .into_boxed_slice();

    DefinitionsIter::new(entries)
}

/// Returns true if the definition is deprecated.
///
/// # Safety
/// - `pointer` must be a valid pointer previously returned by `rdx_graph_new`.
/// - `definition_id` must be a valid definition id.
///
/// # Panics
/// This function will panic if a definition cannot be found.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdx_definition_is_deprecated(pointer: GraphPointer, definition_id: u64) -> bool {
    with_graph(pointer, |graph| {
        let def_id = DefinitionId::new(definition_id);
        let defn = graph.definitions().get(&def_id).expect("definition not found");
        defn.is_deprecated()
    })
}

/// Returns a newly allocated `Location` for the name portion of a definition id.
/// For class, module, singleton class, and method definitions, this returns the location of just
/// the name (e.g., "Bar" in `class Foo::Bar`, or "foo" in `def foo`).
/// For other definition types, returns NULL.
/// Caller must free the returned pointer with `rdx_location_free`.
///
/// # Safety
/// - `pointer` must be a valid pointer previously returned by `rdx_graph_new`.
/// - `definition_id` must be a valid definition id.
///
/// # Panics
/// Panics if the definition's document does not exist in the graph.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdx_definition_name_location(pointer: GraphPointer, definition_id: u64) -> *mut Location {
    with_graph(pointer, |graph| {
        let def_id = DefinitionId::new(definition_id);
        let Some(defn) = graph.definitions().get(&def_id) else {
            return ptr::null_mut();
        };
        let Some(name_offset) = defn.name_offset() else {
            return ptr::null_mut();
        };
        let document = graph.documents().get(defn.uri_id()).expect("document should exist");
        create_location_for_uri_and_offset(graph, document, name_offset)
    })
}

/// Returns the superclass constant reference for a class definition, or NULL if the class has no superclass. Caller
/// must free with `free_c_constant_reference`.
///
/// # Safety
/// - `pointer` must be a valid pointer previously returned by `rdx_graph_new`.
/// - `definition_id` must be a valid definition id for a class definition.
///
/// # Panics
/// This function will panic if the definition cannot be found or is not a class definition.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdx_class_definition_superclass(
    pointer: GraphPointer,
    definition_id: u64,
) -> *const CConstantReference {
    with_graph(pointer, |graph| {
        let def_id = DefinitionId::new(definition_id);
        let defn = graph.definitions().get(&def_id).expect("Definition not found");

        let Definition::Class(class_def) = defn else {
            panic!("Definition is not a class: {definition_id}");
        };

        let Some(ref_id) = class_def.superclass_ref() else {
            return ptr::null();
        };

        Box::into_raw(Box::new(CConstantReference::from_id(graph, *ref_id))).cast_const()
    })
}

/// C-compatible enum representing the kind of a mixin.
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub enum MixinKind {
    Include = 0,
    Prepend = 1,
    Extend = 2,
}

/// C-compatible struct representing a mixin (kind + constant reference).
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct CMixin {
    pub kind: MixinKind,
    pub constant_reference: CConstantReference,
}

#[derive(Debug)]
pub struct MixinsIter {
    entries: Box<[CMixin]>,
    index: usize,
}

iterator!(MixinsIter, entries: CMixin);

/// # Safety
/// `iter` must be a valid pointer previously returned by `rdx_definition_mixins`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdx_mixins_iter_len(iter: *const MixinsIter) -> usize {
    unsafe { MixinsIter::len(iter) }
}

/// # Safety
/// - `iter` must be a valid pointer previously returned by `rdx_definition_mixins`.
/// - `out` must be a valid, writable pointer.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdx_mixins_iter_next(iter: *mut MixinsIter, out: *mut CMixin) -> bool {
    unsafe { MixinsIter::next(iter, out) }
}

/// # Safety
/// - `iter` must be a pointer previously returned by `rdx_definition_mixins`.
/// - `iter` must not be used after being freed.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdx_mixins_iter_free(iter: *mut MixinsIter) {
    unsafe { MixinsIter::free(iter) }
}

fn map_mixin_kind(mixin: &Mixin) -> MixinKind {
    match mixin {
        Mixin::Include(_) => MixinKind::Include,
        Mixin::Prepend(_) => MixinKind::Prepend,
        Mixin::Extend(_) => MixinKind::Extend,
    }
}

/// Returns an iterator over the mixins for a definition (class, module, or singleton class).
/// Returns NULL for definition types that do not support mixins.
///
/// # Safety
/// - `pointer` must be a valid pointer previously returned by `rdx_graph_new`.
/// - `definition_id` must be a valid definition id.
///
/// # Panics
/// This function will panic if the definition cannot be found.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdx_definition_mixins(pointer: GraphPointer, definition_id: u64) -> *mut MixinsIter {
    with_graph(pointer, |graph| {
        let def_id = DefinitionId::new(definition_id);
        let defn = graph.definitions().get(&def_id).expect("Definition not found");

        let mixins = match defn {
            Definition::Class(class_def) => class_def.mixins(),
            Definition::Module(mod_def) => mod_def.mixins(),
            Definition::SingletonClass(singleton_def) => singleton_def.mixins(),
            _ => return ptr::null_mut(),
        };

        let entries: Vec<CMixin> = mixins
            .iter()
            .map(|mixin| CMixin {
                kind: map_mixin_kind(mixin),
                constant_reference: CConstantReference::from_id(graph, *mixin.constant_reference_id()),
            })
            .collect();

        MixinsIter::new(entries.into_boxed_slice())
    })
}