check.cpp 21 KB

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