check_unit.cpp 21 KB

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