check.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  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 "toolchain/base/pretty_stack_trace_function.h"
  7. #include "toolchain/base/value_store.h"
  8. #include "toolchain/check/context.h"
  9. #include "toolchain/diagnostics/diagnostic_emitter.h"
  10. #include "toolchain/lex/token_kind.h"
  11. #include "toolchain/parse/tree.h"
  12. #include "toolchain/parse/tree_node_location_translator.h"
  13. #include "toolchain/sem_ir/file.h"
  14. namespace Carbon::Check {
  15. struct UnitInfo {
  16. // A given import within the file, with its destination.
  17. struct Import {
  18. Parse::Tree::PackagingNames names;
  19. UnitInfo* unit_info;
  20. };
  21. // A file's imports corresponding to a single package, for the map.
  22. struct PackageImports {
  23. // Use the constructor so that the SmallVector is only constructed
  24. // as-needed.
  25. explicit PackageImports(Parse::NodeId node) : node(node) {}
  26. // The first `import` directive in the file, which declared the package's
  27. // identifier (even if the import failed). Used for associating diagnostics
  28. // not specific to a single import.
  29. Parse::NodeId node;
  30. // Whether there's an import that failed to load.
  31. bool has_load_error = false;
  32. // The list of valid imports.
  33. llvm::SmallVector<Import> imports;
  34. };
  35. explicit UnitInfo(Unit& unit)
  36. : unit(&unit),
  37. translator(unit.tokens, unit.tokens->source().filename(),
  38. unit.parse_tree),
  39. err_tracker(*unit.consumer),
  40. emitter(translator, err_tracker) {}
  41. Unit* unit;
  42. // Emitter information.
  43. Parse::NodeLocationTranslator translator;
  44. ErrorTrackingDiagnosticConsumer err_tracker;
  45. DiagnosticEmitter<Parse::NodeId> emitter;
  46. // A map of package names to outgoing imports. If the
  47. // import's target isn't available, the unit will be nullptr to assist with
  48. // name lookup. Invalid imports (for example, `import Main;`) aren't added
  49. // because they won't add identifiers to name lookup.
  50. llvm::DenseMap<IdentifierId, PackageImports> package_imports_map;
  51. // The remaining number of imports which must be checked before this unit can
  52. // be processed.
  53. int32_t imports_remaining = 0;
  54. // A list of incoming imports. This will be empty for `impl` files, because
  55. // imports only touch `api` files.
  56. llvm::SmallVector<UnitInfo*> incoming_imports;
  57. };
  58. // Add imports to the root block.
  59. static auto AddImports(Context& context, UnitInfo& unit_info) -> void {
  60. for (auto& [package_id, package_imports] : unit_info.package_imports_map) {
  61. llvm::SmallVector<const SemIR::File*> sem_irs;
  62. for (auto import : package_imports.imports) {
  63. sem_irs.push_back(&**import.unit_info->unit->sem_ir);
  64. }
  65. context.AddPackageImports(package_imports.node, package_id, sem_irs,
  66. package_imports.has_load_error);
  67. }
  68. }
  69. // Loops over all nodes in the tree. On some errors, this may return early,
  70. // for example if an unrecoverable state is encountered.
  71. static auto ProcessParseNodes(Context& context,
  72. ErrorTrackingDiagnosticConsumer& err_tracker)
  73. -> bool {
  74. for (auto parse_node : context.parse_tree().postorder()) {
  75. // clang warns on unhandled enum values; clang-tidy is incorrect here.
  76. // NOLINTNEXTLINE(bugprone-switch-missing-default-case)
  77. switch (auto parse_kind = context.parse_tree().node_kind(parse_node)) {
  78. #define CARBON_PARSE_NODE_KIND(Name) \
  79. case Parse::NodeKind::Name: { \
  80. if (!Check::Handle##Name(context, parse_node)) { \
  81. CARBON_CHECK(err_tracker.seen_error()) \
  82. << "Handle" #Name " returned false without printing a diagnostic"; \
  83. return false; \
  84. } \
  85. break; \
  86. }
  87. #include "toolchain/parse/node_kind.def"
  88. }
  89. }
  90. return true;
  91. }
  92. // Produces and checks the IR for the provided Parse::Tree.
  93. // TODO: Both valid and invalid imports should be recorded on the SemIR. Invalid
  94. // imports should suppress errors where it makes sense.
  95. static auto CheckParseTree(const SemIR::File& builtin_ir, UnitInfo& unit_info,
  96. llvm::raw_ostream* vlog_stream) -> void {
  97. unit_info.unit->sem_ir->emplace(
  98. *unit_info.unit->value_stores,
  99. unit_info.unit->tokens->source().filename().str(), &builtin_ir);
  100. // For ease-of-access.
  101. SemIR::File& sem_ir = **unit_info.unit->sem_ir;
  102. Context context(*unit_info.unit->tokens, unit_info.emitter,
  103. *unit_info.unit->parse_tree, sem_ir, vlog_stream);
  104. PrettyStackTraceFunction context_dumper(
  105. [&](llvm::raw_ostream& output) { context.PrintForStackDump(output); });
  106. // Add a block for the Parse::Tree.
  107. context.inst_block_stack().Push();
  108. context.PushScope();
  109. AddImports(context, unit_info);
  110. if (!ProcessParseNodes(context, unit_info.err_tracker)) {
  111. context.sem_ir().set_has_errors(true);
  112. return;
  113. }
  114. // Pop information for the file-level scope.
  115. sem_ir.set_top_inst_block_id(context.inst_block_stack().Pop());
  116. context.PopScope();
  117. context.VerifyOnFinish();
  118. sem_ir.set_has_errors(unit_info.err_tracker.seen_error());
  119. #ifndef NDEBUG
  120. if (auto verify = sem_ir.Verify(); !verify.ok()) {
  121. CARBON_FATAL() << sem_ir << "Built invalid semantics IR: " << verify.error()
  122. << "\n";
  123. }
  124. #endif
  125. }
  126. // The package and library names, used as map keys.
  127. using ImportKey = std::pair<llvm::StringRef, llvm::StringRef>;
  128. // Returns a key form of the package object. file_package_id is only used for
  129. // imports, not the main package directive; as a consequence, it will be invalid
  130. // for the main package directive.
  131. static auto GetImportKey(UnitInfo& unit_info, IdentifierId file_package_id,
  132. Parse::Tree::PackagingNames names) -> ImportKey {
  133. auto* stores = unit_info.unit->value_stores;
  134. llvm::StringRef package_name =
  135. names.package_id.is_valid() ? stores->identifiers().Get(names.package_id)
  136. : file_package_id.is_valid() ? stores->identifiers().Get(file_package_id)
  137. : "";
  138. llvm::StringRef library_name =
  139. names.library_id.is_valid()
  140. ? stores->string_literals().Get(names.library_id)
  141. : "";
  142. return {package_name, library_name};
  143. }
  144. static constexpr llvm::StringLiteral ExplicitMainName = "Main";
  145. // Marks an import as required on both the source and target file.
  146. //
  147. // The ID comparisons between the import and unit are okay because they both
  148. // come from the same file.
  149. static auto TrackImport(
  150. llvm::DenseMap<ImportKey, UnitInfo*>& api_map,
  151. llvm::DenseMap<ImportKey, Parse::NodeId>* explicit_import_map,
  152. UnitInfo& unit_info, Parse::Tree::PackagingNames import) -> void {
  153. const auto& packaging = unit_info.unit->parse_tree->packaging_directive();
  154. IdentifierId file_package_id =
  155. packaging ? packaging->names.package_id : IdentifierId::Invalid;
  156. auto import_key = GetImportKey(unit_info, file_package_id, import);
  157. // True if the import has `Main` as the package name, even if it comes from
  158. // the file's packaging (diagnostics may differentiate).
  159. bool is_explicit_main = import_key.first == ExplicitMainName;
  160. // Explicit imports need more validation than implicit ones. We try to do
  161. // these in an order of imports that should be removed, followed by imports
  162. // that might be valid with syntax fixes.
  163. if (explicit_import_map) {
  164. // Diagnose redundant imports.
  165. if (auto [insert_it, success] =
  166. explicit_import_map->insert({import_key, import.node});
  167. !success) {
  168. CARBON_DIAGNOSTIC(RepeatedImport, Error,
  169. "Library imported more than once.");
  170. CARBON_DIAGNOSTIC(FirstImported, Note, "First import here.");
  171. unit_info.emitter.Build(import.node, RepeatedImport)
  172. .Note(insert_it->second, FirstImported)
  173. .Emit();
  174. return;
  175. }
  176. // True if the file's package is implicitly `Main` (by omitting an explicit
  177. // package name).
  178. bool is_file_implicit_main =
  179. !packaging || !packaging->names.package_id.is_valid();
  180. // True if the import is using implicit "current package" syntax (by
  181. // omitting an explicit package name).
  182. bool is_import_implicit_current_package = !import.package_id.is_valid();
  183. // True if the import is using `default` library syntax.
  184. bool is_import_default_library = !import.library_id.is_valid();
  185. // True if the import and file point at the same package, even by
  186. // incorrectly specifying the current package name to `import`.
  187. bool is_same_package = is_import_implicit_current_package ||
  188. import.package_id == file_package_id;
  189. // True if the import points at the same library as the file's library.
  190. bool is_same_library =
  191. is_same_package &&
  192. (packaging ? import.library_id == packaging->names.library_id
  193. : is_import_default_library);
  194. // Diagnose explicit imports of the same library, whether from `api` or
  195. // `impl`.
  196. if (is_same_library) {
  197. CARBON_DIAGNOSTIC(ExplicitImportApi, Error,
  198. "Explicit import of `api` from `impl` file is "
  199. "redundant with implicit import.");
  200. CARBON_DIAGNOSTIC(ImportSelf, Error, "File cannot import itself.");
  201. bool is_impl =
  202. !packaging || packaging->api_or_impl == Parse::Tree::ApiOrImpl::Impl;
  203. unit_info.emitter.Emit(import.node,
  204. is_impl ? ExplicitImportApi : ImportSelf);
  205. return;
  206. }
  207. // Diagnose explicit imports of `Main//default`. There is no `api` for it.
  208. // This lets other diagnostics handle explicit `Main` package naming.
  209. if (is_file_implicit_main && is_import_implicit_current_package &&
  210. is_import_default_library) {
  211. CARBON_DIAGNOSTIC(ImportMainDefaultLibrary, Error,
  212. "Cannot import `Main//default`.");
  213. unit_info.emitter.Emit(import.node, ImportMainDefaultLibrary);
  214. return;
  215. }
  216. if (!is_import_implicit_current_package) {
  217. // Diagnose explicit imports of the same package that use the package
  218. // name.
  219. if (is_same_package || (is_file_implicit_main && is_explicit_main)) {
  220. CARBON_DIAGNOSTIC(
  221. ImportCurrentPackageByName, Error,
  222. "Imports from the current package must omit the package name.");
  223. unit_info.emitter.Emit(import.node, ImportCurrentPackageByName);
  224. return;
  225. }
  226. // Diagnose explicit imports from `Main`.
  227. if (is_explicit_main) {
  228. CARBON_DIAGNOSTIC(ImportMainPackage, Error,
  229. "Cannot import `Main` from other packages.");
  230. unit_info.emitter.Emit(import.node, ImportMainPackage);
  231. return;
  232. }
  233. }
  234. } else if (is_explicit_main) {
  235. // An implicit import with an explicit `Main` occurs when a `package` rule
  236. // has bad syntax, which will have been diagnosed when building the API map.
  237. // As a consequence, we return silently.
  238. return;
  239. }
  240. // Get the package imports.
  241. auto package_imports_it =
  242. unit_info.package_imports_map.try_emplace(import.package_id, import.node)
  243. .first;
  244. if (auto api = api_map.find(import_key); api != api_map.end()) {
  245. // Add references between the file and imported api.
  246. package_imports_it->second.imports.push_back({import, api->second});
  247. ++unit_info.imports_remaining;
  248. api->second->incoming_imports.push_back(&unit_info);
  249. } else {
  250. // The imported api is missing.
  251. package_imports_it->second.has_load_error = true;
  252. CARBON_DIAGNOSTIC(LibraryApiNotFound, Error,
  253. "Corresponding API not found.");
  254. CARBON_DIAGNOSTIC(ImportNotFound, Error, "Imported API not found.");
  255. unit_info.emitter.Emit(
  256. import.node, explicit_import_map ? ImportNotFound : LibraryApiNotFound);
  257. }
  258. }
  259. // Builds a map of `api` files which might be imported. Also diagnoses issues
  260. // related to the packaging because the strings are loaded as part of getting
  261. // the ImportKey (which we then do for `impl` files too).
  262. static auto BuildApiMapAndDiagnosePackaging(
  263. llvm::SmallVector<UnitInfo, 0>& unit_infos)
  264. -> llvm::DenseMap<ImportKey, UnitInfo*> {
  265. llvm::DenseMap<ImportKey, UnitInfo*> api_map;
  266. for (auto& unit_info : unit_infos) {
  267. const auto& packaging = unit_info.unit->parse_tree->packaging_directive();
  268. // An import key formed from the `package` or `library` directive. Or, for
  269. // Main//default, a placeholder key.
  270. auto import_key = packaging ? GetImportKey(unit_info, IdentifierId::Invalid,
  271. packaging->names)
  272. // Construct a boring key for Main//default.
  273. : ImportKey{"", ""};
  274. // Diagnose explicit `Main` uses before they become marked as possible
  275. // APIs.
  276. if (import_key.first == ExplicitMainName) {
  277. CARBON_DIAGNOSTIC(ExplicitMainPackage, Error,
  278. "`Main//default` must omit `package` directive.");
  279. CARBON_DIAGNOSTIC(ExplicitMainLibrary, Error,
  280. "Use `library` directive in `Main` package libraries.");
  281. unit_info.emitter.Emit(packaging->names.node, import_key.second.empty()
  282. ? ExplicitMainPackage
  283. : ExplicitMainLibrary);
  284. continue;
  285. }
  286. bool is_impl =
  287. packaging && packaging->api_or_impl == Parse::Tree::ApiOrImpl::Impl;
  288. // Add to the `api` map and diagnose duplicates. This occurs before the
  289. // file extension check because we might emit both diagnostics in situation
  290. // where the user forgets (or has syntax errors with) a package line
  291. // multiple times.
  292. if (!is_impl) {
  293. auto [entry, success] = api_map.insert({import_key, &unit_info});
  294. if (!success) {
  295. llvm::StringRef prev_filename =
  296. entry->second->unit->tokens->source().filename();
  297. if (packaging) {
  298. CARBON_DIAGNOSTIC(DuplicateLibraryApi, Error,
  299. "Library's API previously provided by `{0}`.",
  300. std::string);
  301. unit_info.emitter.Emit(packaging->names.node, DuplicateLibraryApi,
  302. prev_filename.str());
  303. } else {
  304. CARBON_DIAGNOSTIC(DuplicateMainApi, Error,
  305. "Main//default previously provided by `{0}`.",
  306. std::string);
  307. // Use the invalid node because there's no node to associate with.
  308. unit_info.emitter.Emit(Parse::NodeId::Invalid, DuplicateMainApi,
  309. prev_filename.str());
  310. }
  311. }
  312. }
  313. // Validate file extensions. Note imports rely the packaging directive, not
  314. // the extension. If the input is not a regular file, for example because it
  315. // is stdin, no filename checking is performed.
  316. if (unit_info.unit->tokens->source().is_regular_file()) {
  317. auto filename = unit_info.unit->tokens->source().filename();
  318. static constexpr llvm::StringLiteral ApiExt = ".carbon";
  319. static constexpr llvm::StringLiteral ImplExt = ".impl.carbon";
  320. bool is_api_with_impl_ext = !is_impl && filename.ends_with(ImplExt);
  321. auto want_ext = is_impl ? ImplExt : ApiExt;
  322. if (is_api_with_impl_ext || !filename.ends_with(want_ext)) {
  323. CARBON_DIAGNOSTIC(IncorrectExtension, Error,
  324. "File extension of `{0}` required for `{1}`.",
  325. llvm::StringLiteral, Lex::TokenKind);
  326. auto diag = unit_info.emitter.Build(
  327. packaging ? packaging->names.node : Parse::NodeId::Invalid,
  328. IncorrectExtension, want_ext,
  329. is_impl ? Lex::TokenKind::Impl : Lex::TokenKind::Api);
  330. if (is_api_with_impl_ext) {
  331. CARBON_DIAGNOSTIC(IncorrectExtensionImplNote, Note,
  332. "File extension of `{0}` only allowed for `{1}`.",
  333. llvm::StringLiteral, Lex::TokenKind);
  334. diag.Note(Parse::NodeId::Invalid, IncorrectExtensionImplNote, ImplExt,
  335. Lex::TokenKind::Impl);
  336. }
  337. diag.Emit();
  338. }
  339. }
  340. }
  341. return api_map;
  342. }
  343. auto CheckParseTrees(const SemIR::File& builtin_ir,
  344. llvm::MutableArrayRef<Unit> units,
  345. llvm::raw_ostream* vlog_stream) -> void {
  346. // Prepare diagnostic emitters in case we run into issues during package
  347. // checking.
  348. //
  349. // UnitInfo is big due to its SmallVectors, so we default to 0 on the stack.
  350. llvm::SmallVector<UnitInfo, 0> unit_infos;
  351. unit_infos.reserve(units.size());
  352. for (auto& unit : units) {
  353. unit_infos.emplace_back(unit);
  354. }
  355. llvm::DenseMap<ImportKey, UnitInfo*> api_map =
  356. BuildApiMapAndDiagnosePackaging(unit_infos);
  357. // Mark down imports for all files.
  358. llvm::SmallVector<UnitInfo*> ready_to_check;
  359. ready_to_check.reserve(units.size());
  360. for (auto& unit_info : unit_infos) {
  361. if (const auto& packaging =
  362. unit_info.unit->parse_tree->packaging_directive()) {
  363. if (packaging->api_or_impl == Parse::Tree::ApiOrImpl::Impl) {
  364. // An `impl` has an implicit import of its `api`.
  365. TrackImport(api_map, nullptr, unit_info, packaging->names);
  366. }
  367. }
  368. llvm::DenseMap<ImportKey, Parse::NodeId> explicit_import_map;
  369. for (const auto& import : unit_info.unit->parse_tree->imports()) {
  370. TrackImport(api_map, &explicit_import_map, unit_info, import);
  371. }
  372. // If there were no imports, mark the file as ready to check for below.
  373. if (unit_info.imports_remaining == 0) {
  374. ready_to_check.push_back(&unit_info);
  375. }
  376. }
  377. // Check everything with no dependencies. Earlier entries with dependencies
  378. // will be checked as soon as all their dependencies have been checked.
  379. for (int check_index = 0;
  380. check_index < static_cast<int>(ready_to_check.size()); ++check_index) {
  381. auto* unit_info = ready_to_check[check_index];
  382. CheckParseTree(builtin_ir, *unit_info, vlog_stream);
  383. for (auto* incoming_import : unit_info->incoming_imports) {
  384. --incoming_import->imports_remaining;
  385. if (incoming_import->imports_remaining == 0) {
  386. ready_to_check.push_back(incoming_import);
  387. }
  388. }
  389. }
  390. // If there are still units with remaining imports, it means there's a
  391. // dependency loop.
  392. if (ready_to_check.size() < unit_infos.size()) {
  393. // Go through units and mask out unevaluated imports. This breaks everything
  394. // associated with a loop equivalently, whether it's part of it or depending
  395. // on a part of it.
  396. // TODO: Better identify cycles, maybe try to untangle them.
  397. for (auto& unit_info : unit_infos) {
  398. if (unit_info.imports_remaining > 0) {
  399. for (auto& [package_id, package_imports] :
  400. unit_info.package_imports_map) {
  401. for (auto* import_it = package_imports.imports.begin();
  402. import_it != package_imports.imports.end();) {
  403. if (*import_it->unit_info->unit->sem_ir) {
  404. // The import is checked, so continue.
  405. ++import_it;
  406. } else {
  407. // The import hasn't been checked, indicating a cycle.
  408. CARBON_DIAGNOSTIC(ImportCycleDetected, Error,
  409. "Import cannot be used due to a cycle. Cycle "
  410. "must be fixed to import.");
  411. unit_info.emitter.Emit(import_it->names.node,
  412. ImportCycleDetected);
  413. // Make this look the same as an import which wasn't found.
  414. package_imports.has_load_error = true;
  415. import_it = package_imports.imports.erase(import_it);
  416. }
  417. }
  418. }
  419. }
  420. }
  421. // Check the remaining file contents, which are probably broken due to
  422. // incomplete imports.
  423. for (auto& unit_info : unit_infos) {
  424. if (unit_info.imports_remaining > 0) {
  425. CheckParseTree(builtin_ir, unit_info, vlog_stream);
  426. }
  427. }
  428. }
  429. }
  430. } // namespace Carbon::Check