context.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  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/context.h"
  5. #include <optional>
  6. #include <string>
  7. #include <utility>
  8. #include "common/check.h"
  9. #include "common/vlog.h"
  10. #include "llvm/ADT/Sequence.h"
  11. #include "toolchain/check/decl_name_stack.h"
  12. #include "toolchain/check/eval.h"
  13. #include "toolchain/check/generic.h"
  14. #include "toolchain/check/generic_region_stack.h"
  15. #include "toolchain/check/import.h"
  16. #include "toolchain/check/import_ref.h"
  17. #include "toolchain/check/inst_block_stack.h"
  18. #include "toolchain/check/merge.h"
  19. #include "toolchain/check/type_completion.h"
  20. #include "toolchain/diagnostics/diagnostic_emitter.h"
  21. #include "toolchain/diagnostics/format_providers.h"
  22. #include "toolchain/lex/tokenized_buffer.h"
  23. #include "toolchain/parse/node_ids.h"
  24. #include "toolchain/parse/node_kind.h"
  25. #include "toolchain/sem_ir/file.h"
  26. #include "toolchain/sem_ir/formatter.h"
  27. #include "toolchain/sem_ir/generic.h"
  28. #include "toolchain/sem_ir/ids.h"
  29. #include "toolchain/sem_ir/import_ir.h"
  30. #include "toolchain/sem_ir/inst.h"
  31. #include "toolchain/sem_ir/inst_kind.h"
  32. #include "toolchain/sem_ir/name_scope.h"
  33. #include "toolchain/sem_ir/type_info.h"
  34. #include "toolchain/sem_ir/typed_insts.h"
  35. namespace Carbon::Check {
  36. Context::Context(DiagnosticEmitter* emitter,
  37. Parse::GetTreeAndSubtreesFn tree_and_subtrees_getter,
  38. SemIR::File* sem_ir, int imported_ir_count, int total_ir_count,
  39. llvm::raw_ostream* vlog_stream)
  40. : emitter_(emitter),
  41. tree_and_subtrees_getter_(tree_and_subtrees_getter),
  42. sem_ir_(sem_ir),
  43. vlog_stream_(vlog_stream),
  44. node_stack_(sem_ir->parse_tree(), vlog_stream),
  45. inst_block_stack_("inst_block_stack_", *sem_ir, vlog_stream),
  46. pattern_block_stack_("pattern_block_stack_", *sem_ir, vlog_stream),
  47. param_and_arg_refs_stack_(*sem_ir, vlog_stream, node_stack_),
  48. args_type_info_stack_("args_type_info_stack_", *sem_ir, vlog_stream),
  49. decl_name_stack_(this),
  50. scope_stack_(sem_ir_),
  51. vtable_stack_("vtable_stack_", *sem_ir, vlog_stream),
  52. global_init_(this),
  53. region_stack_(
  54. [this](SemIRLoc loc, std::string label) { TODO(loc, label); }) {
  55. // Prepare fields which relate to the number of IRs available for import.
  56. import_irs().Reserve(imported_ir_count);
  57. import_ir_constant_values_.reserve(imported_ir_count);
  58. check_ir_map_.resize(total_ir_count, SemIR::ImportIRId::None);
  59. // Map the builtin `<error>` and `type` type constants to their corresponding
  60. // special `TypeId` values.
  61. type_ids_for_type_constants_.Insert(
  62. SemIR::ConstantId::ForConcreteConstant(SemIR::ErrorInst::SingletonInstId),
  63. SemIR::ErrorInst::SingletonTypeId);
  64. type_ids_for_type_constants_.Insert(
  65. SemIR::ConstantId::ForConcreteConstant(SemIR::TypeType::SingletonInstId),
  66. SemIR::TypeType::SingletonTypeId);
  67. // TODO: Remove this and add a `VerifyOnFinish` once we properly push and pop
  68. // in the right places.
  69. generic_region_stack().Push();
  70. }
  71. auto Context::TODO(SemIRLoc loc, std::string label) -> bool {
  72. CARBON_DIAGNOSTIC(SemanticsTodo, Error, "semantics TODO: `{0}`", std::string);
  73. emitter_->Emit(loc, SemanticsTodo, std::move(label));
  74. return false;
  75. }
  76. auto Context::VerifyOnFinish() -> void {
  77. // Information in all the various context objects should be cleaned up as
  78. // various pieces of context go out of scope. At this point, nothing should
  79. // remain.
  80. // node_stack_ will still contain top-level entities.
  81. inst_block_stack_.VerifyOnFinish();
  82. pattern_block_stack_.VerifyOnFinish();
  83. param_and_arg_refs_stack_.VerifyOnFinish();
  84. args_type_info_stack_.VerifyOnFinish();
  85. CARBON_CHECK(struct_type_fields_stack_.empty());
  86. // TODO: Add verification for decl_name_stack_ and
  87. // decl_introducer_state_stack_.
  88. scope_stack_.VerifyOnFinish();
  89. // TODO: Add verification for generic_region_stack_.
  90. }
  91. auto Context::GetOrAddInst(SemIR::LocIdAndInst loc_id_and_inst)
  92. -> SemIR::InstId {
  93. if (loc_id_and_inst.loc_id.is_implicit()) {
  94. auto const_id =
  95. TryEvalInst(*this, SemIR::InstId::None, loc_id_and_inst.inst);
  96. if (const_id.has_value()) {
  97. CARBON_VLOG("GetOrAddInst: constant: {0}\n", loc_id_and_inst.inst);
  98. return constant_values().GetInstId(const_id);
  99. }
  100. }
  101. // TODO: For an implicit instruction, this reattempts evaluation.
  102. return AddInst(loc_id_and_inst);
  103. }
  104. // Finish producing an instruction. Set its constant value, and register it in
  105. // any applicable instruction lists.
  106. auto Context::FinishInst(SemIR::InstId inst_id, SemIR::Inst inst) -> void {
  107. GenericRegionStack::DependencyKind dep_kind =
  108. GenericRegionStack::DependencyKind::None;
  109. // If the instruction has a symbolic constant type, track that we need to
  110. // substitute into it.
  111. if (constant_values().DependsOnGenericParameter(
  112. types().GetConstantId(inst.type_id()))) {
  113. dep_kind |= GenericRegionStack::DependencyKind::SymbolicType;
  114. }
  115. // If the instruction has a constant value, compute it.
  116. auto const_id = TryEvalInst(*this, inst_id, inst);
  117. constant_values().Set(inst_id, const_id);
  118. if (const_id.is_constant()) {
  119. CARBON_VLOG("Constant: {0} -> {1}\n", inst,
  120. constant_values().GetInstId(const_id));
  121. // If the constant value is symbolic, track that we need to substitute into
  122. // it.
  123. if (constant_values().DependsOnGenericParameter(const_id)) {
  124. dep_kind |= GenericRegionStack::DependencyKind::SymbolicConstant;
  125. }
  126. }
  127. // Keep track of dependent instructions.
  128. if (dep_kind != GenericRegionStack::DependencyKind::None) {
  129. // TODO: Also check for template-dependent instructions.
  130. generic_region_stack().AddDependentInst(
  131. {.inst_id = inst_id, .kind = dep_kind});
  132. }
  133. }
  134. // Returns whether a parse node associated with an imported instruction of kind
  135. // `imported_kind` is usable as the location of a corresponding local
  136. // instruction of kind `local_kind`.
  137. static auto HasCompatibleImportedNodeKind(SemIR::InstKind imported_kind,
  138. SemIR::InstKind local_kind) -> bool {
  139. if (imported_kind == local_kind) {
  140. return true;
  141. }
  142. if (imported_kind == SemIR::ImportDecl::Kind &&
  143. local_kind == SemIR::Namespace::Kind) {
  144. static_assert(
  145. std::is_convertible_v<decltype(SemIR::ImportDecl::Kind)::TypedNodeId,
  146. decltype(SemIR::Namespace::Kind)::TypedNodeId>);
  147. return true;
  148. }
  149. return false;
  150. }
  151. auto Context::CheckCompatibleImportedNodeKind(
  152. SemIR::ImportIRInstId imported_loc_id, SemIR::InstKind kind) -> void {
  153. auto& import_ir_inst = import_ir_insts().Get(imported_loc_id);
  154. const auto* import_ir = import_irs().Get(import_ir_inst.ir_id).sem_ir;
  155. auto imported_kind = import_ir->insts().Get(import_ir_inst.inst_id).kind();
  156. CARBON_CHECK(
  157. HasCompatibleImportedNodeKind(imported_kind, kind),
  158. "Node of kind {0} created with location of imported node of kind {1}",
  159. kind, imported_kind);
  160. }
  161. auto Context::AddPlaceholderInstInNoBlock(SemIR::LocIdAndInst loc_id_and_inst)
  162. -> SemIR::InstId {
  163. auto inst_id = sem_ir().insts().AddInNoBlock(loc_id_and_inst);
  164. CARBON_VLOG("AddPlaceholderInst: {0}\n", loc_id_and_inst.inst);
  165. constant_values().Set(inst_id, SemIR::ConstantId::None);
  166. return inst_id;
  167. }
  168. auto Context::AddPlaceholderInst(SemIR::LocIdAndInst loc_id_and_inst)
  169. -> SemIR::InstId {
  170. auto inst_id = AddPlaceholderInstInNoBlock(loc_id_and_inst);
  171. inst_block_stack_.AddInstId(inst_id);
  172. return inst_id;
  173. }
  174. auto Context::ReplaceLocIdAndInstBeforeConstantUse(
  175. SemIR::InstId inst_id, SemIR::LocIdAndInst loc_id_and_inst) -> void {
  176. sem_ir().insts().SetLocIdAndInst(inst_id, loc_id_and_inst);
  177. CARBON_VLOG("ReplaceInst: {0} -> {1}\n", inst_id, loc_id_and_inst.inst);
  178. FinishInst(inst_id, loc_id_and_inst.inst);
  179. }
  180. auto Context::ReplaceInstBeforeConstantUse(SemIR::InstId inst_id,
  181. SemIR::Inst inst) -> void {
  182. sem_ir().insts().Set(inst_id, inst);
  183. CARBON_VLOG("ReplaceInst: {0} -> {1}\n", inst_id, inst);
  184. FinishInst(inst_id, inst);
  185. }
  186. auto Context::ReplaceInstPreservingConstantValue(SemIR::InstId inst_id,
  187. SemIR::Inst inst) -> void {
  188. auto old_const_id = sem_ir().constant_values().Get(inst_id);
  189. sem_ir().insts().Set(inst_id, inst);
  190. CARBON_VLOG("ReplaceInst: {0} -> {1}\n", inst_id, inst);
  191. auto new_const_id = TryEvalInst(*this, inst_id, inst);
  192. CARBON_CHECK(old_const_id == new_const_id);
  193. }
  194. auto Context::Finalize() -> void {
  195. // Pop information for the file-level scope.
  196. sem_ir().set_top_inst_block_id(inst_block_stack().Pop());
  197. scope_stack().Pop();
  198. // Finalizes the list of exports on the IR.
  199. inst_blocks().Set(SemIR::InstBlockId::Exports, exports_);
  200. // Finalizes the ImportRef inst block.
  201. inst_blocks().Set(SemIR::InstBlockId::ImportRefs, import_ref_ids_);
  202. // Finalizes __global_init.
  203. global_init_.Finalize();
  204. }
  205. auto Context::GetTypeIdForTypeConstant(SemIR::ConstantId constant_id)
  206. -> SemIR::TypeId {
  207. CARBON_CHECK(constant_id.is_constant(),
  208. "Canonicalizing non-constant type: {0}", constant_id);
  209. auto type_id =
  210. insts().Get(constant_values().GetInstId(constant_id)).type_id();
  211. CARBON_CHECK(type_id == SemIR::TypeType::SingletonTypeId ||
  212. constant_id == SemIR::ErrorInst::SingletonConstantId,
  213. "Forming type ID for non-type constant of type {0}",
  214. types().GetAsInst(type_id));
  215. return SemIR::TypeId::ForTypeConstant(constant_id);
  216. }
  217. auto Context::FacetTypeFromInterface(SemIR::InterfaceId interface_id,
  218. SemIR::SpecificId specific_id)
  219. -> SemIR::FacetType {
  220. SemIR::FacetTypeId facet_type_id = facet_types().Add(
  221. SemIR::FacetTypeInfo{.impls_constraints = {{interface_id, specific_id}},
  222. .other_requirements = false});
  223. return {.type_id = SemIR::TypeType::SingletonTypeId,
  224. .facet_type_id = facet_type_id};
  225. }
  226. // Gets or forms a type_id for a type, given the instruction kind and arguments.
  227. template <typename InstT, typename... EachArgT>
  228. static auto GetTypeImpl(Context& context, EachArgT... each_arg)
  229. -> SemIR::TypeId {
  230. // TODO: Remove inst_id parameter from TryEvalInst.
  231. InstT inst = {SemIR::TypeType::SingletonTypeId, each_arg...};
  232. return context.GetTypeIdForTypeConstant(
  233. TryEvalInst(context, SemIR::InstId::None, inst));
  234. }
  235. // Gets or forms a type_id for a type, given the instruction kind and arguments,
  236. // and completes the type. This should only be used when type completion cannot
  237. // fail.
  238. template <typename InstT, typename... EachArgT>
  239. static auto GetCompleteTypeImpl(Context& context, EachArgT... each_arg)
  240. -> SemIR::TypeId {
  241. auto type_id = GetTypeImpl<InstT>(context, each_arg...);
  242. CompleteTypeOrCheckFail(context, type_id);
  243. return type_id;
  244. }
  245. auto Context::GetStructType(SemIR::StructTypeFieldsId fields_id)
  246. -> SemIR::TypeId {
  247. return GetTypeImpl<SemIR::StructType>(*this, fields_id);
  248. }
  249. auto Context::GetTupleType(llvm::ArrayRef<SemIR::TypeId> type_ids)
  250. -> SemIR::TypeId {
  251. return GetTypeImpl<SemIR::TupleType>(*this,
  252. type_blocks().AddCanonical(type_ids));
  253. }
  254. auto Context::GetAssociatedEntityType(SemIR::TypeId interface_type_id)
  255. -> SemIR::TypeId {
  256. return GetTypeImpl<SemIR::AssociatedEntityType>(*this, interface_type_id);
  257. }
  258. auto Context::GetSingletonType(SemIR::InstId singleton_id) -> SemIR::TypeId {
  259. CARBON_CHECK(SemIR::IsSingletonInstId(singleton_id));
  260. auto type_id = GetTypeIdForTypeInst(singleton_id);
  261. // To keep client code simpler, complete builtin types before returning them.
  262. CompleteTypeOrCheckFail(*this, type_id);
  263. return type_id;
  264. }
  265. auto Context::GetClassType(SemIR::ClassId class_id,
  266. SemIR::SpecificId specific_id) -> SemIR::TypeId {
  267. return GetTypeImpl<SemIR::ClassType>(*this, class_id, specific_id);
  268. }
  269. auto Context::GetFunctionType(SemIR::FunctionId fn_id,
  270. SemIR::SpecificId specific_id) -> SemIR::TypeId {
  271. return GetCompleteTypeImpl<SemIR::FunctionType>(*this, fn_id, specific_id);
  272. }
  273. auto Context::GetFunctionTypeWithSelfType(
  274. SemIR::InstId interface_function_type_id, SemIR::InstId self_id)
  275. -> SemIR::TypeId {
  276. return GetCompleteTypeImpl<SemIR::FunctionTypeWithSelfType>(
  277. *this, interface_function_type_id, self_id);
  278. }
  279. auto Context::GetGenericClassType(SemIR::ClassId class_id,
  280. SemIR::SpecificId enclosing_specific_id)
  281. -> SemIR::TypeId {
  282. return GetCompleteTypeImpl<SemIR::GenericClassType>(*this, class_id,
  283. enclosing_specific_id);
  284. }
  285. auto Context::GetGenericInterfaceType(SemIR::InterfaceId interface_id,
  286. SemIR::SpecificId enclosing_specific_id)
  287. -> SemIR::TypeId {
  288. return GetCompleteTypeImpl<SemIR::GenericInterfaceType>(
  289. *this, interface_id, enclosing_specific_id);
  290. }
  291. auto Context::GetInterfaceType(SemIR::InterfaceId interface_id,
  292. SemIR::SpecificId specific_id) -> SemIR::TypeId {
  293. return GetTypeImpl<SemIR::FacetType>(
  294. *this, FacetTypeFromInterface(interface_id, specific_id).facet_type_id);
  295. }
  296. auto Context::GetPointerType(SemIR::TypeId pointee_type_id) -> SemIR::TypeId {
  297. return GetTypeImpl<SemIR::PointerType>(*this, pointee_type_id);
  298. }
  299. auto Context::GetUnboundElementType(SemIR::TypeId class_type_id,
  300. SemIR::TypeId element_type_id)
  301. -> SemIR::TypeId {
  302. return GetTypeImpl<SemIR::UnboundElementType>(*this, class_type_id,
  303. element_type_id);
  304. }
  305. auto Context::PrintForStackDump(llvm::raw_ostream& output) const -> void {
  306. output << "Check::Context\n";
  307. // In a stack dump, this is probably indented by a tab. We treat that as 8
  308. // spaces then add a couple to indent past the Context label.
  309. constexpr int Indent = 10;
  310. node_stack_.PrintForStackDump(Indent, output);
  311. inst_block_stack_.PrintForStackDump(Indent, output);
  312. pattern_block_stack_.PrintForStackDump(Indent, output);
  313. param_and_arg_refs_stack_.PrintForStackDump(Indent, output);
  314. args_type_info_stack_.PrintForStackDump(Indent, output);
  315. }
  316. auto Context::DumpFormattedFile() const -> void {
  317. SemIR::Formatter formatter(sem_ir_);
  318. formatter.Print(llvm::errs());
  319. }
  320. } // namespace Carbon::Check