check_unit.cpp 18 KB

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