check.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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/parse/tree_node_location_translator.h"
  10. #include "toolchain/sem_ir/file.h"
  11. namespace Carbon::Check {
  12. struct UnitInfo {
  13. explicit UnitInfo(Unit& unit)
  14. : unit(&unit),
  15. translator(unit.tokens, unit.parse_tree),
  16. err_tracker(*unit.consumer),
  17. emitter(translator, err_tracker) {}
  18. Unit* unit;
  19. // Emitter information.
  20. Parse::NodeLocationTranslator translator;
  21. ErrorTrackingDiagnosticConsumer err_tracker;
  22. DiagnosticEmitter<Parse::Node> emitter;
  23. // A list of outgoing imports.
  24. llvm::SmallVector<std::pair<Parse::Node, UnitInfo*>> imports;
  25. // The remaining number of imports which must be checked before this unit can
  26. // be processed.
  27. int32_t imports_remaining = 0;
  28. // A list of incoming imports. This will be empty for `impl` files, because
  29. // imports only touch `api` files.
  30. llvm::SmallVector<UnitInfo*> incoming_imports;
  31. };
  32. // Produces and checks the IR for the provided Parse::Tree.
  33. // TODO: Both valid and invalid imports should be recorded on the SemIR. Invalid
  34. // imports should suppress errors where it makes sense.
  35. static auto CheckParseTree(const SemIR::File& builtin_ir, UnitInfo& unit_info,
  36. llvm::raw_ostream* vlog_stream) -> void {
  37. unit_info.unit->sem_ir->emplace(*unit_info.unit->value_stores,
  38. unit_info.unit->tokens->filename().str(),
  39. &builtin_ir);
  40. // For ease-of-access.
  41. SemIR::File& sem_ir = **unit_info.unit->sem_ir;
  42. const Parse::Tree& parse_tree = *unit_info.unit->parse_tree;
  43. Check::Context context(*unit_info.unit->tokens, unit_info.emitter, parse_tree,
  44. sem_ir, vlog_stream);
  45. PrettyStackTraceFunction context_dumper(
  46. [&](llvm::raw_ostream& output) { context.PrintForStackDump(output); });
  47. // Add a block for the Parse::Tree.
  48. context.inst_block_stack().Push();
  49. context.PushScope();
  50. // Loops over all nodes in the tree. On some errors, this may return early,
  51. // for example if an unrecoverable state is encountered.
  52. for (auto parse_node : parse_tree.postorder()) {
  53. // clang warns on unhandled enum values; clang-tidy is incorrect here.
  54. // NOLINTNEXTLINE(bugprone-switch-missing-default-case)
  55. switch (auto parse_kind = parse_tree.node_kind(parse_node)) {
  56. #define CARBON_PARSE_NODE_KIND(Name) \
  57. case Parse::NodeKind::Name: { \
  58. if (!Check::Handle##Name(context, parse_node)) { \
  59. CARBON_CHECK(unit_info.err_tracker.seen_error()) \
  60. << "Handle" #Name " returned false without printing a diagnostic"; \
  61. sem_ir.set_has_errors(true); \
  62. return; \
  63. } \
  64. break; \
  65. }
  66. #include "toolchain/parse/node_kind.def"
  67. }
  68. }
  69. // Pop information for the file-level scope.
  70. sem_ir.set_top_inst_block_id(context.inst_block_stack().Pop());
  71. context.PopScope();
  72. context.VerifyOnFinish();
  73. sem_ir.set_has_errors(unit_info.err_tracker.seen_error());
  74. #ifndef NDEBUG
  75. if (auto verify = sem_ir.Verify(); !verify.ok()) {
  76. CARBON_FATAL() << sem_ir << "Built invalid semantics IR: " << verify.error()
  77. << "\n";
  78. }
  79. #endif
  80. }
  81. // The package and library names, used as map keys.
  82. using ImportKey = std::pair<llvm::StringRef, llvm::StringRef>;
  83. // Returns a key form of the package object.
  84. static auto GetImportKey(UnitInfo& unit_info,
  85. Parse::Tree::PackagingNames package) -> ImportKey {
  86. auto* stores = unit_info.unit->value_stores;
  87. return {package.package_id.is_valid()
  88. ? stores->identifiers().Get(package.package_id)
  89. : "",
  90. package.library_id.is_valid()
  91. ? stores->string_literals().Get(package.library_id)
  92. : ""};
  93. }
  94. static constexpr llvm::StringLiteral ExplicitMainName = "Main";
  95. // Marks an import as required on both the source and target file.
  96. // TODO: When importing without a package name is supported, check that it's
  97. // used correctly.
  98. static auto TrackImport(
  99. llvm::DenseMap<ImportKey, UnitInfo*>& api_map,
  100. llvm::DenseMap<ImportKey, Parse::Node>* explicit_import_map,
  101. UnitInfo& unit_info, Parse::Tree::PackagingNames import) -> void {
  102. auto import_key = GetImportKey(unit_info, import);
  103. // Specialize the error for imports from `Main`.
  104. if (import_key.first == ExplicitMainName) {
  105. // Implicit imports will have already warned.
  106. if (explicit_import_map) {
  107. CARBON_DIAGNOSTIC(ImportMainPackage, Error,
  108. "Cannot import `Main` from other packages.");
  109. unit_info.emitter.Emit(import.node, ImportMainPackage);
  110. }
  111. return;
  112. }
  113. if (explicit_import_map) {
  114. // Check for redundant imports.
  115. if (auto [insert_it, success] =
  116. explicit_import_map->insert({import_key, import.node});
  117. !success) {
  118. CARBON_DIAGNOSTIC(RepeatedImport, Error,
  119. "Library imported more than once.");
  120. CARBON_DIAGNOSTIC(FirstImported, Note, "First import here.");
  121. unit_info.emitter.Build(import.node, RepeatedImport)
  122. .Note(insert_it->second, FirstImported)
  123. .Emit();
  124. return;
  125. }
  126. // Check for explicit imports of the same library. The ID comparison is okay
  127. // in this case because both come from the same file.
  128. auto packaging = unit_info.unit->parse_tree->packaging_directive();
  129. if (packaging && import.package_id == packaging->names.package_id &&
  130. import.library_id == packaging->names.library_id) {
  131. CARBON_DIAGNOSTIC(ExplicitImportApi, Error,
  132. "Explicit import of `api` from `impl` file is "
  133. "redundant with implicit import.");
  134. CARBON_DIAGNOSTIC(ImportSelf, Error, "File cannot import itself.");
  135. unit_info.emitter.Emit(
  136. import.node, packaging->api_or_impl == Parse::Tree::ApiOrImpl::Impl
  137. ? ExplicitImportApi
  138. : ImportSelf);
  139. return;
  140. }
  141. }
  142. if (auto api = api_map.find(import_key); api != api_map.end()) {
  143. unit_info.imports.push_back({import.node, api->second});
  144. ++unit_info.imports_remaining;
  145. api->second->incoming_imports.push_back(&unit_info);
  146. } else {
  147. CARBON_DIAGNOSTIC(LibraryApiNotFound, Error,
  148. "Corresponding API not found.");
  149. CARBON_DIAGNOSTIC(ImportNotFound, Error, "Imported API not found.");
  150. unit_info.emitter.Emit(
  151. import.node, explicit_import_map ? ImportNotFound : LibraryApiNotFound);
  152. }
  153. }
  154. auto CheckParseTrees(const SemIR::File& builtin_ir,
  155. llvm::MutableArrayRef<Unit> units,
  156. llvm::raw_ostream* vlog_stream) -> void {
  157. // Prepare diagnostic emitters in case we run into issues during package
  158. // checking.
  159. //
  160. // UnitInfo is big due to its SmallVectors, so we default to 0 on the stack.
  161. llvm::SmallVector<UnitInfo, 0> unit_infos;
  162. unit_infos.reserve(units.size());
  163. for (auto& unit : units) {
  164. unit_infos.emplace_back(unit);
  165. }
  166. // Create a map of APIs which might be imported.
  167. llvm::DenseMap<ImportKey, UnitInfo*> api_map;
  168. for (auto& unit_info : unit_infos) {
  169. const auto& packaging = unit_info.unit->parse_tree->packaging_directive();
  170. if (packaging) {
  171. auto import_key = GetImportKey(unit_info, packaging->names);
  172. // Catch explicit `Main` errors before they become marked as possible
  173. // APIs.
  174. if (import_key.first == ExplicitMainName) {
  175. CARBON_DIAGNOSTIC(
  176. ExplicitMainPackage, Error,
  177. "Default `Main` library must omit `package` directive.");
  178. CARBON_DIAGNOSTIC(
  179. ExplicitMainLibrary, Error,
  180. "Use `library` directive in `Main` package libraries.");
  181. unit_info.emitter.Emit(packaging->names.node,
  182. import_key.second.empty() ? ExplicitMainPackage
  183. : ExplicitMainLibrary);
  184. continue;
  185. }
  186. if (packaging->api_or_impl == Parse::Tree::ApiOrImpl::Impl) {
  187. continue;
  188. }
  189. auto [entry, success] = api_map.insert({import_key, &unit_info});
  190. if (!success) {
  191. // TODO: Cross-reference the source, deal with library, etc.
  192. CARBON_DIAGNOSTIC(DuplicateLibraryApi, Error,
  193. "Library's API declared in more than one file.");
  194. unit_info.emitter.Emit(packaging->names.node, DuplicateLibraryApi);
  195. }
  196. }
  197. }
  198. // Mark down imports for all files.
  199. llvm::SmallVector<UnitInfo*> ready_to_check;
  200. ready_to_check.reserve(units.size());
  201. for (auto& unit_info : unit_infos) {
  202. const auto& packaging = unit_info.unit->parse_tree->packaging_directive();
  203. if (packaging && packaging->api_or_impl == Parse::Tree::ApiOrImpl::Impl) {
  204. // An `impl` has an implicit import of its `api`.
  205. TrackImport(api_map, nullptr, unit_info, packaging->names);
  206. }
  207. llvm::DenseMap<ImportKey, Parse::Node> explicit_import_map;
  208. for (const auto& import : unit_info.unit->parse_tree->imports()) {
  209. TrackImport(api_map, &explicit_import_map, unit_info, import);
  210. }
  211. // If there were no imports, mark the file as ready to check for below.
  212. if (unit_info.imports_remaining == 0) {
  213. ready_to_check.push_back(&unit_info);
  214. }
  215. }
  216. // Check everything with no dependencies. Earlier entries with dependencies
  217. // will be checked as soon as all their dependencies have been checked.
  218. for (int check_index = 0;
  219. check_index < static_cast<int>(ready_to_check.size()); ++check_index) {
  220. auto* unit_info = ready_to_check[check_index];
  221. CheckParseTree(builtin_ir, *unit_info, vlog_stream);
  222. for (auto* incoming_import : unit_info->incoming_imports) {
  223. --incoming_import->imports_remaining;
  224. if (incoming_import->imports_remaining == 0) {
  225. ready_to_check.push_back(incoming_import);
  226. }
  227. }
  228. }
  229. // If there are still units with remaining imports, it means there's a
  230. // dependency loop.
  231. if (ready_to_check.size() < unit_infos.size()) {
  232. // Go through units and mask out unevaluated imports. This breaks everything
  233. // associated with a loop equivalently, whether it's part of it or depending
  234. // on a part of it.
  235. // TODO: Better identify cycles, maybe try to untangle them.
  236. for (auto& unit_info : unit_infos) {
  237. if (unit_info.imports_remaining > 0) {
  238. for (auto* import_it = unit_info.imports.begin();
  239. import_it != unit_info.imports.end();) {
  240. auto* import_unit = import_it->second->unit;
  241. if (*import_unit->sem_ir) {
  242. ++import_it;
  243. } else {
  244. CARBON_DIAGNOSTIC(ImportCycleDetected, Error,
  245. "Import cannot be used due to a cycle. Cycle "
  246. "must be fixed to import.");
  247. unit_info.emitter.Emit(import_it->first, ImportCycleDetected);
  248. import_it = unit_info.imports.erase(import_it);
  249. }
  250. }
  251. }
  252. }
  253. // Check the remaining file contents, which are probably broken due to
  254. // incomplete imports.
  255. for (auto& unit_info : unit_infos) {
  256. if (unit_info.imports_remaining > 0) {
  257. CheckParseTree(builtin_ir, unit_info, vlog_stream);
  258. }
  259. }
  260. }
  261. }
  262. } // namespace Carbon::Check