check_unit.cpp 20 KB

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