CppComprehensionEngine.cpp 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009
  1. /*
  2. * Copyright (c) 2021-2022, 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 <LibCpp/AST.h>
  13. #include <LibCpp/Lexer.h>
  14. #include <LibCpp/Parser.h>
  15. #include <LibCpp/Preprocessor.h>
  16. #include <LibFileSystem/FileSystem.h>
  17. #include <LibRegex/Regex.h>
  18. #include <Userland/DevTools/HackStudio/LanguageServers/ConnectionFromClient.h>
  19. namespace CodeComprehension::Cpp {
  20. CppComprehensionEngine::CppComprehensionEngine(FileDB const& filedb)
  21. : CodeComprehensionEngine(filedb, true)
  22. {
  23. }
  24. CppComprehensionEngine::DocumentData const* CppComprehensionEngine::get_or_create_document_data(DeprecatedString const& 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. CppComprehensionEngine::DocumentData const* CppComprehensionEngine::get_document_data(DeprecatedString const& 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(DeprecatedString const& 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_read_from_filesystem(file);
  48. if (!document.has_value())
  49. return {};
  50. return create_document_data(move(document.value()), file);
  51. }
  52. void CppComprehensionEngine::set_document_data(DeprecatedString const& file, OwnPtr<DocumentData>&& data)
  53. {
  54. m_documents.set(filedb().to_absolute_path(file), move(data));
  55. }
  56. Vector<CodeComprehension::AutocompleteResultEntry> CppComprehensionEngine::get_suggestions(DeprecatedString const& 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. auto const* document_ptr = get_or_create_document_data(file);
  61. if (!document_ptr)
  62. return {};
  63. auto const& 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<CodeComprehension::AutocompleteResultEntry>> CppComprehensionEngine::try_autocomplete_name(DocumentData const& document, ASTNode const& node, Optional<Token> containing_token) const
  88. {
  89. auto partial_text = DeprecatedString::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<CodeComprehension::AutocompleteResultEntry>> CppComprehensionEngine::try_autocomplete_property(DocumentData const& document, ASTNode const& 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. auto const& parent = static_cast<MemberExpression const&>(*node.parent());
  102. auto partial_text = DeprecatedString::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<CodeComprehension::AutocompleteResultEntry> CppComprehensionEngine::autocomplete_name(DocumentData const& document, ASTNode const& node, DeprecatedString const& 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 = [&](Symbol const& 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, [&](Symbol const& symbol) {
  130. if (symbol_matches(symbol)) {
  131. matches.append(symbol);
  132. }
  133. return IterationDecision::Continue;
  134. });
  135. Vector<CodeComprehension::AutocompleteResultEntry> 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(ASTNode const& node) const
  149. {
  150. Name const* name = nullptr;
  151. if (node.is_name()) {
  152. // FIXME It looks like this code path is never taken
  153. name = reinterpret_cast<Name const*>(&node);
  154. } else if (node.is_identifier()) {
  155. auto* parent = node.parent();
  156. if (!(parent && parent->is_name()))
  157. return {};
  158. name = reinterpret_cast<Name const*>(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<CodeComprehension::AutocompleteResultEntry> CppComprehensionEngine::autocomplete_property(DocumentData const& document, MemberExpression const& parent, const DeprecatedString partial_text) const
  173. {
  174. VERIFY(parent.object());
  175. auto type = type_of(document, *parent.object());
  176. if (type.is_empty()) {
  177. dbgln_if(CPP_LANGUAGE_SERVER_DEBUG, "Could not infer type of object");
  178. return {};
  179. }
  180. Vector<CodeComprehension::AutocompleteResultEntry> 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(ASTNode const& 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. DeprecatedString CppComprehensionEngine::type_of_property(DocumentData const& document, Identifier const& 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. Type const* 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 DeprecatedString::empty();
  215. }
  216. return {};
  217. }
  218. DeprecatedString CppComprehensionEngine::type_of_variable(Identifier const& identifier) const
  219. {
  220. ASTNode const* 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 DeprecatedString::empty();
  230. }
  231. }
  232. }
  233. current = current->parent();
  234. }
  235. return {};
  236. }
  237. DeprecatedString CppComprehensionEngine::type_of(DocumentData const& document, Expression const& 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<Identifier const&>(*member_expression.property()));
  244. return {};
  245. }
  246. Identifier const* identifier { nullptr };
  247. if (expression.is_name()) {
  248. identifier = static_cast<Name const&>(expression).name();
  249. } else if (expression.is_identifier()) {
  250. identifier = &static_cast<Identifier const&>(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(DocumentData const& document, DeprecatedString const& 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, Vector<StringView> const& scope, NonnullRefPtr<Cpp::Declaration const> declaration, IsLocal is_local)
  284. {
  285. return { { name, scope }, move(declaration), is_local == IsLocal::Yes };
  286. }
  287. Vector<CppComprehensionEngine::Symbol> CppComprehensionEngine::get_child_symbols(ASTNode const& node) const
  288. {
  289. return get_child_symbols(node, {}, Symbol::IsLocal::No);
  290. }
  291. Vector<CppComprehensionEngine::Symbol> CppComprehensionEngine::get_child_symbols(ASTNode const& node, Vector<StringView> const& 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. DeprecatedString 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) -> DeprecatedString {
  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 DeprecatedString::formatted("/usr/include/{}", path);
  316. };
  317. auto document_path_for_user_defined_include = [&](StringView include_path) -> DeprecatedString {
  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_empty())
  325. result = document_path_for_user_defined_include(include_path);
  326. return result;
  327. }
  328. void CppComprehensionEngine::on_edit(DeprecatedString const& file)
  329. {
  330. set_document_data(file, create_document_data_for(file));
  331. }
  332. void CppComprehensionEngine::file_opened([[maybe_unused]] DeprecatedString const& file)
  333. {
  334. get_or_create_document_data(file);
  335. }
  336. Optional<CodeComprehension::ProjectLocation> CppComprehensionEngine::find_declaration_of(DeprecatedString const& filename, const GUI::TextPosition& identifier_position)
  337. {
  338. auto const* document_ptr = get_or_create_document_data(filename);
  339. if (!document_ptr)
  340. return {};
  341. auto const& document = *document_ptr;
  342. auto decl = find_declaration_of(document, identifier_position);
  343. if (decl) {
  344. return CodeComprehension::ProjectLocation { decl->filename(), decl->start().line, decl->start().column };
  345. }
  346. return find_preprocessor_definition(document, identifier_position);
  347. }
  348. RefPtr<Cpp::Declaration const> CppComprehensionEngine::find_declaration_of(DocumentData const& 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<CodeComprehension::ProjectLocation> CppComprehensionEngine::find_preprocessor_definition(DocumentData const& document, const GUI::TextPosition& text_position)
  358. {
  359. Position cpp_position { text_position.line(), text_position.column() };
  360. auto substitution = find_preprocessor_substitution(document, cpp_position);
  361. if (!substitution.has_value())
  362. return {};
  363. return CodeComprehension::ProjectLocation { substitution->defined_value.filename, substitution->defined_value.line, substitution->defined_value.column };
  364. }
  365. Optional<Cpp::Preprocessor::Substitution> CppComprehensionEngine::find_preprocessor_substitution(DocumentData const& document, Cpp::Position const& cpp_position)
  366. {
  367. // Search for a replaced preprocessor token that intersects with text_position
  368. for (auto& substitution : document.preprocessor().substitutions()) {
  369. if (substitution.original_tokens.first().start() > cpp_position)
  370. continue;
  371. if (substitution.original_tokens.first().end() < cpp_position)
  372. continue;
  373. return substitution;
  374. }
  375. return {};
  376. }
  377. struct TargetDeclaration {
  378. enum Type {
  379. Variable,
  380. Type,
  381. Function,
  382. Property,
  383. Scope
  384. } type;
  385. DeprecatedString name;
  386. };
  387. static Optional<TargetDeclaration> get_target_declaration(ASTNode const& node, DeprecatedString name);
  388. static Optional<TargetDeclaration> get_target_declaration(ASTNode const& node)
  389. {
  390. if (node.is_identifier()) {
  391. return get_target_declaration(node, static_cast<Identifier const&>(node).name());
  392. }
  393. if (node.is_declaration()) {
  394. return get_target_declaration(node, verify_cast<Cpp::Declaration>(node).full_name());
  395. }
  396. if (node.is_type() && node.parent() && node.parent()->is_declaration()) {
  397. return get_target_declaration(*node.parent(), verify_cast<Cpp::Declaration>(node.parent())->full_name());
  398. }
  399. dbgln("get_target_declaration: Invalid argument node of type: {}", node.class_name());
  400. return {};
  401. }
  402. static Optional<TargetDeclaration> get_target_declaration(ASTNode const& node, DeprecatedString name)
  403. {
  404. if (node.parent() && node.parent()->is_name()) {
  405. auto& name_node = *verify_cast<Name>(node.parent());
  406. if (&node != name_node.name()) {
  407. // Node is part of scope reference chain
  408. return TargetDeclaration { TargetDeclaration::Type::Scope, name };
  409. }
  410. if (name_node.parent() && name_node.parent()->is_declaration()) {
  411. auto declaration = verify_cast<Cpp::Declaration>(name_node.parent());
  412. if (declaration->is_struct_or_class() || declaration->is_enum()) {
  413. return TargetDeclaration { TargetDeclaration::Type::Type, name };
  414. }
  415. if (declaration->is_function()) {
  416. return TargetDeclaration { TargetDeclaration::Type::Function, name };
  417. }
  418. }
  419. }
  420. if ((node.parent() && node.parent()->is_function_call()) || (node.parent()->is_name() && node.parent()->parent() && node.parent()->parent()->is_function_call())) {
  421. return TargetDeclaration { TargetDeclaration::Type::Function, name };
  422. }
  423. if ((node.parent() && node.parent()->is_type()) || (node.parent()->is_name() && node.parent()->parent() && node.parent()->parent()->is_type()))
  424. return TargetDeclaration { TargetDeclaration::Type::Type, name };
  425. if ((node.parent() && node.parent()->is_member_expression()))
  426. return TargetDeclaration { TargetDeclaration::Type::Property, name };
  427. return TargetDeclaration { TargetDeclaration::Type::Variable, name };
  428. }
  429. RefPtr<Cpp::Declaration const> CppComprehensionEngine::find_declaration_of(DocumentData const& document_data, ASTNode const& node) const
  430. {
  431. dbgln_if(CPP_LANGUAGE_SERVER_DEBUG, "find_declaration_of: {} ({})", document_data.parser().text_of_node(node), node.class_name());
  432. auto target_decl = get_target_declaration(node);
  433. if (!target_decl.has_value())
  434. return {};
  435. auto reference_scope = scope_of_reference_to_symbol(node);
  436. auto current_scope = scope_of_node(node);
  437. auto symbol_matches = [&](Symbol const& symbol) {
  438. bool match_function = target_decl.value().type == TargetDeclaration::Function && symbol.declaration->is_function();
  439. bool match_variable = target_decl.value().type == TargetDeclaration::Variable && symbol.declaration->is_variable_declaration();
  440. bool match_type = target_decl.value().type == TargetDeclaration::Type && (symbol.declaration->is_struct_or_class() || symbol.declaration->is_enum());
  441. bool match_property = target_decl.value().type == TargetDeclaration::Property && symbol.declaration->parent()->is_declaration() && verify_cast<Cpp::Declaration>(symbol.declaration->parent())->is_struct_or_class();
  442. bool match_parameter = target_decl.value().type == TargetDeclaration::Variable && symbol.declaration->is_parameter();
  443. bool match_scope = target_decl.value().type == TargetDeclaration::Scope && (symbol.declaration->is_namespace() || symbol.declaration->is_struct_or_class());
  444. if (match_property) {
  445. // FIXME: This is not really correct, we also need to check that the type of the struct/class matches (not just the property name)
  446. if (symbol.name.name == target_decl.value().name) {
  447. return true;
  448. }
  449. }
  450. if (!is_symbol_available(symbol, current_scope, reference_scope)) {
  451. return false;
  452. }
  453. if (match_function || match_type || match_scope) {
  454. if (symbol.name.name == target_decl->name)
  455. return true;
  456. }
  457. if (match_variable || match_parameter) {
  458. // If this symbol was declared below us in a function, it's not available to us.
  459. bool is_unavailable = symbol.is_local && symbol.declaration->start().line > node.start().line;
  460. if (!is_unavailable && (symbol.name.name == target_decl->name)) {
  461. return true;
  462. }
  463. }
  464. return false;
  465. };
  466. Optional<Symbol> match;
  467. for_each_available_symbol(document_data, [&](Symbol const& symbol) {
  468. if (symbol_matches(symbol)) {
  469. match = symbol;
  470. return IterationDecision::Break;
  471. }
  472. return IterationDecision::Continue;
  473. });
  474. if (!match.has_value())
  475. return {};
  476. return match->declaration;
  477. }
  478. void CppComprehensionEngine::update_declared_symbols(DocumentData& document)
  479. {
  480. for (auto& symbol : get_child_symbols(*document.parser().root_node())) {
  481. document.m_symbols.set(symbol.name, move(symbol));
  482. }
  483. Vector<CodeComprehension::Declaration> declarations;
  484. for (auto& symbol_entry : document.m_symbols) {
  485. auto& symbol = symbol_entry.value;
  486. 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() });
  487. }
  488. for (auto& definition : document.preprocessor().definitions()) {
  489. declarations.append({ definition.key, { document.filename(), definition.value.line, definition.value.column }, CodeComprehension::DeclarationType::PreprocessorDefinition, {} });
  490. }
  491. set_declarations_of_document(document.filename(), move(declarations));
  492. }
  493. void CppComprehensionEngine::update_todo_entries(DocumentData& document)
  494. {
  495. set_todo_entries_of_document(document.filename(), document.parser().get_todo_entries());
  496. }
  497. CodeComprehension::DeclarationType CppComprehensionEngine::type_of_declaration(Cpp::Declaration const& decl)
  498. {
  499. if (decl.is_struct())
  500. return CodeComprehension::DeclarationType::Struct;
  501. if (decl.is_class())
  502. return CodeComprehension::DeclarationType::Class;
  503. if (decl.is_function())
  504. return CodeComprehension::DeclarationType::Function;
  505. if (decl.is_variable_declaration())
  506. return CodeComprehension::DeclarationType::Variable;
  507. if (decl.is_namespace())
  508. return CodeComprehension::DeclarationType::Namespace;
  509. if (decl.is_member())
  510. return CodeComprehension::DeclarationType::Member;
  511. return CodeComprehension::DeclarationType::Variable;
  512. }
  513. OwnPtr<CppComprehensionEngine::DocumentData> CppComprehensionEngine::create_document_data(DeprecatedString text, DeprecatedString const& filename)
  514. {
  515. auto document_data = make<DocumentData>();
  516. document_data->m_filename = filename;
  517. document_data->m_text = move(text);
  518. document_data->m_preprocessor = make<Preprocessor>(document_data->m_filename, document_data->text());
  519. document_data->preprocessor().set_ignore_unsupported_keywords(true);
  520. document_data->preprocessor().set_ignore_invalid_statements(true);
  521. document_data->preprocessor().set_keep_include_statements(true);
  522. document_data->preprocessor().definitions_in_header_callback = [this](StringView include_path) -> Preprocessor::Definitions {
  523. auto included_document = get_or_create_document_data(document_path_from_include_path(include_path));
  524. if (!included_document)
  525. return {};
  526. return included_document->preprocessor().definitions();
  527. };
  528. auto tokens = document_data->preprocessor().process_and_lex();
  529. for (auto include_path : document_data->preprocessor().included_paths()) {
  530. auto include_fullpath = document_path_from_include_path(include_path);
  531. auto included_document = get_or_create_document_data(include_fullpath);
  532. if (!included_document)
  533. continue;
  534. document_data->m_available_headers.set(include_fullpath);
  535. for (auto& header : included_document->m_available_headers)
  536. document_data->m_available_headers.set(header);
  537. }
  538. document_data->m_parser = make<Parser>(move(tokens), filename);
  539. auto root = document_data->parser().parse();
  540. if constexpr (CPP_LANGUAGE_SERVER_DEBUG)
  541. root->dump();
  542. update_declared_symbols(*document_data);
  543. update_todo_entries(*document_data);
  544. return document_data;
  545. }
  546. Vector<StringView> CppComprehensionEngine::scope_of_node(ASTNode const& node) const
  547. {
  548. auto parent = node.parent();
  549. if (!parent)
  550. return {};
  551. auto parent_scope = scope_of_node(*parent);
  552. if (!parent->is_declaration())
  553. return parent_scope;
  554. auto& parent_decl = static_cast<Cpp::Declaration const&>(*parent);
  555. StringView containing_scope;
  556. if (parent_decl.is_namespace())
  557. containing_scope = static_cast<NamespaceDeclaration const&>(parent_decl).full_name();
  558. if (parent_decl.is_struct_or_class())
  559. containing_scope = static_cast<StructOrClassDeclaration const&>(parent_decl).full_name();
  560. if (parent_decl.is_function())
  561. containing_scope = static_cast<FunctionDeclaration const&>(parent_decl).full_name();
  562. parent_scope.append(containing_scope);
  563. return parent_scope;
  564. }
  565. Optional<Vector<CodeComprehension::AutocompleteResultEntry>> CppComprehensionEngine::try_autocomplete_include(DocumentData const&, Token include_path_token, Cpp::Position const& cursor_position) const
  566. {
  567. VERIFY(include_path_token.type() == Token::Type::IncludePath);
  568. auto partial_include = include_path_token.text().trim_whitespace();
  569. enum IncludeType {
  570. Project,
  571. System,
  572. } include_type { Project };
  573. DeprecatedString include_root;
  574. bool already_has_suffix = false;
  575. if (partial_include.starts_with('<')) {
  576. include_root = "/usr/include/";
  577. include_type = System;
  578. if (partial_include.ends_with('>')) {
  579. already_has_suffix = true;
  580. partial_include = partial_include.substring_view(0, partial_include.length() - 1).trim_whitespace();
  581. }
  582. } else if (partial_include.starts_with('"')) {
  583. include_root = filedb().project_root().value_or("");
  584. if (partial_include.length() > 1 && partial_include.ends_with('\"')) {
  585. already_has_suffix = true;
  586. partial_include = partial_include.substring_view(0, partial_include.length() - 1).trim_whitespace();
  587. }
  588. } else
  589. return {};
  590. // The cursor is past the end of the <> or "", and so should not trigger autocomplete.
  591. if (already_has_suffix && include_path_token.end() <= cursor_position)
  592. return {};
  593. auto last_slash = partial_include.find_last('/');
  594. auto include_dir = DeprecatedString::empty();
  595. auto partial_basename = partial_include.substring_view((last_slash.has_value() ? last_slash.value() : 0) + 1);
  596. if (last_slash.has_value()) {
  597. include_dir = partial_include.substring_view(1, last_slash.value());
  598. }
  599. auto full_dir = LexicalPath::join(include_root, include_dir).string();
  600. dbgln_if(CPP_LANGUAGE_SERVER_DEBUG, "searching path: {}, partial_basename: {}", full_dir, partial_basename);
  601. Core::DirIterator it(full_dir, Core::DirIterator::Flags::SkipDots);
  602. Vector<CodeComprehension::AutocompleteResultEntry> options;
  603. auto prefix = include_type == System ? "<" : "\"";
  604. auto suffix = include_type == System ? ">" : "\"";
  605. while (it.has_next()) {
  606. auto path = it.next_path();
  607. if (!path.starts_with(partial_basename))
  608. continue;
  609. if (FileSystem::is_directory(LexicalPath::join(full_dir, path).string())) {
  610. // FIXME: Don't dismiss the autocomplete when filling these suggestions.
  611. auto completion = DeprecatedString::formatted("{}{}{}/", prefix, include_dir, path);
  612. options.empend(completion, include_dir.length() + partial_basename.length() + 1, CodeComprehension::Language::Cpp, path, CodeComprehension::AutocompleteResultEntry::HideAutocompleteAfterApplying::No);
  613. } else if (path.ends_with(".h"sv)) {
  614. // FIXME: Place the cursor after the trailing > or ", even if it was
  615. // already typed.
  616. auto completion = DeprecatedString::formatted("{}{}{}{}", prefix, include_dir, path, already_has_suffix ? "" : suffix);
  617. options.empend(completion, include_dir.length() + partial_basename.length() + 1, CodeComprehension::Language::Cpp, path);
  618. }
  619. }
  620. return options;
  621. }
  622. RefPtr<Cpp::Declaration const> CppComprehensionEngine::find_declaration_of(CppComprehensionEngine::DocumentData const& document, CppComprehensionEngine::SymbolName const& target_symbol_name) const
  623. {
  624. RefPtr<Cpp::Declaration const> target_declaration;
  625. for_each_available_symbol(document, [&](Symbol const& symbol) {
  626. if (symbol.name == target_symbol_name) {
  627. target_declaration = symbol.declaration;
  628. return IterationDecision::Break;
  629. }
  630. return IterationDecision::Continue;
  631. });
  632. return target_declaration;
  633. }
  634. DeprecatedString CppComprehensionEngine::SymbolName::scope_as_string() const
  635. {
  636. if (scope.is_empty())
  637. return DeprecatedString::empty();
  638. StringBuilder builder;
  639. for (size_t i = 0; i < scope.size() - 1; ++i) {
  640. builder.appendff("{}::", scope[i]);
  641. }
  642. builder.append(scope.last());
  643. return builder.to_deprecated_string();
  644. }
  645. CppComprehensionEngine::SymbolName CppComprehensionEngine::SymbolName::create(StringView name, Vector<StringView>&& scope)
  646. {
  647. return { name, move(scope) };
  648. }
  649. CppComprehensionEngine::SymbolName CppComprehensionEngine::SymbolName::create(StringView qualified_name)
  650. {
  651. auto parts = qualified_name.split_view("::"sv);
  652. VERIFY(!parts.is_empty());
  653. auto name = parts.take_last();
  654. return SymbolName::create(name, move(parts));
  655. }
  656. DeprecatedString CppComprehensionEngine::SymbolName::to_deprecated_string() const
  657. {
  658. if (scope.is_empty())
  659. return name;
  660. return DeprecatedString::formatted("{}::{}", scope_as_string(), name);
  661. }
  662. bool CppComprehensionEngine::is_symbol_available(Symbol const& symbol, Vector<StringView> const& current_scope, Vector<StringView> const& reference_scope)
  663. {
  664. if (!reference_scope.is_empty()) {
  665. return reference_scope == symbol.name.scope;
  666. }
  667. // FIXME: Take "using namespace ..." into consideration
  668. // Check if current_scope starts with symbol's scope
  669. if (symbol.name.scope.size() > current_scope.size())
  670. return false;
  671. for (size_t i = 0; i < symbol.name.scope.size(); ++i) {
  672. if (current_scope[i] != symbol.name.scope[i])
  673. return false;
  674. }
  675. return true;
  676. }
  677. Optional<CodeComprehensionEngine::FunctionParamsHint> CppComprehensionEngine::get_function_params_hint(DeprecatedString const& filename, const GUI::TextPosition& identifier_position)
  678. {
  679. auto const* document_ptr = get_or_create_document_data(filename);
  680. if (!document_ptr)
  681. return {};
  682. auto const& document = *document_ptr;
  683. Cpp::Position cpp_position { identifier_position.line(), identifier_position.column() };
  684. auto node = document.parser().node_at(cpp_position);
  685. if (!node) {
  686. dbgln_if(CPP_LANGUAGE_SERVER_DEBUG, "no node at position {}:{}", identifier_position.line(), identifier_position.column());
  687. return {};
  688. }
  689. dbgln_if(CPP_LANGUAGE_SERVER_DEBUG, "node type: {}", node->class_name());
  690. FunctionCall const* call_node { nullptr };
  691. if (node->is_function_call()) {
  692. call_node = verify_cast<FunctionCall>(node.ptr());
  693. auto token = document.parser().token_at(cpp_position);
  694. // If we're in a function call with 0 arguments
  695. if (token.has_value() && (token->type() == Token::Type::LeftParen || token->type() == Token::Type::RightParen)) {
  696. return get_function_params_hint(document, *call_node, call_node->arguments().is_empty() ? 0 : call_node->arguments().size() - 1);
  697. }
  698. }
  699. // Walk upwards in the AST to find a FunctionCall node
  700. while (!call_node && node) {
  701. auto parent_is_call = node->parent() && node->parent()->is_function_call();
  702. if (parent_is_call) {
  703. call_node = verify_cast<FunctionCall>(node->parent());
  704. break;
  705. }
  706. node = node->parent();
  707. }
  708. if (!call_node) {
  709. dbgln("did not find function call");
  710. return {};
  711. }
  712. Optional<size_t> invoked_arg_index;
  713. for (size_t arg_index = 0; arg_index < call_node->arguments().size(); ++arg_index) {
  714. if (call_node->arguments()[arg_index] == node.ptr()) {
  715. invoked_arg_index = arg_index;
  716. break;
  717. }
  718. }
  719. if (!invoked_arg_index.has_value()) {
  720. dbgln_if(CPP_LANGUAGE_SERVER_DEBUG, "could not find argument index, defaulting to the last argument");
  721. invoked_arg_index = call_node->arguments().is_empty() ? 0 : call_node->arguments().size() - 1;
  722. }
  723. dbgln_if(CPP_LANGUAGE_SERVER_DEBUG, "arg index: {}", invoked_arg_index.value());
  724. return get_function_params_hint(document, *call_node, invoked_arg_index.value());
  725. }
  726. Optional<CppComprehensionEngine::FunctionParamsHint> CppComprehensionEngine::get_function_params_hint(
  727. DocumentData const& document,
  728. FunctionCall const& call_node,
  729. size_t argument_index)
  730. {
  731. Identifier const* callee = nullptr;
  732. VERIFY(call_node.callee());
  733. if (call_node.callee()->is_identifier()) {
  734. callee = verify_cast<Identifier>(call_node.callee());
  735. } else if (call_node.callee()->is_name()) {
  736. callee = verify_cast<Name>(*call_node.callee()).name();
  737. } else if (call_node.callee()->is_member_expression()) {
  738. auto& member_exp = verify_cast<MemberExpression>(*call_node.callee());
  739. VERIFY(member_exp.property());
  740. if (member_exp.property()->is_identifier()) {
  741. callee = verify_cast<Identifier>(member_exp.property());
  742. }
  743. }
  744. if (!callee) {
  745. dbgln("unexpected node type for function call: {}", call_node.callee()->class_name());
  746. return {};
  747. }
  748. VERIFY(callee);
  749. auto decl = find_declaration_of(document, *callee);
  750. if (!decl) {
  751. dbgln("func decl not found");
  752. return {};
  753. }
  754. if (!decl->is_function()) {
  755. dbgln("declaration is not a function");
  756. return {};
  757. }
  758. auto& func_decl = verify_cast<FunctionDeclaration>(*decl);
  759. auto document_of_declaration = get_document_data(func_decl.filename());
  760. FunctionParamsHint hint {};
  761. hint.current_index = argument_index;
  762. for (auto& arg : func_decl.parameters()) {
  763. Vector<StringView> tokens_text;
  764. for (auto token : document_of_declaration->parser().tokens_in_range(arg->start(), arg->end())) {
  765. tokens_text.append(token.text());
  766. }
  767. hint.params.append(DeprecatedString::join(' ', tokens_text));
  768. }
  769. return hint;
  770. }
  771. Vector<CodeComprehension::TokenInfo> CppComprehensionEngine::get_tokens_info(DeprecatedString const& filename)
  772. {
  773. dbgln_if(CPP_LANGUAGE_SERVER_DEBUG, "CppComprehensionEngine::get_tokens_info: {}", filename);
  774. auto const* document_ptr = get_or_create_document_data(filename);
  775. if (!document_ptr)
  776. return {};
  777. auto const& document = *document_ptr;
  778. Vector<CodeComprehension::TokenInfo> tokens_info;
  779. for (auto const& token : document.preprocessor().unprocessed_tokens()) {
  780. tokens_info.append({ get_token_semantic_type(document, token),
  781. token.start().line, token.start().column, token.end().line, token.end().column });
  782. dbgln_if(CPP_LANGUAGE_SERVER_DEBUG, "{}: {}", token.text(), CodeComprehension::TokenInfo::type_to_string(tokens_info.last().type));
  783. }
  784. return tokens_info;
  785. }
  786. CodeComprehension::TokenInfo::SemanticType CppComprehensionEngine::get_token_semantic_type(DocumentData const& document, Token const& token)
  787. {
  788. using GUI::AutocompleteProvider;
  789. switch (token.type()) {
  790. case Cpp::Token::Type::Identifier:
  791. return get_semantic_type_for_identifier(document, token.start());
  792. case Cpp::Token::Type::Keyword:
  793. return CodeComprehension::TokenInfo::SemanticType::Keyword;
  794. case Cpp::Token::Type::KnownType:
  795. return CodeComprehension::TokenInfo::SemanticType::Type;
  796. case Cpp::Token::Type::DoubleQuotedString:
  797. case Cpp::Token::Type::SingleQuotedString:
  798. case Cpp::Token::Type::RawString:
  799. return CodeComprehension::TokenInfo::SemanticType::String;
  800. case Cpp::Token::Type::Integer:
  801. case Cpp::Token::Type::Float:
  802. return CodeComprehension::TokenInfo::SemanticType::Number;
  803. case Cpp::Token::Type::IncludePath:
  804. return CodeComprehension::TokenInfo::SemanticType::IncludePath;
  805. case Cpp::Token::Type::EscapeSequence:
  806. return CodeComprehension::TokenInfo::SemanticType::Keyword;
  807. case Cpp::Token::Type::PreprocessorStatement:
  808. case Cpp::Token::Type::IncludeStatement:
  809. return CodeComprehension::TokenInfo::SemanticType::PreprocessorStatement;
  810. case Cpp::Token::Type::Comment:
  811. return CodeComprehension::TokenInfo::SemanticType::Comment;
  812. default:
  813. return CodeComprehension::TokenInfo::SemanticType::Unknown;
  814. }
  815. }
  816. CodeComprehension::TokenInfo::SemanticType CppComprehensionEngine::get_semantic_type_for_identifier(DocumentData const& document, Position position)
  817. {
  818. if (find_preprocessor_substitution(document, position).has_value())
  819. return CodeComprehension::TokenInfo::SemanticType::PreprocessorMacro;
  820. auto decl = find_declaration_of(document, GUI::TextPosition { position.line, position.column });
  821. if (!decl)
  822. return CodeComprehension::TokenInfo::SemanticType::Identifier;
  823. if (decl->is_function())
  824. return CodeComprehension::TokenInfo::SemanticType::Function;
  825. if (decl->is_parameter())
  826. return CodeComprehension::TokenInfo::SemanticType::Parameter;
  827. if (decl->is_variable_declaration()) {
  828. if (decl->is_member())
  829. return CodeComprehension::TokenInfo::SemanticType::Member;
  830. return CodeComprehension::TokenInfo::SemanticType::Variable;
  831. }
  832. if (decl->is_struct_or_class() || decl->is_enum())
  833. return CodeComprehension::TokenInfo::SemanticType::CustomType;
  834. if (decl->is_namespace())
  835. return CodeComprehension::TokenInfo::SemanticType::Namespace;
  836. return CodeComprehension::TokenInfo::SemanticType::Identifier;
  837. }
  838. }