ParserAutoComplete.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  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. #include <Userland/DevTools/HackStudio/LanguageServers/ClientConnection.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_or_create_from_filesystem(file);
  58. if (!document)
  59. return {};
  60. auto content = document->text();
  61. auto document_data = create_document_data(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 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. Vector<GUI::AutocompleteProvider::Entry> ParserAutoComplete::get_suggestions(const String& file, const GUI::TextPosition& autocomplete_position)
  77. {
  78. Cpp::Position position { autocomplete_position.line(), autocomplete_position.column() > 0 ? autocomplete_position.column() - 1 : 0 };
  79. dbgln_if(CPP_LANGUAGE_SERVER_DEBUG, "ParserAutoComplete position {}:{}", position.line, position.column);
  80. const auto* document_ptr = get_or_create_document_data(file);
  81. if (!document_ptr)
  82. return {};
  83. const auto& document = *document_ptr;
  84. auto node = document.parser().node_at(position);
  85. if (!node) {
  86. dbgln_if(CPP_LANGUAGE_SERVER_DEBUG, "no node at position {}:{}", position.line, position.column);
  87. return {};
  88. }
  89. if (node->is_identifier()) {
  90. if (is_property(*node)) {
  91. return autocomplete_property(document, (MemberExpression&)(*node->parent()), document.parser().text_of_node(*node));
  92. }
  93. return autocomplete_name(document, *node, document.parser().text_of_node(*node));
  94. }
  95. if (is_empty_property(document, *node, position)) {
  96. VERIFY(node->parent()->is_member_expression());
  97. return autocomplete_property(document, (MemberExpression&)(*node->parent()), "");
  98. }
  99. String partial_text = String::empty();
  100. auto containing_token = document.parser().token_at(position);
  101. if (containing_token.has_value()) {
  102. partial_text = document.parser().text_of_token(containing_token.value());
  103. }
  104. return autocomplete_name(document, *node, partial_text.view());
  105. }
  106. NonnullRefPtrVector<Declaration> ParserAutoComplete::get_available_declarations(const DocumentData& document, const ASTNode& node) const
  107. {
  108. const Cpp::ASTNode* current = &node;
  109. NonnullRefPtrVector<Declaration> available_declarations;
  110. while (current) {
  111. available_declarations.append(current->declarations());
  112. current = current->parent();
  113. }
  114. available_declarations.append(get_global_declarations_including_headers(document));
  115. return available_declarations;
  116. }
  117. Vector<GUI::AutocompleteProvider::Entry> ParserAutoComplete::autocomplete_name(const DocumentData& document, const ASTNode& node, const String& partial_text) const
  118. {
  119. auto available_declarations = get_available_declarations(document, node);
  120. Vector<StringView> available_names;
  121. auto add_name = [&available_names](auto& name) {
  122. if (name.is_null() || name.is_empty())
  123. return;
  124. if (!available_names.contains_slow(name))
  125. available_names.append(name);
  126. };
  127. for (auto& decl : available_declarations) {
  128. if (decl.filename() == node.filename() && decl.start().line > node.start().line)
  129. continue;
  130. if (decl.is_variable_or_parameter_declaration()) {
  131. add_name(((Cpp::VariableOrParameterDeclaration&)decl).m_name);
  132. }
  133. if (decl.is_struct_or_class()) {
  134. add_name(((Cpp::StructOrClassDeclaration&)decl).m_name);
  135. }
  136. if (decl.is_function()) {
  137. add_name(((Cpp::FunctionDeclaration&)decl).m_name);
  138. }
  139. }
  140. Vector<GUI::AutocompleteProvider::Entry> suggestions;
  141. for (auto& name : available_names) {
  142. if (name.starts_with(partial_text)) {
  143. suggestions.append({ name.to_string(), partial_text.length(), GUI::AutocompleteProvider::CompletionKind::Identifier });
  144. }
  145. }
  146. for (auto& preprocessor_name : document.parser().definitions().keys()) {
  147. if (preprocessor_name.starts_with(partial_text)) {
  148. suggestions.append({ preprocessor_name.to_string(), partial_text.length(), GUI::AutocompleteProvider::CompletionKind::PreprocessorDefinition });
  149. }
  150. }
  151. return suggestions;
  152. }
  153. Vector<GUI::AutocompleteProvider::Entry> ParserAutoComplete::autocomplete_property(const DocumentData& document, const MemberExpression& parent, const String partial_text) const
  154. {
  155. auto type = type_of(document, *parent.m_object);
  156. if (type.is_null()) {
  157. dbgln_if(CPP_LANGUAGE_SERVER_DEBUG, "Could not infer type of object");
  158. return {};
  159. }
  160. Vector<GUI::AutocompleteProvider::Entry> suggestions;
  161. for (auto& prop : properties_of_type(document, type)) {
  162. if (prop.name.starts_with(partial_text)) {
  163. suggestions.append({ prop.name, partial_text.length(), GUI::AutocompleteProvider::CompletionKind::Identifier });
  164. }
  165. }
  166. return suggestions;
  167. }
  168. bool ParserAutoComplete::is_property(const ASTNode& node) const
  169. {
  170. if (!node.parent()->is_member_expression())
  171. return false;
  172. auto& parent = (MemberExpression&)(*node.parent());
  173. return parent.m_property.ptr() == &node;
  174. }
  175. bool ParserAutoComplete::is_empty_property(const DocumentData& document, const ASTNode& node, const Position& autocomplete_position) const
  176. {
  177. if (node.parent() == nullptr)
  178. return false;
  179. if (!node.parent()->is_member_expression())
  180. return false;
  181. auto previous_token = document.parser().token_at(autocomplete_position);
  182. if (!previous_token.has_value())
  183. return false;
  184. return previous_token.value().type() == Token::Type::Dot;
  185. }
  186. String ParserAutoComplete::type_of_property(const DocumentData& document, const Identifier& identifier) const
  187. {
  188. auto& parent = (const MemberExpression&)(*identifier.parent());
  189. auto properties = properties_of_type(document, type_of(document, *parent.m_object));
  190. for (auto& prop : properties) {
  191. if (prop.name == identifier.m_name)
  192. return prop.type->m_name->full_name();
  193. }
  194. return {};
  195. }
  196. String ParserAutoComplete::type_of_variable(const Identifier& identifier) const
  197. {
  198. const ASTNode* current = &identifier;
  199. while (current) {
  200. for (auto& decl : current->declarations()) {
  201. if (decl.is_variable_or_parameter_declaration()) {
  202. auto& var_or_param = (VariableOrParameterDeclaration&)decl;
  203. if (var_or_param.m_name == identifier.m_name) {
  204. return var_or_param.m_type->m_name->full_name();
  205. }
  206. }
  207. }
  208. current = current->parent();
  209. }
  210. return {};
  211. }
  212. String ParserAutoComplete::type_of(const DocumentData& document, const Expression& expression) const
  213. {
  214. if (expression.is_member_expression()) {
  215. auto& member_expression = (const MemberExpression&)expression;
  216. if (member_expression.m_property->is_identifier())
  217. return type_of_property(document, static_cast<const Identifier&>(*member_expression.m_property));
  218. return {};
  219. }
  220. const Identifier* identifier { nullptr };
  221. if (expression.is_name()) {
  222. identifier = static_cast<const Name&>(expression).m_name.ptr();
  223. } else if (expression.is_identifier()) {
  224. identifier = &static_cast<const Identifier&>(expression);
  225. } else {
  226. dbgln("expected identifier or name, got: {}", expression.class_name());
  227. VERIFY_NOT_REACHED(); // TODO
  228. }
  229. VERIFY(identifier);
  230. if (is_property(*identifier))
  231. return type_of_property(document, *identifier);
  232. return type_of_variable(*identifier);
  233. }
  234. Vector<ParserAutoComplete::PropertyInfo> ParserAutoComplete::properties_of_type(const DocumentData& document, const String& type) const
  235. {
  236. auto declarations = get_global_declarations_including_headers(document);
  237. Vector<PropertyInfo> properties;
  238. for (auto& decl : declarations) {
  239. if (!decl.is_struct_or_class())
  240. continue;
  241. auto& struct_or_class = (StructOrClassDeclaration&)decl;
  242. if (struct_or_class.m_name != type)
  243. continue;
  244. for (auto& member : struct_or_class.m_members) {
  245. properties.append({ member.m_name, member.m_type });
  246. }
  247. }
  248. return properties;
  249. }
  250. NonnullRefPtrVector<Declaration> ParserAutoComplete::get_global_declarations_including_headers(const DocumentData& document) const
  251. {
  252. NonnullRefPtrVector<Declaration> declarations;
  253. for (auto& include : document.preprocessor().included_paths()) {
  254. document_path_from_include_path(include);
  255. auto included_document = get_document_data(document_path_from_include_path(include));
  256. if (!included_document)
  257. continue;
  258. declarations.append(get_global_declarations_including_headers(*included_document));
  259. }
  260. declarations.append(get_global_declarations(*document.parser().root_node()));
  261. return declarations;
  262. }
  263. NonnullRefPtrVector<Declaration> ParserAutoComplete::get_global_declarations(const ASTNode& node) const
  264. {
  265. NonnullRefPtrVector<Declaration> declarations;
  266. for (auto& decl : node.declarations()) {
  267. declarations.append(decl);
  268. if (decl.is_namespace()) {
  269. declarations.append(get_global_declarations(decl));
  270. }
  271. if (decl.is_struct_or_class()) {
  272. for (auto& member_decl : static_cast<StructOrClassDeclaration&>(decl).declarations()) {
  273. declarations.append(member_decl);
  274. }
  275. }
  276. }
  277. return declarations;
  278. }
  279. String ParserAutoComplete::document_path_from_include_path(const StringView& include_path) const
  280. {
  281. static Regex<PosixExtended> library_include("<(.+)>");
  282. static Regex<PosixExtended> user_defined_include("\"(.+)\"");
  283. auto document_path_for_library_include = [&](const StringView& include_path) -> String {
  284. RegexResult result;
  285. if (!library_include.search(include_path, result))
  286. return {};
  287. auto path = result.capture_group_matches.at(0).at(0).view.u8view();
  288. return String::formatted("/usr/include/{}", path);
  289. };
  290. auto document_path_for_user_defined_include = [&](const StringView& include_path) -> String {
  291. RegexResult result;
  292. if (!user_defined_include.search(include_path, result))
  293. return {};
  294. return result.capture_group_matches.at(0).at(0).view.u8view();
  295. };
  296. auto result = document_path_for_library_include(include_path);
  297. if (result.is_null())
  298. result = document_path_for_user_defined_include(include_path);
  299. return result;
  300. }
  301. void ParserAutoComplete::on_edit(const String& file)
  302. {
  303. set_document_data(file, create_document_data_for(file));
  304. }
  305. void ParserAutoComplete::file_opened([[maybe_unused]] const String& file)
  306. {
  307. set_document_data(file, create_document_data_for(file));
  308. }
  309. Optional<GUI::AutocompleteProvider::ProjectLocation> ParserAutoComplete::find_declaration_of(const String& file_name, const GUI::TextPosition& identifier_position)
  310. {
  311. const auto* document_ptr = get_or_create_document_data(file_name);
  312. if (!document_ptr)
  313. return {};
  314. const auto& document = *document_ptr;
  315. auto node = document.parser().node_at(Cpp::Position { identifier_position.line(), identifier_position.column() });
  316. if (!node) {
  317. dbgln_if(CPP_LANGUAGE_SERVER_DEBUG, "no node at position {}:{}", identifier_position.line(), identifier_position.column());
  318. return {};
  319. }
  320. auto decl = find_declaration_of(document, *node);
  321. if (decl)
  322. return GUI::AutocompleteProvider::ProjectLocation { decl->filename(), decl->start().line, decl->start().column };
  323. return find_preprocessor_definition(document, identifier_position);
  324. }
  325. Optional<GUI::AutocompleteProvider::ProjectLocation> ParserAutoComplete::find_preprocessor_definition(const DocumentData& document, const GUI::TextPosition& text_position)
  326. {
  327. Position cpp_position { text_position.line(), text_position.column() };
  328. // Search for a replaced preprocessor token that intersects with text_position
  329. for (auto& replaced_token : document.parser().replaced_preprocessor_tokens()) {
  330. if (replaced_token.token.start() > cpp_position)
  331. continue;
  332. if (replaced_token.token.end() < cpp_position)
  333. continue;
  334. return GUI::AutocompleteProvider::ProjectLocation { replaced_token.preprocessor_value.filename, replaced_token.preprocessor_value.line, replaced_token.preprocessor_value.column };
  335. }
  336. return {};
  337. }
  338. struct TargetDeclaration {
  339. enum Type {
  340. Variable,
  341. Type,
  342. Function,
  343. Property
  344. } type;
  345. String name;
  346. };
  347. static Optional<TargetDeclaration> get_target_declaration(const ASTNode& node)
  348. {
  349. if (!node.is_identifier()) {
  350. dbgln_if(CPP_LANGUAGE_SERVER_DEBUG, "node is not an identifier");
  351. return {};
  352. }
  353. String name = static_cast<const Identifier&>(node).m_name;
  354. if ((node.parent() && node.parent()->is_function_call()) || (node.parent()->is_name() && node.parent()->parent() && node.parent()->parent()->is_function_call())) {
  355. return TargetDeclaration { TargetDeclaration::Type::Function, name };
  356. }
  357. if ((node.parent() && node.parent()->is_type()) || (node.parent()->is_name() && node.parent()->parent() && node.parent()->parent()->is_type()))
  358. return TargetDeclaration { TargetDeclaration::Type::Type, name };
  359. if ((node.parent() && node.parent()->is_member_expression()))
  360. return TargetDeclaration { TargetDeclaration::Type::Property, name };
  361. return TargetDeclaration { TargetDeclaration::Type::Variable, name };
  362. }
  363. RefPtr<Declaration> ParserAutoComplete::find_declaration_of(const DocumentData& document_data, const ASTNode& node) const
  364. {
  365. dbgln_if(CPP_LANGUAGE_SERVER_DEBUG, "find_declaration_of: {} ({})", document_data.parser().text_of_node(node), node.class_name());
  366. auto target_decl = get_target_declaration(node);
  367. if (!target_decl.has_value())
  368. return {};
  369. auto declarations = get_available_declarations(document_data, node);
  370. for (auto& decl : declarations) {
  371. if (decl.is_function() && target_decl.value().type == TargetDeclaration::Function) {
  372. if (((Cpp::FunctionDeclaration&)decl).m_name == target_decl.value().name)
  373. return decl;
  374. }
  375. if (decl.is_variable_or_parameter_declaration() && target_decl.value().type == TargetDeclaration::Variable) {
  376. if (((Cpp::VariableOrParameterDeclaration&)decl).m_name == target_decl.value().name)
  377. return decl;
  378. }
  379. if (decl.is_struct_or_class() && target_decl.value().type == TargetDeclaration::Property) {
  380. // TODO: Also check that the type of the struct/class matches (not just the property name)
  381. for (auto& member : ((Cpp::StructOrClassDeclaration&)decl).m_members) {
  382. VERIFY(node.is_identifier());
  383. if (member.m_name == target_decl.value().name) {
  384. return member;
  385. }
  386. }
  387. }
  388. if (decl.is_struct_or_class() && target_decl.value().type == TargetDeclaration::Type) {
  389. if (((Cpp::StructOrClassDeclaration&)decl).m_name == target_decl.value().name)
  390. return decl;
  391. }
  392. }
  393. return {};
  394. }
  395. void ParserAutoComplete::update_declared_symbols(const DocumentData& document)
  396. {
  397. Vector<GUI::AutocompleteProvider::Declaration> declarations;
  398. for (auto& decl : get_global_declarations(*document.parser().root_node())) {
  399. declarations.append({ decl.name(), { document.filename(), decl.start().line, decl.start().column }, type_of_declaration(decl), scope_of_declaration(decl) });
  400. }
  401. for (auto& definition : document.preprocessor().definitions()) {
  402. declarations.append({ definition.key, { document.filename(), definition.value.line, definition.value.column }, GUI::AutocompleteProvider::DeclarationType::PreprocessorDefinition, {} });
  403. }
  404. set_declarations_of_document(document.filename(), move(declarations));
  405. }
  406. GUI::AutocompleteProvider::DeclarationType ParserAutoComplete::type_of_declaration(const Declaration& decl)
  407. {
  408. if (decl.is_struct())
  409. return GUI::AutocompleteProvider::DeclarationType::Struct;
  410. if (decl.is_class())
  411. return GUI::AutocompleteProvider::DeclarationType::Class;
  412. if (decl.is_function())
  413. return GUI::AutocompleteProvider::DeclarationType::Function;
  414. if (decl.is_variable_declaration())
  415. return GUI::AutocompleteProvider::DeclarationType::Variable;
  416. return GUI::AutocompleteProvider::DeclarationType::Variable;
  417. }
  418. OwnPtr<ParserAutoComplete::DocumentData> ParserAutoComplete::create_document_data(String&& text, const String& filename)
  419. {
  420. auto document_data = make<DocumentData>();
  421. document_data->m_filename = move(filename);
  422. document_data->m_text = move(text);
  423. document_data->m_preprocessor = make<Preprocessor>(document_data->m_filename, document_data->text());
  424. document_data->preprocessor().set_ignore_unsupported_keywords(true);
  425. document_data->preprocessor().process();
  426. Preprocessor::Definitions all_definitions;
  427. for (auto item : document_data->preprocessor().definitions())
  428. all_definitions.set(move(item.key), move(item.value));
  429. for (auto include : document_data->preprocessor().included_paths()) {
  430. auto included_document = get_or_create_document_data(document_path_from_include_path(include));
  431. if (!included_document)
  432. continue;
  433. for (auto item : included_document->parser().definitions())
  434. all_definitions.set(move(item.key), move(item.value));
  435. }
  436. document_data->m_parser = make<Parser>(document_data->preprocessor().processed_text(), filename, move(all_definitions));
  437. return document_data;
  438. }
  439. String ParserAutoComplete::scope_of_declaration(const Declaration& decl)
  440. {
  441. auto parent = decl.parent();
  442. if (!parent)
  443. return {};
  444. if (!parent->is_declaration())
  445. return {};
  446. auto& parent_decl = static_cast<Declaration&>(*parent);
  447. auto parent_scope = scope_of_declaration(parent_decl);
  448. String containing_scope;
  449. if (parent_decl.is_namespace())
  450. containing_scope = static_cast<NamespaceDeclaration&>(parent_decl).m_name;
  451. if (parent_decl.is_struct_or_class())
  452. containing_scope = static_cast<StructOrClassDeclaration&>(parent_decl).name();
  453. if (parent_scope.is_null())
  454. return containing_scope;
  455. return String::formatted("{}::{}", parent_scope, containing_scope);
  456. }
  457. }