check.cpp 18 KB

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