ParserAutoComplete.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. /*
  2. * Copyright (c) 2021, Itamar S. <itamar8910@gmail.com>
  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 "ParserAutoComplete.h"
  27. #include <AK/Assertions.h>
  28. #include <AK/HashTable.h>
  29. #include <DevTools/HackStudio/LanguageServers/Cpp/ClientConnection.h>
  30. #include <LibCpp/AST.h>
  31. #include <LibCpp/Lexer.h>
  32. #include <LibCpp/Parser.h>
  33. #include <LibCpp/Preprocessor.h>
  34. #include <LibRegex/Regex.h>
  35. namespace LanguageServers::Cpp {
  36. ParserAutoComplete::ParserAutoComplete(ClientConnection& connection, const FileDB& filedb)
  37. : AutoCompleteEngine(connection, filedb)
  38. {
  39. }
  40. const ParserAutoComplete::DocumentData& ParserAutoComplete::get_or_create_document_data(const String& file)
  41. {
  42. auto absolute_path = filedb().to_absolute_path(file);
  43. if (!m_documents.contains(absolute_path)) {
  44. set_document_data(absolute_path, create_document_data_for(absolute_path));
  45. }
  46. return get_document_data(absolute_path);
  47. }
  48. const ParserAutoComplete::DocumentData& ParserAutoComplete::get_document_data(const String& file) const
  49. {
  50. auto absolute_path = filedb().to_absolute_path(file);
  51. auto document_data = m_documents.get(absolute_path);
  52. VERIFY(document_data.has_value());
  53. return *document_data.value();
  54. }
  55. OwnPtr<ParserAutoComplete::DocumentData> ParserAutoComplete::create_document_data_for(const String& file)
  56. {
  57. auto document = filedb().get(file);
  58. if (!document)
  59. return {};
  60. auto content = document->text();
  61. auto document_data = make<DocumentData>(document->text(), file);
  62. auto root = document_data->parser.parse();
  63. for (auto& path : document_data->preprocessor.included_paths()) {
  64. get_or_create_document_data(document_path_from_include_path(path));
  65. }
  66. #ifdef CPP_LANGUAGE_SERVER_DEBUG
  67. root->dump(0);
  68. #endif
  69. update_declared_symbols(*document_data);
  70. return move(document_data);
  71. }
  72. void ParserAutoComplete::set_document_data(const String& file, OwnPtr<DocumentData>&& data)
  73. {
  74. m_documents.set(filedb().to_absolute_path(file), move(data));
  75. }
  76. ParserAutoComplete::DocumentData::DocumentData(String&& _text, const String& _filename)
  77. : filename(_filename)
  78. , text(move(_text))
  79. , preprocessor(text.view())
  80. , parser(preprocessor.process().view(), filename)
  81. {
  82. }
  83. Vector<GUI::AutocompleteProvider::Entry> ParserAutoComplete::get_suggestions(const String& file, const GUI::TextPosition& autocomplete_position)
  84. {
  85. Cpp::Position position { autocomplete_position.line(), autocomplete_position.column() > 0 ? autocomplete_position.column() - 1 : 0 };
  86. dbgln_if(CPP_LANGUAGE_SERVER_DEBUG, "ParserAutoComplete position {}:{}", position.line, position.column);
  87. const auto& document = get_or_create_document_data(file);
  88. auto node = document.parser.node_at(position);
  89. if (!node) {
  90. dbgln_if(CPP_LANGUAGE_SERVER_DEBUG, "no node at position {}:{}", position.line, position.column);
  91. return {};
  92. }
  93. if (node->is_identifier()) {
  94. if (is_property(*node)) {
  95. return autocomplete_property(document, (MemberExpression&)(*node->parent()), document.parser.text_of_node(*node));
  96. }
  97. return autocomplete_name(document, *node, document.parser.text_of_node(*node));
  98. }
  99. if (is_empty_property(document, *node, position)) {
  100. VERIFY(node->is_member_expression());
  101. return autocomplete_property(document, (MemberExpression&)(*node), "");
  102. }
  103. String partial_text = String::empty();
  104. auto containing_token = document.parser.token_at(position);
  105. if (containing_token.has_value()) {
  106. partial_text = document.parser.text_of_token(containing_token.value());
  107. }
  108. return autocomplete_name(document, *node, partial_text.view());
  109. }
  110. NonnullRefPtrVector<Declaration> ParserAutoComplete::get_available_declarations(const DocumentData& document, const ASTNode& node) const
  111. {
  112. const Cpp::ASTNode* current = &node;
  113. NonnullRefPtrVector<Declaration> available_declarations;
  114. while (current) {
  115. available_declarations.append(current->declarations());
  116. current = current->parent();
  117. }
  118. available_declarations.append(get_declarations_in_outer_scope_including_headers(document));
  119. return available_declarations;
  120. }
  121. Vector<GUI::AutocompleteProvider::Entry> ParserAutoComplete::autocomplete_name(const DocumentData& document, const ASTNode& node, const StringView& partial_text) const
  122. {
  123. auto available_declarations = get_available_declarations(document, node);
  124. Vector<StringView> available_names;
  125. auto add_name = [&available_names](auto& name) {
  126. if (name.is_null() || name.is_empty())
  127. return;
  128. if (!available_names.contains_slow(name))
  129. available_names.append(name);
  130. };
  131. for (auto& decl : available_declarations) {
  132. if (decl.is_variable_or_parameter_declaration()) {
  133. add_name(((Cpp::VariableOrParameterDeclaration&)decl).m_name);
  134. }
  135. if (decl.is_struct_or_class()) {
  136. add_name(((Cpp::StructOrClassDeclaration&)decl).m_name);
  137. }
  138. if (decl.is_function()) {
  139. add_name(((Cpp::FunctionDeclaration&)decl).m_name);
  140. }
  141. }
  142. Vector<GUI::AutocompleteProvider::Entry> suggestions;
  143. for (auto& name : available_names) {
  144. if (name.starts_with(partial_text)) {
  145. suggestions.append({ name.to_string(), partial_text.length(), GUI::AutocompleteProvider::CompletionKind::Identifier });
  146. }
  147. }
  148. return suggestions;
  149. }
  150. Vector<GUI::AutocompleteProvider::Entry> ParserAutoComplete::autocomplete_property(const DocumentData& document, const MemberExpression& parent, const StringView partial_text) const
  151. {
  152. auto type = type_of(document, *parent.m_object);
  153. if (type.is_null()) {
  154. dbgln_if(CPP_LANGUAGE_SERVER_DEBUG, "Could not infer type of object");
  155. return {};
  156. }
  157. Vector<GUI::AutocompleteProvider::Entry> suggestions;
  158. for (auto& prop : properties_of_type(document, type)) {
  159. if (prop.name.starts_with(partial_text)) {
  160. suggestions.append({ prop.name, partial_text.length(), GUI::AutocompleteProvider::CompletionKind::Identifier });
  161. }
  162. }
  163. return suggestions;
  164. }
  165. bool ParserAutoComplete::is_property(const ASTNode& node) const
  166. {
  167. if (!node.parent()->is_member_expression())
  168. return false;
  169. auto& parent = (MemberExpression&)(*node.parent());
  170. return parent.m_property.ptr() == &node;
  171. }
  172. bool ParserAutoComplete::is_empty_property(const DocumentData& document, const ASTNode& node, const Position& autocomplete_position) const
  173. {
  174. if (!node.is_member_expression())
  175. return false;
  176. auto previous_token = document.parser.token_at(autocomplete_position);
  177. if (!previous_token.has_value())
  178. return false;
  179. return previous_token.value().type() == Token::Type::Dot;
  180. }
  181. String ParserAutoComplete::type_of_property(const DocumentData& document, const Identifier& identifier) const
  182. {
  183. auto& parent = (const MemberExpression&)(*identifier.parent());
  184. auto properties = properties_of_type(document, type_of(document, *parent.m_object));
  185. for (auto& prop : properties) {
  186. if (prop.name == identifier.m_name)
  187. return prop.type->m_name;
  188. }
  189. return {};
  190. }
  191. String ParserAutoComplete::type_of_variable(const Identifier& identifier) const
  192. {
  193. const ASTNode* current = &identifier;
  194. while (current) {
  195. for (auto& decl : current->declarations()) {
  196. if (decl.is_variable_or_parameter_declaration()) {
  197. auto& var_or_param = (VariableOrParameterDeclaration&)decl;
  198. if (var_or_param.m_name == identifier.m_name) {
  199. return var_or_param.m_type->m_name;
  200. }
  201. }
  202. }
  203. current = current->parent();
  204. }
  205. return {};
  206. }
  207. String ParserAutoComplete::type_of(const DocumentData& document, const Expression& expression) const
  208. {
  209. if (expression.is_member_expression()) {
  210. auto& member_expression = (const MemberExpression&)expression;
  211. return type_of_property(document, *member_expression.m_property);
  212. }
  213. if (!expression.is_identifier()) {
  214. VERIFY_NOT_REACHED(); // TODO
  215. }
  216. auto& identifier = (const Identifier&)expression;
  217. if (is_property(identifier))
  218. return type_of_property(document, identifier);
  219. return type_of_variable(identifier);
  220. }
  221. Vector<ParserAutoComplete::PropertyInfo> ParserAutoComplete::properties_of_type(const DocumentData& document, const String& type) const
  222. {
  223. auto declarations = get_declarations_in_outer_scope_including_headers(document);
  224. Vector<PropertyInfo> properties;
  225. for (auto& decl : declarations) {
  226. if (!decl.is_struct_or_class())
  227. continue;
  228. auto& struct_or_class = (StructOrClassDeclaration&)decl;
  229. if (struct_or_class.m_name != type)
  230. continue;
  231. for (auto& member : struct_or_class.m_members) {
  232. properties.append({ member.m_name, member.m_type });
  233. }
  234. }
  235. return properties;
  236. }
  237. NonnullRefPtrVector<Declaration> ParserAutoComplete::get_declarations_in_outer_scope_including_headers(const DocumentData& document) const
  238. {
  239. NonnullRefPtrVector<Declaration> declarations;
  240. for (auto& include : document.preprocessor.included_paths()) {
  241. auto included_document = get_document_data(document_path_from_include_path(include));
  242. declarations.append(get_declarations_in_outer_scope_including_headers(included_document));
  243. }
  244. for (auto& decl : document.parser.root_node()->declarations()) {
  245. declarations.append(decl);
  246. }
  247. return declarations;
  248. }
  249. String ParserAutoComplete::document_path_from_include_path(const StringView& include_path) const
  250. {
  251. static Regex<PosixExtended> library_include("<(.+)>");
  252. static Regex<PosixExtended> user_defined_include("\"(.+)\"");
  253. auto document_path_for_library_include = [&](const StringView& include_path) -> String {
  254. RegexResult result;
  255. if (!library_include.search(include_path, result))
  256. return {};
  257. auto path = result.capture_group_matches.at(0).at(0).view.u8view();
  258. return String::formatted("/usr/include/{}", path);
  259. };
  260. auto document_path_for_user_defined_include = [&](const StringView& include_path) -> String {
  261. RegexResult result;
  262. if (!user_defined_include.search(include_path, result))
  263. return {};
  264. return result.capture_group_matches.at(0).at(0).view.u8view();
  265. };
  266. auto result = document_path_for_library_include(include_path);
  267. if (result.is_null())
  268. result = document_path_for_user_defined_include(include_path);
  269. return result;
  270. }
  271. void ParserAutoComplete::on_edit(const String& file)
  272. {
  273. set_document_data(file, create_document_data_for(file));
  274. }
  275. void ParserAutoComplete::file_opened([[maybe_unused]] const String& file)
  276. {
  277. set_document_data(file, create_document_data_for(file));
  278. }
  279. Optional<GUI::AutocompleteProvider::ProjectLocation> ParserAutoComplete::find_declaration_of(const String& file_name, const GUI::TextPosition& identifier_position)
  280. {
  281. const auto& document = get_or_create_document_data(file_name);
  282. auto node = document.parser.node_at(Cpp::Position { identifier_position.line(), identifier_position.column() });
  283. if (!node) {
  284. dbgln_if(CPP_LANGUAGE_SERVER_DEBUG, "no node at position {}:{}", identifier_position.line(), identifier_position.column());
  285. return {};
  286. }
  287. auto decl = find_declaration_of(document, *node);
  288. if (!decl)
  289. return {};
  290. return GUI::AutocompleteProvider::ProjectLocation { decl->filename(), decl->start().line, decl->start().column };
  291. }
  292. RefPtr<Declaration> ParserAutoComplete::find_declaration_of(const DocumentData& document_data, const ASTNode& node) const
  293. {
  294. dbgln_if(CPP_LANGUAGE_SERVER_DEBUG, "find_declaration_of: {}", document_data.parser.text_of_node(node));
  295. auto declarations = get_available_declarations(document_data, node);
  296. for (auto& decl : declarations) {
  297. if (node.is_identifier() && decl.is_variable_or_parameter_declaration()) {
  298. if (((Cpp::VariableOrParameterDeclaration&)decl).m_name == static_cast<const Identifier&>(node).m_name)
  299. return decl;
  300. }
  301. if (node.is_type() && decl.is_struct_or_class()) {
  302. if (((Cpp::StructOrClassDeclaration&)decl).m_name == static_cast<const Type&>(node).m_name)
  303. return decl;
  304. }
  305. if (node.is_function_call() && decl.is_function()) {
  306. if (((Cpp::FunctionDeclaration&)decl).m_name == static_cast<const FunctionCall&>(node).m_name)
  307. return decl;
  308. }
  309. if (is_property(node) && decl.is_struct_or_class()) {
  310. for (auto& member : ((Cpp::StructOrClassDeclaration&)decl).m_members) {
  311. VERIFY(node.is_identifier());
  312. if (member.m_name == ((const Identifier&)node).m_name)
  313. return member;
  314. }
  315. }
  316. }
  317. return {};
  318. }
  319. void ParserAutoComplete::update_declared_symbols(const DocumentData& document)
  320. {
  321. Vector<GUI::AutocompleteProvider::Declaration> declarations;
  322. for (auto& decl : document.parser.root_node()->declarations()) {
  323. declarations.append({ decl.name(), { document.filename, decl.start().line, decl.start().column }, type_of_declaration(decl) });
  324. }
  325. set_declarations_of_document(document.filename, move(declarations));
  326. }
  327. GUI::AutocompleteProvider::DeclarationType ParserAutoComplete::type_of_declaration(const Declaration& decl)
  328. {
  329. if (decl.is_struct())
  330. return GUI::AutocompleteProvider::DeclarationType::Struct;
  331. if (decl.is_class())
  332. return GUI::AutocompleteProvider::DeclarationType::Class;
  333. if (decl.is_function())
  334. return GUI::AutocompleteProvider::DeclarationType::Function;
  335. if (decl.is_variable_declaration())
  336. return GUI::AutocompleteProvider::DeclarationType::Variable;
  337. return GUI::AutocompleteProvider::DeclarationType::Variable;
  338. }
  339. }