check.cpp 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910
  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.h"
  5. #include "common/check.h"
  6. #include "common/map.h"
  7. #include "toolchain/base/kind_switch.h"
  8. #include "toolchain/base/pretty_stack_trace_function.h"
  9. #include "toolchain/check/context.h"
  10. #include "toolchain/check/diagnostic_helpers.h"
  11. #include "toolchain/check/generic.h"
  12. #include "toolchain/check/handle.h"
  13. #include "toolchain/check/import.h"
  14. #include "toolchain/check/import_ref.h"
  15. #include "toolchain/check/node_id_traversal.h"
  16. #include "toolchain/check/sem_ir_diagnostic_converter.h"
  17. #include "toolchain/diagnostics/diagnostic.h"
  18. #include "toolchain/diagnostics/format_providers.h"
  19. #include "toolchain/lex/token_kind.h"
  20. #include "toolchain/parse/node_ids.h"
  21. #include "toolchain/parse/tree.h"
  22. #include "toolchain/parse/tree_node_diagnostic_converter.h"
  23. #include "toolchain/sem_ir/file.h"
  24. #include "toolchain/sem_ir/ids.h"
  25. #include "toolchain/sem_ir/typed_insts.h"
  26. namespace Carbon::Check {
  27. namespace {
  28. struct UnitInfo {
  29. // A given import within the file, with its destination.
  30. struct Import {
  31. Parse::Tree::PackagingNames names;
  32. UnitInfo* unit_info;
  33. };
  34. // A file's imports corresponding to a single package, for the map.
  35. struct PackageImports {
  36. // Use the constructor so that the SmallVector is only constructed
  37. // as-needed.
  38. explicit PackageImports(IdentifierId package_id,
  39. Parse::ImportDeclId node_id)
  40. : package_id(package_id), node_id(node_id) {}
  41. // The identifier of the imported package.
  42. IdentifierId package_id;
  43. // The first `import` declaration in the file, which declared the package's
  44. // identifier (even if the import failed). Used for associating diagnostics
  45. // not specific to a single import.
  46. Parse::ImportDeclId node_id;
  47. // The associated `import` instruction. Only valid once a file is checked.
  48. SemIR::InstId import_decl_id = SemIR::InstId::Invalid;
  49. // Whether there's an import that failed to load.
  50. bool has_load_error = false;
  51. // The list of valid imports.
  52. llvm::SmallVector<Import> imports;
  53. };
  54. explicit UnitInfo(SemIR::CheckIRId check_ir_id, Unit& unit,
  55. Parse::NodeLocConverter& converter)
  56. : check_ir_id(check_ir_id),
  57. unit(&unit),
  58. err_tracker(*unit.consumer),
  59. emitter(converter, err_tracker) {}
  60. SemIR::CheckIRId check_ir_id;
  61. Unit* unit;
  62. // Emitter information.
  63. ErrorTrackingDiagnosticConsumer err_tracker;
  64. DiagnosticEmitter<Parse::NodeLoc> emitter;
  65. // List of the outgoing imports. If a package includes unavailable library
  66. // imports, it has an entry with has_load_error set. Invalid imports (for
  67. // example, `import Main;`) aren't added because they won't add identifiers to
  68. // name lookup.
  69. llvm::SmallVector<PackageImports> package_imports;
  70. // A map of the package names to the outgoing imports above.
  71. Map<IdentifierId, int32_t> package_imports_map;
  72. // The remaining number of imports which must be checked before this unit can
  73. // be processed.
  74. int32_t imports_remaining = 0;
  75. // A list of incoming imports. This will be empty for `impl` files, because
  76. // imports only touch `api` files.
  77. llvm::SmallVector<UnitInfo*> incoming_imports;
  78. // The corresponding `api` unit if this is an `impl` file. The entry should
  79. // also be in the corresponding `PackageImports`.
  80. UnitInfo* api_for_impl = nullptr;
  81. };
  82. } // namespace
  83. // Collects direct imports, for CollectTransitiveImports.
  84. static auto CollectDirectImports(llvm::SmallVector<SemIR::ImportIR>& results,
  85. llvm::MutableArrayRef<int> ir_to_result_index,
  86. SemIR::InstId import_decl_id,
  87. const UnitInfo::PackageImports& imports,
  88. bool is_local) -> void {
  89. for (const auto& import : imports.imports) {
  90. const auto& direct_ir = **import.unit_info->unit->sem_ir;
  91. auto& index = ir_to_result_index[direct_ir.check_ir_id().index];
  92. if (index != -1) {
  93. // This should only happen when doing API imports for an implementation
  94. // file. Don't change the entry; is_export doesn't matter.
  95. continue;
  96. }
  97. index = results.size();
  98. results.push_back({.decl_id = import_decl_id,
  99. // Only tag exports in API files, ignoring the value in
  100. // implementation files.
  101. .is_export = is_local && import.names.is_export,
  102. .sem_ir = &direct_ir});
  103. }
  104. }
  105. // Collects transitive imports, handling deduplication. These will be unified
  106. // between local_imports and api_imports.
  107. static auto CollectTransitiveImports(
  108. SemIR::InstId import_decl_id, const UnitInfo::PackageImports* local_imports,
  109. const UnitInfo::PackageImports* api_imports, int total_ir_count)
  110. -> llvm::SmallVector<SemIR::ImportIR> {
  111. llvm::SmallVector<SemIR::ImportIR> results;
  112. // Track whether an IR was imported in full, including `export import`. This
  113. // distinguishes from IRs that are indirectly added without all names being
  114. // exported to this IR.
  115. llvm::SmallVector<int> ir_to_result_index(total_ir_count, -1);
  116. // First add direct imports. This means that if an entity is imported both
  117. // directly and indirectly, the import path will reflect the direct import.
  118. if (local_imports) {
  119. CollectDirectImports(results, ir_to_result_index, import_decl_id,
  120. *local_imports,
  121. /*is_local=*/true);
  122. }
  123. if (api_imports) {
  124. CollectDirectImports(results, ir_to_result_index, import_decl_id,
  125. *api_imports,
  126. /*is_local=*/false);
  127. }
  128. // Loop through direct imports for any indirect exports. The underlying vector
  129. // is appended during iteration, so take the size first.
  130. const int direct_imports = results.size();
  131. for (int direct_index : llvm::seq(direct_imports)) {
  132. bool is_export = results[direct_index].is_export;
  133. for (const auto& indirect_ir :
  134. results[direct_index].sem_ir->import_irs().array_ref()) {
  135. if (!indirect_ir.is_export) {
  136. continue;
  137. }
  138. auto& indirect_index =
  139. ir_to_result_index[indirect_ir.sem_ir->check_ir_id().index];
  140. if (indirect_index == -1) {
  141. indirect_index = results.size();
  142. // TODO: In the case of a recursive `export import`, this only points at
  143. // the outermost import. May want something that better reflects the
  144. // recursion.
  145. results.push_back({.decl_id = results[direct_index].decl_id,
  146. .is_export = is_export,
  147. .sem_ir = indirect_ir.sem_ir});
  148. } else if (is_export) {
  149. results[indirect_index].is_export = true;
  150. }
  151. }
  152. }
  153. return results;
  154. }
  155. // Imports the current package.
  156. static auto ImportCurrentPackage(Context& context, UnitInfo& unit_info,
  157. int total_ir_count,
  158. SemIR::InstId package_inst_id,
  159. SemIR::TypeId namespace_type_id) -> void {
  160. // Add imports from the current package.
  161. auto import_map_lookup =
  162. unit_info.package_imports_map.Lookup(IdentifierId::Invalid);
  163. if (!import_map_lookup) {
  164. // Push the scope; there are no names to add.
  165. context.scope_stack().Push(package_inst_id, SemIR::NameScopeId::Package);
  166. return;
  167. }
  168. UnitInfo::PackageImports& self_import =
  169. unit_info.package_imports[import_map_lookup.value()];
  170. if (self_import.has_load_error) {
  171. context.name_scopes().Get(SemIR::NameScopeId::Package).has_error = true;
  172. }
  173. ImportLibrariesFromCurrentPackage(
  174. context, namespace_type_id,
  175. CollectTransitiveImports(self_import.import_decl_id, &self_import,
  176. /*api_imports=*/nullptr, total_ir_count));
  177. context.scope_stack().Push(
  178. package_inst_id, SemIR::NameScopeId::Package, SemIR::SpecificId::Invalid,
  179. context.name_scopes().Get(SemIR::NameScopeId::Package).has_error);
  180. }
  181. // Imports all other packages (excluding the current package).
  182. static auto ImportOtherPackages(Context& context, UnitInfo& unit_info,
  183. int total_ir_count,
  184. SemIR::TypeId namespace_type_id) -> void {
  185. // api_imports_list is initially the size of the current file's imports,
  186. // including for API files, for simplicity in iteration. It's only really used
  187. // when processing an implementation file, in order to combine the API file
  188. // imports.
  189. //
  190. // For packages imported by the API file, the IdentifierId is the package name
  191. // and the index is into the API's import list. Otherwise, the initial
  192. // {Invalid, -1} state remains.
  193. llvm::SmallVector<std::pair<IdentifierId, int32_t>> api_imports_list;
  194. api_imports_list.resize(unit_info.package_imports.size(),
  195. {IdentifierId::Invalid, -1});
  196. // When there's an API file, add the mapping to api_imports_list.
  197. if (unit_info.api_for_impl) {
  198. const auto& api_identifiers =
  199. unit_info.api_for_impl->unit->value_stores->identifiers();
  200. auto& impl_identifiers = unit_info.unit->value_stores->identifiers();
  201. for (auto [api_imports_index, api_imports] :
  202. llvm::enumerate(unit_info.api_for_impl->package_imports)) {
  203. // Skip the current package.
  204. if (!api_imports.package_id.is_valid()) {
  205. continue;
  206. }
  207. // Translate the package ID from the API file to the implementation file.
  208. auto impl_package_id =
  209. impl_identifiers.Add(api_identifiers.Get(api_imports.package_id));
  210. if (auto lookup = unit_info.package_imports_map.Lookup(impl_package_id)) {
  211. // On a hit, replace the entry to unify the API and implementation
  212. // imports.
  213. api_imports_list[lookup.value()] = {impl_package_id, api_imports_index};
  214. } else {
  215. // On a miss, add the package as API-only.
  216. api_imports_list.push_back({impl_package_id, api_imports_index});
  217. }
  218. }
  219. }
  220. for (auto [i, api_imports_entry] : llvm::enumerate(api_imports_list)) {
  221. // These variables are updated after figuring out which imports are present.
  222. auto import_decl_id = SemIR::InstId::Invalid;
  223. IdentifierId package_id = IdentifierId::Invalid;
  224. bool has_load_error = false;
  225. // Identify the local package imports if present.
  226. UnitInfo::PackageImports* local_imports = nullptr;
  227. if (i < unit_info.package_imports.size()) {
  228. local_imports = &unit_info.package_imports[i];
  229. if (!local_imports->package_id.is_valid()) {
  230. // Skip the current package.
  231. continue;
  232. }
  233. import_decl_id = local_imports->import_decl_id;
  234. package_id = local_imports->package_id;
  235. has_load_error |= local_imports->has_load_error;
  236. }
  237. // Identify the API package imports if present.
  238. UnitInfo::PackageImports* api_imports = nullptr;
  239. if (api_imports_entry.second != -1) {
  240. api_imports =
  241. &unit_info.api_for_impl->package_imports[api_imports_entry.second];
  242. if (local_imports) {
  243. CARBON_CHECK(package_id == api_imports_entry.first);
  244. } else {
  245. auto import_ir_inst_id = context.import_ir_insts().Add(
  246. {.ir_id = SemIR::ImportIRId::ApiForImpl,
  247. .inst_id = api_imports->import_decl_id});
  248. import_decl_id =
  249. context.AddInst(context.MakeImportedLocAndInst<SemIR::ImportDecl>(
  250. import_ir_inst_id, {.package_id = SemIR::NameId::ForIdentifier(
  251. api_imports_entry.first)}));
  252. package_id = api_imports_entry.first;
  253. }
  254. has_load_error |= api_imports->has_load_error;
  255. }
  256. // Do the actual import.
  257. ImportLibrariesFromOtherPackage(
  258. context, namespace_type_id, import_decl_id, package_id,
  259. CollectTransitiveImports(import_decl_id, local_imports, api_imports,
  260. total_ir_count),
  261. has_load_error);
  262. }
  263. }
  264. // Add imports to the root block.
  265. static auto InitPackageScopeAndImports(Context& context, UnitInfo& unit_info,
  266. int total_ir_count) -> void {
  267. // First create the constant values map for all imported IRs. We'll populate
  268. // these with mappings for namespaces as we go.
  269. size_t num_irs = 0;
  270. for (auto& package_imports : unit_info.package_imports) {
  271. num_irs += package_imports.imports.size();
  272. }
  273. if (!unit_info.api_for_impl) {
  274. // Leave an empty slot for ImportIRId::ApiForImpl.
  275. ++num_irs;
  276. }
  277. context.import_irs().Reserve(num_irs);
  278. context.import_ir_constant_values().reserve(num_irs);
  279. context.SetTotalIRCount(total_ir_count);
  280. // Importing makes many namespaces, so only canonicalize the type once.
  281. auto namespace_type_id =
  282. context.GetBuiltinType(SemIR::BuiltinInstKind::NamespaceType);
  283. // Define the package scope, with an instruction for `package` expressions to
  284. // reference.
  285. auto package_scope_id = context.name_scopes().Add(
  286. SemIR::InstId::PackageNamespace, SemIR::NameId::PackageNamespace,
  287. SemIR::NameScopeId::Invalid);
  288. CARBON_CHECK(package_scope_id == SemIR::NameScopeId::Package);
  289. auto package_inst_id = context.AddInst<SemIR::Namespace>(
  290. Parse::NodeId::Invalid, {.type_id = namespace_type_id,
  291. .name_scope_id = SemIR::NameScopeId::Package,
  292. .import_id = SemIR::InstId::Invalid});
  293. CARBON_CHECK(package_inst_id == SemIR::InstId::PackageNamespace);
  294. // If there is an implicit `api` import, set it first so that it uses the
  295. // ImportIRId::ApiForImpl when processed for imports.
  296. if (unit_info.api_for_impl) {
  297. const auto& names = context.parse_tree().packaging_decl()->names;
  298. auto import_decl_id = context.AddInst<SemIR::ImportDecl>(
  299. names.node_id,
  300. {.package_id = SemIR::NameId::ForIdentifier(names.package_id)});
  301. SetApiImportIR(context,
  302. {.decl_id = import_decl_id,
  303. .is_export = false,
  304. .sem_ir = &**unit_info.api_for_impl->unit->sem_ir});
  305. } else {
  306. SetApiImportIR(context,
  307. {.decl_id = SemIR::InstId::Invalid, .sem_ir = nullptr});
  308. }
  309. // Add import instructions for everything directly imported. Implicit imports
  310. // are handled separately.
  311. for (auto& package_imports : unit_info.package_imports) {
  312. CARBON_CHECK(!package_imports.import_decl_id.is_valid());
  313. package_imports.import_decl_id = context.AddInst<SemIR::ImportDecl>(
  314. package_imports.node_id, {.package_id = SemIR::NameId::ForIdentifier(
  315. package_imports.package_id)});
  316. }
  317. // Process the imports.
  318. if (unit_info.api_for_impl) {
  319. ImportApiFile(context, namespace_type_id,
  320. **unit_info.api_for_impl->unit->sem_ir);
  321. }
  322. ImportCurrentPackage(context, unit_info, total_ir_count, package_inst_id,
  323. namespace_type_id);
  324. CARBON_CHECK(context.scope_stack().PeekIndex() == ScopeIndex::Package);
  325. ImportOtherPackages(context, unit_info, total_ir_count, namespace_type_id);
  326. }
  327. // Checks that each required definition is available. If the definition can be
  328. // generated by resolving a specific, does so, otherwise emits a diagnostic for
  329. // each declaration in context.definitions_required() that doesn't have a
  330. // definition.
  331. static auto CheckRequiredDefinitions(Context& context,
  332. Context::DiagnosticEmitter& emitter)
  333. -> void {
  334. CARBON_DIAGNOSTIC(MissingDefinitionInImpl, Error,
  335. "no definition found for declaration in impl file");
  336. // Note that more required definitions can be added during this loop.
  337. for (size_t i = 0; i != context.definitions_required().size(); ++i) {
  338. SemIR::InstId decl_inst_id = context.definitions_required()[i];
  339. SemIR::Inst decl_inst = context.insts().Get(decl_inst_id);
  340. CARBON_KIND_SWITCH(context.insts().Get(decl_inst_id)) {
  341. case CARBON_KIND(SemIR::ClassDecl class_decl): {
  342. if (!context.classes().Get(class_decl.class_id).is_defined()) {
  343. emitter.Emit(decl_inst_id, MissingDefinitionInImpl);
  344. }
  345. break;
  346. }
  347. case CARBON_KIND(SemIR::FunctionDecl function_decl): {
  348. if (context.functions().Get(function_decl.function_id).definition_id ==
  349. SemIR::InstId::Invalid) {
  350. emitter.Emit(decl_inst_id, MissingDefinitionInImpl);
  351. }
  352. break;
  353. }
  354. case CARBON_KIND(SemIR::ImplDecl impl_decl): {
  355. if (!context.impls().Get(impl_decl.impl_id).is_defined()) {
  356. emitter.Emit(decl_inst_id, MissingDefinitionInImpl);
  357. }
  358. break;
  359. }
  360. case SemIR::InterfaceDecl::Kind: {
  361. // TODO: Handle `interface` as well, once we can test it without
  362. // triggering
  363. // https://github.com/carbon-language/carbon-lang/issues/4071.
  364. CARBON_FATAL("TODO: Support interfaces in DiagnoseMissingDefinitions");
  365. }
  366. case CARBON_KIND(SemIR::SpecificFunction specific_function): {
  367. if (!ResolveSpecificDefinition(context,
  368. specific_function.specific_id)) {
  369. CARBON_DIAGNOSTIC(MissingGenericFunctionDefinition, Error,
  370. "use of undefined generic function");
  371. CARBON_DIAGNOSTIC(MissingGenericFunctionDefinitionHere, Note,
  372. "generic function declared here");
  373. auto generic_decl_id =
  374. context.generics()
  375. .Get(context.specifics()
  376. .Get(specific_function.specific_id)
  377. .generic_id)
  378. .decl_id;
  379. emitter.Build(decl_inst_id, MissingGenericFunctionDefinition)
  380. .Note(generic_decl_id, MissingGenericFunctionDefinitionHere)
  381. .Emit();
  382. }
  383. break;
  384. }
  385. default: {
  386. CARBON_FATAL("Unexpected inst in definitions_required: {0}", decl_inst);
  387. }
  388. }
  389. }
  390. }
  391. // Loops over all nodes in the tree. On some errors, this may return early,
  392. // for example if an unrecoverable state is encountered.
  393. // NOLINTNEXTLINE(readability-function-size)
  394. static auto ProcessNodeIds(Context& context, llvm::raw_ostream* vlog_stream,
  395. ErrorTrackingDiagnosticConsumer& err_tracker,
  396. Parse::NodeLocConverter& converter) -> bool {
  397. NodeIdTraversal traversal(context, vlog_stream);
  398. Parse::NodeId node_id = Parse::NodeId::Invalid;
  399. // On crash, report which token we were handling.
  400. PrettyStackTraceFunction node_dumper([&](llvm::raw_ostream& output) {
  401. auto loc = converter.ConvertLoc(
  402. node_id, [](DiagnosticLoc, const DiagnosticBase<>&) {});
  403. loc.FormatLocation(output);
  404. output << ": checking " << context.parse_tree().node_kind(node_id) << "\n";
  405. // Crash output has a tab indent; try to indent slightly past that.
  406. loc.FormatSnippet(output, /*indent=*/10);
  407. });
  408. while (auto maybe_node_id = traversal.Next()) {
  409. node_id = *maybe_node_id;
  410. auto parse_kind = context.parse_tree().node_kind(node_id);
  411. switch (parse_kind) {
  412. #define CARBON_PARSE_NODE_KIND(Name) \
  413. case Parse::NodeKind::Name: { \
  414. if (!HandleParseNode(context, Parse::Name##Id(node_id))) { \
  415. CARBON_CHECK(err_tracker.seen_error(), \
  416. "Handle" #Name \
  417. " returned false without printing a diagnostic"); \
  418. return false; \
  419. } \
  420. break; \
  421. }
  422. #include "toolchain/parse/node_kind.def"
  423. }
  424. traversal.Handle(parse_kind);
  425. }
  426. return true;
  427. }
  428. // Produces and checks the IR for the provided Parse::Tree.
  429. static auto CheckParseTree(
  430. llvm::MutableArrayRef<Parse::NodeLocConverter> node_converters,
  431. UnitInfo& unit_info, int total_ir_count, llvm::raw_ostream* vlog_stream)
  432. -> void {
  433. Timings::ScopedTiming timing(unit_info.unit->timings, "check");
  434. auto package_id = IdentifierId::Invalid;
  435. auto library_id = StringLiteralValueId::Invalid;
  436. if (const auto& packaging = unit_info.unit->parse_tree->packaging_decl()) {
  437. package_id = packaging->names.package_id;
  438. library_id = packaging->names.library_id;
  439. }
  440. unit_info.unit->sem_ir->emplace(
  441. unit_info.check_ir_id, package_id,
  442. SemIR::LibraryNameId::ForStringLiteralValueId(library_id),
  443. *unit_info.unit->value_stores,
  444. unit_info.unit->tokens->source().filename().str());
  445. SemIR::File& sem_ir = **unit_info.unit->sem_ir;
  446. SemIRDiagnosticConverter converter(node_converters, &sem_ir);
  447. Context::DiagnosticEmitter emitter(converter, unit_info.err_tracker);
  448. Context context(*unit_info.unit->tokens, emitter, *unit_info.unit->parse_tree,
  449. unit_info.unit->get_parse_tree_and_subtrees, sem_ir,
  450. vlog_stream);
  451. PrettyStackTraceFunction context_dumper(
  452. [&](llvm::raw_ostream& output) { context.PrintForStackDump(output); });
  453. // Add a block for the file.
  454. context.inst_block_stack().Push();
  455. InitPackageScopeAndImports(context, unit_info, total_ir_count);
  456. // Eagerly import the impls declared in the api file to prepare to redeclare
  457. // them.
  458. ImportImplsFromApiFile(context);
  459. if (!ProcessNodeIds(context, vlog_stream, unit_info.err_tracker,
  460. node_converters[unit_info.check_ir_id.index])) {
  461. context.sem_ir().set_has_errors(true);
  462. return;
  463. }
  464. CheckRequiredDefinitions(context, emitter);
  465. context.Finalize();
  466. context.VerifyOnFinish();
  467. sem_ir.set_has_errors(unit_info.err_tracker.seen_error());
  468. #ifndef NDEBUG
  469. if (auto verify = sem_ir.Verify(); !verify.ok()) {
  470. CARBON_FATAL("{0}Built invalid semantics IR: {1}\n", sem_ir,
  471. verify.error());
  472. }
  473. #endif
  474. }
  475. // The package and library names, used as map keys.
  476. using ImportKey = std::pair<llvm::StringRef, llvm::StringRef>;
  477. // Returns a key form of the package object. file_package_id is only used for
  478. // imports, not the main package declaration; as a consequence, it will be
  479. // invalid for the main package declaration.
  480. static auto GetImportKey(UnitInfo& unit_info, IdentifierId file_package_id,
  481. Parse::Tree::PackagingNames names) -> ImportKey {
  482. auto* stores = unit_info.unit->value_stores;
  483. llvm::StringRef package_name =
  484. names.package_id.is_valid() ? stores->identifiers().Get(names.package_id)
  485. : file_package_id.is_valid() ? stores->identifiers().Get(file_package_id)
  486. : "";
  487. llvm::StringRef library_name =
  488. names.library_id.is_valid()
  489. ? stores->string_literal_values().Get(names.library_id)
  490. : "";
  491. return {package_name, library_name};
  492. }
  493. static constexpr llvm::StringLiteral ExplicitMainName = "Main";
  494. static auto RenderImportKey(ImportKey import_key) -> std::string {
  495. if (import_key.first.empty()) {
  496. import_key.first = ExplicitMainName;
  497. }
  498. if (import_key.second.empty()) {
  499. return import_key.first.str();
  500. }
  501. return llvm::formatv("{0}//{1}", import_key.first, import_key.second).str();
  502. }
  503. // Marks an import as required on both the source and target file.
  504. //
  505. // The ID comparisons between the import and unit are okay because they both
  506. // come from the same file.
  507. static auto TrackImport(Map<ImportKey, UnitInfo*>& api_map,
  508. Map<ImportKey, Parse::NodeId>* explicit_import_map,
  509. UnitInfo& unit_info, Parse::Tree::PackagingNames import)
  510. -> void {
  511. const auto& packaging = unit_info.unit->parse_tree->packaging_decl();
  512. IdentifierId file_package_id =
  513. packaging ? packaging->names.package_id : IdentifierId::Invalid;
  514. auto import_key = GetImportKey(unit_info, file_package_id, import);
  515. // True if the import has `Main` as the package name, even if it comes from
  516. // the file's packaging (diagnostics may differentiate).
  517. bool is_explicit_main = import_key.first == ExplicitMainName;
  518. // Explicit imports need more validation than implicit ones. We try to do
  519. // these in an order of imports that should be removed, followed by imports
  520. // that might be valid with syntax fixes.
  521. if (explicit_import_map) {
  522. // Diagnose redundant imports.
  523. if (auto insert_result =
  524. explicit_import_map->Insert(import_key, import.node_id);
  525. !insert_result.is_inserted()) {
  526. CARBON_DIAGNOSTIC(RepeatedImport, Error,
  527. "library imported more than once");
  528. CARBON_DIAGNOSTIC(FirstImported, Note, "first import here");
  529. unit_info.emitter.Build(import.node_id, RepeatedImport)
  530. .Note(insert_result.value(), FirstImported)
  531. .Emit();
  532. return;
  533. }
  534. // True if the file's package is implicitly `Main` (by omitting an explicit
  535. // package name).
  536. bool is_file_implicit_main =
  537. !packaging || !packaging->names.package_id.is_valid();
  538. // True if the import is using implicit "current package" syntax (by
  539. // omitting an explicit package name).
  540. bool is_import_implicit_current_package = !import.package_id.is_valid();
  541. // True if the import is using `default` library syntax.
  542. bool is_import_default_library = !import.library_id.is_valid();
  543. // True if the import and file point at the same package, even by
  544. // incorrectly specifying the current package name to `import`.
  545. bool is_same_package = is_import_implicit_current_package ||
  546. import.package_id == file_package_id;
  547. // True if the import points at the same library as the file's library.
  548. bool is_same_library =
  549. is_same_package &&
  550. (packaging ? import.library_id == packaging->names.library_id
  551. : is_import_default_library);
  552. // Diagnose explicit imports of the same library, whether from `api` or
  553. // `impl`.
  554. if (is_same_library) {
  555. CARBON_DIAGNOSTIC(ExplicitImportApi, Error,
  556. "explicit import of `api` from `impl` file is "
  557. "redundant with implicit import");
  558. CARBON_DIAGNOSTIC(ImportSelf, Error, "file cannot import itself");
  559. bool is_impl = !packaging || packaging->is_impl;
  560. unit_info.emitter.Emit(import.node_id,
  561. is_impl ? ExplicitImportApi : ImportSelf);
  562. return;
  563. }
  564. // Diagnose explicit imports of `Main//default`. There is no `api` for it.
  565. // This lets other diagnostics handle explicit `Main` package naming.
  566. if (is_file_implicit_main && is_import_implicit_current_package &&
  567. is_import_default_library) {
  568. CARBON_DIAGNOSTIC(ImportMainDefaultLibrary, Error,
  569. "cannot import `Main//default`");
  570. unit_info.emitter.Emit(import.node_id, ImportMainDefaultLibrary);
  571. return;
  572. }
  573. if (!is_import_implicit_current_package) {
  574. // Diagnose explicit imports of the same package that use the package
  575. // name.
  576. if (is_same_package || (is_file_implicit_main && is_explicit_main)) {
  577. CARBON_DIAGNOSTIC(
  578. ImportCurrentPackageByName, Error,
  579. "imports from the current package must omit the package name");
  580. unit_info.emitter.Emit(import.node_id, ImportCurrentPackageByName);
  581. return;
  582. }
  583. // Diagnose explicit imports from `Main`.
  584. if (is_explicit_main) {
  585. CARBON_DIAGNOSTIC(ImportMainPackage, Error,
  586. "cannot import `Main` from other packages");
  587. unit_info.emitter.Emit(import.node_id, ImportMainPackage);
  588. return;
  589. }
  590. }
  591. } else if (is_explicit_main) {
  592. // An implicit import with an explicit `Main` occurs when a `package` rule
  593. // has bad syntax, which will have been diagnosed when building the API map.
  594. // As a consequence, we return silently.
  595. return;
  596. }
  597. // Get the package imports, or create them if this is the first.
  598. auto create_imports = [&]() -> int32_t {
  599. int32_t index = unit_info.package_imports.size();
  600. unit_info.package_imports.push_back(
  601. UnitInfo::PackageImports(import.package_id, import.node_id));
  602. return index;
  603. };
  604. auto insert_result =
  605. unit_info.package_imports_map.Insert(import.package_id, create_imports);
  606. UnitInfo::PackageImports& package_imports =
  607. unit_info.package_imports[insert_result.value()];
  608. if (auto api_lookup = api_map.Lookup(import_key)) {
  609. // Add references between the file and imported api.
  610. UnitInfo* api = api_lookup.value();
  611. package_imports.imports.push_back({import, api});
  612. ++unit_info.imports_remaining;
  613. api->incoming_imports.push_back(&unit_info);
  614. // If this is the implicit import, note we have it.
  615. if (!explicit_import_map) {
  616. CARBON_CHECK(!unit_info.api_for_impl);
  617. unit_info.api_for_impl = api;
  618. }
  619. } else {
  620. // The imported api is missing.
  621. package_imports.has_load_error = true;
  622. CARBON_DIAGNOSTIC(LibraryApiNotFound, Error,
  623. "corresponding API for '{0}' not found", std::string);
  624. CARBON_DIAGNOSTIC(ImportNotFound, Error, "imported API '{0}' not found",
  625. std::string);
  626. unit_info.emitter.Emit(
  627. import.node_id,
  628. explicit_import_map ? ImportNotFound : LibraryApiNotFound,
  629. RenderImportKey(import_key));
  630. }
  631. }
  632. // Builds a map of `api` files which might be imported. Also diagnoses issues
  633. // related to the packaging because the strings are loaded as part of getting
  634. // the ImportKey (which we then do for `impl` files too).
  635. static auto BuildApiMapAndDiagnosePackaging(
  636. llvm::MutableArrayRef<UnitInfo> unit_infos) -> Map<ImportKey, UnitInfo*> {
  637. Map<ImportKey, UnitInfo*> api_map;
  638. for (auto& unit_info : unit_infos) {
  639. const auto& packaging = unit_info.unit->parse_tree->packaging_decl();
  640. // An import key formed from the `package` or `library` declaration. Or, for
  641. // Main//default, a placeholder key.
  642. auto import_key = packaging ? GetImportKey(unit_info, IdentifierId::Invalid,
  643. packaging->names)
  644. // Construct a boring key for Main//default.
  645. : ImportKey{"", ""};
  646. // Diagnose explicit `Main` uses before they become marked as possible
  647. // APIs.
  648. if (import_key.first == ExplicitMainName) {
  649. CARBON_DIAGNOSTIC(ExplicitMainPackage, Error,
  650. "`Main//default` must omit `package` declaration");
  651. CARBON_DIAGNOSTIC(
  652. ExplicitMainLibrary, Error,
  653. "use `library` declaration in `Main` package libraries");
  654. unit_info.emitter.Emit(packaging->names.node_id,
  655. import_key.second.empty() ? ExplicitMainPackage
  656. : ExplicitMainLibrary);
  657. continue;
  658. }
  659. bool is_impl = packaging && packaging->is_impl;
  660. // Add to the `api` map and diagnose duplicates. This occurs before the
  661. // file extension check because we might emit both diagnostics in situations
  662. // where the user forgets (or has syntax errors with) a package line
  663. // multiple times.
  664. if (!is_impl) {
  665. auto insert_result = api_map.Insert(import_key, &unit_info);
  666. if (!insert_result.is_inserted()) {
  667. llvm::StringRef prev_filename =
  668. insert_result.value()->unit->tokens->source().filename();
  669. if (packaging) {
  670. CARBON_DIAGNOSTIC(DuplicateLibraryApi, Error,
  671. "library's API previously provided by `{0}`",
  672. std::string);
  673. unit_info.emitter.Emit(packaging->names.node_id, DuplicateLibraryApi,
  674. prev_filename.str());
  675. } else {
  676. CARBON_DIAGNOSTIC(DuplicateMainApi, Error,
  677. "`Main//default` previously provided by `{0}`",
  678. std::string);
  679. // Use the invalid node because there's no node to associate with.
  680. unit_info.emitter.Emit(Parse::NodeId::Invalid, DuplicateMainApi,
  681. prev_filename.str());
  682. }
  683. }
  684. }
  685. // Validate file extensions. Note imports rely the packaging declaration,
  686. // not the extension. If the input is not a regular file, for example
  687. // because it is stdin, no filename checking is performed.
  688. if (unit_info.unit->tokens->source().is_regular_file()) {
  689. auto filename = unit_info.unit->tokens->source().filename();
  690. static constexpr llvm::StringLiteral ApiExt = ".carbon";
  691. static constexpr llvm::StringLiteral ImplExt = ".impl.carbon";
  692. bool is_api_with_impl_ext = !is_impl && filename.ends_with(ImplExt);
  693. auto want_ext = is_impl ? ImplExt : ApiExt;
  694. if (is_api_with_impl_ext || !filename.ends_with(want_ext)) {
  695. CARBON_DIAGNOSTIC(
  696. IncorrectExtension, Error,
  697. "file extension of `{0:.impl|}.carbon` required for {0:`impl`|api}",
  698. BoolAsSelect);
  699. auto diag = unit_info.emitter.Build(
  700. packaging ? packaging->names.node_id : Parse::NodeId::Invalid,
  701. IncorrectExtension, is_impl);
  702. if (is_api_with_impl_ext) {
  703. CARBON_DIAGNOSTIC(
  704. IncorrectExtensionImplNote, Note,
  705. "file extension of `.impl.carbon` only allowed for `impl`");
  706. diag.Note(Parse::NodeId::Invalid, IncorrectExtensionImplNote);
  707. }
  708. diag.Emit();
  709. }
  710. }
  711. }
  712. return api_map;
  713. }
  714. auto CheckParseTrees(
  715. llvm::MutableArrayRef<Unit> units,
  716. llvm::MutableArrayRef<Parse::NodeLocConverter> node_converters,
  717. bool prelude_import, llvm::raw_ostream* vlog_stream) -> void {
  718. // UnitInfo is big due to its SmallVectors, so we default to 0 on the
  719. // stack.
  720. llvm::SmallVector<UnitInfo, 0> unit_infos;
  721. unit_infos.reserve(units.size());
  722. for (auto [i, unit] : llvm::enumerate(units)) {
  723. unit_infos.emplace_back(SemIR::CheckIRId(i), unit, node_converters[i]);
  724. }
  725. Map<ImportKey, UnitInfo*> api_map =
  726. BuildApiMapAndDiagnosePackaging(unit_infos);
  727. // Mark down imports for all files.
  728. llvm::SmallVector<UnitInfo*> ready_to_check;
  729. ready_to_check.reserve(units.size());
  730. for (auto& unit_info : unit_infos) {
  731. const auto& packaging = unit_info.unit->parse_tree->packaging_decl();
  732. if (packaging && packaging->is_impl) {
  733. // An `impl` has an implicit import of its `api`.
  734. auto implicit_names = packaging->names;
  735. implicit_names.package_id = IdentifierId::Invalid;
  736. TrackImport(api_map, nullptr, unit_info, implicit_names);
  737. }
  738. Map<ImportKey, Parse::NodeId> explicit_import_map;
  739. // Add the prelude import. It's added to explicit_import_map so that it can
  740. // conflict with an explicit import of the prelude.
  741. IdentifierId core_ident_id =
  742. unit_info.unit->value_stores->identifiers().Add("Core");
  743. if (prelude_import &&
  744. !(packaging && packaging->names.package_id == core_ident_id)) {
  745. auto prelude_id =
  746. unit_info.unit->value_stores->string_literal_values().Add("prelude");
  747. TrackImport(api_map, &explicit_import_map, unit_info,
  748. {.node_id = Parse::InvalidNodeId(),
  749. .package_id = core_ident_id,
  750. .library_id = prelude_id});
  751. }
  752. for (const auto& import : unit_info.unit->parse_tree->imports()) {
  753. TrackImport(api_map, &explicit_import_map, unit_info, import);
  754. }
  755. // If there were no imports, mark the file as ready to check for below.
  756. if (unit_info.imports_remaining == 0) {
  757. ready_to_check.push_back(&unit_info);
  758. }
  759. }
  760. // Check everything with no dependencies. Earlier entries with dependencies
  761. // will be checked as soon as all their dependencies have been checked.
  762. for (int check_index = 0;
  763. check_index < static_cast<int>(ready_to_check.size()); ++check_index) {
  764. auto* unit_info = ready_to_check[check_index];
  765. CheckParseTree(node_converters, *unit_info, units.size(), vlog_stream);
  766. for (auto* incoming_import : unit_info->incoming_imports) {
  767. --incoming_import->imports_remaining;
  768. if (incoming_import->imports_remaining == 0) {
  769. ready_to_check.push_back(incoming_import);
  770. }
  771. }
  772. }
  773. // If there are still units with remaining imports, it means there's a
  774. // dependency loop.
  775. if (ready_to_check.size() < unit_infos.size()) {
  776. // Go through units and mask out unevaluated imports. This breaks everything
  777. // associated with a loop equivalently, whether it's part of it or depending
  778. // on a part of it.
  779. // TODO: Better identify cycles, maybe try to untangle them.
  780. for (auto& unit_info : unit_infos) {
  781. if (unit_info.imports_remaining > 0) {
  782. for (auto& package_imports : unit_info.package_imports) {
  783. for (auto* import_it = package_imports.imports.begin();
  784. import_it != package_imports.imports.end();) {
  785. if (*import_it->unit_info->unit->sem_ir) {
  786. // The import is checked, so continue.
  787. ++import_it;
  788. } else {
  789. // The import hasn't been checked, indicating a cycle.
  790. CARBON_DIAGNOSTIC(ImportCycleDetected, Error,
  791. "import cannot be used due to a cycle; cycle "
  792. "must be fixed to import");
  793. unit_info.emitter.Emit(import_it->names.node_id,
  794. ImportCycleDetected);
  795. // Make this look the same as an import which wasn't found.
  796. package_imports.has_load_error = true;
  797. if (unit_info.api_for_impl == import_it->unit_info) {
  798. unit_info.api_for_impl = nullptr;
  799. }
  800. import_it = package_imports.imports.erase(import_it);
  801. }
  802. }
  803. }
  804. }
  805. }
  806. // Check the remaining file contents, which are probably broken due to
  807. // incomplete imports.
  808. for (auto& unit_info : unit_infos) {
  809. if (unit_info.imports_remaining > 0) {
  810. CheckParseTree(node_converters, unit_info, units.size(), vlog_stream);
  811. }
  812. }
  813. }
  814. }
  815. } // namespace Carbon::Check