CppComprehensionEngine.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709
  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. if (!document_data.has_value())
  36. return nullptr;
  37. return document_data.value();
  38. }
  39. OwnPtr<CppComprehensionEngine::DocumentData> CppComprehensionEngine::create_document_data_for(const String& file)
  40. {
  41. auto document = filedb().get_or_create_from_filesystem(file);
  42. if (!document)
  43. return {};
  44. return create_document_data(document->text(), file);
  45. }
  46. void CppComprehensionEngine::set_document_data(const String& file, OwnPtr<DocumentData>&& data)
  47. {
  48. m_documents.set(filedb().to_absolute_path(file), move(data));
  49. }
  50. Vector<GUI::AutocompleteProvider::Entry> CppComprehensionEngine::get_suggestions(const String& file, const GUI::TextPosition& autocomplete_position)
  51. {
  52. Cpp::Position position { autocomplete_position.line(), autocomplete_position.column() > 0 ? autocomplete_position.column() - 1 : 0 };
  53. dbgln_if(CPP_LANGUAGE_SERVER_DEBUG, "CppComprehensionEngine position {}:{}", position.line, position.column);
  54. const auto* document_ptr = get_or_create_document_data(file);
  55. if (!document_ptr)
  56. return {};
  57. const auto& document = *document_ptr;
  58. auto containing_token = document.parser().token_at(position);
  59. if (containing_token.has_value() && containing_token->type() == Token::Type::IncludePath) {
  60. auto results = try_autocomplete_include(document, containing_token.value());
  61. if (results.has_value())
  62. return results.value();
  63. }
  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->parent() && node->parent()->parent())
  70. dbgln_if(CPP_LANGUAGE_SERVER_DEBUG, "node: {}, parent: {}, grandparent: {}", node->class_name(), node->parent()->class_name(), node->parent()->parent()->class_name());
  71. if (!node->parent())
  72. return {};
  73. auto results = try_autocomplete_property(document, *node, containing_token);
  74. if (results.has_value())
  75. return results.value();
  76. results = try_autocomplete_name(document, *node, containing_token);
  77. if (results.has_value())
  78. return results.value();
  79. return {};
  80. }
  81. Optional<Vector<GUI::AutocompleteProvider::Entry>> CppComprehensionEngine::try_autocomplete_name(const DocumentData& document, const ASTNode& node, Optional<Token> containing_token) const
  82. {
  83. auto partial_text = String::empty();
  84. if (containing_token.has_value() && containing_token.value().type() != Token::Type::ColonColon) {
  85. partial_text = containing_token.value().text();
  86. }
  87. return autocomplete_name(document, node, partial_text);
  88. }
  89. Optional<Vector<GUI::AutocompleteProvider::Entry>> CppComprehensionEngine::try_autocomplete_property(const DocumentData& document, const ASTNode& node, Optional<Token> containing_token) const
  90. {
  91. if (!containing_token.has_value())
  92. return {};
  93. if (!node.parent()->is_member_expression())
  94. return {};
  95. const auto& parent = static_cast<const MemberExpression&>(*node.parent());
  96. auto partial_text = String::empty();
  97. if (containing_token.value().type() != Token::Type::Dot) {
  98. if (&node != parent.m_property)
  99. return {};
  100. partial_text = containing_token.value().text();
  101. }
  102. return autocomplete_property(document, parent, partial_text);
  103. }
  104. Vector<GUI::AutocompleteProvider::Entry> CppComprehensionEngine::autocomplete_name(const DocumentData& document, const ASTNode& node, const String& partial_text) const
  105. {
  106. auto reference_scope = scope_of_reference_to_symbol(node);
  107. auto current_scope = scope_of_node(node);
  108. auto symbol_matches = [&](const Symbol& symbol) {
  109. if (!is_symbol_available(symbol, current_scope, reference_scope)) {
  110. return false;
  111. }
  112. if (!symbol.name.name.starts_with(partial_text))
  113. return false;
  114. if (symbol.is_local) {
  115. // If this symbol was declared bellow us in a function, it's not available to us.
  116. bool is_unavailable = symbol.is_local && symbol.declaration->start().line > node.start().line;
  117. if (is_unavailable)
  118. return false;
  119. }
  120. return true;
  121. };
  122. Vector<Symbol> matches;
  123. for_each_available_symbol(document, [&](const Symbol& symbol) {
  124. if (symbol_matches(symbol)) {
  125. matches.append(symbol);
  126. }
  127. return IterationDecision::Continue;
  128. });
  129. Vector<GUI::AutocompleteProvider::Entry> suggestions;
  130. for (auto& symbol : matches) {
  131. suggestions.append({ symbol.name.name, partial_text.length(), GUI::AutocompleteProvider::CompletionKind::Identifier });
  132. }
  133. if (reference_scope.is_empty()) {
  134. for (auto& preprocessor_name : document.parser().preprocessor_definitions().keys()) {
  135. if (preprocessor_name.starts_with(partial_text)) {
  136. suggestions.append({ preprocessor_name.to_string(), partial_text.length(), GUI::AutocompleteProvider::CompletionKind::PreprocessorDefinition });
  137. }
  138. }
  139. }
  140. return suggestions;
  141. }
  142. Vector<StringView> CppComprehensionEngine::scope_of_reference_to_symbol(const ASTNode& node) const
  143. {
  144. const Name* name = nullptr;
  145. if (node.is_name()) {
  146. name = reinterpret_cast<const Name*>(&node);
  147. } else if (node.is_identifier()) {
  148. auto* parent = node.parent();
  149. if (!(parent && parent->is_name()))
  150. return {};
  151. name = reinterpret_cast<const Name*>(parent);
  152. } else {
  153. return {};
  154. }
  155. VERIFY(name->is_name());
  156. Vector<StringView> scope_parts;
  157. for (auto& scope_part : name->m_scope) {
  158. scope_parts.append(scope_part.m_name);
  159. }
  160. return scope_parts;
  161. }
  162. Vector<GUI::AutocompleteProvider::Entry> CppComprehensionEngine::autocomplete_property(const DocumentData& document, const MemberExpression& parent, const String partial_text) const
  163. {
  164. auto type = type_of(document, *parent.m_object);
  165. if (type.is_null()) {
  166. dbgln_if(CPP_LANGUAGE_SERVER_DEBUG, "Could not infer type of object");
  167. return {};
  168. }
  169. Vector<GUI::AutocompleteProvider::Entry> suggestions;
  170. for (auto& prop : properties_of_type(document, type)) {
  171. if (prop.name.starts_with(partial_text)) {
  172. suggestions.append({ prop.name, partial_text.length(), GUI::AutocompleteProvider::CompletionKind::Identifier });
  173. }
  174. }
  175. return suggestions;
  176. }
  177. bool CppComprehensionEngine::is_property(const ASTNode& node) const
  178. {
  179. if (!node.parent()->is_member_expression())
  180. return false;
  181. auto& parent = (MemberExpression&)(*node.parent());
  182. return parent.m_property.ptr() == &node;
  183. }
  184. String CppComprehensionEngine::type_of_property(const DocumentData& document, const Identifier& identifier) const
  185. {
  186. auto& parent = (const MemberExpression&)(*identifier.parent());
  187. auto properties = properties_of_type(document, type_of(document, *parent.m_object));
  188. for (auto& prop : properties) {
  189. if (prop.name == identifier.m_name && prop.type->is_named_type())
  190. return ((NamedType&)prop.type).m_name->full_name();
  191. }
  192. return {};
  193. }
  194. String CppComprehensionEngine::type_of_variable(const Identifier& identifier) const
  195. {
  196. const ASTNode* current = &identifier;
  197. while (current) {
  198. for (auto& decl : current->declarations()) {
  199. if (decl.is_variable_or_parameter_declaration()) {
  200. auto& var_or_param = (VariableOrParameterDeclaration&)decl;
  201. if (var_or_param.m_name == identifier.m_name && var_or_param.m_type->is_named_type()) {
  202. return ((NamedType&)(*var_or_param.m_type)).m_name->full_name();
  203. }
  204. }
  205. }
  206. current = current->parent();
  207. }
  208. return {};
  209. }
  210. String CppComprehensionEngine::type_of(const DocumentData& document, const Expression& expression) const
  211. {
  212. if (expression.is_member_expression()) {
  213. auto& member_expression = (const MemberExpression&)expression;
  214. if (member_expression.m_property->is_identifier())
  215. return type_of_property(document, static_cast<const Identifier&>(*member_expression.m_property));
  216. return {};
  217. }
  218. const Identifier* identifier { nullptr };
  219. if (expression.is_name()) {
  220. identifier = static_cast<const Name&>(expression).m_name.ptr();
  221. } else if (expression.is_identifier()) {
  222. identifier = &static_cast<const Identifier&>(expression);
  223. } else {
  224. dbgln("expected identifier or name, got: {}", expression.class_name());
  225. VERIFY_NOT_REACHED(); // TODO
  226. }
  227. VERIFY(identifier);
  228. if (is_property(*identifier))
  229. return type_of_property(document, *identifier);
  230. return type_of_variable(*identifier);
  231. }
  232. Vector<CppComprehensionEngine::PropertyInfo> CppComprehensionEngine::properties_of_type(const DocumentData& document, const String& type) const
  233. {
  234. auto decl = find_declaration_of(document, SymbolName::create(type, {}));
  235. if (!decl) {
  236. dbgln("Couldn't find declaration of type: {}", type);
  237. return {};
  238. }
  239. if (!decl->is_struct_or_class()) {
  240. dbgln("Expected declaration of type: {} to be struct or class", type);
  241. return {};
  242. }
  243. auto& struct_or_class = (StructOrClassDeclaration&)*decl;
  244. VERIFY(struct_or_class.m_name == type); // FIXME: this won't work with scoped types
  245. Vector<PropertyInfo> properties;
  246. for (auto& member : struct_or_class.m_members) {
  247. if (!member.is_variable_declaration())
  248. continue;
  249. properties.append({ member.m_name, ((VariableDeclaration&)member).m_type });
  250. }
  251. return properties;
  252. }
  253. CppComprehensionEngine::Symbol CppComprehensionEngine::Symbol::create(StringView name, const Vector<StringView>& scope, NonnullRefPtr<Declaration> declaration, IsLocal is_local)
  254. {
  255. return { { name, scope }, move(declaration), is_local == IsLocal::Yes };
  256. }
  257. Vector<CppComprehensionEngine::Symbol> CppComprehensionEngine::get_child_symbols(const ASTNode& node) const
  258. {
  259. return get_child_symbols(node, {}, Symbol::IsLocal::No);
  260. }
  261. Vector<CppComprehensionEngine::Symbol> CppComprehensionEngine::get_child_symbols(const ASTNode& node, const Vector<StringView>& scope, Symbol::IsLocal is_local) const
  262. {
  263. Vector<Symbol> symbols;
  264. for (auto& decl : node.declarations()) {
  265. symbols.append(Symbol::create(decl.name(), scope, decl, is_local));
  266. bool should_recurse = decl.is_namespace() || decl.is_struct_or_class() || decl.is_function();
  267. bool are_child_symbols_local = decl.is_function();
  268. if (!should_recurse)
  269. continue;
  270. auto new_scope = scope;
  271. new_scope.append(decl.name());
  272. symbols.extend(get_child_symbols(decl, new_scope, are_child_symbols_local ? Symbol::IsLocal::Yes : is_local));
  273. }
  274. return symbols;
  275. }
  276. String CppComprehensionEngine::document_path_from_include_path(const StringView& include_path) const
  277. {
  278. static Regex<PosixExtended> library_include("<(.+)>");
  279. static Regex<PosixExtended> user_defined_include("\"(.+)\"");
  280. auto document_path_for_library_include = [&](const StringView& include_path) -> String {
  281. RegexResult result;
  282. if (!library_include.search(include_path, result))
  283. return {};
  284. auto path = result.capture_group_matches.at(0).at(0).view.u8view();
  285. return String::formatted("/usr/include/{}", path);
  286. };
  287. auto document_path_for_user_defined_include = [&](const StringView& include_path) -> String {
  288. RegexResult result;
  289. if (!user_defined_include.search(include_path, result))
  290. return {};
  291. return result.capture_group_matches.at(0).at(0).view.u8view();
  292. };
  293. auto result = document_path_for_library_include(include_path);
  294. if (result.is_null())
  295. result = document_path_for_user_defined_include(include_path);
  296. return result;
  297. }
  298. void CppComprehensionEngine::on_edit(const String& file)
  299. {
  300. set_document_data(file, create_document_data_for(file));
  301. }
  302. void CppComprehensionEngine::file_opened([[maybe_unused]] const String& file)
  303. {
  304. get_or_create_document_data(file);
  305. }
  306. Optional<GUI::AutocompleteProvider::ProjectLocation> CppComprehensionEngine::find_declaration_of(const String& filename, const GUI::TextPosition& identifier_position)
  307. {
  308. const auto* document_ptr = get_or_create_document_data(filename);
  309. if (!document_ptr)
  310. return {};
  311. const auto& document = *document_ptr;
  312. auto node = document.parser().node_at(Cpp::Position { identifier_position.line(), identifier_position.column() });
  313. if (!node) {
  314. dbgln_if(CPP_LANGUAGE_SERVER_DEBUG, "no node at position {}:{}", identifier_position.line(), identifier_position.column());
  315. return {};
  316. }
  317. auto decl = find_declaration_of(document, *node);
  318. if (decl)
  319. return GUI::AutocompleteProvider::ProjectLocation { decl->filename(), decl->start().line, decl->start().column };
  320. return find_preprocessor_definition(document, identifier_position);
  321. }
  322. Optional<GUI::AutocompleteProvider::ProjectLocation> CppComprehensionEngine::find_preprocessor_definition(const DocumentData& document, const GUI::TextPosition& text_position)
  323. {
  324. Position cpp_position { text_position.line(), text_position.column() };
  325. // Search for a replaced preprocessor token that intersects with text_position
  326. for (auto& replaced_token : document.parser().replaced_preprocessor_tokens()) {
  327. if (replaced_token.token.start() > cpp_position)
  328. continue;
  329. if (replaced_token.token.end() < cpp_position)
  330. continue;
  331. return GUI::AutocompleteProvider::ProjectLocation { replaced_token.preprocessor_value.filename, replaced_token.preprocessor_value.line, replaced_token.preprocessor_value.column };
  332. }
  333. return {};
  334. }
  335. struct TargetDeclaration {
  336. enum Type {
  337. Variable,
  338. Type,
  339. Function,
  340. Property
  341. } type;
  342. String name;
  343. };
  344. static Optional<TargetDeclaration> get_target_declaration(const ASTNode& node)
  345. {
  346. if (!node.is_identifier()) {
  347. dbgln_if(CPP_LANGUAGE_SERVER_DEBUG, "node is not an identifier");
  348. return {};
  349. }
  350. String name = static_cast<const Identifier&>(node).m_name;
  351. if ((node.parent() && node.parent()->is_function_call()) || (node.parent()->is_name() && node.parent()->parent() && node.parent()->parent()->is_function_call())) {
  352. return TargetDeclaration { TargetDeclaration::Type::Function, name };
  353. }
  354. if ((node.parent() && node.parent()->is_type()) || (node.parent()->is_name() && node.parent()->parent() && node.parent()->parent()->is_type()))
  355. return TargetDeclaration { TargetDeclaration::Type::Type, name };
  356. if ((node.parent() && node.parent()->is_member_expression()))
  357. return TargetDeclaration { TargetDeclaration::Type::Property, name };
  358. return TargetDeclaration { TargetDeclaration::Type::Variable, name };
  359. }
  360. RefPtr<Declaration> CppComprehensionEngine::find_declaration_of(const DocumentData& document_data, const ASTNode& node) const
  361. {
  362. dbgln_if(CPP_LANGUAGE_SERVER_DEBUG, "find_declaration_of: {} ({})", document_data.parser().text_of_node(node), node.class_name());
  363. if (!node.is_identifier()) {
  364. dbgln("node is not an identifier, can't find declaration");
  365. }
  366. auto target_decl = get_target_declaration(node);
  367. if (!target_decl.has_value())
  368. return {};
  369. auto reference_scope = scope_of_reference_to_symbol(node);
  370. auto current_scope = scope_of_node(node);
  371. auto symbol_matches = [&](const Symbol& symbol) {
  372. bool match_function = target_decl.value().type == TargetDeclaration::Function && symbol.declaration->is_function();
  373. bool match_variable = target_decl.value().type == TargetDeclaration::Variable && symbol.declaration->is_variable_declaration();
  374. bool match_type = target_decl.value().type == TargetDeclaration::Type && symbol.declaration->is_struct_or_class();
  375. bool match_property = target_decl.value().type == TargetDeclaration::Property && symbol.declaration->parent()->is_declaration() && ((Declaration*)symbol.declaration->parent())->is_struct_or_class();
  376. bool match_parameter = target_decl.value().type == TargetDeclaration::Variable && symbol.declaration->is_parameter();
  377. if (match_property) {
  378. // FIXME: This is not really correct, we also need to check that the type of the struct/class matches (not just the property name)
  379. if (symbol.name.name == target_decl.value().name) {
  380. return true;
  381. }
  382. }
  383. if (!is_symbol_available(symbol, current_scope, reference_scope)) {
  384. return false;
  385. }
  386. if (match_function || match_type) {
  387. if (symbol.name.name == target_decl->name)
  388. return true;
  389. }
  390. if (match_variable || match_parameter) {
  391. // If this symbol was declared bellow us in a function, it's not available to us.
  392. bool is_unavailable = symbol.is_local && symbol.declaration->start().line > node.start().line;
  393. if (!is_unavailable && (symbol.name.name == target_decl->name)) {
  394. return true;
  395. }
  396. }
  397. return false;
  398. };
  399. Optional<Symbol> match;
  400. for_each_available_symbol(document_data, [&](const Symbol& symbol) {
  401. if (symbol_matches(symbol)) {
  402. match = symbol;
  403. return IterationDecision::Break;
  404. }
  405. return IterationDecision::Continue;
  406. });
  407. if (!match.has_value())
  408. return {};
  409. return match->declaration;
  410. }
  411. void CppComprehensionEngine::update_declared_symbols(DocumentData& document)
  412. {
  413. for (auto& symbol : get_child_symbols(*document.parser().root_node())) {
  414. document.m_symbols.set(symbol.name, move(symbol));
  415. }
  416. Vector<GUI::AutocompleteProvider::Declaration> declarations;
  417. for (auto& symbol_entry : document.m_symbols) {
  418. auto& symbol = symbol_entry.value;
  419. declarations.append({ symbol.name.name, { document.filename(), symbol.declaration->start().line, symbol.declaration->start().column }, type_of_declaration(symbol.declaration), symbol.name.scope_as_string() });
  420. }
  421. for (auto& definition : document.preprocessor().definitions()) {
  422. declarations.append({ definition.key, { document.filename(), definition.value.line, definition.value.column }, GUI::AutocompleteProvider::DeclarationType::PreprocessorDefinition, {} });
  423. }
  424. set_declarations_of_document(document.filename(), move(declarations));
  425. }
  426. void CppComprehensionEngine::update_todo_entries(DocumentData& document)
  427. {
  428. set_todo_entries_of_document(document.filename(), document.parser().get_todo_entries());
  429. }
  430. GUI::AutocompleteProvider::DeclarationType CppComprehensionEngine::type_of_declaration(const Declaration& decl)
  431. {
  432. if (decl.is_struct())
  433. return GUI::AutocompleteProvider::DeclarationType::Struct;
  434. if (decl.is_class())
  435. return GUI::AutocompleteProvider::DeclarationType::Class;
  436. if (decl.is_function())
  437. return GUI::AutocompleteProvider::DeclarationType::Function;
  438. if (decl.is_variable_declaration())
  439. return GUI::AutocompleteProvider::DeclarationType::Variable;
  440. if (decl.is_namespace())
  441. return GUI::AutocompleteProvider::DeclarationType::Namespace;
  442. if (decl.is_member())
  443. return GUI::AutocompleteProvider::DeclarationType::Member;
  444. return GUI::AutocompleteProvider::DeclarationType::Variable;
  445. }
  446. OwnPtr<CppComprehensionEngine::DocumentData> CppComprehensionEngine::create_document_data(String&& text, const String& filename)
  447. {
  448. auto document_data = make<DocumentData>();
  449. document_data->m_filename = filename;
  450. document_data->m_text = move(text);
  451. document_data->m_preprocessor = make<Preprocessor>(document_data->m_filename, document_data->text());
  452. document_data->preprocessor().set_ignore_unsupported_keywords(true);
  453. document_data->preprocessor().set_keep_include_statements(true);
  454. document_data->preprocessor().process();
  455. Preprocessor::Definitions preprocessor_definitions;
  456. for (auto item : document_data->preprocessor().definitions())
  457. preprocessor_definitions.set(move(item.key), move(item.value));
  458. for (auto include_path : document_data->preprocessor().included_paths()) {
  459. auto include_fullpath = document_path_from_include_path(include_path);
  460. auto included_document = get_or_create_document_data(include_fullpath);
  461. if (!included_document)
  462. continue;
  463. document_data->m_available_headers.set(include_fullpath);
  464. for (auto& header : included_document->m_available_headers)
  465. document_data->m_available_headers.set(header);
  466. for (auto item : included_document->parser().preprocessor_definitions())
  467. preprocessor_definitions.set(move(item.key), move(item.value));
  468. }
  469. document_data->m_parser = make<Parser>(document_data->preprocessor().processed_text(), filename, move(preprocessor_definitions));
  470. auto root = document_data->parser().parse();
  471. if constexpr (CPP_LANGUAGE_SERVER_DEBUG)
  472. root->dump();
  473. update_declared_symbols(*document_data);
  474. update_todo_entries(*document_data);
  475. return document_data;
  476. }
  477. Vector<StringView> CppComprehensionEngine::scope_of_node(const ASTNode& node) const
  478. {
  479. auto parent = node.parent();
  480. if (!parent)
  481. return {};
  482. auto parent_scope = scope_of_node(*parent);
  483. if (!parent->is_declaration())
  484. return parent_scope;
  485. auto& parent_decl = static_cast<Declaration&>(*parent);
  486. StringView containing_scope;
  487. if (parent_decl.is_namespace())
  488. containing_scope = static_cast<NamespaceDeclaration&>(parent_decl).m_name;
  489. if (parent_decl.is_struct_or_class())
  490. containing_scope = static_cast<StructOrClassDeclaration&>(parent_decl).name();
  491. if (parent_decl.is_function())
  492. containing_scope = static_cast<FunctionDeclaration&>(parent_decl).name();
  493. parent_scope.append(containing_scope);
  494. return parent_scope;
  495. }
  496. Optional<Vector<GUI::AutocompleteProvider::Entry>> CppComprehensionEngine::try_autocomplete_include(const DocumentData&, Token include_path_token)
  497. {
  498. VERIFY(include_path_token.type() == Token::Type::IncludePath);
  499. auto partial_include = include_path_token.text().trim_whitespace();
  500. String include_root;
  501. auto include_type = GUI::AutocompleteProvider::CompletionKind::ProjectInclude;
  502. if (partial_include.starts_with("<")) {
  503. include_root = "/usr/include/";
  504. include_type = GUI::AutocompleteProvider::CompletionKind::SystemInclude;
  505. } else if (partial_include.starts_with("\"")) {
  506. include_root = filedb().project_root();
  507. } else
  508. return {};
  509. auto last_slash = partial_include.find_last_of("/");
  510. auto include_dir = String::empty();
  511. auto partial_basename = partial_include.substring_view((last_slash.has_value() ? last_slash.value() : 0) + 1);
  512. if (last_slash.has_value()) {
  513. include_dir = partial_include.substring_view(1, last_slash.value());
  514. }
  515. auto full_dir = String::formatted("{}{}", include_root, include_dir);
  516. dbgln_if(CPP_LANGUAGE_SERVER_DEBUG, "searching path: {}, partial_basename: {}", full_dir, partial_basename);
  517. Core::DirIterator it(full_dir, Core::DirIterator::Flags::SkipDots);
  518. Vector<GUI::AutocompleteProvider::Entry> options;
  519. while (it.has_next()) {
  520. auto path = it.next_path();
  521. if (!(path.ends_with(".h") || Core::File::is_directory(LexicalPath::join(full_dir, path).string())))
  522. continue;
  523. if (path.starts_with(partial_basename)) {
  524. options.append({ path, partial_basename.length(), include_type, GUI::AutocompleteProvider::Language::Cpp });
  525. }
  526. }
  527. return options;
  528. }
  529. RefPtr<Declaration> CppComprehensionEngine::find_declaration_of(const CppComprehensionEngine::DocumentData& document, const CppComprehensionEngine::SymbolName& target_symbol_name) const
  530. {
  531. RefPtr<Declaration> target_declaration;
  532. for_each_available_symbol(document, [&](const Symbol& symbol) {
  533. if (symbol.name == target_symbol_name) {
  534. target_declaration = symbol.declaration;
  535. return IterationDecision::Break;
  536. }
  537. return IterationDecision::Continue;
  538. });
  539. return target_declaration;
  540. }
  541. String CppComprehensionEngine::SymbolName::scope_as_string() const
  542. {
  543. if (scope.is_empty())
  544. return String::empty();
  545. StringBuilder builder;
  546. for (size_t i = 0; i < scope.size() - 1; ++i) {
  547. builder.appendff("{}::", scope[i]);
  548. }
  549. builder.append(scope.last());
  550. return builder.to_string();
  551. }
  552. CppComprehensionEngine::SymbolName CppComprehensionEngine::SymbolName::create(StringView name, Vector<StringView>&& scope)
  553. {
  554. return { name, move(scope) };
  555. }
  556. String CppComprehensionEngine::SymbolName::to_string() const
  557. {
  558. if (scope.is_empty())
  559. return name;
  560. return String::formatted("{}::{}", scope_as_string(), name);
  561. }
  562. bool CppComprehensionEngine::is_symbol_available(const Symbol& symbol, const Vector<StringView>& current_scope, const Vector<StringView>& reference_scope)
  563. {
  564. if (!reference_scope.is_empty()) {
  565. return reference_scope == symbol.name.scope;
  566. }
  567. // FIXME: Consider "using namespace ..."
  568. // Check if current_scope starts with symbol's scope
  569. if (symbol.name.scope.size() > current_scope.size())
  570. return false;
  571. for (size_t i = 0; i < symbol.name.scope.size(); ++i) {
  572. if (current_scope[i] != symbol.name.scope[i])
  573. return false;
  574. }
  575. return true;
  576. }
  577. }