Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions ext/rubydex/declaration.c
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
#include "handle.h"
#include "reference.h"
#include "rustbindings.h"
#include "signature.h"
#include "utils.h"

VALUE cDeclaration;
Expand Down Expand Up @@ -331,6 +332,18 @@ static VALUE rdxr_declaration_references(VALUE self) {
return self;
}

// Method#signatures -> [Rubydex::Signature]
static VALUE rdxr_method_declaration_signatures(VALUE self) {
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we need to expose Declaration#signature? Signatures are associated to the specific Definition that creates them, so I'd expect us to access it like this:

method_decl = graph["Foo#bar()"]
signatures = method_decl.definitions.map(&:signature)

I think we can remove this one.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd like to keep #signatures as a utility API. #definitions can contain method aliases, so definitions.flat_map(&:signatures) wouldn't work transparently — users would need to handle alias resolution themselves.

We could add a separate API for alias normalization, but if we're adding an API anyway, I think #signatures that does it all in one shot is the better choice.

HandleData *data;
TypedData_Get_Struct(self, HandleData, &handle_type, data);

void *graph;
TypedData_Get_Struct(data->graph_obj, void *, &graph_type, graph);

SignatureArray *arr = rdx_declaration_method_signatures(graph, data->id);
return rdxi_signatures_to_ruby(arr, data->graph_obj, Qnil);
}

void rdxi_initialize_declaration(VALUE mRubydex) {
cDeclaration = rb_define_class_under(mRubydex, "Declaration", rb_cObject);
cNamespace = rb_define_class_under(mRubydex, "Namespace", cDeclaration);
Expand All @@ -341,6 +354,7 @@ void rdxi_initialize_declaration(VALUE mRubydex) {
cConstant = rb_define_class_under(mRubydex, "Constant", cDeclaration);
cConstantAlias = rb_define_class_under(mRubydex, "ConstantAlias", cDeclaration);
cMethod = rb_define_class_under(mRubydex, "Method", cDeclaration);
rb_define_method(cMethod, "signatures", rdxr_method_declaration_signatures, 0);
cGlobalVariable = rb_define_class_under(mRubydex, "GlobalVariable", cDeclaration);
cInstanceVariable = rb_define_class_under(mRubydex, "InstanceVariable", cDeclaration);
cClassVariable = rb_define_class_under(mRubydex, "ClassVariable", cDeclaration);
Expand Down
14 changes: 14 additions & 0 deletions ext/rubydex/definition.c
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
#include "location.h"
#include "ruby/internal/scan_args.h"
#include "rustbindings.h"
#include "signature.h"

static VALUE mRubydex;
VALUE cComment;
Expand Down Expand Up @@ -161,6 +162,18 @@ static VALUE rdxr_definition_name_location(VALUE self) {
return location;
}

// MethodDefinition#signatures -> [Rubydex::Signature]
static VALUE rdxr_method_definition_signatures(VALUE self) {
HandleData *data;
TypedData_Get_Struct(self, HandleData, &handle_type, data);

void *graph;
TypedData_Get_Struct(data->graph_obj, void *, &graph_type, graph);

SignatureArray *arr = rdx_definition_signatures(graph, data->id);
return rdxi_signatures_to_ruby(arr, data->graph_obj, self);
}

void rdxi_initialize_definition(VALUE mod) {
mRubydex = mod;

Expand All @@ -182,6 +195,7 @@ void rdxi_initialize_definition(VALUE mod) {
cConstantDefinition = rb_define_class_under(mRubydex, "ConstantDefinition", cDefinition);
cConstantAliasDefinition = rb_define_class_under(mRubydex, "ConstantAliasDefinition", cDefinition);
cMethodDefinition = rb_define_class_under(mRubydex, "MethodDefinition", cDefinition);
rb_define_method(cMethodDefinition, "signatures", rdxr_method_definition_signatures, 0);
cAttrAccessorDefinition = rb_define_class_under(mRubydex, "AttrAccessorDefinition", cDefinition);
cAttrReaderDefinition = rb_define_class_under(mRubydex, "AttrReaderDefinition", cDefinition);
cAttrWriterDefinition = rb_define_class_under(mRubydex, "AttrWriterDefinition", cDefinition);
Expand Down
2 changes: 2 additions & 0 deletions ext/rubydex/rubydex.c
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
#include "graph.h"
#include "location.h"
#include "reference.h"
#include "signature.h"

VALUE mRubydex;

Expand All @@ -19,4 +20,5 @@ void Init_rubydex(void) {
rdxi_initialize_location(mRubydex);
rdxi_initialize_diagnostic(mRubydex);
rdxi_initialize_reference(mRubydex);
rdxi_initialize_signature(mRubydex);
}
68 changes: 68 additions & 0 deletions ext/rubydex/signature.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
#include "signature.h"
#include "definition.h"
#include "handle.h"
#include "location.h"

VALUE cSignature;

static VALUE parameter_kind_to_symbol(ParameterKind kind) {
switch (kind) {
case ParameterKind_Req: return ID2SYM(rb_intern("req"));
case ParameterKind_Opt: return ID2SYM(rb_intern("opt"));
case ParameterKind_Rest: return ID2SYM(rb_intern("rest"));
case ParameterKind_Keyreq: return ID2SYM(rb_intern("keyreq"));
case ParameterKind_Key: return ID2SYM(rb_intern("key"));
case ParameterKind_Keyrest: return ID2SYM(rb_intern("keyrest"));
case ParameterKind_Block: return ID2SYM(rb_intern("block"));
case ParameterKind_Forward: return ID2SYM(rb_intern("forward"));
default: rb_raise(rb_eRuntimeError, "Unknown ParameterKind: %d", kind);
}
}

VALUE rdxi_signatures_to_ruby(SignatureArray *arr, VALUE graph_obj, VALUE default_method_def) {
if (arr == NULL || arr->len == 0) {
if (arr != NULL) {
rdx_definition_signatures_free(arr);
}
return rb_ary_new();
}

VALUE signatures = rb_ary_new_capa((long)arr->len);

for (size_t i = 0; i < arr->len; i++) {
SignatureEntry sig_entry = arr->items[i];

VALUE method_def;
if (default_method_def != Qnil) {
method_def = default_method_def;
} else {
VALUE def_argv[] = {graph_obj, ULL2NUM(sig_entry.definition_id)};
method_def = rb_class_new_instance(2, def_argv, cMethodDefinition);
}

VALUE parameters = rb_ary_new_capa((long)sig_entry.parameters_len);
for (size_t j = 0; j < sig_entry.parameters_len; j++) {
ParameterEntry param_entry = sig_entry.parameters[j];

VALUE kind_sym = parameter_kind_to_symbol(param_entry.kind);
VALUE name_sym = ID2SYM(rb_intern(param_entry.name));
VALUE location = rdxi_build_location_value(param_entry.location);

rb_ary_push(parameters, rb_ary_new_from_args(3, kind_sym, name_sym, location));
}

VALUE sig_kwargs = rb_hash_new();
rb_hash_aset(sig_kwargs, ID2SYM(rb_intern("parameters")), parameters);
rb_hash_aset(sig_kwargs, ID2SYM(rb_intern("method_definition")), method_def);
VALUE signature = rb_class_new_instance_kw(1, &sig_kwargs, cSignature, RB_PASS_KEYWORDS);

rb_ary_push(signatures, signature);
}

rdx_definition_signatures_free(arr);
return signatures;
}

void rdxi_initialize_signature(VALUE mRubydex) {
cSignature = rb_define_class_under(mRubydex, "Signature", rb_cObject);
}
17 changes: 17 additions & 0 deletions ext/rubydex/signature.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
#ifndef RUBYDEX_SIGNATURE_H
#define RUBYDEX_SIGNATURE_H

#include "ruby.h"
#include "rustbindings.h"

extern VALUE cSignature;

// Convert a SignatureArray into a Ruby array of Rubydex::Signature objects.
// If default_method_def is not Qnil, it is used as method_definition for all signatures.
// Otherwise, a new MethodDefinition handle is built from each SignatureEntry's definition_id.
// The SignatureArray is freed after conversion.
VALUE rdxi_signatures_to_ruby(SignatureArray *arr, VALUE graph_obj, VALUE default_method_def);

void rdxi_initialize_signature(VALUE mRubydex);

#endif // RUBYDEX_SIGNATURE_H
1 change: 1 addition & 0 deletions lib/rubydex.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,6 @@
require "rubydex/failures"
require "rubydex/location"
require "rubydex/comment"
require "rubydex/signature"
require "rubydex/diagnostic"
require "rubydex/graph"
37 changes: 37 additions & 0 deletions lib/rubydex/signature.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# frozen_string_literal: true

module Rubydex
# Represents a single signature of a method definition.
#
# A method definition may have multiple signatures when defined with overloads in RBS.
class Signature
# Returns the parameters of the signature.
#
# Each parameter is a 3-element array of `[kind, name, location]`,
# following the same format as `Method#parameters` with an additional location element.
#
# The kind symbol is one of:
# - `:req` — required positional parameter (`a`) or post-rest positional parameter (`d` in `def foo(*c, d)`)
# - `:opt` — optional positional parameter (`b = 1`)
# - `:rest` — rest positional parameter (`*c`)
# - `:keyreq` — required keyword parameter (`e:`)
# - `:key` — optional keyword parameter (`f: 1`)
# - `:keyrest` — rest keyword parameter (`**g`)
# - `:block` — block parameter (`&h`)
# - `:forward` — forward parameter (`...`), Rubydex-specific (Ruby expands this to `:rest`, `:keyrest`, `:block`)
#
#: Array[[Symbol, Symbol, Location]]
Comment on lines +10 to +23
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's please create Ruby objects to represent each parameter type instead of using symbols.

I suspect you only need a parent class and then a bunch of empty definitions:

class Parameter
  def initialize(name, location)
    # ...
  end
end

class PositionalParameter < Parameter; end
class OptionalPositionalParameter < Parameter; end
class KeywordParameter < Parameter; end
class OptionalKeywordParameter < Parameter; end
# ...

attr_reader :parameters

# Returns the method definition this signature belongs to.
#
#: MethodDefinition
attr_reader :method_definition

#: (parameters: Array[[Symbol, Symbol, Location]], method_definition: MethodDefinition) -> void
def initialize(parameters:, method_definition:)
@parameters = parameters
@method_definition = method_definition
end
end
end
43 changes: 42 additions & 1 deletion rust/rubydex-sys/src/declaration_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ use rubydex::model::declaration::{Ancestor, Declaration, Namespace};
use std::ffi::CString;
use std::ptr;

use crate::definition_api::{DefinitionsIter, rdx_definitions_iter_new_from_ids};
use crate::definition_api::{
DefinitionsIter, SignatureArray, SignatureEntry, collect_method_signatures, rdx_definitions_iter_new_from_ids,
};
use crate::graph_api::{GraphPointer, with_graph};
use crate::reference_api::{CReference, ReferenceKind, ReferencesIter};
use crate::utils;
Expand Down Expand Up @@ -439,3 +441,42 @@ pub unsafe extern "C" fn rdx_declaration_references_iter_new(
ReferencesIter::new(entries.into_boxed_slice())
})
}

/// Returns a newly allocated array of signatures for the given method declaration id.
/// Aggregates signatures from all definitions. For alias definitions, resolves to the
/// original method's signatures.
/// Returns NULL if the declaration is not a method declaration.
/// Caller must free the returned pointer with `rdx_definition_signatures_free`.
///
/// # Safety
/// - `pointer` must be a valid pointer previously returned by `rdx_graph_new`.
/// - `declaration_id` must be a valid declaration id.
///
/// # Panics
/// This function will panic if declarations or definitions cannot be found.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdx_declaration_method_signatures(
pointer: GraphPointer,
declaration_id: u64,
) -> *mut SignatureArray {
with_graph(pointer, |graph| {
let decl_id = DeclarationId::new(declaration_id);
let method_defs = rubydex::query::method_definitions(graph, decl_id);

if method_defs.is_empty() {
return ptr::null_mut();
}

let mut sig_entries: Vec<SignatureEntry> = Vec::new();
for method_def in &method_defs {
collect_method_signatures(graph, method_def, method_def.id().get(), &mut sig_entries);
}

let mut boxed = sig_entries.into_boxed_slice();
let len = boxed.len();
let items_ptr = boxed.as_mut_ptr();
std::mem::forget(boxed);

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