check_unit.cpp 19 KB

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