CppComprehensionEngine.cpp 37 KB

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