check.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  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 <string>
  6. #include <utility>
  7. #include "common/check.h"
  8. #include "common/map.h"
  9. #include "toolchain/check/check_unit.h"
  10. #include "toolchain/check/context.h"
  11. #include "toolchain/check/diagnostic_emitter.h"
  12. #include "toolchain/check/diagnostic_helpers.h"
  13. #include "toolchain/check/import_cpp.h"
  14. #include "toolchain/diagnostics/diagnostic.h"
  15. #include "toolchain/diagnostics/diagnostic_consumer.h"
  16. #include "toolchain/diagnostics/format_providers.h"
  17. #include "toolchain/lex/token_kind.h"
  18. #include "toolchain/parse/node_ids.h"
  19. #include "toolchain/parse/tree.h"
  20. #include "toolchain/sem_ir/file.h"
  21. #include "toolchain/sem_ir/formatter.h"
  22. #include "toolchain/sem_ir/typed_insts.h"
  23. namespace Carbon::Check {
  24. // The package and library names, used as map keys.
  25. using ImportKey = std::pair<llvm::StringRef, llvm::StringRef>;
  26. // Returns a key form of the package object. file_package_id is only used for
  27. // imports, not the main package declaration; as a consequence, it will be
  28. // `None` for the main package declaration.
  29. static auto GetImportKey(UnitAndImports& unit_info,
  30. PackageNameId file_package_id,
  31. Parse::Tree::PackagingNames names) -> ImportKey {
  32. auto* stores = unit_info.unit->value_stores;
  33. PackageNameId package_id =
  34. names.package_id.has_value() ? names.package_id : file_package_id;
  35. llvm::StringRef package_name;
  36. if (package_id.has_value()) {
  37. auto package_ident_id = package_id.AsIdentifierId();
  38. package_name = package_ident_id.has_value()
  39. ? stores->identifiers().Get(package_ident_id)
  40. : package_id.AsSpecialName();
  41. }
  42. llvm::StringRef library_name =
  43. names.library_id.has_value()
  44. ? stores->string_literal_values().Get(names.library_id)
  45. : "";
  46. return {package_name, library_name};
  47. }
  48. static constexpr llvm::StringLiteral CppPackageName = "Cpp";
  49. static constexpr llvm::StringLiteral MainPackageName = "Main";
  50. static auto RenderImportKey(ImportKey import_key) -> std::string {
  51. if (import_key.first.empty()) {
  52. import_key.first = MainPackageName;
  53. }
  54. if (import_key.second.empty()) {
  55. return import_key.first.str();
  56. }
  57. return llvm::formatv("{0}//{1}", import_key.first, import_key.second).str();
  58. }
  59. // Marks an import as required on both the source and target file.
  60. //
  61. // The ID comparisons between the import and unit are okay because they both
  62. // come from the same file.
  63. static auto TrackImport(Map<ImportKey, UnitAndImports*>& api_map,
  64. Map<ImportKey, Parse::NodeId>* explicit_import_map,
  65. UnitAndImports& unit_info,
  66. Parse::Tree::PackagingNames import, bool fuzzing)
  67. -> void {
  68. const auto& packaging = unit_info.parse_tree().packaging_decl();
  69. PackageNameId file_package_id =
  70. packaging ? packaging->names.package_id : PackageNameId::None;
  71. const auto import_key = GetImportKey(unit_info, file_package_id, import);
  72. const auto& [import_package_name, import_library_name] = import_key;
  73. if (import_package_name == CppPackageName) {
  74. if (import_library_name.empty()) {
  75. CARBON_DIAGNOSTIC(CppInteropMissingLibrary, Error,
  76. "`Cpp` import missing library");
  77. unit_info.emitter.Emit(import.node_id, CppInteropMissingLibrary);
  78. return;
  79. }
  80. if (fuzzing) {
  81. // Clang is not crash-resilient.
  82. CARBON_DIAGNOSTIC(CppInteropFuzzing, Error,
  83. "`Cpp` import found during fuzzing");
  84. unit_info.emitter.Emit(import.node_id, CppInteropFuzzing);
  85. return;
  86. }
  87. unit_info.cpp_import_names.push_back(import);
  88. return;
  89. }
  90. // True if the import has `Main` as the package name, even if it comes from
  91. // the file's packaging (diagnostics may differentiate).
  92. bool is_explicit_main = import_package_name == MainPackageName;
  93. // Explicit imports need more validation than implicit ones. We try to do
  94. // these in an order of imports that should be removed, followed by imports
  95. // that might be valid with syntax fixes.
  96. if (explicit_import_map) {
  97. // Diagnose redundant imports.
  98. if (auto insert_result =
  99. explicit_import_map->Insert(import_key, import.node_id);
  100. !insert_result.is_inserted()) {
  101. CARBON_DIAGNOSTIC(RepeatedImport, Error,
  102. "library imported more than once");
  103. CARBON_DIAGNOSTIC(FirstImported, Note, "first import here");
  104. unit_info.emitter.Build(import.node_id, RepeatedImport)
  105. .Note(insert_result.value(), FirstImported)
  106. .Emit();
  107. return;
  108. }
  109. // True if the file's package is implicitly `Main` (by omitting an explicit
  110. // package name).
  111. bool is_file_implicit_main =
  112. !packaging || !packaging->names.package_id.has_value();
  113. // True if the import is using implicit "current package" syntax (by
  114. // omitting an explicit package name).
  115. bool is_import_implicit_current_package = !import.package_id.has_value();
  116. // True if the import is using `default` library syntax.
  117. bool is_import_default_library = !import.library_id.has_value();
  118. // True if the import and file point at the same package, even by
  119. // incorrectly specifying the current package name to `import`.
  120. bool is_same_package = is_import_implicit_current_package ||
  121. import.package_id == file_package_id;
  122. // True if the import points at the same library as the file's library.
  123. bool is_same_library =
  124. is_same_package &&
  125. (packaging ? import.library_id == packaging->names.library_id
  126. : is_import_default_library);
  127. // Diagnose explicit imports of the same library, whether from `api` or
  128. // `impl`.
  129. if (is_same_library) {
  130. CARBON_DIAGNOSTIC(ExplicitImportApi, Error,
  131. "explicit import of `api` from `impl` file is "
  132. "redundant with implicit import");
  133. CARBON_DIAGNOSTIC(ImportSelf, Error, "file cannot import itself");
  134. bool is_impl = !packaging || packaging->is_impl;
  135. unit_info.emitter.Emit(import.node_id,
  136. is_impl ? ExplicitImportApi : ImportSelf);
  137. return;
  138. }
  139. // Diagnose explicit imports of `Main//default`. There is no `api` for it.
  140. // This lets other diagnostics handle explicit `Main` package naming.
  141. if (is_file_implicit_main && is_import_implicit_current_package &&
  142. is_import_default_library) {
  143. CARBON_DIAGNOSTIC(ImportMainDefaultLibrary, Error,
  144. "cannot import `Main//default`");
  145. unit_info.emitter.Emit(import.node_id, ImportMainDefaultLibrary);
  146. return;
  147. }
  148. if (!is_import_implicit_current_package) {
  149. // Diagnose explicit imports of the same package that use the package
  150. // name.
  151. if (is_same_package || (is_file_implicit_main && is_explicit_main)) {
  152. CARBON_DIAGNOSTIC(
  153. ImportCurrentPackageByName, Error,
  154. "imports from the current package must omit the package name");
  155. unit_info.emitter.Emit(import.node_id, ImportCurrentPackageByName);
  156. return;
  157. }
  158. // Diagnose explicit imports from `Main`.
  159. if (is_explicit_main) {
  160. CARBON_DIAGNOSTIC(ImportMainPackage, Error,
  161. "cannot import `Main` from other packages");
  162. unit_info.emitter.Emit(import.node_id, ImportMainPackage);
  163. return;
  164. }
  165. }
  166. } else if (is_explicit_main) {
  167. // An implicit import with an explicit `Main` occurs when a `package` rule
  168. // has bad syntax, which will have been diagnosed when building the API map.
  169. // As a consequence, we return silently.
  170. return;
  171. }
  172. // Get the package imports, or create them if this is the first.
  173. auto create_imports = [&]() -> int32_t {
  174. int32_t index = unit_info.package_imports.size();
  175. unit_info.package_imports.push_back(
  176. PackageImports(import.package_id, import.node_id));
  177. return index;
  178. };
  179. auto insert_result =
  180. unit_info.package_imports_map.Insert(import.package_id, create_imports);
  181. PackageImports& package_imports =
  182. unit_info.package_imports[insert_result.value()];
  183. if (auto api_lookup = api_map.Lookup(import_key)) {
  184. // Add references between the file and imported api.
  185. UnitAndImports* api = api_lookup.value();
  186. package_imports.imports.push_back({import, api});
  187. ++unit_info.imports_remaining;
  188. api->incoming_imports.push_back(&unit_info);
  189. // If this is the implicit import, note we have it.
  190. if (!explicit_import_map) {
  191. CARBON_CHECK(!unit_info.api_for_impl);
  192. unit_info.api_for_impl = api;
  193. }
  194. } else {
  195. // The imported api is missing.
  196. package_imports.has_load_error = true;
  197. if (!explicit_import_map && import_package_name == CppPackageName) {
  198. // Don't diagnose the implicit import in `impl package Cpp`, because we'll
  199. // have diagnosed the use of `Cpp` in the declaration.
  200. return;
  201. }
  202. CARBON_DIAGNOSTIC(LibraryApiNotFound, Error,
  203. "corresponding API for '{0}' not found", std::string);
  204. CARBON_DIAGNOSTIC(ImportNotFound, Error, "imported API '{0}' not found",
  205. std::string);
  206. unit_info.emitter.Emit(
  207. import.node_id,
  208. explicit_import_map ? ImportNotFound : LibraryApiNotFound,
  209. RenderImportKey(import_key));
  210. }
  211. }
  212. // Builds a map of `api` files which might be imported. Also diagnoses issues
  213. // related to the packaging because the strings are loaded as part of getting
  214. // the ImportKey (which we then do for `impl` files too).
  215. static auto BuildApiMapAndDiagnosePackaging(
  216. llvm::MutableArrayRef<UnitAndImports> unit_infos)
  217. -> Map<ImportKey, UnitAndImports*> {
  218. Map<ImportKey, UnitAndImports*> api_map;
  219. for (auto& unit_info : unit_infos) {
  220. const auto& packaging = unit_info.parse_tree().packaging_decl();
  221. // An import key formed from the `package` or `library` declaration. Or, for
  222. // Main//default, a placeholder key.
  223. auto import_key = packaging ? GetImportKey(unit_info, PackageNameId::None,
  224. packaging->names)
  225. // Construct a boring key for Main//default.
  226. : ImportKey{"", ""};
  227. // Diagnose restricted package names before they become marked as possible
  228. // APIs.
  229. if (import_key.first == MainPackageName) {
  230. CARBON_DIAGNOSTIC(ExplicitMainPackage, Error,
  231. "`Main//default` must omit `package` declaration");
  232. CARBON_DIAGNOSTIC(
  233. ExplicitMainLibrary, Error,
  234. "use `library` declaration in `Main` package libraries");
  235. unit_info.emitter.Emit(packaging->names.node_id,
  236. import_key.second.empty() ? ExplicitMainPackage
  237. : ExplicitMainLibrary);
  238. continue;
  239. } else if (import_key.first == CppPackageName) {
  240. CARBON_DIAGNOSTIC(CppPackageDeclaration, Error,
  241. "`Cpp` cannot be used by a `package` declaration");
  242. unit_info.emitter.Emit(packaging->names.node_id, CppPackageDeclaration);
  243. continue;
  244. }
  245. bool is_impl = packaging && packaging->is_impl;
  246. // Add to the `api` map and diagnose duplicates. This occurs before the
  247. // file extension check because we might emit both diagnostics in situations
  248. // where the user forgets (or has syntax errors with) a package line
  249. // multiple times.
  250. if (!is_impl) {
  251. auto insert_result = api_map.Insert(import_key, &unit_info);
  252. if (!insert_result.is_inserted()) {
  253. llvm::StringRef prev_filename =
  254. insert_result.value()->source().filename();
  255. if (packaging) {
  256. CARBON_DIAGNOSTIC(DuplicateLibraryApi, Error,
  257. "library's API previously provided by `{0}`",
  258. std::string);
  259. unit_info.emitter.Emit(packaging->names.node_id, DuplicateLibraryApi,
  260. prev_filename.str());
  261. } else {
  262. CARBON_DIAGNOSTIC(DuplicateMainApi, Error,
  263. "`Main//default` previously provided by `{0}`",
  264. std::string);
  265. // Use `NodeId::None` because there's no node to associate with.
  266. unit_info.emitter.Emit(Parse::NodeId::None, DuplicateMainApi,
  267. prev_filename.str());
  268. }
  269. }
  270. }
  271. // Validate file extensions. Note imports rely the packaging declaration,
  272. // not the extension. If the input is not a regular file, for example
  273. // because it is stdin, no filename checking is performed.
  274. if (unit_info.source().is_regular_file()) {
  275. auto filename = unit_info.source().filename();
  276. static constexpr llvm::StringLiteral ApiExt = ".carbon";
  277. static constexpr llvm::StringLiteral ImplExt = ".impl.carbon";
  278. bool is_api_with_impl_ext = !is_impl && filename.ends_with(ImplExt);
  279. auto want_ext = is_impl ? ImplExt : ApiExt;
  280. if (is_api_with_impl_ext || !filename.ends_with(want_ext)) {
  281. CARBON_DIAGNOSTIC(
  282. IncorrectExtension, Error,
  283. "file extension of `{0:.impl|}.carbon` required for {0:`impl`|api}",
  284. Diagnostics::BoolAsSelect);
  285. auto diag = unit_info.emitter.Build(
  286. packaging ? packaging->names.node_id : Parse::NodeId::None,
  287. IncorrectExtension, is_impl);
  288. if (is_api_with_impl_ext) {
  289. CARBON_DIAGNOSTIC(
  290. IncorrectExtensionImplNote, Note,
  291. "file extension of `.impl.carbon` only allowed for `impl`");
  292. diag.Note(Parse::NodeId::None, IncorrectExtensionImplNote);
  293. }
  294. diag.Emit();
  295. }
  296. }
  297. }
  298. return api_map;
  299. }
  300. // Handles printing of formatted SemIR.
  301. static auto MaybeDumpFormattedSemIR(
  302. const SemIR::File& sem_ir,
  303. Parse::GetTreeAndSubtreesFn tree_and_subtrees_getter, bool include_in_dumps,
  304. const CheckParseTreesOptions& options) -> void {
  305. bool dump = options.dump_stream && include_in_dumps;
  306. if (!options.vlog_stream && !dump) {
  307. return;
  308. }
  309. bool has_ranges = sem_ir.parse_tree().tokens().has_dump_sem_ir_ranges();
  310. if (options.dump_sem_ir_ranges ==
  311. CheckParseTreesOptions::DumpSemIRRanges::Only &&
  312. !has_ranges) {
  313. return;
  314. }
  315. bool use_dump_sem_ir_ranges =
  316. options.dump_sem_ir_ranges !=
  317. CheckParseTreesOptions::DumpSemIRRanges::Ignore &&
  318. has_ranges;
  319. SemIR::Formatter formatter(&sem_ir, tree_and_subtrees_getter,
  320. options.include_in_dumps, use_dump_sem_ir_ranges);
  321. formatter.Format();
  322. if (options.vlog_stream) {
  323. CARBON_VLOG_TO(options.vlog_stream, "*** SemIR::File ***\n");
  324. formatter.Write(*options.vlog_stream);
  325. }
  326. if (dump) {
  327. formatter.Write(*options.dump_stream);
  328. }
  329. }
  330. // Handles options for dumping SemIR, including verbose output.
  331. static auto MaybeDumpSemIR(
  332. llvm::ArrayRef<Unit> units,
  333. const Parse::GetTreeAndSubtreesStore& tree_and_subtrees_getters,
  334. const CheckParseTreesOptions& options) -> void {
  335. if (!options.vlog_stream && !options.dump_stream &&
  336. !options.raw_dump_stream) {
  337. return;
  338. }
  339. // Flush diagnostics before printing.
  340. for (const auto& unit : units) {
  341. unit.consumer->Flush();
  342. }
  343. for (const auto& unit : units) {
  344. bool include_in_dumps =
  345. options.include_in_dumps->Get(unit.sem_ir->check_ir_id());
  346. if (include_in_dumps && options.raw_dump_stream) {
  347. unit.sem_ir->Print(*options.raw_dump_stream,
  348. options.dump_raw_sem_ir_builtins);
  349. }
  350. MaybeDumpFormattedSemIR(
  351. *unit.sem_ir, tree_and_subtrees_getters.Get(unit.sem_ir->check_ir_id()),
  352. include_in_dumps, options);
  353. }
  354. }
  355. auto CheckParseTrees(
  356. llvm::MutableArrayRef<Unit> units,
  357. const Parse::GetTreeAndSubtreesStore& tree_and_subtrees_getters,
  358. llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> fs,
  359. const CheckParseTreesOptions& options,
  360. std::shared_ptr<clang::CompilerInvocation> clang_invocation) -> void {
  361. // UnitAndImports is big due to its SmallVectors, so we default to 0 on the
  362. // stack.
  363. llvm::SmallVector<UnitAndImports, 0> unit_infos(
  364. llvm::map_range(units, [&](Unit& unit) {
  365. return UnitAndImports(
  366. &unit, tree_and_subtrees_getters.Get(unit.sem_ir->check_ir_id()));
  367. }));
  368. Map<ImportKey, UnitAndImports*> api_map =
  369. BuildApiMapAndDiagnosePackaging(unit_infos);
  370. // Mark down imports for all files.
  371. llvm::SmallVector<UnitAndImports*> ready_to_check;
  372. ready_to_check.reserve(units.size());
  373. for (auto& unit_info : unit_infos) {
  374. const auto& packaging = unit_info.parse_tree().packaging_decl();
  375. if (packaging && packaging->is_impl) {
  376. // An `impl` has an implicit import of its `api`.
  377. auto implicit_names = packaging->names;
  378. implicit_names.package_id = PackageNameId::None;
  379. TrackImport(api_map, nullptr, unit_info, implicit_names, options.fuzzing);
  380. }
  381. Map<ImportKey, Parse::NodeId> explicit_import_map;
  382. // Add the prelude import. It's added to explicit_import_map so that it can
  383. // conflict with an explicit import of the prelude.
  384. if (options.prelude_import &&
  385. !(packaging && packaging->names.package_id == PackageNameId::Core)) {
  386. auto prelude_id =
  387. unit_info.unit->value_stores->string_literal_values().Add("prelude");
  388. TrackImport(api_map, &explicit_import_map, unit_info,
  389. {.node_id = Parse::NoneNodeId(),
  390. .package_id = PackageNameId::Core,
  391. .library_id = prelude_id},
  392. options.fuzzing);
  393. }
  394. for (const auto& import : unit_info.parse_tree().imports()) {
  395. TrackImport(api_map, &explicit_import_map, unit_info, import,
  396. options.fuzzing);
  397. }
  398. // If there were no imports, mark the file as ready to check for below.
  399. if (unit_info.imports_remaining == 0) {
  400. ready_to_check.push_back(&unit_info);
  401. }
  402. }
  403. // Check everything with no dependencies. Earlier entries with dependencies
  404. // will be checked as soon as all their dependencies have been checked.
  405. for (int check_index = 0;
  406. check_index < static_cast<int>(ready_to_check.size()); ++check_index) {
  407. auto* unit_info = ready_to_check[check_index];
  408. CheckUnit(unit_info, &tree_and_subtrees_getters, fs, clang_invocation,
  409. options.gen_implicit_type_impls, options.vlog_stream)
  410. .Run();
  411. for (auto* incoming_import : unit_info->incoming_imports) {
  412. --incoming_import->imports_remaining;
  413. if (incoming_import->imports_remaining == 0) {
  414. ready_to_check.push_back(incoming_import);
  415. }
  416. }
  417. }
  418. // If there are still units with remaining imports, it means there's a
  419. // dependency loop.
  420. if (ready_to_check.size() < unit_infos.size()) {
  421. // Go through units and mask out unevaluated imports. This breaks everything
  422. // associated with a loop equivalently, whether it's part of it or depending
  423. // on a part of it.
  424. // TODO: Better identify cycles, maybe try to untangle them.
  425. for (auto& unit_info : unit_infos) {
  426. if (unit_info.imports_remaining > 0) {
  427. for (auto& package_imports : unit_info.package_imports) {
  428. for (auto* import_it = package_imports.imports.begin();
  429. import_it != package_imports.imports.end();) {
  430. if (import_it->unit_info->is_checked) {
  431. // The import is checked, so continue.
  432. ++import_it;
  433. } else {
  434. // The import hasn't been checked, indicating a cycle.
  435. CARBON_DIAGNOSTIC(ImportCycleDetected, Error,
  436. "import cannot be used due to a cycle; cycle "
  437. "must be fixed to import");
  438. unit_info.emitter.Emit(import_it->names.node_id,
  439. ImportCycleDetected);
  440. // Make this look the same as an import which wasn't found.
  441. package_imports.has_load_error = true;
  442. if (unit_info.api_for_impl == import_it->unit_info) {
  443. unit_info.api_for_impl = nullptr;
  444. }
  445. import_it = package_imports.imports.erase(import_it);
  446. }
  447. }
  448. }
  449. }
  450. }
  451. // Check the remaining file contents, which are probably broken due to
  452. // incomplete imports.
  453. for (auto& unit_info : unit_infos) {
  454. if (unit_info.imports_remaining > 0) {
  455. CheckUnit(&unit_info, &tree_and_subtrees_getters, fs, clang_invocation,
  456. options.gen_implicit_type_impls, options.vlog_stream)
  457. .Run();
  458. }
  459. }
  460. }
  461. MaybeDumpSemIR(units, tree_and_subtrees_getters, options);
  462. }
  463. } // namespace Carbon::Check