Skip to content
Merged
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
264 changes: 262 additions & 2 deletions rust/rubydex/src/indexing/rbs_indexer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@
use core::panic;

use ruby_rbs::node::{
self, AliasKind, ClassNode, CommentNode, ConstantNode, ExtendNode, FunctionTypeNode, GlobalNode, IncludeNode,
ModuleNode, Node, NodeList, PrependNode, TypeNameNode, Visit,
self, AliasKind, AttrAccessorNode, AttrReaderNode, AttrWriterNode, AttributeKind, AttributeVisibility, ClassNode,
CommentNode, ConstantNode, ExtendNode, FunctionTypeNode, GlobalNode, IncludeNode, ModuleNode, Node, NodeList,
PrependNode, TypeNameNode, Visit,
};

use crate::diagnostic::Rule;
Expand Down Expand Up @@ -222,6 +223,133 @@ impl<'a> RBSIndexer<'a> {
definition_id
}

#[allow(clippy::too_many_arguments)]
fn register_attribute_methods(
&mut self,
name: &str,
offset: Offset,
name_offset: Offset,
comments: Box<[Comment]>,
flags: DefinitionFlags,
lexical_nesting_id: Option<DefinitionId>,
kind: AttributeKind,
attribute_visibility: AttributeVisibility,
reader: bool,
writer: bool,
) {
let (visibility, receiver) = match kind {
AttributeKind::Instance => {
let visibility = match attribute_visibility {
AttributeVisibility::Public => Visibility::Public,
AttributeVisibility::Private => Visibility::Private,
AttributeVisibility::Unspecified => self.current_visibility,
};
(visibility, None)
}
AttributeKind::Singleton => {
let visibility = match attribute_visibility {
AttributeVisibility::Private => Visibility::Private,
AttributeVisibility::Public | AttributeVisibility::Unspecified => Visibility::Public,
};
(
visibility,
Some(Receiver::SelfReceiver(
lexical_nesting_id.expect("Singleton attribute must have a lexical enclosing scope"),
)),
)
}
};

match (reader, writer) {
(true, true) => {
self.register_attribute_method(
name,
false,
offset.clone(),
name_offset.clone(),
comments.clone(),
flags.clone(),
lexical_nesting_id,
visibility,
receiver.clone(),
);
self.register_attribute_method(
name,
true,
offset,
name_offset,
comments,
flags,
lexical_nesting_id,
visibility,
receiver,
);
}
(true, false) => self.register_attribute_method(
name,
false,
offset,
name_offset,
comments,
flags,
lexical_nesting_id,
visibility,
receiver,
),
(false, true) => self.register_attribute_method(
name,
true,
offset,
name_offset,
comments,
flags,
lexical_nesting_id,
visibility,
receiver,
),
(false, false) => unreachable!("attribute must have a reader or writer"),
}
}

#[allow(clippy::too_many_arguments)]
fn register_attribute_method(
&mut self,
name: &str,
writer: bool,
offset: Offset,
name_offset: Offset,
comments: Box<[Comment]>,
flags: DefinitionFlags,
lexical_nesting_id: Option<DefinitionId>,
visibility: Visibility,
receiver: Option<Receiver>,
) {
let str_id = self
.local_graph
.intern_string(format!("{name}{}()", if writer { "=" } else { "" }));
let signatures = if writer {
let parameter_name = self.local_graph.intern_string(name.to_owned());
let parameter = Parameter::RequiredPositional(ParameterStruct::new(name_offset.clone(), parameter_name));
Signatures::Simple(vec![parameter].into_boxed_slice())
} else {
Signatures::Simple(Box::new([]))
};

let definition = Definition::Method(Box::new(MethodDefinition::new(
Comment thread
soutaro marked this conversation as resolved.
str_id,
self.uri_id,
offset,
name_offset,
comments,
flags,
lexical_nesting_id,
signatures,
visibility,
receiver,
)));
self.register_definition(definition, lexical_nesting_id);
}

#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
fn source_at(&self, location: &node::RBSLocationRange) -> String {
let start = location.start() as usize;
Expand Down Expand Up @@ -573,6 +701,51 @@ impl Visit for RBSIndexer<'_> {
self.register_definition(definition, lexical_nesting_id);
}

fn visit_attr_reader_node(&mut self, attribute_node: &AttrReaderNode) {
self.register_attribute_methods(
attribute_node.name().as_str(),
Offset::from_rbs_location(&attribute_node.location()),
Offset::from_rbs_location(&attribute_node.name_location()),
self.collect_comments(attribute_node.comment()),
Self::flags(&attribute_node.annotations()),
self.parent_lexical_scope_id(),
attribute_node.kind(),
attribute_node.visibility(),
true,
false,
);
}

fn visit_attr_writer_node(&mut self, attribute_node: &AttrWriterNode) {
self.register_attribute_methods(
attribute_node.name().as_str(),
Offset::from_rbs_location(&attribute_node.location()),
Offset::from_rbs_location(&attribute_node.name_location()),
self.collect_comments(attribute_node.comment()),
Self::flags(&attribute_node.annotations()),
self.parent_lexical_scope_id(),
attribute_node.kind(),
attribute_node.visibility(),
false,
true,
);
}

fn visit_attr_accessor_node(&mut self, attribute_node: &AttrAccessorNode) {
self.register_attribute_methods(
attribute_node.name().as_str(),
Offset::from_rbs_location(&attribute_node.location()),
Offset::from_rbs_location(&attribute_node.name_location()),
self.collect_comments(attribute_node.comment()),
Self::flags(&attribute_node.annotations()),
self.parent_lexical_scope_id(),
attribute_node.kind(),
attribute_node.visibility(),
true,
true,
);
}

fn visit_method_definition_node(&mut self, def_node: &node::MethodDefinitionNode) {
let str_id = self.local_graph.intern_string(format!("{}()", def_node.name()));
let offset = Offset::from_rbs_location(&def_node.location());
Expand Down Expand Up @@ -1055,6 +1228,93 @@ mod tests {
});
}

#[test]
fn indexes_attribute_members_as_methods_without_retaining_types_or_instance_variables() {
let context = index_source({
"
class Foo
# Reader documentation
%a{deprecated}
attr_reader inferred: Integer
attr_reader absent(): Symbol
attr_writer explicit (@writer): String
attr_accessor accessor: bool
private
attr_reader inherited_visibility: Float
public
private attr_accessor self.class_value (@class_value): bool
end
"
});

assert_no_local_diagnostics!(&context);
assert_eq!(context.graph().definitions().len(), 9);

let method = |name: &str| {
context
.graph()
.definitions()
.values()
.find_map(|definition| match definition {
Definition::Method(method)
if context
.graph()
.strings()
.get(method.str_id())
.is_some_and(|string| string.as_str() == name) =>
{
Some(method)
}
_ => None,
})
.unwrap_or_else(|| panic!("expected `{name}` method definition"))
};

for name in [
"inferred()",
"absent()",
"explicit=()",
"accessor()",
"accessor=()",
"inherited_visibility()",
"class_value()",
"class_value=()",
] {
assert_eq!(method(name).signatures().as_slice().len(), 1);
}

for name in [
"inferred()",
"absent()",
"accessor()",
"inherited_visibility()",
"class_value()",
] {
assert!(method(name).signatures().as_slice()[0].is_empty());
}

for (name, parameter_name) in [
("explicit=()", "explicit"),
("accessor=()", "accessor"),
("class_value=()", "class_value"),
] {
let signature = &method(name).signatures().as_slice()[0];
let [Parameter::RequiredPositional(parameter)] = signature.as_ref() else {
panic!("expected `{name}` to have one required positional parameter");
};
assert_string_eq!(&context, parameter.str(), parameter_name);
assert_offset_string!(&context, parameter.offset(), parameter_name);
}

assert_eq!(method("class_value()").visibility(), &Visibility::Private);
assert_eq!(method("class_value=()").visibility(), &Visibility::Private);
assert_eq!(method("inherited_visibility()").visibility(), &Visibility::Private);
assert_method_has_receiver!(&context, method("class_value()"), "Foo");
assert_method_has_receiver!(&context, method("class_value=()"), "Foo");
assert_def_comments_eq!(&context, method("inferred()"), ["# Reader documentation"]);
assert!(method("inferred()").flags().contains(DefinitionFlags::DEPRECATED));
}

#[test]
fn index_alias_node() {
let context = index_source({
Expand Down
32 changes: 32 additions & 0 deletions rust/rubydex/src/resolution_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5218,6 +5218,38 @@ mod rbs_tests {
);
}

#[test]
fn rbs_attributes_create_method_declarations_without_instance_variable_declarations() {
let mut context = graph_test();
context.index_rbs_uri("file:///attributes.rbs", {
r"
class Foo
attr_reader reader: String
attr_writer writer (@writer): Integer
attr_accessor accessor(): bool
private attr_accessor self.class_value (@class_value): Symbol
end
"
});
context.resolve();

assert_no_diagnostics!(&context);
for method in [
"Foo#reader()",
"Foo#writer=()",
"Foo#accessor()",
"Foo#accessor=()",
"Foo::<Foo>#class_value()",
"Foo::<Foo>#class_value=()",
] {
assert_declaration_exists!(context, method);
assert_declaration_kind_eq!(context, method, "Method");
}
for instance_variable in ["Foo#@reader", "Foo#@writer", "Foo::<Foo>#@class_value"] {
assert_declaration_does_not_exist!(context, instance_variable);
}
}

#[test]
fn rbs_mixin_resolution() {
let mut context = graph_test();
Expand Down
Loading