check.cpp 18 KB

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