language_server.cpp 5.9 KB

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