- 
                Notifications
    You must be signed in to change notification settings 
- Fork 225
Add basic Goto Implementation Request support #644
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
      
      
            smheidrich
  wants to merge
  7
  commits into
  python-lsp:develop
  
    
      
        
          
  
    
      Choose a base branch
      
     
    
      
        
      
      
        
          
          
        
        
          
            
              
              
              
  
           
        
        
          
            
              
              
           
        
       
     
  
        
          
            
          
            
          
        
       
    
      
from
smheidrich:implement-basic-goto-implementation
  
      
      
   
  
    
  
  
  
 
  
      
    base: develop
Could not load branches
            
              
  
    Branch not found: {{ refName }}
  
            
                
      Loading
              
            Could not load tags
            
            
              Nothing to show
            
              
  
            
                
      Loading
              
            Are you sure you want to change the base?
            Some commits from the old base branch may be removed from the timeline,
            and old review comments may become outdated.
          
          
  
     Draft
                    Changes from all commits
      Commits
    
    
            Show all changes
          
          
            7 commits
          
        
        Select commit
          Hold shift + click to select a range
      
      84cb3a5
              
                Add basic Goto Implementation Request support
              
              
                smheidrich b7fb666
              
                Add test_implementation based on test_definition
              
              
                smheidrich 41a8852
              
                Fix test_implementations by using real on-FS file
              
              
                smheidrich 9c715d1
              
                Determine columns for found implementations
              
              
                smheidrich c1437e8
              
                Add Python 3.8 support for rope_implementations
              
              
                smheidrich f38d3ef
              
                Handle Rope find_implementations errors explicitly
              
              
                smheidrich b460f31
              
                Fix linting issues in rope_implementation & tests
              
              
                smheidrich File filter
Filter by extension
Conversations
          Failed to load comments.   
        
        
          
      Loading
        
  Jump to
        
          Jump to file
        
      
      
          Failed to load files.   
        
        
          
      Loading
        
  Diff view
Diff view
There are no files selected for viewing
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,74 @@ | ||
| # Copyright 2017-2020 Palantir Technologies, Inc. | ||
| # Copyright 2021- Python Language Server Contributors. | ||
| import logging | ||
| import os | ||
| from typing import Any, Dict, Tuple | ||
|  | ||
| from rope.base.project import Project | ||
| from rope.base.resources import Resource | ||
| from rope.contrib.findit import Location, find_implementations | ||
|  | ||
| from pylsp import hookimpl, uris | ||
|  | ||
| log = logging.getLogger(__name__) | ||
|  | ||
|  | ||
| @hookimpl | ||
| def pylsp_settings(): | ||
| # Default to enabled (no reason not to) | ||
| return {"plugins": {"rope_implementation": {"enabled": True}}} | ||
|  | ||
|  | ||
| @hookimpl | ||
| def pylsp_implementations(config, workspace, document, position): | ||
| offset = document.offset_at_position(position) | ||
| rope_config = config.settings(document_path=document.path).get("rope", {}) | ||
| rope_project = workspace._rope_project_builder(rope_config) | ||
| rope_resource = document._rope_resource(rope_config) | ||
|  | ||
| try: | ||
| impls = find_implementations(rope_project, rope_resource, offset) | ||
| except Exception as e: | ||
| log.debug("Failed to run Rope implementations finder: %s", e) | ||
| return [] | ||
|  | ||
| return [ | ||
| { | ||
| "uri": uris.uri_with( | ||
| document.uri, | ||
| path=os.path.join(workspace.root_path, impl.resource.path), | ||
| There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Under certain circumstances I seem to get URIs like  | ||
| ), | ||
| "range": _rope_location_to_range(impl, rope_project), | ||
| } | ||
| for impl in impls | ||
| ] | ||
|  | ||
|  | ||
| def _rope_location_to_range( | ||
| location: Location, rope_project: Project | ||
| ) -> Dict[str, Any]: | ||
| # NOTE: This assumes the result is confined to a single line, which should | ||
| # always be the case here because Python doesn't allow splitting up | ||
| # identifiers across more than one line. | ||
| start_column, end_column = _rope_region_to_columns( | ||
| location.region, location.lineno, location.resource, rope_project | ||
| ) | ||
| return { | ||
| "start": {"line": location.lineno - 1, "character": start_column}, | ||
| "end": {"line": location.lineno - 1, "character": end_column}, | ||
| } | ||
|  | ||
|  | ||
| def _rope_region_to_columns( | ||
| offsets: Tuple[int, int], line: int, rope_resource: Resource, rope_project: Project | ||
| ) -> Tuple[int, int]: | ||
| """ | ||
| Convert pair of offsets from start of file to columns within line. | ||
|  | ||
| Assumes both offsets reside within the same line and will return nonsense | ||
| for the end offset if this isn't the case. | ||
| """ | ||
| line_start_offset = rope_project.get_pymodule(rope_resource).lines.get_line_start( | ||
| line | ||
| ) | ||
| return offsets[0] - line_start_offset, offsets[1] - line_start_offset | ||
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,30 @@ | ||
| from abc import ABC, abstractmethod | ||
|  | ||
|  | ||
| class Animal(ABC): | ||
| @abstractmethod | ||
| def breathe(self): | ||
| pass | ||
|  | ||
| @property | ||
| @abstractmethod | ||
| def size(self) -> str: | ||
| pass | ||
|  | ||
| class WingedAnimal(Animal): | ||
| @abstractmethod | ||
| def fly(self, destination): | ||
| pass | ||
|  | ||
| class Bird(WingedAnimal): | ||
| def breathe(self): | ||
| print("*inhales like a bird*") | ||
|  | ||
| def fly(self, destination): | ||
| print("*flies like a bird*") | ||
|  | ||
| @property | ||
| def size(self) -> str: | ||
| return "bird-sized" | ||
|  | ||
| print("not a method at all") | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,102 @@ | ||
| # Copyright 2017-2020 Palantir Technologies, Inc. | ||
| # Copyright 2021- Python Language Server Contributors. | ||
|  | ||
| from pathlib import Path | ||
|  | ||
| import pytest | ||
|  | ||
| import test | ||
| from pylsp import uris | ||
| from pylsp.config.config import Config | ||
| from pylsp.plugins.rope_implementation import pylsp_implementations | ||
| from pylsp.workspace import Workspace | ||
|  | ||
|  | ||
| # We use a real file because the part of Rope that this feature uses | ||
| # (`rope.findit.find_implementations`) *always* loads files from the | ||
| # filesystem, in contrast to e.g. `code_assist` which takes a `source` argument | ||
| # that can be more easily faked. | ||
| # An alternative to using real files would be `unittest.mock.patch`, but that | ||
| # ends up being more trouble than it's worth... | ||
| @pytest.fixture | ||
| def examples_dir_path() -> Path: | ||
| # In Python 3.12+, this should be obtained using `importlib.resources`, | ||
| # but as we need to support older versions, we do it the hacky way: | ||
| return Path(test.__file__).parent / "data/implementations_examples" | ||
|  | ||
|  | ||
| @pytest.fixture | ||
| def doc_uri(examples_dir_path: Path) -> str: | ||
| return uris.from_fs_path(str(examples_dir_path / "example.py")) | ||
|  | ||
|  | ||
| # Similarly to the above, we need our workspace to point to the actual location | ||
| # on the filesystem containing the example modules, so we override the fixture: | ||
| @pytest.fixture | ||
| def workspace(examples_dir_path: Path, endpoint) -> None: | ||
| ws = Workspace(uris.from_fs_path(str(examples_dir_path)), endpoint) | ||
| ws._config = Config(ws.root_uri, {}, 0, {}) | ||
| yield ws | ||
| ws.close() | ||
|  | ||
|  | ||
| def test_implementations(config, workspace, doc_uri) -> None: | ||
| # Over 'fly' in WingedAnimal.fly | ||
| cursor_pos = {"line": 15, "character": 8} | ||
|  | ||
| # The implementation of 'Bird.fly' | ||
| def_range = { | ||
| "start": {"line": 22, "character": 8}, | ||
| "end": {"line": 22, "character": 11}, | ||
| } | ||
|  | ||
| doc = workspace.get_document(doc_uri) | ||
| assert [{"uri": doc_uri, "range": def_range}] == pylsp_implementations( | ||
| config, workspace, doc, cursor_pos | ||
| ) | ||
|  | ||
|  | ||
| def test_implementations_skipping_one_class(config, workspace, doc_uri) -> None: | ||
| # Over 'Animal.breathe' | ||
| cursor_pos = {"line": 5, "character": 8} | ||
|  | ||
| # The implementation of 'breathe', skipping intermediate classes | ||
| def_range = { | ||
| "start": {"line": 19, "character": 8}, | ||
| "end": {"line": 19, "character": 15}, | ||
| } | ||
|  | ||
| doc = workspace.get_document(doc_uri) | ||
| assert [{"uri": doc_uri, "range": def_range}] == pylsp_implementations( | ||
| config, workspace, doc, cursor_pos | ||
| ) | ||
|  | ||
|  | ||
| @pytest.mark.xfail( | ||
| reason="not implemented upstream (Rope)", strict=True, raises=AssertionError | ||
| ) | ||
| def test_property_implementations(config, workspace, doc_uri) -> None: | ||
| # Over 'Animal.size' | ||
| cursor_pos = {"line": 10, "character": 9} | ||
|  | ||
| # The property implementation 'Bird.size' | ||
| def_range = { | ||
| "start": {"line": 26, "character": 8}, | ||
| "end": {"line": 26, "character": 12}, | ||
| } | ||
|  | ||
| doc = workspace.get_document(doc_uri) | ||
| assert [{"uri": doc_uri, "range": def_range}] == pylsp_implementations( | ||
| config, workspace, doc, cursor_pos | ||
| ) | ||
|  | ||
|  | ||
| def test_implementations_not_a_method(config, workspace, doc_uri) -> None: | ||
| # Over 'print(...)' call | ||
| cursor_pos = {"line": 29, "character": 0} | ||
|  | ||
| doc = workspace.get_document(doc_uri) | ||
|  | ||
| # Rope produces an error because we're not over a method, which we then | ||
| # turn into an empty result list: | ||
| assert [] == pylsp_implementations(config, workspace, doc, cursor_pos) | 
      
      Oops, something went wrong.
        
    
  
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I guess it would also make sense to add
find_definition?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If you mean using
rope.contrib.findit.find_definitionto implement the LSPtextDocument/definitionrequest, that one is already implemented inpython-lsp-serverusing Jedi, so I don't think adding an additional Rope-powered implementation makes sense. But maybe I misunderstand it?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes, that's what I meant. My reasoning is twofold:
Of note, rope is disabled by default in general because it is hard to guarantee it works well and does not conflict with jedi (e.g. by de-duplciating responses).
For the best UX for an average user I think it would be best to add
textDocument/implementationusing jedi, but I would not object to adding one with rope as in this PR.I was just curious as to your reasoning for adding only
textDocument/implementationand not alsotextDocument/definitionwhich would be my choice if I was adding a rope version for it.Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
(Comment deleted because it doesn't make sense, give me a minute while I write a new one)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I originally wrote a response disagreeing but there was a glaring mistake in it because I overlooked that the current Rope
find_implementationsimplementation is much buggier than I thought: E.g. for a file likeusing Rope's
find_implementationson thea.f()call will go toB.ffor some reason 😕It works well for moving between overridden methods within a class hierarchy, where it nicely complements the Jedi
textDocument/definition, which always moves "up", by moving "down" instead.But my guess is that it would take quite a lot of effort to fix Rope's
find_implementationsso it works correctly when used on method calls as well 😔I'll open an issue but this PR should be on hold until it's fixed, no point merging something that's fundamentally buggy from day 1.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Rope issue created:
findit.find_implementationson method call finds implementation for different subclass python-rope/rope#812