AutoComplete.cpp 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. /*
  2. * Copyright (c) 2020, the SerenityOS developers.
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include "AutoComplete.h"
  27. #include <AK/Assertions.h>
  28. #include <AK/HashTable.h>
  29. #include <LibRegex/Regex.h>
  30. #include <Userland/DevTools/HackStudio/LanguageServers/ClientConnection.h>
  31. namespace LanguageServers::Shell {
  32. RefPtr<::Shell::Shell> AutoComplete::s_shell {};
  33. AutoComplete::AutoComplete(ClientConnection& connection, const FileDB& filedb)
  34. : AutoCompleteEngine(connection, filedb, true)
  35. {
  36. }
  37. const AutoComplete::DocumentData& AutoComplete::get_or_create_document_data(const String& file)
  38. {
  39. auto absolute_path = filedb().to_absolute_path(file);
  40. if (!m_documents.contains(absolute_path)) {
  41. set_document_data(absolute_path, create_document_data_for(absolute_path));
  42. }
  43. return get_document_data(absolute_path);
  44. }
  45. const AutoComplete::DocumentData& AutoComplete::get_document_data(const String& file) const
  46. {
  47. auto absolute_path = filedb().to_absolute_path(file);
  48. auto document_data = m_documents.get(absolute_path);
  49. VERIFY(document_data.has_value());
  50. return *document_data.value();
  51. }
  52. OwnPtr<AutoComplete::DocumentData> AutoComplete::create_document_data_for(const String& file)
  53. {
  54. auto document = filedb().get(file);
  55. if (!document)
  56. return {};
  57. auto content = document->text();
  58. auto document_data = make<DocumentData>(document->text(), file);
  59. for (auto& path : document_data->sourced_paths())
  60. get_or_create_document_data(path);
  61. update_declared_symbols(*document_data);
  62. return document_data;
  63. }
  64. void AutoComplete::set_document_data(const String& file, OwnPtr<DocumentData>&& data)
  65. {
  66. m_documents.set(filedb().to_absolute_path(file), move(data));
  67. }
  68. AutoComplete::DocumentData::DocumentData(String&& _text, String _filename)
  69. : filename(move(_filename))
  70. , text(move(_text))
  71. , node(parse())
  72. {
  73. }
  74. const Vector<String>& AutoComplete::DocumentData::sourced_paths() const
  75. {
  76. if (all_sourced_paths.has_value())
  77. return all_sourced_paths.value();
  78. struct : public ::Shell::AST::NodeVisitor {
  79. void visit(const ::Shell::AST::CastToCommand* node) override
  80. {
  81. auto& inner = node->inner();
  82. if (inner->is_list()) {
  83. if (auto* list = dynamic_cast<const ::Shell::AST::ListConcatenate*>(inner.ptr())) {
  84. auto& entries = list->list();
  85. if (entries.size() == 2 && entries.first()->is_bareword() && static_ptr_cast<::Shell::AST::BarewordLiteral>(entries.first())->text() == "source") {
  86. auto& filename = entries[1];
  87. if (filename->would_execute())
  88. return;
  89. auto name_list = const_cast<::Shell::AST::Node*>(filename.ptr())->run(nullptr)->resolve_as_list(nullptr);
  90. StringBuilder builder;
  91. builder.join(" ", name_list);
  92. sourced_files.set(builder.build());
  93. }
  94. }
  95. }
  96. ::Shell::AST::NodeVisitor::visit(node);
  97. }
  98. HashTable<String> sourced_files;
  99. } visitor;
  100. node->visit(visitor);
  101. Vector<String> sourced_paths;
  102. for (auto& entry : visitor.sourced_files)
  103. sourced_paths.append(move(entry));
  104. all_sourced_paths = move(sourced_paths);
  105. return all_sourced_paths.value();
  106. }
  107. NonnullRefPtr<::Shell::AST::Node> AutoComplete::DocumentData::parse() const
  108. {
  109. ::Shell::Parser parser { text };
  110. if (auto node = parser.parse())
  111. return node.release_nonnull();
  112. return ::Shell::AST::create<::Shell::AST::SyntaxError>(::Shell::AST::Position {}, "Unable to parse file");
  113. }
  114. size_t AutoComplete::resolve(const AutoComplete::DocumentData& document, const GUI::TextPosition& position)
  115. {
  116. size_t offset = 0;
  117. if (position.line() > 0) {
  118. auto first = true;
  119. size_t line = 0;
  120. for (auto& line_view : document.text.split_limit('\n', position.line() + 1, true)) {
  121. if (line == position.line())
  122. break;
  123. if (first)
  124. first = false;
  125. else
  126. ++offset; // For the newline.
  127. offset += line_view.length();
  128. ++line;
  129. }
  130. }
  131. offset += position.column() + 1;
  132. return offset;
  133. }
  134. Vector<GUI::AutocompleteProvider::Entry> AutoComplete::get_suggestions(const String& file, const GUI::TextPosition& position)
  135. {
  136. dbgln_if(SH_LANGUAGE_SERVER_DEBUG, "AutoComplete position {}:{}", position.line(), position.column());
  137. const auto& document = get_or_create_document_data(file);
  138. size_t offset_in_file = resolve(document, position);
  139. ::Shell::AST::HitTestResult hit_test = document.node->hit_test_position(offset_in_file);
  140. if (!hit_test.matching_node) {
  141. dbgln_if(SH_LANGUAGE_SERVER_DEBUG, "no node at position {}:{}", position.line(), position.column());
  142. return {};
  143. }
  144. auto completions = const_cast<::Shell::AST::Node*>(document.node.ptr())->complete_for_editor(shell(), offset_in_file, hit_test);
  145. Vector<GUI::AutocompleteProvider::Entry> entries;
  146. for (auto& completion : completions)
  147. entries.append({ completion.text_string, completion.input_offset });
  148. return entries;
  149. }
  150. void AutoComplete::on_edit(const String& file)
  151. {
  152. set_document_data(file, create_document_data_for(file));
  153. }
  154. void AutoComplete::file_opened([[maybe_unused]] const String& file)
  155. {
  156. set_document_data(file, create_document_data_for(file));
  157. }
  158. Optional<GUI::AutocompleteProvider::ProjectLocation> AutoComplete::find_declaration_of(const String& file_name, const GUI::TextPosition& identifier_position)
  159. {
  160. dbgln_if(SH_LANGUAGE_SERVER_DEBUG, "find_declaration_of({}, {}:{})", file_name, identifier_position.line(), identifier_position.column());
  161. const auto& document = get_or_create_document_data(file_name);
  162. auto position = resolve(document, identifier_position);
  163. auto result = document.node->hit_test_position(position);
  164. if (!result.matching_node) {
  165. dbgln_if(SH_LANGUAGE_SERVER_DEBUG, "no node at position {}:{}", identifier_position.line(), identifier_position.column());
  166. return {};
  167. }
  168. if (!result.matching_node->is_bareword()) {
  169. dbgln_if(SH_LANGUAGE_SERVER_DEBUG, "no bareword at position {}:{}", identifier_position.line(), identifier_position.column());
  170. return {};
  171. }
  172. auto name = static_ptr_cast<::Shell::AST::BarewordLiteral>(result.matching_node)->text();
  173. auto& declarations = all_declarations();
  174. for (auto& entry : declarations) {
  175. for (auto& declaration : entry.value) {
  176. if (declaration.name == name)
  177. return declaration.position;
  178. }
  179. }
  180. return {};
  181. }
  182. void AutoComplete::update_declared_symbols(const DocumentData& document)
  183. {
  184. struct Visitor : public ::Shell::AST::NodeVisitor {
  185. explicit Visitor(const String& filename)
  186. : filename(filename)
  187. {
  188. }
  189. void visit(const ::Shell::AST::VariableDeclarations* node) override
  190. {
  191. for (auto& entry : node->variables()) {
  192. auto literal = entry.name->leftmost_trivial_literal();
  193. if (!literal)
  194. continue;
  195. String name;
  196. if (literal->is_bareword())
  197. name = static_ptr_cast<::Shell::AST::BarewordLiteral>(literal)->text();
  198. if (!name.is_empty()) {
  199. dbgln("Found variable {}", name);
  200. declarations.append({ move(name), { filename, entry.name->position().start_line.line_number, entry.name->position().start_line.line_column }, GUI::AutocompleteProvider::DeclarationType::Variable });
  201. }
  202. }
  203. ::Shell::AST::NodeVisitor::visit(node);
  204. }
  205. void visit(const ::Shell::AST::FunctionDeclaration* node) override
  206. {
  207. dbgln("Found function {}", node->name().name);
  208. declarations.append({ node->name().name, { filename, node->position().start_line.line_number, node->position().start_line.line_column }, GUI::AutocompleteProvider::DeclarationType::Function });
  209. }
  210. const String& filename;
  211. Vector<GUI::AutocompleteProvider::Declaration> declarations;
  212. } visitor { document.filename };
  213. document.node->visit(visitor);
  214. set_declarations_of_document(document.filename, move(visitor.declarations));
  215. }
  216. }