A semantic search engine for source code https://bitshift.benkurtovic.com/
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 
 

95 linhas
2.6 KiB

  1. import json, pygments.lexers as pgl, sys, socket, struct
  2. from ..languages import LANGS
  3. from .python import parse_py
  4. _all__ = ["parse"]
  5. class UnsupportedFileError(Exception):
  6. pass
  7. def _lang(codelet):
  8. """
  9. Private function to identify the language of a codelet.
  10. :param codelet: The codelet object to identified.
  11. :type code: Codelet
  12. .. todo::
  13. Modify function to incorporate tags from stackoverflow.
  14. """
  15. if codelet.filename is not None:
  16. try:
  17. return LANGS.index(
  18. pgl.get_lexer_for_filename(codelet.filename).name)
  19. except:
  20. raise UnsupportedFileError('Could not find a lexer for the codelet\'s filename')
  21. return LANGS.index(pgl.guess_lexer(codelet.code))
  22. def _recv_data(server_socket):
  23. """
  24. Private function to read string response from a server. It reads a certain
  25. amount of data based on the size it is sent from the server.
  26. :param server_socket: The server that the client is connected to, and will,
  27. read from.
  28. :type code: socket.ServerSocket
  29. """
  30. recv_size = 8192
  31. total_data = []; size_data = cur_data = ''
  32. total_size = 0; size = sys.maxint
  33. while total_size < size:
  34. cur_data = server_socket.recv(recv_size)
  35. if not total_data:
  36. if len(size_data) > 4:
  37. size_data += cur_data
  38. size = struct.unpack('>i', size_data[:4])[0]
  39. recv_size = size
  40. if recv_size > sys.maxint: recv_size = sys.maxint
  41. total_data.append(size_data[4:])
  42. else:
  43. size_data += cur_data
  44. else:
  45. total_data.append(cur_data)
  46. total_size = sum([len(s) for s in total_data])
  47. server_socket.close()
  48. return ''.join(total_data);
  49. def parse(codelet):
  50. """
  51. Dispatches the codelet to the correct parser based on its language.
  52. It is the job of the respective parsers to accumulate data about the
  53. code and to convert it into a string representing a python dict.
  54. The codelet is then given dict as its 'symbols' field.
  55. :param codelet: The codelet object to parsed.
  56. :type code: Codelet
  57. """
  58. lang = _lang(codelet); source = codelet.code
  59. codelet.language = lang
  60. server_socket_number = 5000 + lang
  61. if lang == LANGS.index('Python'):
  62. parse_py(codelet)
  63. else:
  64. server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  65. server_socket.connect(("localhost", server_socket_number))
  66. server_socket.send("%d\n%s" % (len(source), source));
  67. symbols = json.loads(_recv_data(server_socket))
  68. codelet.symbols = symbols