check.cpp 15 KB

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