check_unit.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  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::ForIdentifier(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::ForIdentifier(
  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(IdentifierId::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 IdentifierId is the package name
  219. // and the index is into the API's import list. Otherwise, the initial
  220. // {None, -1} state remains.
  221. llvm::SmallVector<std::pair<IdentifierId, int32_t>> api_imports_list;
  222. api_imports_list.resize(unit_and_imports_->package_imports.size(),
  223. {IdentifierId::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 =
  238. impl_identifiers.Add(api_identifiers.Get(api_imports.package_id));
  239. if (auto lookup =
  240. unit_and_imports_->package_imports_map.Lookup(impl_package_id)) {
  241. // On a hit, replace the entry to unify the API and implementation
  242. // imports.
  243. api_imports_list[lookup.value()] = {impl_package_id, api_imports_index};
  244. } else {
  245. // On a miss, add the package as API-only.
  246. api_imports_list.push_back({impl_package_id, api_imports_index});
  247. }
  248. }
  249. }
  250. for (auto [i, api_imports_entry] : llvm::enumerate(api_imports_list)) {
  251. // These variables are updated after figuring out which imports are present.
  252. auto import_decl_id = SemIR::InstId::None;
  253. IdentifierId package_id = IdentifierId::None;
  254. bool has_load_error = false;
  255. // Identify the local package imports if present.
  256. PackageImports* local_imports = nullptr;
  257. if (i < unit_and_imports_->package_imports.size()) {
  258. local_imports = &unit_and_imports_->package_imports[i];
  259. if (!local_imports->package_id.has_value()) {
  260. // Skip the current package.
  261. continue;
  262. }
  263. import_decl_id = local_imports->import_decl_id;
  264. package_id = local_imports->package_id;
  265. has_load_error |= local_imports->has_load_error;
  266. }
  267. // Identify the API package imports if present.
  268. PackageImports* api_imports = nullptr;
  269. if (api_imports_entry.second != -1) {
  270. api_imports = &unit_and_imports_->api_for_impl
  271. ->package_imports[api_imports_entry.second];
  272. if (local_imports) {
  273. CARBON_CHECK(package_id == api_imports_entry.first);
  274. } else {
  275. auto import_ir_inst_id = context_.import_ir_insts().Add(
  276. {.ir_id = SemIR::ImportIRId::ApiForImpl,
  277. .inst_id = api_imports->import_decl_id});
  278. import_decl_id =
  279. context_.AddInst(context_.MakeImportedLocAndInst<SemIR::ImportDecl>(
  280. import_ir_inst_id, {.package_id = SemIR::NameId::ForIdentifier(
  281. api_imports_entry.first)}));
  282. package_id = api_imports_entry.first;
  283. }
  284. has_load_error |= api_imports->has_load_error;
  285. }
  286. // Do the actual import.
  287. ImportLibrariesFromOtherPackage(
  288. context_, namespace_type_id, import_decl_id, package_id,
  289. CollectTransitiveImports(import_decl_id, local_imports, api_imports),
  290. has_load_error);
  291. }
  292. }
  293. auto CheckUnit::ImportCppPackages() -> void {
  294. const auto& imports = unit_and_imports_->cpp_imports;
  295. if (imports.empty()) {
  296. return;
  297. }
  298. llvm::SmallVector<std::pair<llvm::StringRef, SemIRLoc>> import_pairs;
  299. import_pairs.reserve(imports.size());
  300. for (const auto& import : imports) {
  301. import_pairs.push_back(
  302. {unit_and_imports_->unit->value_stores->string_literal_values().Get(
  303. import.library_id),
  304. import.node_id});
  305. }
  306. ImportCppFiles(context_, unit_and_imports_->unit->sem_ir->filename(),
  307. import_pairs, fs_);
  308. }
  309. // Loops over all nodes in the tree. On some errors, this may return early,
  310. // for example if an unrecoverable state is encountered.
  311. // NOLINTNEXTLINE(readability-function-size)
  312. auto CheckUnit::ProcessNodeIds() -> bool {
  313. NodeIdTraversal traversal(context_, vlog_stream_);
  314. Parse::NodeId node_id = Parse::NodeId::None;
  315. // On crash, report which token we were handling.
  316. PrettyStackTraceFunction node_dumper([&](llvm::raw_ostream& output) {
  317. const auto& tree = unit_and_imports_->unit->tree_and_subtrees_getter();
  318. auto converted = tree.NodeToDiagnosticLoc(node_id, /*token_only=*/false);
  319. converted.loc.FormatLocation(output);
  320. output << "checking " << context_.parse_tree().node_kind(node_id) << "\n";
  321. // Crash output has a tab indent; try to indent slightly past that.
  322. converted.loc.FormatSnippet(output, /*indent=*/10);
  323. });
  324. while (auto maybe_node_id = traversal.Next()) {
  325. node_id = *maybe_node_id;
  326. emitter_.AdvanceToken(context_.parse_tree().node_token(node_id));
  327. if (context_.parse_tree().node_has_error(node_id)) {
  328. context_.TODO(node_id, "handle invalid parse trees in `check`");
  329. return false;
  330. }
  331. bool result;
  332. auto parse_kind = context_.parse_tree().node_kind(node_id);
  333. switch (parse_kind) {
  334. #define CARBON_PARSE_NODE_KIND(Name) \
  335. case Parse::NodeKind::Name: { \
  336. result = HandleParseNode(context_, Parse::Name##Id(node_id)); \
  337. break; \
  338. }
  339. #include "toolchain/parse/node_kind.def"
  340. }
  341. if (!result) {
  342. CARBON_CHECK(
  343. unit_and_imports_->err_tracker.seen_error(),
  344. "HandleParseNode for `{0}` returned false without diagnosing.",
  345. parse_kind);
  346. return false;
  347. }
  348. traversal.Handle(parse_kind);
  349. }
  350. return true;
  351. }
  352. auto CheckUnit::CheckRequiredDefinitions() -> void {
  353. CARBON_DIAGNOSTIC(MissingDefinitionInImpl, Error,
  354. "no definition found for declaration in impl file");
  355. // Note that more required definitions can be added during this loop.
  356. for (size_t i = 0; i != context_.definitions_required().size(); ++i) {
  357. SemIR::InstId decl_inst_id = context_.definitions_required()[i];
  358. SemIR::Inst decl_inst = context_.insts().Get(decl_inst_id);
  359. CARBON_KIND_SWITCH(context_.insts().Get(decl_inst_id)) {
  360. case CARBON_KIND(SemIR::ClassDecl class_decl): {
  361. if (!context_.classes().Get(class_decl.class_id).is_defined()) {
  362. emitter_.Emit(decl_inst_id, MissingDefinitionInImpl);
  363. }
  364. break;
  365. }
  366. case CARBON_KIND(SemIR::FunctionDecl function_decl): {
  367. if (context_.functions().Get(function_decl.function_id).definition_id ==
  368. SemIR::InstId::None) {
  369. emitter_.Emit(decl_inst_id, MissingDefinitionInImpl);
  370. }
  371. break;
  372. }
  373. case CARBON_KIND(SemIR::ImplDecl impl_decl): {
  374. auto& impl = context_.impls().Get(impl_decl.impl_id);
  375. if (!impl.is_defined()) {
  376. FillImplWitnessWithErrors(context_, impl);
  377. CARBON_DIAGNOSTIC(ImplMissingDefinition, Error,
  378. "impl declared but not defined");
  379. emitter_.Emit(decl_inst_id, ImplMissingDefinition);
  380. }
  381. break;
  382. }
  383. case SemIR::InterfaceDecl::Kind: {
  384. // TODO: Handle `interface` as well, once we can test it without
  385. // triggering
  386. // https://github.com/carbon-language/carbon-lang/issues/4071.
  387. CARBON_FATAL("TODO: Support interfaces in DiagnoseMissingDefinitions");
  388. }
  389. case CARBON_KIND(SemIR::SpecificFunction specific_function): {
  390. // TODO: Track a location for the use. In general we may want to track a
  391. // list of enclosing locations if this was used from a generic.
  392. SemIRLoc use_loc = decl_inst_id;
  393. if (!ResolveSpecificDefinition(context_, use_loc,
  394. specific_function.specific_id)) {
  395. CARBON_DIAGNOSTIC(MissingGenericFunctionDefinition, Error,
  396. "use of undefined generic function");
  397. CARBON_DIAGNOSTIC(MissingGenericFunctionDefinitionHere, Note,
  398. "generic function declared here");
  399. auto generic_decl_id =
  400. context_.generics()
  401. .Get(context_.specifics()
  402. .Get(specific_function.specific_id)
  403. .generic_id)
  404. .decl_id;
  405. emitter_.Build(decl_inst_id, MissingGenericFunctionDefinition)
  406. .Note(generic_decl_id, MissingGenericFunctionDefinitionHere)
  407. .Emit();
  408. }
  409. break;
  410. }
  411. default: {
  412. CARBON_FATAL("Unexpected inst in definitions_required: {0}", decl_inst);
  413. }
  414. }
  415. }
  416. }
  417. } // namespace Carbon::Check