check.cpp 21 KB

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