ParserAutoComplete.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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 <LibCpp/AST.h>
  30. #include <LibCpp/Lexer.h>
  31. #include <LibCpp/Parser.h>
  32. #include <LibCpp/Preprocessor.h>
  33. #include <LibRegex/Regex.h>
  34. // #define AUTOCOMPLETE_VERBOSE
  35. #ifdef AUTOCOMPLETE_VERBOSE
  36. # define VERBOSE(fmt, ...) dbgln(fmt, ##__VA_ARGS__)
  37. #else
  38. # define VERBOSE(fmt, ...) \
  39. do { \
  40. } while (0)
  41. #endif
  42. namespace LanguageServers::Cpp {
  43. ParserAutoComplete::ParserAutoComplete(const FileDB& filedb)
  44. : AutoCompleteEngine(filedb)
  45. {
  46. }
  47. const ParserAutoComplete::DocumentData& ParserAutoComplete::get_or_create_document_data(const String& file)
  48. {
  49. auto absolute_path = filedb().to_absolute_path(file);
  50. if (!m_documents.contains(absolute_path)) {
  51. set_document_data(absolute_path, create_document_data_for(absolute_path));
  52. }
  53. return get_document_data(absolute_path);
  54. }
  55. const ParserAutoComplete::DocumentData& ParserAutoComplete::get_document_data(const String& file) const
  56. {
  57. auto absolute_path = filedb().to_absolute_path(file);
  58. auto document_data = m_documents.get(absolute_path);
  59. ASSERT(document_data.has_value());
  60. return *document_data.value();
  61. }
  62. OwnPtr<ParserAutoComplete::DocumentData> ParserAutoComplete::create_document_data_for(const String& file)
  63. {
  64. auto document = filedb().get(file);
  65. ASSERT(document);
  66. auto content = document->text();
  67. auto document_data = make<DocumentData>(document->text());
  68. auto root = document_data->parser.parse();
  69. for (auto& path : document_data->preprocessor.included_paths()) {
  70. get_or_create_document_data(document_path_from_include_path(path));
  71. }
  72. #ifdef DEBUG_AUTOCOMPLETE
  73. root->dump(0);
  74. #endif
  75. return move(document_data);
  76. }
  77. void ParserAutoComplete::set_document_data(const String& file, OwnPtr<DocumentData>&& data)
  78. {
  79. m_documents.set(filedb().to_absolute_path(file), move(data));
  80. }
  81. ParserAutoComplete::DocumentData::DocumentData(String&& _text)
  82. : text(move(_text))
  83. , preprocessor(text.view())
  84. , parser(preprocessor.process().view())
  85. {
  86. }
  87. Vector<GUI::AutocompleteProvider::Entry> ParserAutoComplete::get_suggestions(const String& file, const GUI::TextPosition& autocomplete_position)
  88. {
  89. ASSERT(autocomplete_position.column() > 0);
  90. Cpp::Position position { autocomplete_position.line(), autocomplete_position.column() - 1 };
  91. VERBOSE("ParserAutoComplete position {}:{}", position.line, position.column);
  92. const auto& document = get_or_create_document_data(file);
  93. auto node = document.parser.node_at(position);
  94. if (!node) {
  95. VERBOSE("no node at position {}:{}", position.line, position.column);
  96. return {};
  97. }
  98. if (!node->is_identifier()) {
  99. if (is_empty_property(document, *node, position)) {
  100. ASSERT(node->is_member_expression());
  101. return autocomplete_property(document, (MemberExpression&)(*node), "");
  102. }
  103. return {};
  104. }
  105. if (is_property(*node)) {
  106. return autocomplete_property(document, (MemberExpression&)(*node->parent()), document.parser.text_of_node(*node));
  107. }
  108. return autocomplete_identifier(document, *node);
  109. }
  110. Vector<GUI::AutocompleteProvider::Entry> ParserAutoComplete::autocomplete_identifier(const DocumentData& document, const ASTNode& node) const
  111. {
  112. const Cpp::ASTNode* current = &node;
  113. NonnullRefPtrVector<Cpp::Declaration> available_declarations;
  114. while (current) {
  115. available_declarations.append(current->declarations());
  116. current = current->parent();
  117. }
  118. Vector<StringView> available_names;
  119. auto add_name = [&available_names](auto& name) {
  120. if (name.is_null() || name.is_empty())
  121. return;
  122. if (!available_names.contains_slow(name))
  123. available_names.append(name);
  124. };
  125. for (auto& decl : available_declarations) {
  126. if (decl.is_variable_or_parameter_declaration()) {
  127. add_name(((Cpp::VariableOrParameterDeclaration&)decl).m_name);
  128. }
  129. if (decl.is_struct_or_class()) {
  130. add_name(((Cpp::StructOrClassDeclaration&)decl).m_name);
  131. }
  132. if (decl.is_function()) {
  133. add_name(((Cpp::FunctionDeclaration&)decl).m_name);
  134. }
  135. }
  136. auto partial_text = document.parser.text_of_node(node);
  137. Vector<GUI::AutocompleteProvider::Entry> suggestions;
  138. for (auto& name : available_names) {
  139. if (name.starts_with(partial_text)) {
  140. suggestions.append({ name.to_string(), partial_text.length(), GUI::AutocompleteProvider::CompletionKind::Identifier });
  141. }
  142. }
  143. return suggestions;
  144. }
  145. Vector<GUI::AutocompleteProvider::Entry> ParserAutoComplete::autocomplete_property(const DocumentData& document, const MemberExpression& parent, const StringView partial_text) const
  146. {
  147. auto type = type_of(document, *parent.m_object);
  148. if (type.is_null()) {
  149. VERBOSE("Could not infer type of object");
  150. return {};
  151. }
  152. Vector<GUI::AutocompleteProvider::Entry> suggestions;
  153. for (auto& prop : properties_of_type(document, type)) {
  154. if (prop.name.starts_with(partial_text)) {
  155. suggestions.append({ prop.name, partial_text.length(), GUI::AutocompleteProvider::CompletionKind::Identifier });
  156. }
  157. }
  158. return suggestions;
  159. }
  160. bool ParserAutoComplete::is_property(const ASTNode& node) const
  161. {
  162. if (!node.parent()->is_member_expression())
  163. return false;
  164. auto& parent = (MemberExpression&)(*node.parent());
  165. return parent.m_property.ptr() == &node;
  166. }
  167. bool ParserAutoComplete::is_empty_property(const DocumentData& document, const ASTNode& node, const Position& autocomplete_position) const
  168. {
  169. if (!node.is_member_expression())
  170. return false;
  171. auto previous_token = document.parser.token_at(autocomplete_position);
  172. if (!previous_token.has_value())
  173. return false;
  174. return previous_token.value().type() == Token::Type::Dot;
  175. }
  176. String ParserAutoComplete::type_of_property(const DocumentData& document, const Identifier& identifier) const
  177. {
  178. auto& parent = (const MemberExpression&)(*identifier.parent());
  179. auto properties = properties_of_type(document, type_of(document, *parent.m_object));
  180. for (auto& prop : properties) {
  181. if (prop.name == identifier.m_name)
  182. return prop.type->m_name;
  183. }
  184. return {};
  185. }
  186. String ParserAutoComplete::type_of_variable(const Identifier& identifier) const
  187. {
  188. const ASTNode* current = &identifier;
  189. while (current) {
  190. for (auto& decl : current->declarations()) {
  191. if (decl.is_variable_or_parameter_declaration()) {
  192. auto& var_or_param = (VariableOrParameterDeclaration&)decl;
  193. if (var_or_param.m_name == identifier.m_name) {
  194. return var_or_param.m_type->m_name;
  195. }
  196. }
  197. }
  198. current = current->parent();
  199. }
  200. return {};
  201. }
  202. String ParserAutoComplete::type_of(const DocumentData& document, const Expression& expression) const
  203. {
  204. if (expression.is_member_expression()) {
  205. auto& member_expression = (const MemberExpression&)expression;
  206. return type_of_property(document, *member_expression.m_property);
  207. }
  208. if (!expression.is_identifier()) {
  209. ASSERT_NOT_REACHED(); // TODO
  210. }
  211. auto& identifier = (const Identifier&)expression;
  212. if (is_property(identifier))
  213. return type_of_property(document, identifier);
  214. return type_of_variable(identifier);
  215. }
  216. Vector<ParserAutoComplete::PropertyInfo> ParserAutoComplete::properties_of_type(const DocumentData& document, const String& type) const
  217. {
  218. auto declarations = get_declarations_in_outer_scope_including_headers(document);
  219. Vector<PropertyInfo> properties;
  220. for (auto& decl : declarations) {
  221. if (!decl.is_struct_or_class())
  222. continue;
  223. auto& struct_or_class = (StructOrClassDeclaration&)decl;
  224. if (struct_or_class.m_name != type)
  225. continue;
  226. for (auto& member : struct_or_class.m_members) {
  227. properties.append({ member.m_name, member.m_type });
  228. }
  229. }
  230. return properties;
  231. }
  232. NonnullRefPtrVector<Declaration> ParserAutoComplete::get_declarations_in_outer_scope_including_headers(const DocumentData& document) const
  233. {
  234. NonnullRefPtrVector<Declaration> declarations;
  235. for (auto& include : document.preprocessor.included_paths()) {
  236. auto included_document = get_document_data(document_path_from_include_path(include));
  237. declarations.append(get_declarations_in_outer_scope_including_headers(included_document));
  238. }
  239. for (auto& decl : document.parser.root_node()->declarations()) {
  240. declarations.append(decl);
  241. }
  242. return declarations;
  243. }
  244. String ParserAutoComplete::document_path_from_include_path(const StringView& include_path) const
  245. {
  246. static Regex<PosixExtended> library_include("<(.+)>");
  247. static Regex<PosixExtended> user_defined_include("\"(.+)\"");
  248. auto document_path_for_library_include = [&](const StringView& include_path) -> String {
  249. RegexResult result;
  250. if (!library_include.search(include_path, result))
  251. return {};
  252. auto path = result.capture_group_matches.at(0).at(0).view.u8view();
  253. return String::formatted("/usr/include/{}", path);
  254. };
  255. auto document_path_for_user_defined_include = [&](const StringView& include_path) -> String {
  256. RegexResult result;
  257. if (!user_defined_include.search(include_path, result))
  258. return {};
  259. return result.capture_group_matches.at(0).at(0).view.u8view();
  260. };
  261. auto result = document_path_for_library_include(include_path);
  262. if (result.is_null())
  263. result = document_path_for_user_defined_include(include_path);
  264. return result;
  265. }
  266. void ParserAutoComplete::on_edit(const String& file)
  267. {
  268. set_document_data(file, create_document_data_for(file));
  269. }
  270. void ParserAutoComplete::file_opened([[maybe_unused]] const String& file)
  271. {
  272. set_document_data(file, create_document_data_for(file));
  273. }
  274. }