CppComprehensionEngine.cpp 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991
  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 <AK/ScopeGuard.h>
  11. #include <LibCore/DirIterator.h>
  12. #include <LibCore/File.h>
  13. #include <LibCpp/AST.h>
  14. #include <LibCpp/Lexer.h>
  15. #include <LibCpp/Parser.h>
  16. #include <LibCpp/Preprocessor.h>
  17. #include <LibRegex/Regex.h>
  18. #include <Userland/DevTools/HackStudio/LanguageServers/ConnectionFromClient.h>
  19. namespace LanguageServers::Cpp {
  20. CppComprehensionEngine::CppComprehensionEngine(const FileDB& filedb)
  21. : CodeComprehensionEngine(filedb, true)
  22. {
  23. }
  24. const CppComprehensionEngine::DocumentData* CppComprehensionEngine::get_or_create_document_data(const String& file)
  25. {
  26. auto absolute_path = filedb().to_absolute_path(file);
  27. if (!m_documents.contains(absolute_path)) {
  28. set_document_data(absolute_path, create_document_data_for(absolute_path));
  29. }
  30. return get_document_data(absolute_path);
  31. }
  32. const CppComprehensionEngine::DocumentData* CppComprehensionEngine::get_document_data(const String& file) const
  33. {
  34. auto absolute_path = filedb().to_absolute_path(file);
  35. auto document_data = m_documents.get(absolute_path);
  36. if (!document_data.has_value())
  37. return nullptr;
  38. return document_data.value();
  39. }
  40. OwnPtr<CppComprehensionEngine::DocumentData> CppComprehensionEngine::create_document_data_for(const String& file)
  41. {
  42. if (m_unfinished_documents.contains(file)) {
  43. return {};
  44. }
  45. m_unfinished_documents.set(file);
  46. ScopeGuard mark_finished([&file, this]() { m_unfinished_documents.remove(file); });
  47. auto document = filedb().get_or_create_from_filesystem(file);
  48. if (!document)
  49. return {};
  50. return create_document_data(document->text(), file);
  51. }
  52. void CppComprehensionEngine::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> CppComprehensionEngine::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, "CppComprehensionEngine 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 containing_token = document.parser().token_at(position);
  65. if (containing_token.has_value() && containing_token->type() == Token::Type::IncludePath) {
  66. auto results = try_autocomplete_include(document, containing_token.value(), position);
  67. if (results.has_value())
  68. return results.value();
  69. }
  70. auto node = document.parser().node_at(position);
  71. if (!node) {
  72. dbgln_if(CPP_LANGUAGE_SERVER_DEBUG, "no node at position {}:{}", position.line, position.column);
  73. return {};
  74. }
  75. if (node->parent() && node->parent()->parent())
  76. dbgln_if(CPP_LANGUAGE_SERVER_DEBUG, "node: {}, parent: {}, grandparent: {}", node->class_name(), node->parent()->class_name(), node->parent()->parent()->class_name());
  77. if (!node->parent())
  78. return {};
  79. auto results = try_autocomplete_property(document, *node, containing_token);
  80. if (results.has_value())
  81. return results.value();
  82. results = try_autocomplete_name(document, *node, containing_token);
  83. if (results.has_value())
  84. return results.value();
  85. return {};
  86. }
  87. Optional<Vector<GUI::AutocompleteProvider::Entry>> CppComprehensionEngine::try_autocomplete_name(const DocumentData& document, const ASTNode& node, Optional<Token> containing_token) const
  88. {
  89. auto partial_text = String::empty();
  90. if (containing_token.has_value() && containing_token.value().type() != Token::Type::ColonColon) {
  91. partial_text = containing_token.value().text();
  92. }
  93. return autocomplete_name(document, node, partial_text);
  94. }
  95. Optional<Vector<GUI::AutocompleteProvider::Entry>> CppComprehensionEngine::try_autocomplete_property(const DocumentData& document, const ASTNode& node, Optional<Token> containing_token) const
  96. {
  97. if (!containing_token.has_value())
  98. return {};
  99. if (!node.parent()->is_member_expression())
  100. return {};
  101. const auto& parent = static_cast<const MemberExpression&>(*node.parent());
  102. auto partial_text = String::empty();
  103. if (containing_token.value().type() != Token::Type::Dot) {
  104. if (&node != parent.property())
  105. return {};
  106. partial_text = containing_token.value().text();
  107. }
  108. return autocomplete_property(document, parent, partial_text);
  109. }
  110. Vector<GUI::AutocompleteProvider::Entry> CppComprehensionEngine::autocomplete_name(const DocumentData& document, const ASTNode& node, const String& partial_text) const
  111. {
  112. auto reference_scope = scope_of_reference_to_symbol(node);
  113. auto current_scope = scope_of_node(node);
  114. auto symbol_matches = [&](const Symbol& symbol) {
  115. if (!is_symbol_available(symbol, current_scope, reference_scope)) {
  116. return false;
  117. }
  118. if (!symbol.name.name.starts_with(partial_text))
  119. return false;
  120. if (symbol.is_local) {
  121. // If this symbol was declared below us in a function, it's not available to us.
  122. bool is_unavailable = symbol.is_local && symbol.declaration->start().line > node.start().line;
  123. if (is_unavailable)
  124. return false;
  125. }
  126. return true;
  127. };
  128. Vector<Symbol> matches;
  129. for_each_available_symbol(document, [&](const Symbol& symbol) {
  130. if (symbol_matches(symbol)) {
  131. matches.append(symbol);
  132. }
  133. return IterationDecision::Continue;
  134. });
  135. Vector<GUI::AutocompleteProvider::Entry> suggestions;
  136. for (auto& symbol : matches) {
  137. suggestions.append({ symbol.name.name, partial_text.length() });
  138. }
  139. if (reference_scope.is_empty()) {
  140. for (auto& preprocessor_name : document.preprocessor().definitions().keys()) {
  141. if (preprocessor_name.starts_with(partial_text)) {
  142. suggestions.append({ preprocessor_name, partial_text.length() });
  143. }
  144. }
  145. }
  146. return suggestions;
  147. }
  148. Vector<StringView> CppComprehensionEngine::scope_of_reference_to_symbol(const ASTNode& node) const
  149. {
  150. const Name* name = nullptr;
  151. if (node.is_name()) {
  152. // FIXME It looks like this code path is never taken
  153. name = reinterpret_cast<const Name*>(&node);
  154. } else if (node.is_identifier()) {
  155. auto* parent = node.parent();
  156. if (!(parent && parent->is_name()))
  157. return {};
  158. name = reinterpret_cast<const Name*>(parent);
  159. } else {
  160. return {};
  161. }
  162. VERIFY(name->is_name());
  163. Vector<StringView> scope_parts;
  164. for (auto& scope_part : name->scope()) {
  165. // If the target node is part of a scope reference, we want to end the scope chain before it.
  166. if (&scope_part == &node)
  167. break;
  168. scope_parts.append(scope_part.name());
  169. }
  170. return scope_parts;
  171. }
  172. Vector<GUI::AutocompleteProvider::Entry> CppComprehensionEngine::autocomplete_property(const DocumentData& document, const MemberExpression& parent, const String partial_text) const
  173. {
  174. VERIFY(parent.object());
  175. auto type = type_of(document, *parent.object());
  176. if (type.is_null()) {
  177. dbgln_if(CPP_LANGUAGE_SERVER_DEBUG, "Could not infer type of object");
  178. return {};
  179. }
  180. Vector<GUI::AutocompleteProvider::Entry> suggestions;
  181. for (auto& prop : properties_of_type(document, type)) {
  182. if (prop.name.name.starts_with(partial_text)) {
  183. suggestions.append({ prop.name.name, partial_text.length() });
  184. }
  185. }
  186. return suggestions;
  187. }
  188. bool CppComprehensionEngine::is_property(const ASTNode& node) const
  189. {
  190. if (!node.parent()->is_member_expression())
  191. return false;
  192. auto& parent = verify_cast<MemberExpression>(*node.parent());
  193. return parent.property() == &node;
  194. }
  195. String CppComprehensionEngine::type_of_property(const DocumentData& document, const Identifier& identifier) const
  196. {
  197. auto& parent = verify_cast<MemberExpression>(*identifier.parent());
  198. VERIFY(parent.object());
  199. auto properties = properties_of_type(document, type_of(document, *parent.object()));
  200. for (auto& prop : properties) {
  201. if (prop.name.name != identifier.name())
  202. continue;
  203. const Type* type { nullptr };
  204. if (prop.declaration->is_variable_declaration()) {
  205. type = verify_cast<VariableDeclaration>(*prop.declaration).type();
  206. }
  207. if (!type)
  208. continue;
  209. if (!type->is_named_type())
  210. continue;
  211. VERIFY(verify_cast<NamedType>(*type).name());
  212. if (verify_cast<NamedType>(*type).name())
  213. return verify_cast<NamedType>(*type).name()->full_name();
  214. return String::empty();
  215. }
  216. return {};
  217. }
  218. String CppComprehensionEngine::type_of_variable(const Identifier& identifier) const
  219. {
  220. const ASTNode* current = &identifier;
  221. while (current) {
  222. for (auto& decl : current->declarations()) {
  223. if (decl.is_variable_or_parameter_declaration()) {
  224. auto& var_or_param = verify_cast<VariableOrParameterDeclaration>(decl);
  225. if (var_or_param.full_name() == identifier.name() && var_or_param.type()->is_named_type()) {
  226. VERIFY(verify_cast<NamedType>(*var_or_param.type()).name());
  227. if (verify_cast<NamedType>(*var_or_param.type()).name())
  228. return verify_cast<NamedType>(*var_or_param.type()).name()->full_name();
  229. return String::empty();
  230. }
  231. }
  232. }
  233. current = current->parent();
  234. }
  235. return {};
  236. }
  237. String CppComprehensionEngine::type_of(const DocumentData& document, const Expression& expression) const
  238. {
  239. if (expression.is_member_expression()) {
  240. auto& member_expression = verify_cast<MemberExpression>(expression);
  241. VERIFY(member_expression.property());
  242. if (member_expression.property()->is_identifier())
  243. return type_of_property(document, static_cast<const Identifier&>(*member_expression.property()));
  244. return {};
  245. }
  246. const Identifier* identifier { nullptr };
  247. if (expression.is_name()) {
  248. identifier = static_cast<const Name&>(expression).name();
  249. } else if (expression.is_identifier()) {
  250. identifier = &static_cast<const Identifier&>(expression);
  251. } else {
  252. dbgln("expected identifier or name, got: {}", expression.class_name());
  253. VERIFY_NOT_REACHED(); // TODO
  254. }
  255. VERIFY(identifier);
  256. if (is_property(*identifier))
  257. return type_of_property(document, *identifier);
  258. return type_of_variable(*identifier);
  259. }
  260. Vector<CppComprehensionEngine::Symbol> CppComprehensionEngine::properties_of_type(const DocumentData& document, const String& type) const
  261. {
  262. auto type_symbol = SymbolName::create(type);
  263. auto decl = find_declaration_of(document, type_symbol);
  264. if (!decl) {
  265. dbgln("Couldn't find declaration of type: {}", type);
  266. return {};
  267. }
  268. if (!decl->is_struct_or_class()) {
  269. dbgln("Expected declaration of type: {} to be struct or class", type);
  270. return {};
  271. }
  272. auto& struct_or_class = verify_cast<StructOrClassDeclaration>(*decl);
  273. VERIFY(struct_or_class.full_name() == type_symbol.name);
  274. Vector<Symbol> properties;
  275. for (auto& member : struct_or_class.members()) {
  276. Vector<StringView> scope(type_symbol.scope);
  277. scope.append(type_symbol.name);
  278. // FIXME: We don't have to create the Symbol here, it should already exist in the 'm_symbol' table of some DocumentData we already parsed.
  279. properties.append(Symbol::create(member.full_name(), scope, member, Symbol::IsLocal::No));
  280. }
  281. return properties;
  282. }
  283. CppComprehensionEngine::Symbol CppComprehensionEngine::Symbol::create(StringView name, const Vector<StringView>& scope, NonnullRefPtr<Declaration> declaration, IsLocal is_local)
  284. {
  285. return { { name, scope }, move(declaration), is_local == IsLocal::Yes };
  286. }
  287. Vector<CppComprehensionEngine::Symbol> CppComprehensionEngine::get_child_symbols(const ASTNode& node) const
  288. {
  289. return get_child_symbols(node, {}, Symbol::IsLocal::No);
  290. }
  291. Vector<CppComprehensionEngine::Symbol> CppComprehensionEngine::get_child_symbols(const ASTNode& node, const Vector<StringView>& scope, Symbol::IsLocal is_local) const
  292. {
  293. Vector<Symbol> symbols;
  294. for (auto& decl : node.declarations()) {
  295. symbols.append(Symbol::create(decl.full_name(), scope, decl, is_local));
  296. bool should_recurse = decl.is_namespace() || decl.is_struct_or_class() || decl.is_function();
  297. bool are_child_symbols_local = decl.is_function();
  298. if (!should_recurse)
  299. continue;
  300. auto new_scope = scope;
  301. new_scope.append(decl.full_name());
  302. symbols.extend(get_child_symbols(decl, new_scope, are_child_symbols_local ? Symbol::IsLocal::Yes : is_local));
  303. }
  304. return symbols;
  305. }
  306. String CppComprehensionEngine::document_path_from_include_path(StringView include_path) const
  307. {
  308. static Regex<PosixExtended> library_include("<(.+)>");
  309. static Regex<PosixExtended> user_defined_include("\"(.+)\"");
  310. auto document_path_for_library_include = [&](StringView include_path) -> String {
  311. RegexResult result;
  312. if (!library_include.search(include_path, result))
  313. return {};
  314. auto path = result.capture_group_matches.at(0).at(0).view.string_view();
  315. return String::formatted("/usr/include/{}", path);
  316. };
  317. auto document_path_for_user_defined_include = [&](StringView include_path) -> String {
  318. RegexResult result;
  319. if (!user_defined_include.search(include_path, result))
  320. return {};
  321. return result.capture_group_matches.at(0).at(0).view.string_view();
  322. };
  323. auto result = document_path_for_library_include(include_path);
  324. if (result.is_null())
  325. result = document_path_for_user_defined_include(include_path);
  326. return result;
  327. }
  328. void CppComprehensionEngine::on_edit(const String& file)
  329. {
  330. set_document_data(file, create_document_data_for(file));
  331. }
  332. void CppComprehensionEngine::file_opened([[maybe_unused]] const String& file)
  333. {
  334. get_or_create_document_data(file);
  335. }
  336. Optional<GUI::AutocompleteProvider::ProjectLocation> CppComprehensionEngine::find_declaration_of(const String& filename, const GUI::TextPosition& identifier_position)
  337. {
  338. const auto* document_ptr = get_or_create_document_data(filename);
  339. if (!document_ptr)
  340. return {};
  341. const auto& document = *document_ptr;
  342. auto decl = find_declaration_of(document, identifier_position);
  343. if (decl) {
  344. return GUI::AutocompleteProvider::ProjectLocation { decl->filename(), decl->start().line, decl->start().column };
  345. }
  346. return find_preprocessor_definition(document, identifier_position);
  347. }
  348. RefPtr<Declaration> CppComprehensionEngine::find_declaration_of(const DocumentData& document, const GUI::TextPosition& identifier_position)
  349. {
  350. auto node = document.parser().node_at(Cpp::Position { identifier_position.line(), identifier_position.column() });
  351. if (!node) {
  352. dbgln_if(CPP_LANGUAGE_SERVER_DEBUG, "no node at position {}:{}", identifier_position.line(), identifier_position.column());
  353. return {};
  354. }
  355. return find_declaration_of(document, *node);
  356. }
  357. Optional<GUI::AutocompleteProvider::ProjectLocation> CppComprehensionEngine::find_preprocessor_definition(const DocumentData& document, const GUI::TextPosition& text_position)
  358. {
  359. Position cpp_position { text_position.line(), text_position.column() };
  360. // Search for a replaced preprocessor token that intersects with text_position
  361. for (auto& substitution : document.preprocessor().substitutions()) {
  362. if (substitution.original_tokens.first().start() > cpp_position)
  363. continue;
  364. if (substitution.original_tokens.first().end() < cpp_position)
  365. continue;
  366. return GUI::AutocompleteProvider::ProjectLocation { substitution.defined_value.filename, substitution.defined_value.line, substitution.defined_value.column };
  367. }
  368. return {};
  369. }
  370. struct TargetDeclaration {
  371. enum Type {
  372. Variable,
  373. Type,
  374. Function,
  375. Property,
  376. Scope
  377. } type;
  378. String name;
  379. };
  380. static Optional<TargetDeclaration> get_target_declaration(const ASTNode& node, String name);
  381. static Optional<TargetDeclaration> get_target_declaration(const ASTNode& node)
  382. {
  383. if (node.is_identifier()) {
  384. return get_target_declaration(node, static_cast<const Identifier&>(node).name());
  385. }
  386. if (node.is_declaration()) {
  387. return get_target_declaration(node, verify_cast<Declaration>(node).full_name());
  388. }
  389. if (node.is_type() && node.parent() && node.parent()->is_declaration()) {
  390. return get_target_declaration(*node.parent(), verify_cast<Declaration>(node.parent())->full_name());
  391. }
  392. dbgln("get_target_declaration: Invalid argument node of type: {}", node.class_name());
  393. return {};
  394. }
  395. static Optional<TargetDeclaration> get_target_declaration(const ASTNode& node, String name)
  396. {
  397. if (node.parent() && node.parent()->is_name()) {
  398. if (&node != verify_cast<Name>(node.parent())->name()) {
  399. return TargetDeclaration { TargetDeclaration::Type::Scope, name };
  400. }
  401. }
  402. if ((node.parent() && node.parent()->is_function_call()) || (node.parent()->is_name() && node.parent()->parent() && node.parent()->parent()->is_function_call())) {
  403. return TargetDeclaration { TargetDeclaration::Type::Function, name };
  404. }
  405. if ((node.parent() && node.parent()->is_type()) || (node.parent()->is_name() && node.parent()->parent() && node.parent()->parent()->is_type()))
  406. return TargetDeclaration { TargetDeclaration::Type::Type, name };
  407. if ((node.parent() && node.parent()->is_member_expression()))
  408. return TargetDeclaration { TargetDeclaration::Type::Property, name };
  409. return TargetDeclaration { TargetDeclaration::Type::Variable, name };
  410. }
  411. RefPtr<Declaration> CppComprehensionEngine::find_declaration_of(const DocumentData& document_data, const ASTNode& node) const
  412. {
  413. dbgln_if(CPP_LANGUAGE_SERVER_DEBUG, "find_declaration_of: {} ({})", document_data.parser().text_of_node(node), node.class_name());
  414. auto target_decl = get_target_declaration(node);
  415. if (!target_decl.has_value())
  416. return {};
  417. auto reference_scope = scope_of_reference_to_symbol(node);
  418. auto current_scope = scope_of_node(node);
  419. auto symbol_matches = [&](const Symbol& symbol) {
  420. bool match_function = target_decl.value().type == TargetDeclaration::Function && symbol.declaration->is_function();
  421. bool match_variable = target_decl.value().type == TargetDeclaration::Variable && symbol.declaration->is_variable_declaration();
  422. bool match_type = target_decl.value().type == TargetDeclaration::Type && symbol.declaration->is_struct_or_class();
  423. bool match_property = target_decl.value().type == TargetDeclaration::Property && symbol.declaration->parent()->is_declaration() && verify_cast<Declaration>(symbol.declaration->parent())->is_struct_or_class();
  424. bool match_parameter = target_decl.value().type == TargetDeclaration::Variable && symbol.declaration->is_parameter();
  425. bool match_scope = target_decl.value().type == TargetDeclaration::Scope && (symbol.declaration->is_namespace() || symbol.declaration->is_struct_or_class());
  426. if (match_property) {
  427. // FIXME: This is not really correct, we also need to check that the type of the struct/class matches (not just the property name)
  428. if (symbol.name.name == target_decl.value().name) {
  429. return true;
  430. }
  431. }
  432. if (!is_symbol_available(symbol, current_scope, reference_scope)) {
  433. return false;
  434. }
  435. if (match_function || match_type || match_scope) {
  436. if (symbol.name.name == target_decl->name)
  437. return true;
  438. }
  439. if (match_variable || match_parameter) {
  440. // If this symbol was declared below us in a function, it's not available to us.
  441. bool is_unavailable = symbol.is_local && symbol.declaration->start().line > node.start().line;
  442. if (!is_unavailable && (symbol.name.name == target_decl->name)) {
  443. return true;
  444. }
  445. }
  446. return false;
  447. };
  448. Optional<Symbol> match;
  449. for_each_available_symbol(document_data, [&](const Symbol& symbol) {
  450. if (symbol_matches(symbol)) {
  451. match = symbol;
  452. return IterationDecision::Break;
  453. }
  454. return IterationDecision::Continue;
  455. });
  456. if (!match.has_value())
  457. return {};
  458. return match->declaration;
  459. }
  460. void CppComprehensionEngine::update_declared_symbols(DocumentData& document)
  461. {
  462. for (auto& symbol : get_child_symbols(*document.parser().root_node())) {
  463. document.m_symbols.set(symbol.name, move(symbol));
  464. }
  465. Vector<GUI::AutocompleteProvider::Declaration> declarations;
  466. for (auto& symbol_entry : document.m_symbols) {
  467. auto& symbol = symbol_entry.value;
  468. 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() });
  469. }
  470. for (auto& definition : document.preprocessor().definitions()) {
  471. declarations.append({ definition.key, { document.filename(), definition.value.line, definition.value.column }, GUI::AutocompleteProvider::DeclarationType::PreprocessorDefinition, {} });
  472. }
  473. set_declarations_of_document(document.filename(), move(declarations));
  474. }
  475. void CppComprehensionEngine::update_todo_entries(DocumentData& document)
  476. {
  477. set_todo_entries_of_document(document.filename(), document.parser().get_todo_entries());
  478. }
  479. GUI::AutocompleteProvider::DeclarationType CppComprehensionEngine::type_of_declaration(const Declaration& decl)
  480. {
  481. if (decl.is_struct())
  482. return GUI::AutocompleteProvider::DeclarationType::Struct;
  483. if (decl.is_class())
  484. return GUI::AutocompleteProvider::DeclarationType::Class;
  485. if (decl.is_function())
  486. return GUI::AutocompleteProvider::DeclarationType::Function;
  487. if (decl.is_variable_declaration())
  488. return GUI::AutocompleteProvider::DeclarationType::Variable;
  489. if (decl.is_namespace())
  490. return GUI::AutocompleteProvider::DeclarationType::Namespace;
  491. if (decl.is_member())
  492. return GUI::AutocompleteProvider::DeclarationType::Member;
  493. return GUI::AutocompleteProvider::DeclarationType::Variable;
  494. }
  495. OwnPtr<CppComprehensionEngine::DocumentData> CppComprehensionEngine::create_document_data(String&& text, const String& filename)
  496. {
  497. auto document_data = make<DocumentData>();
  498. document_data->m_filename = filename;
  499. document_data->m_text = move(text);
  500. document_data->m_preprocessor = make<Preprocessor>(document_data->m_filename, document_data->text());
  501. document_data->preprocessor().set_ignore_unsupported_keywords(true);
  502. document_data->preprocessor().set_ignore_invalid_statements(true);
  503. document_data->preprocessor().set_keep_include_statements(true);
  504. document_data->preprocessor().definitions_in_header_callback = [this](StringView include_path) -> Preprocessor::Definitions {
  505. auto included_document = get_or_create_document_data(document_path_from_include_path(include_path));
  506. if (!included_document)
  507. return {};
  508. return included_document->preprocessor().definitions();
  509. };
  510. auto tokens = document_data->preprocessor().process_and_lex();
  511. for (auto include_path : document_data->preprocessor().included_paths()) {
  512. auto include_fullpath = document_path_from_include_path(include_path);
  513. auto included_document = get_or_create_document_data(include_fullpath);
  514. if (!included_document)
  515. continue;
  516. document_data->m_available_headers.set(include_fullpath);
  517. for (auto& header : included_document->m_available_headers)
  518. document_data->m_available_headers.set(header);
  519. }
  520. document_data->m_parser = make<Parser>(move(tokens), filename);
  521. auto root = document_data->parser().parse();
  522. if constexpr (CPP_LANGUAGE_SERVER_DEBUG)
  523. root->dump();
  524. update_declared_symbols(*document_data);
  525. update_todo_entries(*document_data);
  526. return document_data;
  527. }
  528. Vector<StringView> CppComprehensionEngine::scope_of_node(const ASTNode& node) const
  529. {
  530. auto parent = node.parent();
  531. if (!parent)
  532. return {};
  533. auto parent_scope = scope_of_node(*parent);
  534. if (!parent->is_declaration())
  535. return parent_scope;
  536. auto& parent_decl = static_cast<Declaration&>(*parent);
  537. StringView containing_scope;
  538. if (parent_decl.is_namespace())
  539. containing_scope = static_cast<NamespaceDeclaration&>(parent_decl).full_name();
  540. if (parent_decl.is_struct_or_class())
  541. containing_scope = static_cast<StructOrClassDeclaration&>(parent_decl).full_name();
  542. if (parent_decl.is_function())
  543. containing_scope = static_cast<FunctionDeclaration&>(parent_decl).full_name();
  544. parent_scope.append(containing_scope);
  545. return parent_scope;
  546. }
  547. Optional<Vector<GUI::AutocompleteProvider::Entry>> CppComprehensionEngine::try_autocomplete_include(const DocumentData&, Token include_path_token, Cpp::Position const& cursor_position) const
  548. {
  549. VERIFY(include_path_token.type() == Token::Type::IncludePath);
  550. auto partial_include = include_path_token.text().trim_whitespace();
  551. enum IncludeType {
  552. Project,
  553. System,
  554. } include_type { Project };
  555. String include_root;
  556. bool already_has_suffix = false;
  557. if (partial_include.starts_with("<")) {
  558. include_root = "/usr/include/";
  559. include_type = System;
  560. if (partial_include.ends_with(">")) {
  561. already_has_suffix = true;
  562. partial_include = partial_include.substring_view(0, partial_include.length() - 1).trim_whitespace();
  563. }
  564. } else if (partial_include.starts_with("\"")) {
  565. include_root = filedb().project_root();
  566. if (partial_include.length() > 1 && partial_include.ends_with("\"")) {
  567. already_has_suffix = true;
  568. partial_include = partial_include.substring_view(0, partial_include.length() - 1).trim_whitespace();
  569. }
  570. } else
  571. return {};
  572. // The cursor is past the end of the <> or "", and so should not trigger autocomplete.
  573. if (already_has_suffix && include_path_token.end() <= cursor_position)
  574. return {};
  575. auto last_slash = partial_include.find_last('/');
  576. auto include_dir = String::empty();
  577. auto partial_basename = partial_include.substring_view((last_slash.has_value() ? last_slash.value() : 0) + 1);
  578. if (last_slash.has_value()) {
  579. include_dir = partial_include.substring_view(1, last_slash.value());
  580. }
  581. auto full_dir = LexicalPath::join(include_root, include_dir).string();
  582. dbgln_if(CPP_LANGUAGE_SERVER_DEBUG, "searching path: {}, partial_basename: {}", full_dir, partial_basename);
  583. Core::DirIterator it(full_dir, Core::DirIterator::Flags::SkipDots);
  584. Vector<GUI::AutocompleteProvider::Entry> options;
  585. auto prefix = include_type == System ? "<" : "\"";
  586. auto suffix = include_type == System ? ">" : "\"";
  587. while (it.has_next()) {
  588. auto path = it.next_path();
  589. if (!path.starts_with(partial_basename))
  590. continue;
  591. if (Core::File::is_directory(LexicalPath::join(full_dir, path).string())) {
  592. // FIXME: Don't dismiss the autocomplete when filling these suggestions.
  593. auto completion = String::formatted("{}{}{}/", prefix, include_dir, path);
  594. options.empend(completion, include_dir.length() + partial_basename.length() + 1, GUI::AutocompleteProvider::Language::Cpp, path, GUI::AutocompleteProvider::Entry::HideAutocompleteAfterApplying::No);
  595. } else if (path.ends_with(".h")) {
  596. // FIXME: Place the cursor after the trailing > or ", even if it was
  597. // already typed.
  598. auto completion = String::formatted("{}{}{}{}", prefix, include_dir, path, already_has_suffix ? "" : suffix);
  599. options.empend(completion, include_dir.length() + partial_basename.length() + 1, GUI::AutocompleteProvider::Language::Cpp, path);
  600. }
  601. }
  602. return options;
  603. }
  604. RefPtr<Declaration> CppComprehensionEngine::find_declaration_of(const CppComprehensionEngine::DocumentData& document, const CppComprehensionEngine::SymbolName& target_symbol_name) const
  605. {
  606. RefPtr<Declaration> target_declaration;
  607. for_each_available_symbol(document, [&](const Symbol& symbol) {
  608. if (symbol.name == target_symbol_name) {
  609. target_declaration = symbol.declaration;
  610. return IterationDecision::Break;
  611. }
  612. return IterationDecision::Continue;
  613. });
  614. return target_declaration;
  615. }
  616. String CppComprehensionEngine::SymbolName::scope_as_string() const
  617. {
  618. if (scope.is_empty())
  619. return String::empty();
  620. StringBuilder builder;
  621. for (size_t i = 0; i < scope.size() - 1; ++i) {
  622. builder.appendff("{}::", scope[i]);
  623. }
  624. builder.append(scope.last());
  625. return builder.to_string();
  626. }
  627. CppComprehensionEngine::SymbolName CppComprehensionEngine::SymbolName::create(StringView name, Vector<StringView>&& scope)
  628. {
  629. return { name, move(scope) };
  630. }
  631. CppComprehensionEngine::SymbolName CppComprehensionEngine::SymbolName::create(StringView qualified_name)
  632. {
  633. auto parts = qualified_name.split_view("::");
  634. VERIFY(!parts.is_empty());
  635. auto name = parts.take_last();
  636. return SymbolName::create(name, move(parts));
  637. }
  638. String CppComprehensionEngine::SymbolName::to_string() const
  639. {
  640. if (scope.is_empty())
  641. return name;
  642. return String::formatted("{}::{}", scope_as_string(), name);
  643. }
  644. bool CppComprehensionEngine::is_symbol_available(const Symbol& symbol, const Vector<StringView>& current_scope, const Vector<StringView>& reference_scope)
  645. {
  646. if (!reference_scope.is_empty()) {
  647. return reference_scope == symbol.name.scope;
  648. }
  649. // FIXME: Take "using namespace ..." into consideration
  650. // Check if current_scope starts with symbol's scope
  651. if (symbol.name.scope.size() > current_scope.size())
  652. return false;
  653. for (size_t i = 0; i < symbol.name.scope.size(); ++i) {
  654. if (current_scope[i] != symbol.name.scope[i])
  655. return false;
  656. }
  657. return true;
  658. }
  659. Optional<CodeComprehensionEngine::FunctionParamsHint> CppComprehensionEngine::get_function_params_hint(const String& filename, const GUI::TextPosition& identifier_position)
  660. {
  661. const auto* document_ptr = get_or_create_document_data(filename);
  662. if (!document_ptr)
  663. return {};
  664. const auto& document = *document_ptr;
  665. Cpp::Position cpp_position { identifier_position.line(), identifier_position.column() };
  666. auto node = document.parser().node_at(cpp_position);
  667. if (!node) {
  668. dbgln_if(CPP_LANGUAGE_SERVER_DEBUG, "no node at position {}:{}", identifier_position.line(), identifier_position.column());
  669. return {};
  670. }
  671. dbgln_if(CPP_LANGUAGE_SERVER_DEBUG, "node type: {}", node->class_name());
  672. FunctionCall* call_node { nullptr };
  673. if (node->is_function_call()) {
  674. call_node = verify_cast<FunctionCall>(node.ptr());
  675. auto token = document.parser().token_at(cpp_position);
  676. // If we're in a function call with 0 arguments
  677. if (token.has_value() && (token->type() == Token::Type::LeftParen || token->type() == Token::Type::RightParen)) {
  678. return get_function_params_hint(document, *call_node, call_node->arguments().is_empty() ? 0 : call_node->arguments().size() - 1);
  679. }
  680. }
  681. // Walk upwards in the AST to find a FunctionCall node
  682. while (!call_node && node) {
  683. auto parent_is_call = node->parent() && node->parent()->is_function_call();
  684. if (parent_is_call) {
  685. call_node = verify_cast<FunctionCall>(node->parent());
  686. break;
  687. }
  688. node = node->parent();
  689. }
  690. if (!call_node) {
  691. dbgln("did not find function call");
  692. return {};
  693. }
  694. Optional<size_t> invoked_arg_index;
  695. for (size_t arg_index = 0; arg_index < call_node->arguments().size(); ++arg_index) {
  696. if (&call_node->arguments()[arg_index] == node.ptr()) {
  697. invoked_arg_index = arg_index;
  698. break;
  699. }
  700. }
  701. if (!invoked_arg_index.has_value()) {
  702. dbgln_if(CPP_LANGUAGE_SERVER_DEBUG, "could not find argument index, defaulting to the last argument");
  703. invoked_arg_index = call_node->arguments().is_empty() ? 0 : call_node->arguments().size() - 1;
  704. }
  705. dbgln_if(CPP_LANGUAGE_SERVER_DEBUG, "arg index: {}", invoked_arg_index.value());
  706. return get_function_params_hint(document, *call_node, invoked_arg_index.value());
  707. }
  708. Optional<CppComprehensionEngine::FunctionParamsHint> CppComprehensionEngine::get_function_params_hint(
  709. DocumentData const& document,
  710. FunctionCall& call_node,
  711. size_t argument_index)
  712. {
  713. const Identifier* callee = nullptr;
  714. VERIFY(call_node.callee());
  715. if (call_node.callee()->is_identifier()) {
  716. callee = verify_cast<Identifier>(call_node.callee());
  717. } else if (call_node.callee()->is_name()) {
  718. callee = verify_cast<Name>(*call_node.callee()).name();
  719. } else if (call_node.callee()->is_member_expression()) {
  720. auto& member_exp = verify_cast<MemberExpression>(*call_node.callee());
  721. VERIFY(member_exp.property());
  722. if (member_exp.property()->is_identifier()) {
  723. callee = verify_cast<Identifier>(member_exp.property());
  724. }
  725. }
  726. if (!callee) {
  727. dbgln("unexpected node type for function call: {}", call_node.callee()->class_name());
  728. return {};
  729. }
  730. VERIFY(callee);
  731. auto decl = find_declaration_of(document, *callee);
  732. if (!decl) {
  733. dbgln("func decl not found");
  734. return {};
  735. }
  736. if (!decl->is_function()) {
  737. dbgln("declaration is not a function");
  738. return {};
  739. }
  740. auto& func_decl = verify_cast<FunctionDeclaration>(*decl);
  741. auto document_of_declaration = get_document_data(func_decl.filename());
  742. FunctionParamsHint hint {};
  743. hint.current_index = argument_index;
  744. for (auto& arg : func_decl.parameters()) {
  745. Vector<StringView> tokens_text;
  746. for (auto token : document_of_declaration->parser().tokens_in_range(arg.start(), arg.end())) {
  747. tokens_text.append(token.text());
  748. }
  749. hint.params.append(String::join(" ", tokens_text));
  750. }
  751. return hint;
  752. }
  753. Vector<GUI::AutocompleteProvider::TokenInfo> CppComprehensionEngine::get_tokens_info(const String& filename)
  754. {
  755. dbgln_if(CPP_LANGUAGE_SERVER_DEBUG, "CppComprehensionEngine::get_tokens_info: {}", filename);
  756. const auto* document_ptr = get_or_create_document_data(filename);
  757. if (!document_ptr)
  758. return {};
  759. const auto& document = *document_ptr;
  760. Vector<GUI::AutocompleteProvider::TokenInfo> tokens_info;
  761. size_t i = 0;
  762. for (auto const& token : document.preprocessor().unprocessed_tokens()) {
  763. tokens_info.append({ get_token_semantic_type(document, token),
  764. token.start().line, token.start().column, token.end().line, token.end().column });
  765. ++i;
  766. }
  767. return tokens_info;
  768. }
  769. GUI::AutocompleteProvider::TokenInfo::SemanticType CppComprehensionEngine::get_token_semantic_type(DocumentData const& document, Token const& token)
  770. {
  771. using GUI::AutocompleteProvider;
  772. switch (token.type()) {
  773. case Cpp::Token::Type::Identifier:
  774. return get_semantic_type_for_identifier(document, token.start());
  775. case Cpp::Token::Type::Keyword:
  776. return AutocompleteProvider::TokenInfo::SemanticType::Keyword;
  777. case Cpp::Token::Type::KnownType:
  778. return AutocompleteProvider::TokenInfo::SemanticType::Type;
  779. case Cpp::Token::Type::DoubleQuotedString:
  780. case Cpp::Token::Type::SingleQuotedString:
  781. case Cpp::Token::Type::RawString:
  782. return AutocompleteProvider::TokenInfo::SemanticType::String;
  783. case Cpp::Token::Type::Integer:
  784. case Cpp::Token::Type::Float:
  785. return AutocompleteProvider::TokenInfo::SemanticType::Number;
  786. case Cpp::Token::Type::IncludePath:
  787. return AutocompleteProvider::TokenInfo::SemanticType::IncludePath;
  788. case Cpp::Token::Type::EscapeSequence:
  789. return AutocompleteProvider::TokenInfo::SemanticType::Keyword;
  790. case Cpp::Token::Type::PreprocessorStatement:
  791. case Cpp::Token::Type::IncludeStatement:
  792. return AutocompleteProvider::TokenInfo::SemanticType::PreprocessorStatement;
  793. case Cpp::Token::Type::Comment:
  794. return AutocompleteProvider::TokenInfo::SemanticType::Comment;
  795. default:
  796. return AutocompleteProvider::TokenInfo::SemanticType::Unknown;
  797. }
  798. }
  799. GUI::AutocompleteProvider::TokenInfo::SemanticType CppComprehensionEngine::get_semantic_type_for_identifier(DocumentData const& document, Position position)
  800. {
  801. auto decl = find_declaration_of(document, GUI::TextPosition { position.line, position.column });
  802. if (!decl)
  803. return GUI::AutocompleteProvider::TokenInfo::SemanticType::Identifier;
  804. if (decl->is_function())
  805. return GUI::AutocompleteProvider::TokenInfo::SemanticType::Function;
  806. if (decl->is_parameter())
  807. return GUI::AutocompleteProvider::TokenInfo::SemanticType::Parameter;
  808. if (decl->is_variable_declaration()) {
  809. if (decl->is_member())
  810. return GUI::AutocompleteProvider::TokenInfo::SemanticType::Member;
  811. return GUI::AutocompleteProvider::TokenInfo::SemanticType::Variable;
  812. }
  813. if (decl->is_struct_or_class())
  814. return GUI::AutocompleteProvider::TokenInfo::SemanticType::CustomType;
  815. if (decl->is_namespace())
  816. return GUI::AutocompleteProvider::TokenInfo::SemanticType::Namespace;
  817. return GUI::AutocompleteProvider::TokenInfo::SemanticType::Identifier;
  818. }
  819. }