Skip to content

[ty] Add initial implementation of goto definition for loads of local names #19123

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft
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
574 changes: 571 additions & 3 deletions crates/ty_ide/src/goto.rs

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion crates/ty_ide/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ mod markup;

pub use completion::completion;
pub use db::Db;
pub use goto::goto_type_definition;
pub use goto::{goto_definition, goto_type_definition};
pub use hover::hover;
pub use inlay_hints::inlay_hints;
pub use markup::MarkupKind;
Expand Down
2 changes: 1 addition & 1 deletion crates/ty_python_semantic/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ pub use program::{
PythonVersionWithSource, SearchPathSettings,
};
pub use python_platform::PythonPlatform;
pub use semantic_model::{Completion, HasType, NameKind, SemanticModel};
pub use semantic_model::{Completion, HasDefinition, HasType, NameKind, SemanticModel};
pub use site_packages::{PythonEnvironment, SitePackagesPaths, SysPrefixPathOrigin};
pub use util::diagnostics::add_inferred_python_version_hint_to_diagnostic;

Expand Down
39 changes: 38 additions & 1 deletion crates/ty_python_semantic/src/semantic_model.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
use ruff_db::files::{File, FilePath};
use ruff_db::source::line_index;
use ruff_python_ast as ast;
use ruff_python_ast::{self as ast, ExprContext};
use ruff_python_ast::{Expr, ExprRef, name::Name};
use ruff_source_file::LineIndex;

use crate::Db;
use crate::module_name::ModuleName;
use crate::module_resolver::{KnownModule, Module, resolve_module};
use crate::semantic_index::ast_ids::HasScopedUseId;
use crate::semantic_index::definition::Definition;
use crate::semantic_index::place::FileScopeId;
use crate::semantic_index::semantic_index;
use crate::types::ide_support::all_declarations_and_bindings;
Expand Down Expand Up @@ -175,6 +177,41 @@ pub struct Completion {
pub builtin: bool,
}

pub trait HasDefinition {
/// Returns the definitions of `self`.
///
/// ## Panics
/// May panic if `self` is from another file than `model`.
fn definitions<'db>(&self, model: &SemanticModel<'db>) -> Option<Vec<Definition<'db>>>;
}

impl HasDefinition for ast::ExprRef<'_> {
fn definitions<'db>(&self, model: &SemanticModel<'db>) -> Option<Vec<Definition<'db>>> {
match self {
ExprRef::Name(name) => match name.ctx {
ExprContext::Load => {
let index = semantic_index(model.db, model.file);
let file_scope = index.expression_scope_id(*self);
let scope = file_scope.to_scope_id(model.db, model.file);
let use_def = index.use_def_map(file_scope);
let use_id = self.scoped_use_id(model.db, scope);

Some(
use_def
.bindings_at_use(use_id)
.filter_map(|binding| binding.binding.definition())
.collect(),
)
}
Comment on lines +192 to +205
Copy link
Member

Choose a reason for hiding this comment

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

Oh hmm, I see what you mean based on what you mentioned on Discord. So, this implementation would be limited to only provide definitions if they're defined in the current scope, right? The following doesn't work:

x = 1


def _():
    x<CURSOR>

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yes correct.

ExprContext::Store => None,
Copy link
Member

Choose a reason for hiding this comment

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

This might a bit tricky because the definition that corresponds to this expression itself should also be included in the list of definitions. For example, here both definitions should be included:

def _():
    x = 1
    x<CURSOR> = 2

ExprContext::Del => None,
Copy link
Member

Choose a reason for hiding this comment

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

I think we can include ExprContext::Del here as the following should go to the definition of x:

def _():
    x = 1
    del x<CURSOR>

ExprContext::Invalid => None,
},
_ => None,
}
}
}

pub trait HasType {
/// Returns the inferred type of `self`.
///
Expand Down
3 changes: 2 additions & 1 deletion crates/ty_server/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use crate::session::{AllOptions, ClientOptions, Session};
use lsp_server::Connection;
use lsp_types::{
ClientCapabilities, DiagnosticOptions, DiagnosticServerCapabilities, HoverProviderCapability,
InlayHintOptions, InlayHintServerCapabilities, MessageType, ServerCapabilities,
InlayHintOptions, InlayHintServerCapabilities, MessageType, OneOf, ServerCapabilities,
TextDocumentSyncCapability, TextDocumentSyncKind, TextDocumentSyncOptions,
TypeDefinitionProviderCapability, Url,
};
Expand Down Expand Up @@ -183,6 +183,7 @@ impl Server {
..Default::default()
},
)),
definition_provider: Some(OneOf::Left(true)),
type_definition_provider: Some(TypeDefinitionProviderCapability::Simple(true)),
hover_provider: Some(HoverProviderCapability::Simple(true)),
inlay_hint_provider: Some(lsp_types::OneOf::Right(
Expand Down
3 changes: 3 additions & 0 deletions crates/ty_server/src/server/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@ pub(super) fn request(req: server::Request) -> Task {
>(
req, BackgroundSchedule::Worker
),
requests::GotoDefinitionRequestHandler::METHOD => background_document_request_task::<
requests::GotoDefinitionRequestHandler,
>(req, BackgroundSchedule::Worker),
requests::HoverRequestHandler::METHOD => background_document_request_task::<
requests::HoverRequestHandler,
>(req, BackgroundSchedule::Worker),
Expand Down
2 changes: 2 additions & 0 deletions crates/ty_server/src/server/api/requests.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
mod completion;
mod diagnostic;
mod goto_definition;
mod goto_type_definition;
mod hover;
mod inlay_hints;
Expand All @@ -8,6 +9,7 @@ mod workspace_diagnostic;

pub(super) use completion::CompletionRequestHandler;
pub(super) use diagnostic::DocumentDiagnosticRequestHandler;
pub(super) use goto_definition::GotoDefinitionRequestHandler;
pub(super) use goto_type_definition::GotoTypeDefinitionRequestHandler;
pub(super) use hover::HoverRequestHandler;
pub(super) use inlay_hints::InlayHintRequestHandler;
Expand Down
77 changes: 77 additions & 0 deletions crates/ty_server/src/server/api/requests/goto_definition.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
use std::borrow::Cow;

use lsp_types::GotoDefinitionParams;
use lsp_types::request::GotoDefinition;
use lsp_types::{GotoDefinitionResponse, Url};
use ruff_db::source::{line_index, source_text};
use ty_ide::goto_definition;
use ty_project::ProjectDatabase;

use crate::DocumentSnapshot;
use crate::document::{PositionExt, ToLink};
use crate::server::api::traits::{
BackgroundDocumentRequestHandler, RequestHandler, RetriableRequestHandler,
};
use crate::session::client::Client;

pub(crate) struct GotoDefinitionRequestHandler;

impl RequestHandler for GotoDefinitionRequestHandler {
type RequestType = GotoDefinition;
}
Comment on lines +17 to +21
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Everything in this file is a copy of goto_type_definition but changed to goto_definition


impl BackgroundDocumentRequestHandler for GotoDefinitionRequestHandler {
fn document_url(params: &GotoDefinitionParams) -> Cow<Url> {
Cow::Borrowed(&params.text_document_position_params.text_document.uri)
}

fn run_with_snapshot(
db: &ProjectDatabase,
snapshot: DocumentSnapshot,
_client: &Client,
params: GotoDefinitionParams,
) -> crate::server::Result<Option<GotoDefinitionResponse>> {
if snapshot.client_settings().is_language_services_disabled() {
return Ok(None);
}

let Some(file) = snapshot.file(db) else {
tracing::debug!("Failed to resolve file for {:?}", params);
return Ok(None);
};

let source = source_text(db, file);
let line_index = line_index(db, file);
let offset = params.text_document_position_params.position.to_text_size(
&source,
&line_index,
snapshot.encoding(),
);

let Some(ranged) = goto_definition(db, file, offset) else {
return Ok(None);
};

if snapshot
.resolved_client_capabilities()
.type_definition_link_support
Comment on lines +55 to +57
Copy link
Member

Choose a reason for hiding this comment

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

This should use the linkSupport value from the DefinitionClientCapabilities instead: https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocument_definition

You'll need to add a new definition_link_support field in ResolvedClientCapabilities which takes it's value from document.definition.link_support. Refer to how type_definition_link_support is being computed.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Hmm what distinguishes this from goto_type_definition, which has the same impl? (or is this a "also fix goto_type_definition"?)

Copy link
Member

Choose a reason for hiding this comment

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

These are the client capabilities, so if a client has link support for goto type definition but not for goto definition (for whatever reason), the server needs to respect that. These capabilities are provided to the server during initialization where we make note of all the things that the client supports through which the server needs to make certain decisions. This is one of them.

{
let src = Some(ranged.range);
let links: Vec<_> = ranged
.into_iter()
.filter_map(|target| target.to_link(db, src, snapshot.encoding()))
.collect();

Ok(Some(GotoDefinitionResponse::Link(links)))
} else {
let locations: Vec<_> = ranged
.into_iter()
.filter_map(|target| target.to_location(db, snapshot.encoding()))
.collect();

Ok(Some(GotoDefinitionResponse::Array(locations)))
}
}
}

impl RetriableRequestHandler for GotoDefinitionRequestHandler {}
Loading