ParserAutoComplete.cpp 20 KB

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