language_server.cpp 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include "language_server/language_server.h"
  5. #include "clang-tools-extra/clangd/Protocol.h"
  6. #include "toolchain/diagnostics/null_diagnostics.h"
  7. #include "toolchain/lex/tokenized_buffer.h"
  8. #include "toolchain/parse/node_kind.h"
  9. #include "toolchain/parse/tree.h"
  10. #include "toolchain/source/source_buffer.h"
  11. namespace Carbon::LS {
  12. void LanguageServer::OnDidOpenTextDocument(
  13. clang::clangd::DidOpenTextDocumentParams const& params) {
  14. files_.emplace(params.textDocument.uri.file(), params.textDocument.text);
  15. }
  16. void LanguageServer::OnDidChangeTextDocument(
  17. clang::clangd::DidChangeTextDocumentParams const& params) {
  18. // full text is sent if full sync is specified in capabilities.
  19. assert(params.contentChanges.size() == 1);
  20. std::string file = params.textDocument.uri.file().str();
  21. files_[file] = params.contentChanges[0].text;
  22. }
  23. void LanguageServer::OnInitialize(
  24. clang::clangd::NoParams const& client_capabilities,
  25. clang::clangd::Callback<llvm::json::Object> cb) {
  26. llvm::json::Object capabilities{{"documentSymbolProvider", true},
  27. {"textDocumentSync", /*Full=*/1}};
  28. llvm::json::Object reply{{"capabilities", std::move(capabilities)}};
  29. cb(reply);
  30. };
  31. auto LanguageServer::onNotify(llvm::StringRef method, llvm::json::Value value)
  32. -> bool {
  33. if (method == "exit") {
  34. return false;
  35. }
  36. if (auto handler = handlers_.NotificationHandlers.find(method);
  37. handler != handlers_.NotificationHandlers.end()) {
  38. handler->second(std::move(value));
  39. } else {
  40. clang::clangd::log("unhandled notification {0}", method);
  41. }
  42. return true;
  43. }
  44. auto LanguageServer::onCall(llvm::StringRef method, llvm::json::Value params,
  45. llvm::json::Value id) -> bool {
  46. if (auto handler = handlers_.MethodHandlers.find(method);
  47. handler != handlers_.MethodHandlers.end()) {
  48. // TODO: improve this if add threads
  49. handler->second(std::move(params),
  50. [&](llvm::Expected<llvm::json::Value> reply) {
  51. transport_->reply(id, std::move(reply));
  52. });
  53. } else {
  54. transport_->reply(
  55. id, llvm::make_error<clang::clangd::LSPError>(
  56. "method not found", clang::clangd::ErrorCode::MethodNotFound));
  57. }
  58. return true;
  59. }
  60. auto LanguageServer::onReply(llvm::json::Value /*id*/,
  61. llvm::Expected<llvm::json::Value> /*result*/)
  62. -> bool {
  63. return true;
  64. }
  65. // Returns the text of first child of kind Parse::NodeKind::Name.
  66. static auto getName(Parse::Tree& p, Parse::Node node)
  67. -> std::optional<llvm::StringRef> {
  68. for (auto ch : p.children(node)) {
  69. if (p.node_kind(ch) == Parse::NodeKind::Name) {
  70. return p.GetNodeText(ch);
  71. }
  72. }
  73. return std::nullopt;
  74. }
  75. void LanguageServer::OnDocumentSymbol(
  76. clang::clangd::DocumentSymbolParams const& params,
  77. clang::clangd::Callback<std::vector<clang::clangd::DocumentSymbol>> cb) {
  78. llvm::vfs::InMemoryFileSystem vfs;
  79. auto file = params.textDocument.uri.file().str();
  80. vfs.addFile(file, /*mtime=*/0,
  81. llvm::MemoryBuffer::getMemBufferCopy(files_.at(file)));
  82. auto buf = SourceBuffer::CreateFromFile(vfs, file, NullDiagnosticConsumer());
  83. auto lexed = Lex::TokenizedBuffer::Lex(*buf, NullDiagnosticConsumer());
  84. auto parsed = Parse::Tree::Parse(lexed, NullDiagnosticConsumer(), nullptr);
  85. std::vector<clang::clangd::DocumentSymbol> result;
  86. for (const auto& node : parsed.postorder()) {
  87. clang::clangd::SymbolKind symbol_kind;
  88. switch (parsed.node_kind(node)) {
  89. case Parse::NodeKind::FunctionDeclaration:
  90. case Parse::NodeKind::FunctionDefinitionStart:
  91. symbol_kind = clang::clangd::SymbolKind::Function;
  92. break;
  93. case Parse::NodeKind::Namespace:
  94. symbol_kind = clang::clangd::SymbolKind::Namespace;
  95. break;
  96. case Parse::NodeKind::InterfaceDefinitionStart:
  97. case Parse::NodeKind::NamedConstraintDefinitionStart:
  98. symbol_kind = clang::clangd::SymbolKind::Interface;
  99. break;
  100. case Parse::NodeKind::ClassDefinitionStart:
  101. symbol_kind = clang::clangd::SymbolKind::Class;
  102. break;
  103. default:
  104. continue;
  105. }
  106. if (auto name = getName(parsed, node)) {
  107. auto tok = parsed.node_token(node);
  108. clang::clangd::Position pos{lexed.GetLineNumber(tok) - 1,
  109. lexed.GetColumnNumber(tok) - 1};
  110. clang::clangd::DocumentSymbol symbol{
  111. .name = std::string(*name),
  112. .kind = symbol_kind,
  113. .range = {.start = pos, .end = pos},
  114. .selectionRange = {.start = pos, .end = pos},
  115. };
  116. result.push_back(symbol);
  117. }
  118. }
  119. cb(result);
  120. }
  121. void LanguageServer::Start() {
  122. auto transport =
  123. clang::clangd::newJSONTransport(stdin, llvm::outs(), nullptr, true);
  124. LanguageServer ls(std::move(transport));
  125. clang::clangd::LSPBinder binder(ls.handlers_, ls);
  126. binder.notification("textDocument/didOpen", &ls,
  127. &LanguageServer::OnDidOpenTextDocument);
  128. binder.notification("textDocument/didChange", &ls,
  129. &LanguageServer::OnDidChangeTextDocument);
  130. binder.method("initialize", &ls, &LanguageServer::OnInitialize);
  131. binder.method("textDocument/documentSymbol", &ls,
  132. &LanguageServer::OnDocumentSymbol);
  133. auto error = ls.transport_->loop(ls);
  134. llvm::errs() << "Error: " << error << "\n";
  135. }
  136. } // namespace Carbon::LS