def ConvertNotificationToMessage( self, request_data, notification ):
    if notification[ 'method' ] == 'language/status':
      message = notification[ 'params' ][ 'message' ]
      if notification[ 'params' ][ 'type' ] == 'Started':
        self._started_message_sent = True
        return responses.BuildDisplayMessageResponse(
          f'Initializing Java completer: { message }' )

      if not self._started_message_sent:
        return responses.BuildDisplayMessageResponse(
          f'Initializing Java completer: { message }' )

    return super().ConvertNotificationToMessage( request_data, notification )
Example #2
0
 def ConvertNotificationToMessage( self, request_data, notification ):
   if notification[ 'method' ] == 'experimental/serverStatus':
     message = notification[ 'params' ][ 'health' ]
     if message != 'ok' and notification[ 'params' ][ 'message' ] is not None:
       message += ' - ' + notification[ 'params' ][ 'message' ]
     return responses.BuildDisplayMessageResponse(
       f'Initializing Rust completer: { message }' )
   # TODO: Once rustup catches up, we should drop this notification.
   if notification[ 'method' ] == 'rust-analyzer/status':
     message = notification[ 'params' ]
     if message != 'invalid': # RA produces a better message for `invalid`
       return responses.BuildDisplayMessageResponse(
         f'Initializing Rust completer: { message }' )
   return super().ConvertNotificationToMessage( request_data, notification )
Example #3
0
    def GetType(self, request_data):
        try:
            hover_response = self.GetHoverResponse(request_data)['value']
        except language_server_completer.NoHoverInfoException:
            raise RuntimeError('Unknown type.')

        # rust-analyzer's hover format looks like this:
        #
        # ```rust
        # namespace
        # ```
        #
        # ```rust
        # type info
        # ```
        #
        # ___
        # docstring
        #
        # To extract the type info, we take everything up to `___` line,
        # then find the last occurence of "```" as the end index and "```rust"
        # as the start index and return the slice.
        hover_response = hover_response.split('\n___\n', 2)[0]
        start = hover_response.rfind('```rust\n') + len('```rust\n')
        end = hover_response.rfind('\n```')
        return responses.BuildDisplayMessageResponse(hover_response[start:end])
Example #4
0
 def ConvertNotificationToMessage(self, request_data, notification):
     if notification['method'] == 'rust-analyzer/status':
         message = notification['params']
         if message != 'invalid':  # RA produces a better message for `invalid`
             return responses.BuildDisplayMessageResponse(
                 'Initializing Rust completer: {}'.format(message))
     return super().ConvertNotificationToMessage(request_data, notification)
Example #5
0
 def GetType( self, request_data ):
   try:
     result = json.loads(
         self.GetHoverResponse( request_data )[ 'value' ] )[ 'signature' ]
     return responses.BuildDisplayMessageResponse( result )
   except language_server_completer.NoHoverInfoException:
     raise RuntimeError( 'Unknown type.' )
Example #6
0
    def GetDetailedDiagnostic(self, request_data):
        ts_diagnostics = self.GetTsDiagnosticsForCurrentFile(request_data)
        ts_diagnostics_on_line = list(
            filter(
                partial(IsLineInTsDiagnosticRange, request_data['line_num']),
                ts_diagnostics))

        if not ts_diagnostics_on_line:
            raise ValueError(NO_DIAGNOSTIC_MESSAGE)

        closest_ts_diagnostic = None
        distance_to_closest_ts_diagnostic = None

        line_value = request_data['line_value']
        current_byte_offset = request_data['column_num']

        for ts_diagnostic in ts_diagnostics_on_line:
            distance = GetByteOffsetDistanceFromTsDiagnosticRange(
                current_byte_offset, line_value, ts_diagnostic)
            if (not closest_ts_diagnostic
                    or distance < distance_to_closest_ts_diagnostic):
                distance_to_closest_ts_diagnostic = distance
                closest_ts_diagnostic = ts_diagnostic

        closest_diagnostic = self._TsDiagnosticToYcmdDiagnostic(
            request_data, closest_ts_diagnostic)

        return responses.BuildDisplayMessageResponse(closest_diagnostic.text_)
Example #7
0
    def OnUserCommand(self, arguments, request_data):
        memfilepath, cfile, _ = _CreateTmpFile(request_data)

        completion = _GetCompletions(cfile, memfilepath,
                                     request_data['line_num'],
                                     request_data['column_num'], 'def')

        if not completion:
            raise ValueError("No idea")

        completion = completion[0].split('\t')

        if len(completion) < 6:
            raise ValueError("No such symbol")

        _, ctype, fullname, rtype, ffile, row, col, docstr = completion

        if not arguments:
            raise ValueError(self.UserCommandsHelpMessage())
        elif arguments[0] == 'GetType':
            reply = '[' + TokenTypeMap.get(ctype, '') + '] (' + fullname + ')'
            if len(rtype) != 0:
                reply += ': ' + rtype + '\n--------------------------------------------------------------------------------\n' + FormatDocStr(
                    docstr)
            return responses.BuildDisplayMessageResponse(ToUtf8IfNeeded(reply))
        elif arguments[0] == 'GoTo':
            return responses.BuildGoToResponse(
                ToUtf8IfNeeded(ffile), int(row),
                int(col) + 1, ToUtf8IfNeeded(FormatDocStr(docstr)))
        else:
            raise RuntimeError(arguments)
Example #8
0
  def GetDetailedDiagnostic( self, request_data ):
    current_line = request_data[ 'line_num' ]
    current_column = request_data[ 'column_num' ]
    current_file = request_data[ 'filepath' ]

    if not self._diagnostic_store:
      raise ValueError( NO_DIAGNOSTIC_MESSAGE )

    diagnostics = self._diagnostic_store[ current_file ][ current_line ]
    if not diagnostics:
      raise ValueError( NO_DIAGNOSTIC_MESSAGE )

    closest_diagnostic = None
    distance_to_closest_diagnostic = 999

    # FIXME: all of these calculations are currently working with byte
    # offsets, which are technically incorrect. We should be working with
    # codepoint offsets, as we want the nearest character-wise diagnostic
    for diagnostic in diagnostics:
      distance = abs( current_column - diagnostic.location_.column_number_ )
      if distance < distance_to_closest_diagnostic:
        distance_to_closest_diagnostic = distance
        closest_diagnostic = diagnostic

    return responses.BuildDisplayMessageResponse(
      closest_diagnostic.text_ )
Example #9
0
    def _GetSemanticInfo(self, request_data, func, reparse=True):
        filename = request_data['filepath']
        if not filename:
            raise ValueError(INVALID_FILE_MESSAGE)

        gotofilename = filename
        filename = self._ParentForRequest(filename)

        flags = self._FlagsForRequest(request_data)
        if not flags:
            raise ValueError(NO_COMPILE_FLAGS_MESSAGE)

        files = self.GetUnsavedFilesVector(request_data)
        line = request_data['line_num']
        column = request_data['column_num']

        message = getattr(self._completer,
                          func)(ToUtf8IfNeeded(filename),
                                ToUtf8IfNeeded(gotofilename), line, column,
                                files, flags, reparse)

        if not message:
            message = "No semantic information available"

        return responses.BuildDisplayMessageResponse(message)
Example #10
0
    def GetType(self, request_data):
        hover_response = self.GetHoverResponse(request_data)

        # The LSP defines the hover response as either:
        # - a string
        # - a list of strings
        # - an object with keys language, value
        # - a list of objects with keys language, value
        # - an object with keys kind, value

        # That's right. All of the above.

        # However it would appear that dart only ever returns useful data when it
        # is a list of objects-with-keys-language-value, and the type information is
        # always in the first such list element, so we only handle that case and
        # throw any other time.

        # Strictly we seem to receive:
        # - [""]
        #   when there really is no documentation or type info available
        # - [{language:dart, value:<type info>}]
        #   when there only the type information is available
        # - [{language:dart, value:<type info>},
        #    'doc line 1',
        #    'doc line 2',
        #    ...]
        #   when there is type and documentation information available.

        try:
            get_type_dart = hover_response[0]['value']
        except (KeyError, TypeError, IndexError):
            raise RuntimeError('Unknown type')

        return responses.BuildDisplayMessageResponse(get_type_dart)
Example #11
0
    def GetType(self, request_data):
        hover_response = self.GetHoverResponse(request_data)

        for item in hover_response:
            if isinstance(item, dict) and 'value' in item:
                return responses.BuildDisplayMessageResponse(item['value'])

        raise RuntimeError('Unknown type.')
Example #12
0
    def _GetType(self, request_data):
        query = {
            'type': 'type',
        }

        response = self._GetResponse(query, request_data)

        return responses.BuildDisplayMessageResponse(response['type'])
Example #13
0
 def GetType(self, request_data):
     try:
         result = self.GetHoverResponse(request_data)['value']
         return responses.BuildDisplayMessageResponse(result)
     except RuntimeError as e:
         if e.args[0] == 'No hover information.':
             raise RuntimeError('Unknown type.')
         raise
Example #14
0
    def ConvertNotificationToMessage(self, request_data, notification):
        if notification['method'] == 'language/status':
            message = notification['params']['message']
            return responses.BuildDisplayMessageResponse(
                'Initializing Dart completer: {0}'.format(message))

        return super(DartCompleter, self).ConvertNotificationToMessage(
            request_data, notification)
Example #15
0
 def _GetType( self, request_data ):
   self._Reload( request_data )
   info = self._SendRequest( 'quickinfo', {
     'file':   request_data[ 'filepath' ],
     'line':   request_data[ 'line_num' ],
     'offset': request_data[ 'column_codepoint' ]
   } )
   return responses.BuildDisplayMessageResponse( info[ 'displayString' ] )
Example #16
0
  def _GetType( self, request_data ):
    request = self._DefaultParameters( request_data )
    request[ "IncludeDocumentation" ] = False

    result = self._GetResponse( '/typelookup', request )
    message = result[ "Type" ]

    return responses.BuildDisplayMessageResponse( message )
Example #17
0
 def _GetType( self, request_data ):
   with self._jedi_lock:
     definitions = self._GetJediScript( request_data ).goto_definitions()
     type_info = [ self._BuildTypeInfo( definition )
                   for definition in definitions ]
   type_info = ', '.join( type_info )
   if type_info:
     return responses.BuildDisplayMessageResponse( type_info )
   raise RuntimeError( 'No type information available.' )
Example #18
0
 def GetDoc( self, request_data ):
   assert self._settings[ 'hoverKind' ] == 'Structured'
   try:
     result = json.loads( self.GetHoverResponse( request_data )[ 'value' ] )
     docs = result[ 'signature' ] + '\n' + result[ 'fullDocumentation' ]
     return responses.BuildDisplayMessageResponse( docs.strip() )
   except RuntimeError as e:
     if e.args[ 0 ] == 'No hover information.':
       raise RuntimeError( 'No documentation available.' )
     raise
Example #19
0
 def GetType( self, request_data ):
   # Clangd's hover response looks like this:
   #     Declared in namespace <namespace name>
   #
   #     <declaration line>
   #
   #     <docstring>
   # GetType gets the first two lines.
   value = self.GetHoverResponse( request_data )[ 'value' ].split( '\n\n', 2 )
   return responses.BuildDisplayMessageResponse( '\n\n'.join( value[ : 2 ] ) )
Example #20
0
    def _GetType(self, request_data):
        request = self._DefaultParameters(request_data)
        request["IncludeDocumentation"] = False

        result = self._GetResponse('/typelookup', request)
        message = result["Type"]

        if not message:
            raise RuntimeError('No type info available.')
        return responses.BuildDisplayMessageResponse(message)
Example #21
0
  def _GetType( self, request_data ):
    with self._lock:
      self._Reload( request_data )
      seq = self._SendRequest( 'quickinfo', {
        'file':   request_data[ 'filepath' ],
        'line':   request_data[ 'line_num' ],
        'offset': request_data[ 'column_num' ]
      })

      info = self._ReadResponse( seq )[ 'body' ]
      return responses.BuildDisplayMessageResponse( info[ 'displayString' ] )
Example #22
0
 def _GetType( self, request_data ):
   with self._jedi_lock:
     line = request_data[ 'line_num' ]
     # Jedi expects columns to start at 0, not 1, and for them to be Unicode
     # codepoint offsets.
     column = request_data[ 'start_codepoint' ] - 1
     definitions = self._GetJediScript( request_data ).infer( line, column )
     type_info = [ self._BuildTypeInfo( definition )
                   for definition in definitions ]
   type_info = ', '.join( type_info )
   if type_info:
     return responses.BuildDisplayMessageResponse( type_info )
   raise RuntimeError( 'No type information available.' )
Example #23
0
    def _GetDoc(self, request_data, args):
        query = self._GetQueryWord(request_data)
        if query in self._raw_names: 
            type = self._raw_names[query]
            ret = subprocess.run(
                    ['cmake', '--help-{}'.format(type), query],
                    capture_output=True)
            if ret.returncode == 0:
                msg = ret.stdout.decode()
                return responses.BuildDetailedInfoResponse(str(request_data))

        msg = "Can't find doc for {}".format(query)
        return responses.BuildDisplayMessageResponse(msg)
Example #24
0
    def GetDetailedDiagnostic(self, request_data):
        self._UpdateServerWithFileContents(request_data)

        current_line_lsp = request_data['line_num'] - 1
        current_file = request_data['filepath']

        if not self._latest_diagnostics:
            return responses.BuildDisplayMessageResponse(
                'Diagnostics are not ready yet.')

        with self._server_info_mutex:
            diagnostics = list(
                self._latest_diagnostics[lsp.FilePathToUri(current_file)])

        if not diagnostics:
            return responses.BuildDisplayMessageResponse(
                'No diagnostics for current file.')

        current_column = lsp.CodepointsToUTF16CodeUnits(
            GetFileLines(request_data, current_file)[current_line_lsp],
            request_data['column_codepoint'])
        minimum_distance = None

        message = 'No diagnostics for current line.'
        for diagnostic in diagnostics:
            start = diagnostic['range']['start']
            end = diagnostic['range']['end']
            if current_line_lsp < start['line'] or end[
                    'line'] < current_line_lsp:
                continue
            point = {'line': current_line_lsp, 'character': current_column}
            distance = DistanceOfPointToRange(point, diagnostic['range'])
            if minimum_distance is None or distance < minimum_distance:
                message = diagnostic['message']
                if distance == 0:
                    break
                minimum_distance = distance

        return responses.BuildDisplayMessageResponse(message)
Example #25
0
 def GetType(self, request_data):
     try:
         hover_value = self.GetHoverResponse(request_data)['value']
         # Last "paragraph" contains the signature/declaration - i.e. type info.
         type_info = hover_value.split('\n\n')[-1]
         # The first line might contain the info of enclosing scope.
         if type_info.startswith('// In'):
             comment, signature = type_info.split('\n', 1)
             type_info = signature + '; ' + comment
         # Condense multi-line function declarations into one line.
         type_info = re.sub(r'\s+', ' ', type_info)
         return responses.BuildDisplayMessageResponse(type_info)
     except language_server_completer.NoHoverInfoException:
         raise RuntimeError('Unknown type.')
Example #26
0
 def GetType( self, request_data ):
   try:
     # Clangd's hover response looks like this:
     #     Declared in namespace <namespace name>
     #
     #     <declaration line>
     #
     #     <docstring>
     # GetType gets the first two lines.
     hover_value = self.GetHoverResponse( request_data )[ 'value' ]
     type_info = '\n\n'.join( hover_value.split( '\n\n', 2 )[ : 2 ] )
     return responses.BuildDisplayMessageResponse( type_info )
   except language_server_completer.NoHoverInfoException:
     raise RuntimeError( 'Unknown type.' )
Example #27
0
    def GetType(self, request_data):
        hover_response = self.GetHoverResponse(request_data)

        # The LSP defines the hover response as either:
        # - a string
        # - a list of strings
        # - an object with keys language, value
        # - a list of objects with keys language, value
        # - an object with keys kind, value

        # That's right. All of the above.

        # However it would appear that jdt.ls only ever returns useful data when it
        # is a list of objects-with-keys-language-value, and the type information is
        # always in the first such list element, so we only handle that case and
        # throw any other time.

        # Strictly we seem to receive:
        # - ""
        #   when there really is no documentation or type info available
        # - {language:java, value:<type info>}
        #   when there only the type information is available
        # - [{language:java, value:<type info>},
        #    'doc line 1',
        #    'doc line 2',
        #    ...]
        #   when there is type and documentation information available.

        if not hover_response:
            raise RuntimeError('Unknown type')

        if isinstance(hover_response, list):
            hover_response = hover_response[0]

        if (not isinstance(hover_response, dict)
                or hover_response.get('language') != 'java'
                or 'value' not in hover_response):
            raise RuntimeError('Unknown type')

        return responses.BuildDisplayMessageResponse(hover_response['value'])
Example #28
0
  def GetDetailedDiagnostic( self, request_data ):
    current_line = request_data[ 'line_num' ]
    current_column = request_data[ 'column_num' ]
    current_file = request_data[ 'filepath' ]

    if not self._diagnostic_store:
      raise ValueError( NO_DIAGNOSTIC_MESSAGE )

    diagnostics = self._diagnostic_store[ current_file ][ current_line ]
    if not diagnostics:
      raise ValueError( NO_DIAGNOSTIC_MESSAGE )

    closest_diagnostic = None
    distance_to_closest_diagnostic = 999

    for diagnostic in diagnostics:
      distance = abs( current_column - diagnostic.location_.column_number_ )
      if distance < distance_to_closest_diagnostic:
        distance_to_closest_diagnostic = distance
        closest_diagnostic = diagnostic

    return responses.BuildDisplayMessageResponse(
      closest_diagnostic.long_formatted_text_ )
Example #29
0
 def GetType(self, request_data):
     hover_response = self.GetHoverResponse(request_data)
     return responses.BuildDisplayMessageResponse(hover_response['value'])
Example #30
0
 def GetType( self, request_data ):
   try:
     result = self.GetHoverResponse( request_data )[ 'value' ]
     return responses.BuildDisplayMessageResponse( result )
   except language_server_completer.ResponseFailedException:
     raise RuntimeError( 'Unknown type.' )