check_unit.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include "toolchain/check/check_unit.h"
  5. #include <string>
  6. #include <utility>
  7. #include "llvm/ADT/IntrusiveRefCntPtr.h"
  8. #include "llvm/ADT/StringRef.h"
  9. #include "llvm/Support/VirtualFileSystem.h"
  10. #include "toolchain/base/kind_switch.h"
  11. #include "toolchain/base/pretty_stack_trace_function.h"
  12. #include "toolchain/check/generic.h"
  13. #include "toolchain/check/handle.h"
  14. #include "toolchain/check/impl.h"
  15. #include "toolchain/check/import.h"
  16. #include "toolchain/check/import_cpp.h"
  17. #include "toolchain/check/import_ref.h"
  18. #include "toolchain/check/inst.h"
  19. #include "toolchain/check/node_id_traversal.h"
  20. #include "toolchain/check/type.h"
  21. #include "toolchain/sem_ir/function.h"
  22. #include "toolchain/sem_ir/ids.h"
  23. #include "toolchain/sem_ir/import_ir.h"
  24. namespace Carbon::Check {
  25. // Returns the number of imported IRs, to assist in Context construction.
  26. static auto GetImportedIRCount(UnitAndImports* unit_and_imports) -> int {
  27. int count = 0;
  28. for (auto& package_imports : unit_and_imports->package_imports) {
  29. count += package_imports.imports.size();
  30. }
  31. if (!unit_and_imports->api_for_impl) {
  32. // Leave an empty slot for ImportIRId::ApiForImpl.
  33. ++count;
  34. }
  35. return count;
  36. }
  37. CheckUnit::CheckUnit(
  38. UnitAndImports* unit_and_imports,
  39. llvm::ArrayRef<Parse::GetTreeAndSubtreesFn> tree_and_subtrees_getters,
  40. llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> fs,
  41. llvm::raw_ostream* vlog_stream)
  42. : unit_and_imports_(unit_and_imports),
  43. total_ir_count_(tree_and_subtrees_getters.size()),
  44. fs_(std::move(fs)),
  45. vlog_stream_(vlog_stream),
  46. emitter_(&unit_and_imports_->err_tracker, tree_and_subtrees_getters,
  47. unit_and_imports_->unit->sem_ir),
  48. context_(&emitter_, unit_and_imports_->unit->tree_and_subtrees_getter,
  49. unit_and_imports_->unit->sem_ir,
  50. GetImportedIRCount(unit_and_imports),
  51. tree_and_subtrees_getters.size(), vlog_stream) {}
  52. auto CheckUnit::Run() -> void {
  53. Timings::ScopedTiming timing(unit_and_imports_->unit->timings, "check");
  54. // We can safely mark this as checked at the start.
  55. unit_and_imports_->is_checked = true;
  56. PrettyStackTraceFunction context_dumper(
  57. [&](llvm::raw_ostream& output) { context_.PrintForStackDump(output); });
  58. // Add a block for the file.
  59. context_.inst_block_stack().Push();
  60. InitPackageScopeAndImports();
  61. // Eagerly import the impls declared in the api file to prepare to redeclare
  62. // them.
  63. ImportImplsFromApiFile(context_);
  64. if (!ProcessNodeIds()) {
  65. context_.sem_ir().set_has_errors(true);
  66. return;
  67. }
  68. FinishRun();
  69. }
  70. auto CheckUnit::InitPackageScopeAndImports() -> void {
  71. // Importing makes many namespaces, so only canonicalize the type once.
  72. auto namespace_type_id =
  73. GetSingletonType(context_, SemIR::NamespaceType::TypeInstId);
  74. // Define the package scope, with an instruction for `package` expressions to
  75. // reference.
  76. auto package_scope_id = context_.name_scopes().Add(
  77. SemIR::Namespace::PackageInstId, SemIR::NameId::PackageNamespace,
  78. SemIR::NameScopeId::None);
  79. CARBON_CHECK(package_scope_id == SemIR::NameScopeId::Package);
  80. auto package_inst_id =
  81. AddInst<SemIR::Namespace>(context_, Parse::NodeId::None,
  82. {.type_id = namespace_type_id,
  83. .name_scope_id = SemIR::NameScopeId::Package,
  84. .import_id = SemIR::InstId::None});
  85. CARBON_CHECK(package_inst_id == SemIR::Namespace::PackageInstId);
  86. // If there is an implicit `api` import, set it first so that it uses the
  87. // ImportIRId::ApiForImpl when processed for imports.
  88. if (unit_and_imports_->api_for_impl) {
  89. const auto& names = context_.parse_tree().packaging_decl()->names;
  90. auto import_decl_id = AddInst<SemIR::ImportDecl>(
  91. context_, names.node_id,
  92. {.package_id = SemIR::NameId::ForPackageName(names.package_id)});
  93. SetApiImportIR(context_,
  94. {.decl_id = import_decl_id,
  95. .is_export = false,
  96. .sem_ir = unit_and_imports_->api_for_impl->unit->sem_ir});
  97. } else {
  98. SetApiImportIR(context_,
  99. {.decl_id = SemIR::InstId::None, .sem_ir = nullptr});
  100. }
  101. // Add import instructions for everything directly imported. Implicit imports
  102. // are handled separately.
  103. for (auto& package_imports : unit_and_imports_->package_imports) {
  104. CARBON_CHECK(!package_imports.import_decl_id.has_value());
  105. package_imports.import_decl_id = AddInst<SemIR::ImportDecl>(
  106. context_, package_imports.node_id,
  107. {.package_id =
  108. SemIR::NameId::ForPackageName(package_imports.package_id)});
  109. }
  110. // Process the imports.
  111. if (unit_and_imports_->api_for_impl) {
  112. ImportApiFile(context_, namespace_type_id,
  113. *unit_and_imports_->api_for_impl->unit->sem_ir);
  114. }
  115. ImportCurrentPackage(package_inst_id, namespace_type_id);
  116. CARBON_CHECK(context_.scope_stack().PeekIndex() == ScopeIndex::Package);
  117. ImportOtherPackages(namespace_type_id);
  118. const auto& cpp_import_names = unit_and_imports_->cpp_import_names;
  119. if (!cpp_import_names.empty()) {
  120. auto* cpp_ast = unit_and_imports_->unit->cpp_ast;
  121. CARBON_CHECK(cpp_ast);
  122. CARBON_CHECK(!cpp_ast->get());
  123. *cpp_ast =
  124. ImportCppFiles(context_, unit_and_imports_->unit->sem_ir->filename(),
  125. cpp_import_names, fs_);
  126. }
  127. }
  128. auto CheckUnit::CollectDirectImports(
  129. llvm::SmallVector<SemIR::ImportIR>& results,
  130. llvm::MutableArrayRef<int> ir_to_result_index, SemIR::InstId import_decl_id,
  131. const PackageImports& imports, bool is_local) -> void {
  132. for (const auto& import : imports.imports) {
  133. const auto& direct_ir = *import.unit_info->unit->sem_ir;
  134. auto& index = ir_to_result_index[direct_ir.check_ir_id().index];
  135. if (index != -1) {
  136. // This should only happen when doing API imports for an implementation
  137. // file. Don't change the entry; is_export doesn't matter.
  138. continue;
  139. }
  140. index = results.size();
  141. results.push_back({.decl_id = import_decl_id,
  142. // Only tag exports in API files, ignoring the value in
  143. // implementation files.
  144. .is_export = is_local && import.names.is_export,
  145. .sem_ir = &direct_ir});
  146. }
  147. }
  148. auto CheckUnit::CollectTransitiveImports(SemIR::InstId import_decl_id,
  149. const PackageImports* local_imports,
  150. const PackageImports* api_imports)
  151. -> llvm::SmallVector<SemIR::ImportIR> {
  152. llvm::SmallVector<SemIR::ImportIR> results;
  153. // Track whether an IR was imported in full, including `export import`. This
  154. // distinguishes from IRs that are indirectly added without all names being
  155. // exported to this IR.
  156. llvm::SmallVector<int> ir_to_result_index(total_ir_count_, -1);
  157. // First add direct imports. This means that if an entity is imported both
  158. // directly and indirectly, the import path will reflect the direct import.
  159. if (local_imports) {
  160. CollectDirectImports(results, ir_to_result_index, import_decl_id,
  161. *local_imports,
  162. /*is_local=*/true);
  163. }
  164. if (api_imports) {
  165. CollectDirectImports(results, ir_to_result_index, import_decl_id,
  166. *api_imports,
  167. /*is_local=*/false);
  168. }
  169. // Loop through direct imports for any indirect exports. The underlying vector
  170. // is appended during iteration, so take the size first.
  171. const int direct_imports = results.size();
  172. for (int direct_index : llvm::seq(direct_imports)) {
  173. bool is_export = results[direct_index].is_export;
  174. for (const auto& indirect_ir :
  175. results[direct_index].sem_ir->import_irs().array_ref()) {
  176. if (!indirect_ir.is_export) {
  177. continue;
  178. }
  179. auto& indirect_index =
  180. ir_to_result_index[indirect_ir.sem_ir->check_ir_id().index];
  181. if (indirect_index == -1) {
  182. indirect_index = results.size();
  183. // TODO: In the case of a recursive `export import`, this only points at
  184. // the outermost import. May want something that better reflects the
  185. // recursion.
  186. results.push_back({.decl_id = results[direct_index].decl_id,
  187. .is_export = is_export,
  188. .sem_ir = indirect_ir.sem_ir});
  189. } else if (is_export) {
  190. results[indirect_index].is_export = true;
  191. }
  192. }
  193. }
  194. return results;
  195. }
  196. auto CheckUnit::ImportCurrentPackage(SemIR::InstId package_inst_id,
  197. SemIR::TypeId namespace_type_id) -> void {
  198. // Add imports from the current package.
  199. auto import_map_lookup =
  200. unit_and_imports_->package_imports_map.Lookup(PackageNameId::None);
  201. if (!import_map_lookup) {
  202. // Push the scope; there are no names to add.
  203. context_.scope_stack().Push(package_inst_id, SemIR::NameScopeId::Package);
  204. return;
  205. }
  206. PackageImports& self_import =
  207. unit_and_imports_->package_imports[import_map_lookup.value()];
  208. if (self_import.has_load_error) {
  209. context_.name_scopes().Get(SemIR::NameScopeId::Package).set_has_error();
  210. }
  211. ImportLibrariesFromCurrentPackage(
  212. context_, namespace_type_id,
  213. CollectTransitiveImports(self_import.import_decl_id, &self_import,
  214. /*api_imports=*/nullptr));
  215. context_.scope_stack().Push(
  216. package_inst_id, SemIR::NameScopeId::Package, SemIR::SpecificId::None,
  217. context_.name_scopes().Get(SemIR::NameScopeId::Package).has_error());
  218. }
  219. auto CheckUnit::ImportOtherPackages(SemIR::TypeId namespace_type_id) -> void {
  220. // api_imports_list is initially the size of the current file's imports,
  221. // including for API files, for simplicity in iteration. It's only really used
  222. // when processing an implementation file, in order to combine the API file
  223. // imports.
  224. //
  225. // For packages imported by the API file, the PackageNameId is the package
  226. // name and the index is into the API's import list. Otherwise, the initial
  227. // {None, -1} state remains.
  228. llvm::SmallVector<std::pair<PackageNameId, int32_t>> api_imports_list;
  229. api_imports_list.resize(unit_and_imports_->package_imports.size(),
  230. {PackageNameId::None, -1});
  231. // When there's an API file, add the mapping to api_imports_list.
  232. if (unit_and_imports_->api_for_impl) {
  233. const auto& api_identifiers =
  234. unit_and_imports_->api_for_impl->unit->value_stores->identifiers();
  235. auto& impl_identifiers =
  236. unit_and_imports_->unit->value_stores->identifiers();
  237. for (auto [api_imports_index, api_imports] :
  238. llvm::enumerate(unit_and_imports_->api_for_impl->package_imports)) {
  239. // Skip the current package.
  240. if (!api_imports.package_id.has_value()) {
  241. continue;
  242. }
  243. // Translate the package ID from the API file to the implementation file.
  244. auto impl_package_id = api_imports.package_id;
  245. if (auto package_identifier_id = impl_package_id.AsIdentifierId();
  246. package_identifier_id.has_value()) {
  247. impl_package_id = PackageNameId::ForIdentifier(
  248. impl_identifiers.Add(api_identifiers.Get(package_identifier_id)));
  249. }
  250. if (auto lookup =
  251. unit_and_imports_->package_imports_map.Lookup(impl_package_id)) {
  252. // On a hit, replace the entry to unify the API and implementation
  253. // imports.
  254. api_imports_list[lookup.value()] = {impl_package_id, api_imports_index};
  255. } else {
  256. // On a miss, add the package as API-only.
  257. api_imports_list.push_back({impl_package_id, api_imports_index});
  258. }
  259. }
  260. }
  261. for (auto [i, api_imports_entry] : llvm::enumerate(api_imports_list)) {
  262. // These variables are updated after figuring out which imports are present.
  263. auto import_decl_id = SemIR::InstId::None;
  264. PackageNameId package_id = PackageNameId::None;
  265. bool has_load_error = false;
  266. // Identify the local package imports if present.
  267. PackageImports* local_imports = nullptr;
  268. if (i < unit_and_imports_->package_imports.size()) {
  269. local_imports = &unit_and_imports_->package_imports[i];
  270. if (!local_imports->package_id.has_value()) {
  271. // Skip the current package.
  272. continue;
  273. }
  274. import_decl_id = local_imports->import_decl_id;
  275. package_id = local_imports->package_id;
  276. has_load_error |= local_imports->has_load_error;
  277. }
  278. // Identify the API package imports if present.
  279. PackageImports* api_imports = nullptr;
  280. if (api_imports_entry.second != -1) {
  281. api_imports = &unit_and_imports_->api_for_impl
  282. ->package_imports[api_imports_entry.second];
  283. if (local_imports) {
  284. CARBON_CHECK(package_id == api_imports_entry.first);
  285. } else {
  286. auto import_ir_inst_id = context_.import_ir_insts().Add(
  287. {.ir_id = SemIR::ImportIRId::ApiForImpl,
  288. .inst_id = api_imports->import_decl_id});
  289. import_decl_id =
  290. AddInst(context_, MakeImportedLocIdAndInst<SemIR::ImportDecl>(
  291. context_, import_ir_inst_id,
  292. {.package_id = SemIR::NameId::ForPackageName(
  293. api_imports_entry.first)}));
  294. package_id = api_imports_entry.first;
  295. }
  296. has_load_error |= api_imports->has_load_error;
  297. }
  298. // Do the actual import.
  299. ImportLibrariesFromOtherPackage(
  300. context_, namespace_type_id, import_decl_id, package_id,
  301. CollectTransitiveImports(import_decl_id, local_imports, api_imports),
  302. has_load_error);
  303. }
  304. }
  305. // Loops over all nodes in the tree. On some errors, this may return early,
  306. // for example if an unrecoverable state is encountered.
  307. // NOLINTNEXTLINE(readability-function-size)
  308. auto CheckUnit::ProcessNodeIds() -> bool {
  309. NodeIdTraversal traversal(&context_, vlog_stream_);
  310. Parse::NodeId node_id = Parse::NodeId::None;
  311. // On crash, report which token we were handling.
  312. PrettyStackTraceFunction node_dumper([&](llvm::raw_ostream& output) {
  313. const auto& tree = unit_and_imports_->unit->tree_and_subtrees_getter();
  314. auto converted = tree.NodeToDiagnosticLoc(node_id, /*token_only=*/false);
  315. converted.loc.FormatLocation(output);
  316. output << "checking " << context_.parse_tree().node_kind(node_id) << "\n";
  317. // Crash output has a tab indent; try to indent slightly past that.
  318. converted.loc.FormatSnippet(output, /*indent=*/10);
  319. });
  320. while (auto maybe_node_id = traversal.Next()) {
  321. node_id = *maybe_node_id;
  322. emitter_.AdvanceToken(context_.parse_tree().node_token(node_id));
  323. if (context_.parse_tree().node_has_error(node_id)) {
  324. context_.TODO(node_id, "handle invalid parse trees in `check`");
  325. return false;
  326. }
  327. bool result;
  328. auto parse_kind = context_.parse_tree().node_kind(node_id);
  329. switch (parse_kind) {
  330. #define CARBON_PARSE_NODE_KIND(Name) \
  331. case Parse::NodeKind::Name: { \
  332. result = HandleParseNode( \
  333. context_, context_.parse_tree().As<Parse::Name##Id>(node_id)); \
  334. break; \
  335. }
  336. #include "toolchain/parse/node_kind.def"
  337. }
  338. if (!result) {
  339. CARBON_CHECK(
  340. unit_and_imports_->err_tracker.seen_error(),
  341. "HandleParseNode for `{0}` returned false without diagnosing.",
  342. parse_kind);
  343. return false;
  344. }
  345. traversal.Handle(parse_kind);
  346. }
  347. return true;
  348. }
  349. auto CheckUnit::CheckRequiredDeclarations() -> void {
  350. for (const auto& function : context_.functions().array_ref()) {
  351. if (!function.first_owning_decl_id.has_value() &&
  352. function.extern_library_id == context_.sem_ir().library_id()) {
  353. auto function_loc_id =
  354. context_.insts().GetLocId(function.non_owning_decl_id);
  355. CARBON_CHECK(function_loc_id.kind() ==
  356. SemIR::LocId::Kind::ImportIRInstId);
  357. auto import_ir_id = context_.sem_ir()
  358. .import_ir_insts()
  359. .Get(function_loc_id.import_ir_inst_id())
  360. .ir_id;
  361. auto& import_ir = context_.import_irs().Get(import_ir_id);
  362. if (import_ir.sem_ir->package_id().has_value() !=
  363. context_.sem_ir().package_id().has_value()) {
  364. continue;
  365. }
  366. CARBON_DIAGNOSTIC(
  367. MissingOwningDeclarationInApi, Error,
  368. "owning declaration required for non-owning declaration");
  369. if (!import_ir.sem_ir->package_id().has_value() &&
  370. !context_.sem_ir().package_id().has_value()) {
  371. emitter_.Emit(function.non_owning_decl_id,
  372. MissingOwningDeclarationInApi);
  373. continue;
  374. }
  375. if (import_ir.sem_ir->identifiers().Get(
  376. import_ir.sem_ir->package_id().AsIdentifierId()) ==
  377. context_.sem_ir().identifiers().Get(
  378. context_.sem_ir().package_id().AsIdentifierId())) {
  379. emitter_.Emit(function.non_owning_decl_id,
  380. MissingOwningDeclarationInApi);
  381. }
  382. }
  383. }
  384. }
  385. auto CheckUnit::CheckRequiredDefinitions() -> void {
  386. CARBON_DIAGNOSTIC(MissingDefinitionInImpl, Error,
  387. "no definition found for declaration in impl file");
  388. // Note that more required definitions can be added during this loop.
  389. // NOLINTNEXTLINE(modernize-loop-convert)
  390. for (size_t i = 0; i != context_.definitions_required_by_decl().size(); ++i) {
  391. SemIR::InstId decl_inst_id = context_.definitions_required_by_decl()[i];
  392. SemIR::Inst decl_inst = context_.insts().Get(decl_inst_id);
  393. CARBON_KIND_SWITCH(context_.insts().Get(decl_inst_id)) {
  394. case CARBON_KIND(SemIR::ClassDecl class_decl): {
  395. if (!context_.classes().Get(class_decl.class_id).is_complete()) {
  396. emitter_.Emit(decl_inst_id, MissingDefinitionInImpl);
  397. }
  398. break;
  399. }
  400. case CARBON_KIND(SemIR::FunctionDecl function_decl): {
  401. if (context_.functions().Get(function_decl.function_id).definition_id ==
  402. SemIR::InstId::None) {
  403. emitter_.Emit(decl_inst_id, MissingDefinitionInImpl);
  404. }
  405. break;
  406. }
  407. case CARBON_KIND(SemIR::ImplDecl impl_decl): {
  408. auto& impl = context_.impls().Get(impl_decl.impl_id);
  409. if (!impl.is_complete()) {
  410. FillImplWitnessWithErrors(context_, impl);
  411. CARBON_DIAGNOSTIC(ImplMissingDefinition, Error,
  412. "impl declared but not defined");
  413. emitter_.Emit(decl_inst_id, ImplMissingDefinition);
  414. }
  415. break;
  416. }
  417. case SemIR::InterfaceDecl::Kind: {
  418. // TODO: Handle `interface` as well, once we can test it without
  419. // triggering
  420. // https://github.com/carbon-language/carbon-lang/issues/4071.
  421. CARBON_FATAL("TODO: Support interfaces in DiagnoseMissingDefinitions");
  422. }
  423. default: {
  424. CARBON_FATAL("Unexpected inst in definitions_required_by_decl: {0}",
  425. decl_inst);
  426. }
  427. }
  428. }
  429. // Note that more required definitions can be added during this loop.
  430. // NOLINTNEXTLINE(modernize-loop-convert)
  431. for (size_t i = 0; i != context_.definitions_required_by_use().size(); ++i) {
  432. // This is using the location for the use. We could track the
  433. // list of enclosing locations if this was used from a generic.
  434. auto [loc, specific_id] = context_.definitions_required_by_use()[i];
  435. if (!ResolveSpecificDefinition(context_, loc, specific_id)) {
  436. CARBON_DIAGNOSTIC(MissingGenericFunctionDefinition, Error,
  437. "use of undefined generic function");
  438. CARBON_DIAGNOSTIC(MissingGenericFunctionDefinitionHere, Note,
  439. "generic function declared here");
  440. auto generic_decl_id =
  441. context_.generics()
  442. .Get(context_.specifics().Get(specific_id).generic_id)
  443. .decl_id;
  444. emitter_.Build(loc, MissingGenericFunctionDefinition)
  445. .Note(generic_decl_id, MissingGenericFunctionDefinitionHere)
  446. .Emit();
  447. }
  448. }
  449. }
  450. auto CheckUnit::FinishRun() -> void {
  451. CheckRequiredDeclarations();
  452. CheckRequiredDefinitions();
  453. // Pop information for the file-level scope.
  454. context_.sem_ir().set_top_inst_block_id(context_.inst_block_stack().Pop());
  455. context_.scope_stack().Pop();
  456. // Finalizes the list of exports on the IR.
  457. context_.inst_blocks().ReplacePlaceholder(SemIR::InstBlockId::Exports,
  458. context_.exports());
  459. // Finalizes the ImportRef inst block.
  460. context_.inst_blocks().ReplacePlaceholder(SemIR::InstBlockId::ImportRefs,
  461. context_.import_ref_ids());
  462. // Finalizes __global_init.
  463. context_.global_init().Finalize();
  464. context_.sem_ir().set_has_errors(unit_and_imports_->err_tracker.seen_error());
  465. // Verify that Context cleanly finished.
  466. context_.VerifyOnFinish();
  467. }
  468. } // namespace Carbon::Check