check_unit.cpp 18 KB

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