ParserAutoComplete.cpp 20 KB

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