check.cpp 17 KB

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