CppComprehensionEngine.cpp 37 KB

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