check_unit.cpp 21 KB

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