Now I understand the structure. Let me look at the completion.rs file again more carefully to understand what's happening. The issue is that when you have a variable of an interface type and you type ex., the LSP doesn't provide completions for the interface methods.
Looking at get_instance_completions, it handles:
- Struct fields
- Methods registered for that type (like
Type.method_name)
But for interfaces, the methods are registered differently. Let me check how the completion is detecting the context.
In detect_dot_context, when you type ex. where ex: Example (an interface), it calls expression.get_type() and then type_name(&ty). If the type is a Nominal type with the interface's qualified name, it should return that name.
Then in get_instance_completions, it tries to:
- Find struct fields (only for Struct definitions)
- Find methods with prefix
type_id.method_name
The problem is that interface methods are registered with a different naming convention. Let me check how interface methods are named in the definitions.
From the methods.rs file, I can see that interface methods are registered as:
let method_qualified_name = format!("{}.{}.{}", module_id, interface_name, method_name);
So for an interface Example in module main, methods would be registered as main.Example.method_name.
But wait, the issue is that when you have a variable of interface type, the type name returned by type_name would be the interface's qualified name (e.g., main.Example). And then get_instance_completions would look for methods with prefix main.Example. which should match the interface methods.
Let me re-read the is_instance_method function:
fn is_instance_method(ty: &syntax::types::Type, type_id: &str) -> bool {
let func_ty = match ty {
syntax::types::Type::Forall { body, .. } => body,
other => other,
};
match func_ty {
syntax::types::Type::Function { params, .. } if !params.is_empty() => {
type_name(¶ms[0]).is_some_and(|name| name == type_id)
}
_ => false,
}
}
This checks if the first parameter of the function type has the given type_id. For interface methods, the first parameter should be the interface itself (or a receiver placeholder).
But wait, interface methods have a ReceiverPlaceholder as their first parameter, not the actual interface type. So is_instance_method would return false for interface methods.
Let me verify this by looking at how interface methods are created:
all_interface_methods.insert(name.clone(), substituted.with_receiver_placeholder());
So yes, interface methods have ReceiverPlaceholder as their first parameter, not the interface type itself. This means is_instance_method returns false for interface methods, and they're not included in the completions.
This is the bug! When completing for an interface type, we need to also include the interface methods, not just the methods whose receiver type matches the interface.
Let me also check if there's a way to detect if a type is an interface type:
if let Some(definition) = snapshot.definitions().get(type_id)
&& matches!(definition.body, DefinitionBody::Interface { .. })
So we can detect if a type is an interface by checking its definition.
Now let me understand the fix:
- In
get_instance_completions, when the type_id corresponds to an interface, we should also include the interface methods.
- Interface methods are registered with the qualified name
{module_id}.{interface_name}.{method_name} and have DefinitionBody::Value.
- The current
is_instance_method check will return false for interface methods (because of ReceiverPlaceholder), so they won't be included.
The fix should be to add interface methods to the completions when the type_id corresponds to an interface. Let me look at how to get the interface methods.
Actually, looking at the code more carefully, I see that the issue might be different. Let me trace through what happens:
- User types
ex. where ex: Example (interface)
detect_dot_context is called
- It finds the expression type, which is the interface type (e.g.,
main.Example)
- It returns
DotContext::Instance("main.Example")
- In the completion handler,
get_instance_completions("main.Example", ...) is called
- In
get_instance_completions:
- It doesn't find a struct definition for
main.Example (it's an interface)
- It looks for definitions with prefix
main.Example. - this would match interface methods like main.Example.example
- But then it checks
is_instance_method(definition.ty(), type_id) which returns false for interface methods (because they have ReceiverPlaceholder)
So the fix is to also include methods where the type corresponds to an interface. Let me think about the best approach:
Option 1: Modify is_instance_method to also check if the type is an interface type and the method is registered under that interface.
Option 2: Add a separate check in get_instance_completions to include interface methods when the type_id is an interface.
I think Option 2 is cleaner because it's more explicit and doesn't change the behavior of is_instance_method for other cases.
Let me also check if there are parent interfaces that need to be handled. Looking at the interface definition:
pub struct Interface {
pub name: EcoString,
pub generics: Vec<Generic>,
pub parents: Vec<Type>,
pub methods: HashMap<EcoString, Type>,
}
Interfaces can have parent interfaces, so we need to handle that too.
Let me write the fix:
pub(crate) fn get_instance_completions(
type_id: &str,
snapshot: &AnalysisSnapshot,
same_module: bool,
) -> Vec<CompletionItem> {
let mut items = Vec::new();
if let Some(syntax::program::Definition {
body: syntax::program::DefinitionBody::Struct { fields, .. },
..
}) = snapshot.definitions().get(type_id)
{
for field in fields {
if same_module || field.visibility.is_public() {
items.push(CompletionItem {
label: field.name.to_string(),
kind: Some(CompletionItemKind::FIELD),
detail: Some(field.ty.to_string()),
..Default::default()
});
}
}
}
let method_prefix = format!("{type_id}.");
for (qname, definition) in snapshot.definitions().iter() {
if let Some(method_name) = qname.strip_prefix(method_prefix.as_str())
&& !method_name.contains('.')
&& matches!(
definition.body,
syntax::program::DefinitionBody::Value { .. }
)
&& (is_instance_method(definition.ty(), type_id)
|| is_interface_method(definition.ty(), type_id, snapshot))
&& (same_module || definition.visibility().is_public())
{
items.push(CompletionItem {
label: method_name.to_string(),
kind: Some(CompletionItemKind::METHOD),
detail: Some(definition.ty().to_string()),
..Default::default()
});
}
}
items
}
/// Check if a method is an interface method (first parameter is ReceiverPlaceholder
/// and the type_id corresponds to the interface).
fn is_interface_method(
ty: &syntax::types::Type,
type_id: &str,
snapshot: &AnalysisSnapshot,
) -> bool {
// Check if the type_id corresponds to an interface definition
if !matches!(
snapshot.definitions().get(type_id).map(|d| &d.body),
Some(syntax::program::DefinitionBody::Interface { .. })
) {
return false;
}
// Check if the method has ReceiverPlaceholder as first parameter
let func_ty = match ty {
syntax::types::Type::Forall { body, .. } => body.as_ref(),
other => other,
};
matches!(
func_ty,
syntax::types::Type::Function {
params,
..
} if !params.is_empty()
&& matches!(
params.first(),
Some(syntax::types::Type::ReceiverPlaceholder)
)
)
}
Wait, but this approach has a problem. The is_instance_method function is used in both get_instance_completions and get_type_completions. In get_type_completions, we only want instance methods (methods whose receiver is the type), not static methods or interface methods.
Let me look at the structure more carefully:
get_instance_completions is called when completing after a dot access on an instance (e.g., ex.)
get_type_completions is called when completing after a dot access on a type (e.g., Example.)
For get_instance_completions:
- We want both struct fields and methods (including interface methods)
is_instance_method currently only matches methods where the receiver type is the instance type
- Interface methods have
ReceiverPlaceholder as their receiver, so they don't match
For get_type_completions:
- We want static methods (methods where the receiver type is NOT the instance type)
is_instance_method correctly filters these out
So the fix for get_instance_completions is to also include methods where:
- The type_id corresponds to an interface, AND
- The method has
ReceiverPlaceholder as its first parameter
But wait, I need to also consider that interface methods are registered with the qualified name {module_id}.{interface_name}.{method_name}. So when we iterate over all definitions with prefix main.Example., we should find the interface methods.
Let me verify this by checking how interface methods are registered:
let method_qualified_name = format!("{}.{}.{}", module_id, interface_name, method_name);
Yes, so for interface Example in module main, methods would be main.Example.method_name.
So the fix is correct. Let me also think about edge cases:
-
Inherited methods from parent interfaces: Interface methods from parent interfaces should also be included. The parent interface methods are registered with the parent's qualified name (e.g., main.Parent.method_name). We need to handle this case.
-
Generic interfaces: Interface generics are handled by the get_all_methods function in the store, but for LSP completions, we're just looking at definitions, not the store. So we need to make sure we're looking at the right definitions.
Let me think about how to handle parent interfaces:
When get_instance_completions("main.Example", ...) is called, we need to also look at methods from parent interfaces. We can do this by:
- Getting the interface definition
- Finding all parent interfaces
- Looking up their methods
Actually, let me look at how parent interface methods are registered. From the methods.rs file:
self.collect_interface_methods(
store,
parent_id,
parent_simple,
methods,
visited,
);
And in collect_interface_methods:
let method_qualified_name = format!("{}.{}.{}", module_id, interface_name, method_name);
So parent interface methods are registered with the parent's name, not the child's name. This means when we're completing for main.Example, we also need to look for methods from parent interfaces.
To do this, we need to:
- Get the interface definition for
main.Example
- For each parent interface, look for methods with prefix
main.{parent_name}.
Let me update the fix:
pub(crate) fn get_instance_completions(
type_id: &str,
snapshot: &AnalysisSnapshot,
same_module: bool,
) -> Vec<CompletionItem> {
let mut items = Vec::new();
let mut seen_methods = std::collections::HashSet::new();
if let Some(syntax::program::Definition {
body: syntax::program::DefinitionBody::Struct { fields, .. },
..
}) = snapshot.definitions().get(type_id)
{
for field in fields {
if same_module || field.visibility.is_public() {
items.push(CompletionItem {
label: field.name.to_string(),
kind: Some(CompletionItemKind::FIELD),
detail: Some(field.ty.to_string()),
..Default::default()
});
}
}
}
// Collect interface types to get their methods
let mut interfaces_to_check = Vec::new();
// Add the main type if it's an interface
if let Some(definition) = snapshot.definitions().get(type_id) {
if let syntax::program::DefinitionBody::Interface { definition: interface_def } = &definition.body {
interfaces_to_check.push((type_id.to_string(), interface_def.parents.clone()));
}
}
// Collect methods from all interfaces
while let Some((interface_id, parents)) = interfaces_to_check.pop() {
let method_prefix = format!("{interface_id}.");
for (qname, definition) in snapshot.definitions().iter() {
if let Some(method_name) = qname.strip_prefix(method_prefix.as_str())
&& !method_name.contains('.')
&& matches!(
definition.body,
syntax::program::DefinitionBody::Value { .. }
)
&& is_interface_method(definition.ty(), &interface_id, snapshot)
&& !items.iter().any(|i| i.label == method_name)
&& (same_module || definition.visibility().is_public())
{
items.push(CompletionItem {
label: method_name.to_string(),
kind: Some(CompletionItemKind::METHOD),
detail: Some(definition.ty().to_string()),
..Default::default()
});
}
}
// Add parent interfaces to check
for parent_ty in parents {
if let Some(parent_id) = parent_ty.get_qualified_id() {
if !interfaces_to_check.iter().any(|(id, _)| id == parent_id)
&& snapshot.definitions().get(parent_id).map(|d| &d.body)
== Some(&syntax::program::DefinitionBody::Interface { definition: std::mem::discriminant(&syntax::program::Interface {
name: EcoString::from(""),
generics: Vec::new(),
parents: Vec::new(),
methods: std::collections::HashMap::new(),
}) })
{
if let Some(parent_def) = snapshot.definitions().get(parent_id) {
if let syntax::program::DefinitionBody::Interface { definition: parent_interface } = &parent_def.body {
interfaces_to_check.push((parent_id.to_string(), parent_interface.parents.clone()));
}
}
}
}
}
}
// Also include instance methods (non-interface)
let method_prefix = format!("{type_id}.");
for (qname, definition) in snapshot.definitions().iter() {
if let Some(method_name) = qname.strip_prefix(method_prefix.as_str())
&& !method_name.contains('.')
&& matches!(
definition.body,
syntax::program::DefinitionBody::Value { .. }
)
&& is_instance_method(definition.ty(), type_id)
&& (same_module || definition.visibility().is_public())
&& !items.iter().any(|i| i.label == method_name)
{
items.push(CompletionItem {
label: method_name.to_string(),
kind: Some(CompletionItemKind::METHOD),
detail: Some(definition.ty().to_string()),
..Default::default()
});
}
}
items
}
Hmm, this is getting complicated. Let me simplify.
Actually, looking at the code again, I realize that the fix can be simpler. The key insight is:
- For struct types, we get struct fields and instance methods
- For interface types, we should get the interface methods
Interface methods are registered with the qualified name {module_id}.{interface_name}.{method_name}, so they will match the prefix main.Example..
The only issue is that is_instance_method returns false for interface methods (because they have ReceiverPlaceholder).
So the fix is:
- Check if the type_id is an interface type
- If so, include all methods with that prefix (interface methods don't need the
is_instance_method check)
Let me rewrite this more simply:
pub(crate) fn get_instance_completions(
type_id: &str,
snapshot: &AnalysisSnapshot,
same_module: bool,
) -> Vec<CompletionItem> {
let mut items = Vec::new();
// Check if this is an interface type
let is_interface = matches!(
snapshot.definitions().get(type_id).map(|d| &d.body),
Some(syntax::program::DefinitionBody::Interface { .. })
);
if !is_interface {
// Only add struct fields for non-interface types
if let Some(syntax::program::Definition {
body: syntax::program::DefinitionBody::Struct { fields, .. },
..
}) = snapshot.definitions().get(type_id)
{
for field in fields {
if same_module || field.visibility.is_public() {
items.push(CompletionItem {
label: field.name.to_string(),
kind: Some(CompletionItemKind::FIELD),
detail: Some(field.ty.to_string()),
..Default::default()
});
}
}
}
}
let method_prefix = format!("{type_id}.");
for (qname, definition) in snapshot.definitions().iter() {
if let Some(method_name) = qname.strip_prefix(method_prefix.as_str())
&& !method_name.contains('.')
&& matches!(
definition.body,
syntax::program::DefinitionBody::Value { .. }
)
&& (is_interface
|| is_instance_method(definition.ty(), type_id))
&& (same_module || definition.visibility().is_public())
{
items.push(CompletionItem {
label: method_name.to_string(),
kind: Some(CompletionItemKind::METHOD),
detail: Some(definition.ty().to_string()),
..Default::default()
});
}
}
items
}
Wait, but this still has the issue of parent interfaces. Let me check if parent interface methods are registered with the child interface's prefix or the parent interface's prefix.
From the methods.rs file:
fn collect_interface_methods(
&self,
store: &Store,
interface_id: &str,
source_name: &str,
methods: &mut Vec<(String, Type, String)>,
visited: &mut rustc_hash::FxHashSet<String>,
) {
if !visited.insert(interface_id.to_string()) {
return;
}
if let Some(interface) = store.get_interface(interface_id) {
for (method_name, method_ty) in &interface.methods {
methods.push((
method_name.to_string(),
method_ty.clone(),
source_name.to_string(),
));
}
for parent_ty in &interface.parents {
if let Some(parent_id) = parent_ty.get_qualified_id() {
let parent_simple = unqualified_name(parent_id);
self.collect_interface_methods(
store,
parent_id,
parent_simple,
methods,
visited,
);
}
}
}
}
And then:
let method_qualified_name = format!("{}.{}.{}", module_id, interface_name, method_name);
So parent interface methods are registered with the PARENT interface's name, not the child's name. This means when we're completing for main.Example (which might have a parent main.Container), the parent's methods would be registered as main.Container.method_name, not main.Example.method_name.
So we need to handle parent interfaces. Let me update the fix:
pub(crate) fn get_instance_completions(
type_id: &str,
snapshot: &AnalysisSnapshot,
same_module: bool,
) -> Vec<CompletionItem> {
let mut items = Vec::new();
// Check if this is an interface type and collect all interface prefixes
let is_interface = snapshot.definitions().get(type_id).map(|d| &d.body)
== Some(&syntax::program::DefinitionBody::Interface { .. });
let mut interface_prefixes = Vec::new();
if is_interface {
interface_prefixes.push(type_id.to_string());
// Collect all parent interfaces recursively
let mut visited = rustc_hash::FxHashSet::new();
let mut stack = vec![type_id.to_string()];
while let Some(current_id) = stack.pop() {
if !visited.insert(current_id.clone()) {
continue;
}
if let Some(syntax::program::Definition {
body: syntax::program::DefinitionBody::Interface { definition: interface_def },
..
}) = snapshot.definitions().get(¤t_id)
{
for parent_ty in &interface_def.parents {
if let Some(parent_id) = parent_ty.get_qualified_id() {
// Build the simple name for the parent
let parent_simple = simple_name_from_type_id(parent_id);
let prefix = format!("{}.{}", type_id.rsplit_once('.').map(|(module, _)| module).unwrap_or(¤t_id), parent_simple);
// Actually, we need to figure out the parent's qualified name
// Let me reconsider...
}
}
}
}
}
// ... rest of the function
}
Hmm, this is getting complicated. Let me think about this differently.
Actually, looking at the registration code more carefully:
let method_qualified_name = format!("{}.{}.{}", module_id, interface_name, method_name);
The interface_name here is the LOCAL name of the interface (not the qualified name). And module_id is the module where the interface is defined.
So for an interface Example defined in module main, methods would be main.Example.method_name.
For a parent interface Container also defined in module main, methods would be main.Container.method_name.
So when completing for main.Example, we need to:
- Look for methods with prefix
main.Example. (direct methods)
- Look for methods with prefix
main.Container. (inherited methods)
But how do we get the parent interface's qualified name? Let me look at the interface struct again:
pub struct Interface {
pub name: EcoString,
pub generics: Vec<Generic>,
pub parents: Vec<Type>,
pub methods: HashMap<EcoString, Type>,
}
The parents are Types, and they can be resolved to qualified names:
for parent_ty in &interface.parents {
if let Some(parent_id) = parent_ty.get_qualified_id() {
// parent_id is the qualified name like "main.Container"
}
}
So we can get the parent interface's qualified name and then look up its methods.
But here's the issue: methods are registered with the INTERFACE'S NAME, not the TYPE'S NAME. So for a parent interface with qualified name main.Container, methods would be main.Container.method_name.
Actually, let me re-read the code:
let method_qualified_name = format!("{}.{}.{}", module_id, interface_name, method_name);
The interface_name here is the LOCAL name of the interface. So for an interface Example in module main, the qualified name would be main.Example.
And from the Interface definition:
pub struct Interface {
pub name: EcoString, // Local name
pub parents: Vec<Type>, // Parent interface types
}
So the parent types would have their own qualified names. If a parent interface is Container in the same module, its qualified name would be main.Container.
So the fix is:
- For the main interface type, look for methods with prefix
{type_id}.
- For each parent interface type, look for methods with prefix
{parent_id}.
But there's another complication: what if the parent interface is in a different module? The methods would be registered with the PARENT's module, not the child's module.
Let me check the registration code again:
let method_qualified_name = format!("{}.{}.{}", module_id, interface_name, method_name);
The module_id is from self.cursor.module_id, which is the current module where the interface is being registered. So methods are registered in the CURRENT module, not the PARENT module.
But wait, when collecting parent interface methods:
let parent_simple = unqualified_name(parent_id);
self.collect_interface_methods(
store,
parent_id,
parent_simple,
methods,
visited,
);
The source_name is the simple (local) name of the parent. And then:
let method_qualified_name = format!("{}.{}.{}", module_id, interface_name, method_name);
So even parent interface methods are registered with the CHILD interface's local name. But that doesn't seem right...
Wait, let me re-read more carefully. The interface_name in the registration:
fn register_interface_methods(
&mut self,
store: &Store,
qualified_name: &str,
interface_name: &str,
name_span: Span,
method_defs: Vec<(EcoString, Type, Vec<String>, Vec<String>, Visibility)>,
visibility: Visibility,
)
So interface_name is passed in. Let me see how it's called:
self.register_interface_methods(
&store,
&qualified_name,
interface.name.as_str(),
name_span,
method_defs,
visibility,
);
And interface is from:
let interface = Interface {
name: type_name.clone(),
generics: generics.clone(),
parents: parent_interfaces,
methods: method_map,
};
So interface_name is the LOCAL name of the interface being defined, not the parent interface.
But in collect_interface_methods:
let method_qualified_name = format!("{}.{}.{}", module_id, interface_name, method_name);
So ALL methods (including inherited ones) are registered with the CHILD interface's name, not the parent's name.
This means when we're completing for main.Example, methods from parent interfaces should also have the prefix main.Example..
Let me verify this by looking at the full registration flow:
fn register_interface(
&mut self,
store: &Store,
interface: Box<Interface>,
name_span: Span,
) {
let interface_name = interface.name.to_string();
let qualified_name = format!("{}.{}", self.cursor.module_id, interface_name);
// ... validation ...
let method_defs = self.collect_interface_method_definitions(
&store,
&qualified_name,
&interface_name,
name_span,
);
self.register_interface_methods(
&store,
&qualified_name,
&interface_name,
name_span,
method_defs,
visibility,
);
}
fn register_interface_methods(
&mut self,
store: &Store,
qualified_name: &str,
interface_name: &str,
name_span: Span,
method_defs: Vec<(EcoString, Type, Vec<String>, Vec<String>, Visibility)>,
visibility: Visibility,
) {
// ... create the interface definition ...
// Register interface methods as Definition::Value entries
let module_id = self.cursor.module_id.clone();
for (method_name, method_ty, go_hints, allowed_lints) in method_defs {
let method_qualified_name = format!("{}.{}.{}", module_id, interface_name, method_name);
module.definitions.insert(
method_qualified_name.into(),
Definition {
// ...
},
);
}
}
fn collect_interface_method_definitions(
&mut self,
store: &Store,
qualified_name: &str,
interface_name: &str,
name_span: Span,
) -> Vec<(EcoString, Type, Vec<String>, Vec<String>, Visibility)> {
let mut method_defs = Vec::new();
let mut inherited_methods: Vec<(String, Type, String)> = Vec::new();
self.collect_interface_methods(
store,
qualified_name,
interface_name,
&mut inherited_methods,
&mut Default::default(),
);
// ... process inherited methods and add them to method_defs ...
}
OK so I see now. The collect_interface_method_definitions collects methods from both the interface and its parents, and then they're all registered with the CHILD interface's name. So when we complete for main.Example, we should find all methods with prefix main.Example..
This means my initial fix should work:
- Check if the type_id is an interface
- If so, include all methods with that prefix (not just those that match
is_instance_method)
But wait, there's still a subtle issue. The is_instance_method check is there to ensure that we don't include static methods (methods where the receiver is NOT the instance type). For interface types, all methods ARE instance methods (they all have self as the receiver, represented as ReceiverPlaceholder).
So the fix should be:
- Check if the type_id is an interface
- If so, include all methods with that prefix
- If not, use the existing
is_instance_method check
But there's another subtle issue. The type_id in get_instance_completions might not be the same as the interface's qualified name. For example, if the type is Ref<Example>, the type_id would be main.Example (after stripping the Ref wrapper), but the methods might be registered under main.Example.
Let me check how type_name handles this:
pub(crate) fn type_name(ty: &syntax::types::Type) -> Option<String> {
match ty {
syntax::types::Type::Nominal {
underlying_ty: Some(u),
..
} => type_name(u),
syntax::types::Type::Nominal { id, .. } => Some(id.to_string()),
syntax::types::Type::Compound {
kind: syntax::types::CompoundKind::Ref,
args,
} => args.first().and_then(type_name),
// ...
}
}
So type_name strips Ref wrappers. Good.
But what about generic instantiations? If the type is Example<T> (where Example is a generic interface), the type_name would return the qualified name. Let me check:
syntax::types::Type::Nominal { id, .. } => Some(id.to_string()),
Yes, it returns the id which should be the qualified name.
OK so I think the fix is correct. Let me also consider the case where the interface is in a different module. But that shouldn't matter because interface methods are registered in the module where the interface is defined, and the type_id would be the fully qualified name.
Let me also think about the case where the interface is a type parameter (bounded by an interface). But that's a different case and probably not relevant here.
OK let me finalize the fix. The key change is in get_instance_completions:
pub(crate) fn get_instance_completions(
type_id: &str,
snapshot: &AnalysisSnapshot,
same_module: bool,
) -> Vec<CompletionItem> {
let mut items = Vec::new();
// Check if this is an interface type
let is_interface = matches!(
snapshot.definitions().get(type_id).map(|d| &d.body),
Some(syntax::program::DefinitionBody::Interface { .. })
);
if !is_interface {
if let Some(syntax::program::Definition {
body: syntax::program::DefinitionBody::Struct { fields, .. },
..
}) = snapshot.definitions().get(type_id)
{
for field in fields {
if same_module || field.visibility.is_public() {
items.push(CompletionItem {
label: field.name.to_string(),
kind: Some(CompletionItemKind::FIELD),
detail: Some(field.ty.to_string()),
..Default::default()
});
}
}
}
}
let method_prefix = format!("{type_id}.");
for (qname, definition) in snapshot.definitions().iter() {
if let Some(method_name) = qname.strip_prefix(method_prefix.as_str())
&& !method_name.contains('.')
&& matches!(
definition.body,
syntax::program::DefinitionBody::Value { .. }
)
&& (is_interface || is_instance_method(definition.ty(), type_id))
&& (same_module || definition.visibility().is_public())
{
items.push(CompletionItem {
label: method_name.to_string(),
kind: Some(CompletionItemKind::METHOD),
detail: Some(definition.ty().to_string()),
..Default::default()
});
}
}
items
}
Wait, I also need to consider the case where get_type_completions might need to be updated. Let me check:
pub(crate) fn get_type_completions(
type_id: &str,
snapshot: &AnalysisSnapshot,
same_module: bool,
) -> Vec<CompletionItem> {
// ... enum variants ...
let method_prefix = format!("{type_id}.");
for (qname, definition) in snapshot.definitions().iter() {
if let Some(method_name) = qname.strip_prefix(method_prefix.as_str())
&& !method_name.contains('.')
&& matches!(definition.body, DefinitionBody::Value { .. })
&& !is_instance_method(definition.ty(), type_id)
&& (same_module || definition.visibility().is_public())
&& !items.iter().any(|i| i.label == method_name)
{
items.push(CompletionItem {
label: method_name.to_string(),
kind: Some(CompletionItemKind::METHOD),
detail: Some(definition.ty().to_string()),
..Default::default()
});
}
}
items
}
get_type_completions is used for type-level completions (e.g., Example. where Example is a type). It includes static methods (methods where the receiver is NOT the instance type).
For interface types, there are no static methods (all methods are instance methods), so get_type_completions doesn't need to be updated.
Actually wait, I need to double-check something. Let me look at how detect_dot_context works:
pub(crate) fn detect_dot_context(
file: &syntax::program::File,
offset: u32,
snapshot: &AnalysisSnapshot,
) -> Option<DotContext> {
let Expression::DotAccess {
expression, member, ..
} = find_expression_at(&file.items, offset.saturating_sub(1))?
else {
return None;
};
if !member.is_empty() {
if !matches!(
get_root_expression(expression),
Expression::Identifier {
binding_id: None,
..
}
) {
let ty = expression.get_type();
return type_name(&ty).map(DotContext::Instance);
}
return None;
}
// ... type-level completions ...
let ty = expression.get_type();
if let Some(type_id) = type_name(&ty) {
return Some(DotContext::Instance(type_id));
}
// ... self handling ...
None
}
So detect_dot_context returns DotContext::Instance(type_id) when the expression has a type. For ex. where ex: Example (interface), it should return DotContext::Instance("main.Example").
Then in the completion handler:
if let Some(context) = detect_dot_context(&file, offset, &snapshot) {
match context {
DotContext::Instance(type_id) => {
let same_module = type_id.starts_with(file.module_id.as_str())
&& type_id.as_bytes().get(file.module_id.len()) == Some(&b'.');
let items = get_instance_completions(&type_id, &snapshot, same_module);
return Ok(Some(CompletionResponse::Array(items)));
}
DotContext::TypeLevel(type_id) => {
// ...
}
}
}
So get_instance_completions is called with type_id = "main.Example" and same_module = true.
And in get_instance_completions, we check if main.Example is an interface type and include all methods with prefix main.Example..
This should work!
But wait, I need to also handle the case where the type_id is a type alias pointing to an interface. Let me check:
pub fn is_type_definition(&self) -> bool {
matches!(
self.body,
DefinitionBody::Struct { .. }
| DefinitionBody::Enum { .. }
| DefinitionBody::ValueEnum { .. }
| DefinitionBody::TypeAlias { .. }
)
}
The is_type_definition function returns true for TypeAlias, but the is_interface check in my fix only checks for Interface. So if someone has a type alias like type ExampleAlias = Example, the fix might not work.
Let me check if this is a valid concern. The type_name function would return the type alias's qualified name, not the underlying type's name. So if the user has ex: ExampleAlias and types ex., the type_id would be main.ExampleAlias, and we'd check if main.ExampleAlias is an interface type.
Since ExampleAlias is a type alias, it's not an interface, so is_interface would be false. But the underlying type is an interface, so we should still include interface methods.
This is a more complex case. Let me think about how to handle it:
- If
type_id is an interface, include interface methods.
- If
type_id is a type alias, get the underlying type and check if it's an interface.
For case 2, we'd need to follow the type alias chain to find the underlying type. This is similar to what get_all_methods does in the store:
// Type aliases inherit methods from the underlying type.
if let Some(definition) = self.get_definition(&qualified_name)
&& matches!(definition.body, DefinitionBody::TypeAlias { .. })
{
let alias_ty = &definition.ty;
let underlying = match alias_ty {
Type::Forall { body, .. } => body.as_ref(),
other => other,
};
// ...
}
But this is getting complicated. Let me first implement the basic fix and then handle type aliases as an edge case.
Actually, let me think about whether type aliases are a concern for this issue. The issue description says:
The LSP isn't providing completions for interfaces from either stdlib or user-defined.
So the issue is specifically about interfaces, not type aliases. Let me focus on the basic fix first.
Also, I need to consider the get_type_completions function. When would it be called for an interface type?
for prefix in [file.module_id.as_str(), "prelude"] {
let qualified = format!("{prefix}.{value}");
if let Some(definition) = snapshot.definitions().get(qualified.as_str())
&& definition.is_type_definition()
{
return Some(DotContext::TypeLevel(qualified));
}
}
is_type_definition returns false for interfaces, so DotContext::TypeLevel would not be returned for interfaces. This means get_type_completions is not called for interface types.
OK so my fix should work. Let me also check the case where we're completing for a struct field that is an interface type. For example:
struct Container {
item: Example,
}
fn example_call(c: Container) -> string {
c.item.
}
In this case, detect_dot_context would return DotContext::Instance("main.Example") (the type of c.item), and get_instance_completions would be called. My fix would handle this case correctly.
But wait, there's another issue. The detect_dot_context function checks if the expression is a DotAccess with an empty member:
let Expression::DotAccess {
expression, member, ..
} = find_expression_at(&file.items, offset.saturating_sub(1))?
else {
return None;
};
if !member.is_empty() {
// ...
}
So if the user types ex. (with a trailing dot but no member name), the member would be empty, and we'd proceed to the next check.
And if the user types ex. where ex is a simple identifier, the expression would be an Identifier with no binding_id, so the second check (get_root_expression) would return true and we'd skip to the next check.
Then we check if the expression's type is an interface type. If so, we return DotContext::Instance(type_id).
Wait, actually, looking at the code more carefully:
if !member.is_empty() {
if !matches!(
get_root_expression(expression),
Expression::Identifier {
binding_id: None,
..
}
) {
let ty = expression.get_type();
return type_name(&ty).map(DotContext::Instance);
}
return None;
}
If the member is not empty (e.g., ex.foo.), we only return DotContext::Instance if the expression is not a simple identifier. This is to avoid completing on module names.
If the member is empty (e.g., ex.), we proceed to the next checks.
Then we check if the expression is a module prefix:
if let Expression::Identifier { value, .. } = expression.as_ref() {
for prefix in [file.module_id.as_str(), "prelude"] {
let qualified = format!("{prefix}.{value}");
if let Some(definition) = snapshot.definitions().get(qualified.as_str())
&& definition.is_type_definition()
{
return Some(DotContext::TypeLevel(qualified));
}
}
}
This checks if the identifier is a module prefix (e.g., main. or prelude.) and if the value is a type definition. If so, we return DotContext::TypeLevel.
Then we check if the expression's type is a simple type:
let ty = expression.get_type();
if let Some(type_id) = type_name(&ty) {
return Some(DotContext::Instance(type_id));
}
If the expression has a type, we return DotContext::Instance.
For ex. where ex: Example (interface), the expression would be an Identifier with a type (the interface type), and type_name would return main.Example.
So the flow is:
member is empty (user typed ex.)
- Expression is an
Identifier, so we check if it's a module prefix
- If
ex is not a module prefix, we skip to the next check
- Expression has a type (the interface type), so we return
DotContext::Instance("main.Example")
Then get_instance_completions is called with type_id = "main.Example".
OK so my fix should work. Let me now also think about the get_type_completions function. If someone types Example. where Example is an interface, we'd get DotContext::TypeLevel("main.Example"), and get_type_completions would be called.
But wait, the is_type_definition check in detect_dot_context only returns true for structs, enums, value enums, and type aliases. So if someone types Example. where Example is an interface, we wouldn't get DotContext::TypeLevel.
Actually, let me re-read the check:
if let Some(definition) = snapshot.definitions().get(qualified.as_str())
&& definition.is_type_definition()
is_type_definition returns false for interfaces, so we'd skip this check. Then we'd proceed to:
let ty = expression.get_type();
if let Some(type_id) = type_name(&ty) {
return Some(DotContext::Instance(type_id));
}
But what is the type of Example (the identifier)? If Example is an interface type (not a value), it might have a Nominal type. Let me check...
Actually, I'm not sure what the type of a type identifier would be. Let me think about this.
In Lisette, you can write Example to refer to a type, not a value. The type of the identifier Example would be the type itself, which is a Nominal type.
But wait, in the context of Example., the expression Example is being used as a type, not a value. So the expression's type might be different.
Let me look at how expressions are represented:
enum Expression {
Identifier { binding_id: Option<u32>, value: EcoString, ty: Type, span: Span },
// ...
}
The ty field is the type of the expression. For a type identifier, the type might be the type itself or some special "type" kind.
I'm not sure how the type system represents this. Let me not worry about this edge case for now and focus on the main fix.
Actually, let me re-check. The issue is about completing after a dot on a variable of interface type, not on the type itself. So the main use case is:
fn example_call(ex: Example) -> string {
ex.
}
Where ex is a variable of interface type Example. In this case, detect_dot_context returns DotContext::Instance("main.Example"), and get_instance_completions is called.
My fix would handle this case correctly.
OK let me now also check the get_type_completions function for interfaces:
pub(crate) fn get_type_completions(
type_id: &str,
snapshot: &AnalysisSnapshot,
same_module: bool,
) -> Vec<CompletionItem> {
use syntax::program::DefinitionBody;
let mut items = Vec::new();
match snapshot.definitions().get(type_id).map(|d| &d.body) {
Some(DefinitionBody::Enum { variants, .. }) => {
// ... enum variants ...
}
Some(DefinitionBody::ValueEnum { variants, .. }) => {
// ... enum variants ...
}
_ => {}
}
let method_prefix = format!("{type_id}.");
for (qname, definition) in snapshot.definitions().iter() {
if let Some(method_name) = qname.strip_prefix(method_prefix.as_str())
&& !method_name.contains('.')
&& matches!(definition.body, DefinitionBody::Value { .. })
&& !is_instance_method(definition.ty(), type_id)
&& (same_module || definition.visibility().is_public())
&& !items.iter().any(|i| i.label == method_name)
{
items.push(CompletionItem {
label: method_name.to_string(),
kind: Some(CompletionItemKind::METHOD),
detail: Some(definition.ty().to_string()),
..Default::default()
});
}
}
items
}
get_type_completions is called for type-level completions. It includes enum variants and static methods (methods where the receiver is NOT the instance type).
For interface types, there are no enum variants, and all methods are instance methods (not static methods), so get_type_completions wouldn't return any methods for interfaces.
But should interfaces have type-level completions? If someone types Example. where Example is an interface, should we provide completions?
In most languages, you don't access members on a type name for interfaces. You access members on instances of the interface. So get_type_completions not returning methods for interfaces is probably correct.
OK so my fix is focused on get_instance_completions, which is the right place.
Now let me also think about edge cases:
-
Interface with parent interfaces: My fix checks if the type is an interface and includes all methods with the type's prefix. Since interface methods from parent interfaces are registered with the child interface's prefix, this should work.
-
Generic interfaces: Interface generics are handled by the type system, but for LSP completions, we're just looking at definitions. The type_id would be the fully qualified name of the interface (with or without type parameters). As long as the methods are registered with the same name, this should work.
-
Interfaces from different modules: Interface methods are registered in the module where the interface is defined. If an interface from module foo is used in module bar, the type_id would be foo.Example, and we'd look for methods with prefix foo.Example.. This should work as long as the definitions are accessible.
-
Type aliases for interfaces: If a type alias points to an interface, the type_id would be the alias's qualified name, not the interface's. My fix would not handle this case, but it's a more complex edge case that I'll address later.
-
Anonymous interface types (e.g., function parameters with interface bounds): This is a more complex case that's probably outside the scope of the current issue.
OK I think my fix is solid for the main use case. Let me now also consider whether I need to update get_type_completions.
Actually, wait. Let me re-read the issue:
LSP doesn't provide completion for interfaces
The LSP isn't providing completions for interfaces from either stdlib or user-defined.
The issue is that LSP completions don't work for interfaces at all. My fix should address this.
But I should also check if there are any other places where interfaces need to be handled. Let me look at the completion handler in lib.rs:
async fn completion(&self, params: CompletionParams) -> Result<Option<CompletionResponse>> {
// ... get snapshot and file ...
let offset = line_index.position_to_offset(position).ok_or_else(|| { ... })?;
let Some(expression) = find_expression_at(&file.items, offset).ok_or_else(|| { ... })?;
// ... handle different expression types ...
// Check for dot access context
if let Some(context) = detect_dot_context(&file, offset, &snapshot) {
match context {
DotContext::Instance(type_id) => {
let same_module = type_id.starts_with(file.module_id.as_str())
&& type_id.as_bytes().get(file.module_id.len()) == Some(&b'.');
let items = get_instance_completions(&type_id, &snapshot, same_module);
return Ok(Some(CompletionResponse::Array(items)));
}
DotContext::TypeLevel(type_id) => {
let same_module = type_id.starts_with(file.module_id.as_str())
&& type_id.as_bytes().get(file.module_id.len()) == Some(&b'.');
let items = get_type_completions(&type_id, &snapshot, same_module);
return Ok(Some(CompletionResponse::Array(items)));
}
}
}
// ... other completions (prefix, keywords, etc.) ...
}
So the completion flow is:
- Try to detect dot access context
- If found, return instance or type-level completions
- Otherwise, fall through to prefix completions (keywords, module definitions, bindings, etc.)
My fix modifies get_instance_completions to handle interfaces, which should be the right place.
Now let me also check if there's a module prefix completion case for interfaces:
let module_prefix = format!("{}.", file.module_id);
for (qname, definition) in snapshot.definitions().iter() {
if let Some(name) = qname.strip_prefix(&module_prefix)
&& !name.contains('.')
{
items.push(CompletionItem {
label: name.to_string(),
kind: Some(definition_to_completion_kind(definition)),
detail: Some(definition.ty().to_string()),
..Default::default()
});
}
}
This iterates over all definitions in the current module and includes those that don't have a dot in their name (i.e., top-level definitions). Interface methods would have a dot in their name (e.g., main.Example.method), so they wouldn't be included here.
This is correct behavior - interface methods shouldn't be listed as top-level definitions.
OK so my fix is focused on get_instance_completions, which is the right place.
Let me now write the actual fix. I'll modify the get_instance_completions function in completion.rs:
pub(crate) fn get_instance_completions(
type_id: &str,
snapshot: &AnalysisSnapshot,
same_module: bool,
) -> Vec<CompletionItem> {
let mut items = Vec::new();
// Check if the type_id corresponds to an interface
let is_interface = matches!(
snapshot.definitions().get(type_id).map(|d| &d.body),
Some(syntax::program::DefinitionBody::Interface { .. })
);
// Only include struct fields for non-interface types
if !is_interface {
if let Some(syntax::program::Definition {
body: syntax::program::DefinitionBody::Struct { fields, .. },
..
}) = snapshot.definitions().get(type_id)
{
for field in fields {
if same_module || field.visibility.is_public() {
items.push(CompletionItem {
label: field.name.to_string(),
kind: Some(CompletionItemKind::FIELD),
detail: Some(field.ty.to_string()),
..Default::default()
});
}
}
}
}
let method_prefix = format!("{type_id}.");
for (qname, definition) in snapshot.definitions().iter() {
if let Some(method_name) = qname.strip_prefix(method_prefix.as_str())
&& !method_name.contains('.')
&& matches!(
definition.body,
syntax::program::DefinitionBody::Value { .. }
)
// For interfaces, include all methods (which have ReceiverPlaceholder as receiver)
// For non-interfaces, use the existing instance method check
&& (is_interface || is_instance_method(definition.ty(), type_id))
&& (same_module || definition.visibility().is_public())
{
items.push(CompletionItem {
label: method_name.to_string(),
kind: Some(CompletionItemKind::METHOD),
detail: Some(definition.ty().to_string()),
..Default::default()
});
}
}
items
}
Wait, but there's still the issue of parent interfaces. If an interface has parent interfaces, are their methods registered with the child interface's prefix or the parent's?
Let me re-read the registration code:
fn collect_interface_method_definitions(
&mut self,
store: &Store,
qualified_name: &str,
interface_name: &str,
name_span: Span,
) -> Vec<(EcoString, Type, Vec<String>, Vec<String>, Visibility)> {
let mut method_defs: Vec<(EcoString, Type, Vec<String>, Vec<String>, Visibility)> = Vec::new();
let mut inherited_methods: Vec<(String, Type, String)> = Vec::new();
self.collect_interface_methods(
store,
qualified_name,
interface_name,
&mut inherited_methods,
&mut Default::default(),
);
// ... process inherited methods ...
for (method_name, method_ty, source_name) in &inherited_methods {
// ... create method definitions ...
}
method_defs
}
fn register_interface_methods(
&mut self,
store: &Store,
qualified_name: &str,
interface_name: &str,
name_span: Span,
method_defs: Vec<(EcoString, Type, Vec<String>, Vec<String>, Visibility)>,
visibility: Visibility,
) {
// ... create the interface definition ...
// Register interface methods as Definition::Value entries
let module_id = self.cursor.module_id.clone();
for (method_name, method_ty, go_hints, allowed_lints) in method_defs {
let method_qualified_name = format!("{}.{}.{}", module_id, interface_name, method_name);
module.definitions.insert(
method_qualified_name.into(),
Definition {
// ...
},
);
}
}
So the flow is:
collect_interface_method_definitions collects all methods (direct + inherited)
register_interface_methods registers them with the CHILD interface's name
This means all methods (including inherited ones) are registered with the child interface's prefix. So my fix should work for interfaces with parent interfaces.
Let me verify by tracing through an example:
interface Container {
fn get(self) -> int
}
interface Example: Container {
fn example(self, name: string) -> string
}
When Example is defined:
collect_interface_methods is called with interface_name = "Example"
- It collects direct methods:
example
- It collects inherited methods from
Container: get
- All methods are returned to
register_interface_methods
- Methods are registered as
main.Example.example and main.Example.get
So when completing for an Example instance, we'd find both example and get under the prefix main.Example..
Great, my fix should work!
Now let me also think about whether I need to handle the get_type_completions function. Should we provide type-level completions for interfaces?
For types, you might want to create an instance:
let x: Example. // Complete with the constructor?
But interfaces don't have constructors, so there's nothing to complete. So get_type_completions not returning anything for interfaces is correct.
Actually, wait. Let me check if interfaces should be considered as type definitions for the purpose of is_type_definition:
pub fn is_type_definition(&self) -> bool {
matches!(
self.body,
DefinitionBody::Struct { .. }
| DefinitionBody::Enum { .. }
| DefinitionBody::ValueEnum { .. }
| DefinitionBody::TypeAlias { .. }
)
}
The function returns false for interfaces. This means when someone types Example. where Example is an interface, we'd fall through to the next check:
let ty = expression.get_type();
if let Some(type_id) = type_name(&ty) {
return Some(DotContext::Instance(type_id));
}
And detect_dot_context would return DotContext::Instance("main.Example"), and get_instance_completions would be called.
But wait, what is the type of the expression Example (the interface name) when used in Example.? Is it a Nominal type or something else?
Actually, in Lisette, you can write Example to refer to the interface type itself (not an instance). So the type of Example would be the interface type, which is a Nominal type.
But then type_name would return main.Example, and detect_dot_context would return DotContext::Instance("main.Example").
Hmm, but this is a type-level access, not an instance-level access. Should we treat Example. as a type-level completion?
Let me think about this. In most languages, you can't access instance methods on a type name for interfaces. So Example. shouldn't return instance methods.
But Example. might be used for type-level operations (e.g., creating an instance). For interfaces, there are no constructors, so there's nothing to complete.
Actually, I think the current behavior is correct. When you type Example. where Example is an interface, you probably want to access instance methods, so DotContext::Instance is the right context.
OK let me now also consider the case where the interface is from a different module. If an interface from module foo is used, the type_id would be foo.Example. And we'd look for methods with prefix foo.Example..
If the methods are registered in module foo (not the current module), we'd still find them because snapshot.definitions() includes definitions from all loaded modules.
But the same_module check might filter them out. Let me check:
&& (same_module || definition.visibility().is_public())
If same_module is false (the type is from a different module), we'd still include public methods.
And for cross-module types:
let same_module = type_id.starts_with(file.module_id.as_str())
&& type_id.as_bytes().get(file.module_id.len()) == Some(&b'.');
If type_id is foo.Example and file.module_id is main, then same_module would be false.
So for cross-module interface types, we'd still include public methods. This is correct.
OK I think my fix is complete. Let me now also think about whether I need to handle the definition_to_completion_kind function:
pub(crate) fn definition_to_completion_kind(
definition: &syntax::program::Definition,
) -> CompletionItemKind {
use syntax::program::DefinitionBody;
match &definition.body {
DefinitionBody::Struct { .. } => CompletionItemKind::STRUCT,
DefinitionBody::Enum { .. } | DefinitionBody::ValueEnum { .. } => CompletionItemKind::ENUM,
DefinitionBody::Interface { .. } => CompletionItemKind::INTERFACE,
DefinitionBody::TypeAlias { .. } => CompletionItemKind::TYPE_PARAMETER,
DefinitionBody::Value { .. } => {
if matches!(
&definition.ty,
syntax::types::Type::Function { .. } | syntax::types::Type::Forall { .. }
) {
CompletionItemKind::FUNCTION
} else {
CompletionItemKind::CONSTANT
}
}
}
}
This is used for top-level completions (prefix completions). Interface methods are registered as DefinitionBody::Value, so they'd be classified as FUNCTION or CONSTANT depending on their type. This is correct.
OK I'm confident that my fix is correct. Let me now also consider whether there are any other issues I should address.
Looking at the issue description again:
LSP doesn't provide completion for interfaces
The LSP isn't providing completions for interfaces from either stdlib or user-defined.
My fix addresses the case where an instance of an interface type has a dot accessed on it. This should cover both stdlib and user-defined interfaces.
Let me also check if there's a stdlib interface that I can test with:
find /lisette -name "*.lis" | xargs grep -l "interface" | head -10
Let me do that next.
Now let me also check if there are any tests for LSP completion that I should run:
find /lisette -name "*.rs" | xargs grep -l "test.*completion\|completion.*test" | head -10
Let me also look for test files:
find /lisette -name "*test*.rs" -o -name "tests.rs" | head -20
Let me proceed with implementing and testing the fix.
Let me first look at how tests are organized and if there's a way to test LSP completions.
Now let me look at the tests.
<tool_call>
<function=bash_terminal>
<parameter=command>
grep -rn "test" /lisette/crates/lsp --include="*.rs" | grep -E "fn test|#[test]" | head -20
</tool_call>