CppComprehensionEngine.cpp 24 KB

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