check_unit.cpp 17 KB

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