CppComprehensionEngine.cpp 38 KB

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