context.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  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. #ifndef CARBON_TOOLCHAIN_CHECK_CONTEXT_H_
  5. #define CARBON_TOOLCHAIN_CHECK_CONTEXT_H_
  6. #include "llvm/ADT/DenseMap.h"
  7. #include "llvm/ADT/FoldingSet.h"
  8. #include "llvm/ADT/SmallVector.h"
  9. #include "toolchain/check/decl_name_stack.h"
  10. #include "toolchain/check/decl_state.h"
  11. #include "toolchain/check/diagnostic_helpers.h"
  12. #include "toolchain/check/inst_block_stack.h"
  13. #include "toolchain/check/node_stack.h"
  14. #include "toolchain/check/param_and_arg_refs_stack.h"
  15. #include "toolchain/check/scope_stack.h"
  16. #include "toolchain/parse/node_ids.h"
  17. #include "toolchain/parse/tree.h"
  18. #include "toolchain/sem_ir/file.h"
  19. #include "toolchain/sem_ir/ids.h"
  20. #include "toolchain/sem_ir/import_ir.h"
  21. #include "toolchain/sem_ir/inst.h"
  22. namespace Carbon::Check {
  23. // Context and shared functionality for semantics handlers.
  24. class Context {
  25. public:
  26. using DiagnosticEmitter = Carbon::DiagnosticEmitter<SemIRLoc>;
  27. using DiagnosticBuilder = DiagnosticEmitter::DiagnosticBuilder;
  28. // Stores references for work.
  29. explicit Context(const Lex::TokenizedBuffer& tokens,
  30. DiagnosticEmitter& emitter, const Parse::Tree& parse_tree,
  31. SemIR::File& sem_ir, llvm::raw_ostream* vlog_stream);
  32. // Marks an implementation TODO. Always returns false.
  33. auto TODO(SemIRLoc loc, std::string label) -> bool;
  34. // Runs verification that the processing cleanly finished.
  35. auto VerifyOnFinish() -> void;
  36. // Adds an instruction to the current block, returning the produced ID.
  37. auto AddInst(SemIR::LocIdAndInst loc_id_and_inst) -> SemIR::InstId;
  38. // Adds an instruction in no block, returning the produced ID. Should be used
  39. // rarely.
  40. auto AddInstInNoBlock(SemIR::LocIdAndInst loc_id_and_inst) -> SemIR::InstId;
  41. // Adds an instruction to the current block, returning the produced ID. The
  42. // instruction is a placeholder that is expected to be replaced by
  43. // `ReplaceInstBeforeConstantUse`.
  44. auto AddPlaceholderInst(SemIR::LocIdAndInst loc_id_and_inst) -> SemIR::InstId;
  45. // Adds an instruction in no block, returning the produced ID. Should be used
  46. // rarely. The instruction is a placeholder that is expected to be replaced by
  47. // `ReplaceInstBeforeConstantUse`.
  48. auto AddPlaceholderInstInNoBlock(SemIR::LocIdAndInst loc_id_and_inst)
  49. -> SemIR::InstId;
  50. // Adds an instruction to the constants block, returning the produced ID.
  51. auto AddConstant(SemIR::Inst inst, bool is_symbolic) -> SemIR::ConstantId;
  52. // Pushes a parse tree node onto the stack, storing the SemIR::Inst as the
  53. // result. Only valid if the LocId is for a NodeId.
  54. auto AddInstAndPush(SemIR::LocIdAndInst loc_id_and_inst) -> void;
  55. // Replaces the instruction `inst_id` with `loc_id_and_inst`. The instruction
  56. // is required to not have been used in any constant evaluation, either
  57. // because it's newly created and entirely unused, or because it's only used
  58. // in a position that constant evaluation ignores, such as a return slot.
  59. auto ReplaceLocIdAndInstBeforeConstantUse(SemIR::InstId inst_id,
  60. SemIR::LocIdAndInst loc_id_and_inst)
  61. -> void;
  62. // Replaces the instruction `inst_id` with `inst`, not affecting location.
  63. // The instruction is required to not have been used in any constant
  64. // evaluation, either because it's newly created and entirely unused, or
  65. // because it's only used in a position that constant evaluation ignores, such
  66. // as a return slot.
  67. auto ReplaceInstBeforeConstantUse(SemIR::InstId inst_id, SemIR::Inst inst)
  68. -> void;
  69. // Sets only the parse node of an instruction. This is only used when setting
  70. // the parse node of an imported namespace. Versus
  71. // ReplaceInstBeforeConstantUse, it is safe to use after the namespace is used
  72. // in constant evaluation. It's exposed this way mainly so that `insts()` can
  73. // remain const.
  74. auto SetNamespaceNodeId(SemIR::InstId inst_id, Parse::NodeId node_id)
  75. -> void {
  76. sem_ir().insts().SetLocId(inst_id, SemIR::LocId(node_id));
  77. }
  78. // Adds a name to name lookup. Prints a diagnostic for name conflicts.
  79. auto AddNameToLookup(SemIR::NameId name_id, SemIR::InstId target_id) -> void;
  80. // Performs name lookup in a specified scope for a name appearing in a
  81. // declaration, returning the referenced instruction. If scope_id is invalid,
  82. // uses the current contextual scope.
  83. auto LookupNameInDecl(SemIR::LocId loc_id, SemIR::NameId name_id,
  84. SemIR::NameScopeId scope_id) -> SemIR::InstId;
  85. // Performs an unqualified name lookup, returning the referenced instruction.
  86. auto LookupUnqualifiedName(Parse::NodeId node_id, SemIR::NameId name_id)
  87. -> SemIR::InstId;
  88. // Performs a name lookup in a specified scope, returning the referenced
  89. // instruction. Does not look into extended scopes. Returns an invalid
  90. // instruction if the name is not found.
  91. auto LookupNameInExactScope(SemIRLoc loc, SemIR::NameId name_id,
  92. SemIR::NameScopeId scope_id,
  93. const SemIR::NameScope& scope) -> SemIR::InstId;
  94. // Performs a qualified name lookup in a specified scope and in scopes that
  95. // it extends, returning the referenced instruction.
  96. auto LookupQualifiedName(Parse::NodeId node_id, SemIR::NameId name_id,
  97. SemIR::NameScopeId scope_id, bool required = true)
  98. -> SemIR::InstId;
  99. // Returns the instruction corresponding to a name in the core package, or
  100. // BuiltinError if not found.
  101. auto LookupNameInCore(SemIRLoc loc, llvm::StringRef name) -> SemIR::InstId;
  102. // Prints a diagnostic for a duplicate name.
  103. auto DiagnoseDuplicateName(SemIRLoc dup_def, SemIRLoc prev_def) -> void;
  104. // Prints a diagnostic for a missing name.
  105. auto DiagnoseNameNotFound(SemIRLoc loc, SemIR::NameId name_id) -> void;
  106. // Adds a note to a diagnostic explaining that a class is incomplete.
  107. auto NoteIncompleteClass(SemIR::ClassId class_id, DiagnosticBuilder& builder)
  108. -> void;
  109. // Adds a note to a diagnostic explaining that an interface is not defined.
  110. auto NoteUndefinedInterface(SemIR::InterfaceId interface_id,
  111. DiagnosticBuilder& builder) -> void;
  112. // Returns the current scope, if it is of the specified kind. Otherwise,
  113. // returns nullopt.
  114. template <typename InstT>
  115. auto GetCurrentScopeAs() -> std::optional<InstT> {
  116. return scope_stack().GetCurrentScopeAs<InstT>(sem_ir());
  117. }
  118. // Adds a `Branch` instruction branching to a new instruction block, and
  119. // returns the ID of the new block. All paths to the branch target must go
  120. // through the current block, though not necessarily through this branch.
  121. auto AddDominatedBlockAndBranch(Parse::NodeId node_id) -> SemIR::InstBlockId;
  122. // Adds a `Branch` instruction branching to a new instruction block with a
  123. // value, and returns the ID of the new block. All paths to the branch target
  124. // must go through the current block.
  125. auto AddDominatedBlockAndBranchWithArg(Parse::NodeId node_id,
  126. SemIR::InstId arg_id)
  127. -> SemIR::InstBlockId;
  128. // Adds a `BranchIf` instruction branching to a new instruction block, and
  129. // returns the ID of the new block. All paths to the branch target must go
  130. // through the current block.
  131. auto AddDominatedBlockAndBranchIf(Parse::NodeId node_id,
  132. SemIR::InstId cond_id)
  133. -> SemIR::InstBlockId;
  134. // Handles recovergence of control flow. Adds branches from the top
  135. // `num_blocks` on the instruction block stack to a new block, pops the
  136. // existing blocks, and pushes the new block onto the instruction block stack.
  137. auto AddConvergenceBlockAndPush(Parse::NodeId node_id, int num_blocks)
  138. -> void;
  139. // Handles recovergence of control flow with a result value. Adds branches
  140. // from the top few blocks on the instruction block stack to a new block, pops
  141. // the existing blocks, and pushes the new block onto the instruction block
  142. // stack. The number of blocks popped is the size of `block_args`, and the
  143. // corresponding result values are the elements of `block_args`. Returns an
  144. // instruction referring to the result value.
  145. auto AddConvergenceBlockWithArgAndPush(
  146. Parse::NodeId node_id, std::initializer_list<SemIR::InstId> block_args)
  147. -> SemIR::InstId;
  148. // Sets the constant value of a block argument created as the result of a
  149. // branch. `select_id` should be a `BlockArg` that selects between two
  150. // values. `cond_id` is the condition, `if_false` is the value to use if the
  151. // condition is false, and `if_true` is the value to use if the condition is
  152. // true. We don't track enough information in the `BlockArg` inst for
  153. // `TryEvalInst` to do this itself.
  154. auto SetBlockArgResultBeforeConstantUse(SemIR::InstId select_id,
  155. SemIR::InstId cond_id,
  156. SemIR::InstId if_true,
  157. SemIR::InstId if_false) -> void;
  158. // Add the current code block to the enclosing function.
  159. // TODO: The node_id is taken for expressions, which can occur in
  160. // non-function contexts. This should be refactored to support non-function
  161. // contexts, and node_id removed.
  162. auto AddCurrentCodeBlockToFunction(
  163. Parse::NodeId node_id = Parse::NodeId::Invalid) -> void;
  164. // Returns whether the current position in the current block is reachable.
  165. auto is_current_position_reachable() -> bool;
  166. // Returns the type ID for a constant of type `type`.
  167. auto GetTypeIdForTypeConstant(SemIR::ConstantId constant_id) -> SemIR::TypeId;
  168. // Returns the type ID for an instruction whose constant value is of type
  169. // `type`.
  170. auto GetTypeIdForTypeInst(SemIR::InstId inst_id) -> SemIR::TypeId {
  171. return GetTypeIdForTypeConstant(constant_values().Get(inst_id));
  172. }
  173. // Attempts to complete the type `type_id`. Returns `true` if the type is
  174. // complete, or `false` if it could not be completed. A complete type has
  175. // known object and value representations.
  176. //
  177. // If the type is not complete, `diagnoser` is invoked to diagnose the issue,
  178. // if a `diagnoser` is provided. The builder it returns will be annotated to
  179. // describe the reason why the type is not complete.
  180. auto TryToCompleteType(
  181. SemIR::TypeId type_id,
  182. std::optional<llvm::function_ref<auto()->DiagnosticBuilder>> diagnoser =
  183. std::nullopt) -> bool;
  184. // Returns the type `type_id` as a complete type, or produces an incomplete
  185. // type error and returns an error type. This is a convenience wrapper around
  186. // TryToCompleteType.
  187. auto AsCompleteType(SemIR::TypeId type_id,
  188. llvm::function_ref<auto()->DiagnosticBuilder> diagnoser)
  189. -> SemIR::TypeId {
  190. return TryToCompleteType(type_id, diagnoser) ? type_id
  191. : SemIR::TypeId::Error;
  192. }
  193. // TODO: Consider moving these `Get*Type` functions to a separate class.
  194. // Gets the type for the name of an associated entity.
  195. auto GetAssociatedEntityType(SemIR::InterfaceId interface_id,
  196. SemIR::TypeId entity_type_id) -> SemIR::TypeId;
  197. // Gets a builtin type. The returned type will be complete.
  198. auto GetBuiltinType(SemIR::BuiltinKind kind) -> SemIR::TypeId;
  199. // Gets a function type. The returned type will be complete.
  200. auto GetFunctionType(SemIR::FunctionId fn_id) -> SemIR::TypeId;
  201. // Gets a generic class type, which is the type of a name of a generic class,
  202. // such as the type of `Vector` given `class Vector(T:! type)`. The returned
  203. // type will be complete.
  204. auto GetGenericClassType(SemIR::ClassId class_id) -> SemIR::TypeId;
  205. // Returns a pointer type whose pointee type is `pointee_type_id`.
  206. auto GetPointerType(SemIR::TypeId pointee_type_id) -> SemIR::TypeId;
  207. // Returns a struct type with the given fields, which should be a block of
  208. // `StructTypeField`s.
  209. auto GetStructType(SemIR::InstBlockId refs_id) -> SemIR::TypeId;
  210. // Returns a tuple type with the given element types.
  211. auto GetTupleType(llvm::ArrayRef<SemIR::TypeId> type_ids) -> SemIR::TypeId;
  212. // Returns an unbound element type.
  213. auto GetUnboundElementType(SemIR::TypeId class_type_id,
  214. SemIR::TypeId element_type_id) -> SemIR::TypeId;
  215. // Removes any top-level `const` qualifiers from a type.
  216. auto GetUnqualifiedType(SemIR::TypeId type_id) -> SemIR::TypeId;
  217. // Adds an exported name.
  218. auto AddExport(SemIR::InstId inst_id) -> void { exports_.push_back(inst_id); }
  219. // Finalizes the list of exports on the IR.
  220. auto FinalizeExports() -> void {
  221. inst_blocks().Set(SemIR::InstBlockId::Exports, exports_);
  222. }
  223. // Finalizes the initialization function (__global_init).
  224. auto FinalizeGlobalInit() -> void;
  225. // Sets the total number of IRs which exist. This is used to prepare a map
  226. // from IR to imported IR.
  227. auto SetTotalIRCount(int num_irs) -> void {
  228. CARBON_CHECK(check_ir_map_.empty())
  229. << "SetTotalIRCount is only called once";
  230. check_ir_map_.resize(num_irs, SemIR::ImportIRId::Invalid);
  231. }
  232. // Returns the imported IR ID for an IR, or invalid if not imported.
  233. auto GetImportIRId(const SemIR::File& sem_ir) -> SemIR::ImportIRId& {
  234. return check_ir_map_[sem_ir.check_ir_id().index];
  235. }
  236. // Prints information for a stack dump.
  237. auto PrintForStackDump(llvm::raw_ostream& output) const -> void;
  238. // Get the Lex::TokenKind of a node for diagnostics.
  239. auto token_kind(Parse::NodeId node_id) -> Lex::TokenKind {
  240. return tokens().GetKind(parse_tree().node_token(node_id));
  241. }
  242. auto tokens() -> const Lex::TokenizedBuffer& { return *tokens_; }
  243. auto emitter() -> DiagnosticEmitter& { return *emitter_; }
  244. auto parse_tree() -> const Parse::Tree& { return *parse_tree_; }
  245. auto sem_ir() -> SemIR::File& { return *sem_ir_; }
  246. auto node_stack() -> NodeStack& { return node_stack_; }
  247. auto inst_block_stack() -> InstBlockStack& { return inst_block_stack_; }
  248. auto param_and_arg_refs_stack() -> ParamAndArgRefsStack& {
  249. return param_and_arg_refs_stack_;
  250. }
  251. auto args_type_info_stack() -> InstBlockStack& {
  252. return args_type_info_stack_;
  253. }
  254. auto decl_name_stack() -> DeclNameStack& { return decl_name_stack_; }
  255. auto decl_state_stack() -> DeclStateStack& { return decl_state_stack_; }
  256. auto scope_stack() -> ScopeStack& { return scope_stack_; }
  257. auto return_scope_stack() -> llvm::SmallVector<ScopeStack::ReturnScope>& {
  258. return scope_stack().return_scope_stack();
  259. }
  260. auto break_continue_stack()
  261. -> llvm::SmallVector<ScopeStack::BreakContinueScope>& {
  262. return scope_stack().break_continue_stack();
  263. }
  264. auto import_ir_constant_values()
  265. -> llvm::SmallVector<SemIR::ConstantValueStore, 0>& {
  266. return import_ir_constant_values_;
  267. }
  268. // Directly expose SemIR::File data accessors for brevity in calls.
  269. auto identifiers() -> StringStoreWrapper<IdentifierId>& {
  270. return sem_ir().identifiers();
  271. }
  272. auto ints() -> ValueStore<IntId>& { return sem_ir().ints(); }
  273. auto reals() -> ValueStore<RealId>& { return sem_ir().reals(); }
  274. auto floats() -> ValueStore<FloatId>& { return sem_ir().floats(); }
  275. auto string_literal_values() -> StringStoreWrapper<StringLiteralValueId>& {
  276. return sem_ir().string_literal_values();
  277. }
  278. auto bind_names() -> ValueStore<SemIR::BindNameId>& {
  279. return sem_ir().bind_names();
  280. }
  281. auto functions() -> ValueStore<SemIR::FunctionId>& {
  282. return sem_ir().functions();
  283. }
  284. auto classes() -> ValueStore<SemIR::ClassId>& { return sem_ir().classes(); }
  285. auto interfaces() -> ValueStore<SemIR::InterfaceId>& {
  286. return sem_ir().interfaces();
  287. }
  288. auto impls() -> SemIR::ImplStore& { return sem_ir().impls(); }
  289. auto import_irs() -> ValueStore<SemIR::ImportIRId>& {
  290. return sem_ir().import_irs();
  291. }
  292. auto import_ir_insts() -> ValueStore<SemIR::ImportIRInstId>& {
  293. return sem_ir().import_ir_insts();
  294. }
  295. auto names() -> SemIR::NameStoreWrapper { return sem_ir().names(); }
  296. auto name_scopes() -> SemIR::NameScopeStore& {
  297. return sem_ir().name_scopes();
  298. }
  299. auto types() -> SemIR::TypeStore& { return sem_ir().types(); }
  300. auto type_blocks() -> SemIR::BlockValueStore<SemIR::TypeBlockId>& {
  301. return sem_ir().type_blocks();
  302. }
  303. // Instructions should be added with `AddInst` or `AddInstInNoBlock`. This is
  304. // `const` to prevent accidental misuse.
  305. auto insts() -> const SemIR::InstStore& { return sem_ir().insts(); }
  306. auto constant_values() -> SemIR::ConstantValueStore& {
  307. return sem_ir().constant_values();
  308. }
  309. auto inst_blocks() -> SemIR::InstBlockStore& {
  310. return sem_ir().inst_blocks();
  311. }
  312. auto constants() -> SemIR::ConstantStore& { return sem_ir().constants(); }
  313. private:
  314. // A FoldingSet node for a type.
  315. class TypeNode : public llvm::FastFoldingSetNode {
  316. public:
  317. explicit TypeNode(const llvm::FoldingSetNodeID& node_id,
  318. SemIR::TypeId type_id)
  319. : llvm::FastFoldingSetNode(node_id), type_id_(type_id) {}
  320. auto type_id() -> SemIR::TypeId { return type_id_; }
  321. private:
  322. SemIR::TypeId type_id_;
  323. };
  324. // Tokens for getting data on literals.
  325. const Lex::TokenizedBuffer* tokens_;
  326. // Handles diagnostics.
  327. DiagnosticEmitter* emitter_;
  328. // The file's parse tree.
  329. const Parse::Tree* parse_tree_;
  330. // The SemIR::File being added to.
  331. SemIR::File* sem_ir_;
  332. // Whether to print verbose output.
  333. llvm::raw_ostream* vlog_stream_;
  334. // The stack during Build. Will contain file-level parse nodes on return.
  335. NodeStack node_stack_;
  336. // The stack of instruction blocks being used for general IR generation.
  337. InstBlockStack inst_block_stack_;
  338. // The stack of instruction blocks being used for param and arg ref blocks.
  339. ParamAndArgRefsStack param_and_arg_refs_stack_;
  340. // The stack of instruction blocks being used for type information while
  341. // processing arguments. This is used in parallel with
  342. // param_and_arg_refs_stack_. It's currently only used for struct literals,
  343. // where we need to track names for a type separate from the literal
  344. // arguments.
  345. InstBlockStack args_type_info_stack_;
  346. // The stack used for qualified declaration name construction.
  347. DeclNameStack decl_name_stack_;
  348. // The stack of declarations that could have modifiers.
  349. DeclStateStack decl_state_stack_;
  350. // The stack of scopes we are currently within.
  351. ScopeStack scope_stack_;
  352. // Cache of reverse mapping from type constants to types.
  353. //
  354. // TODO: Instead of mapping to a dense `TypeId` space, we could make `TypeId`
  355. // be a thin wrapper around `ConstantId` and only perform the lookup only when
  356. // we want to access the completeness and value representation of a type. It's
  357. // not clear whether that would result in more or fewer lookups.
  358. //
  359. // TODO: Should this be part of the `TypeStore`?
  360. llvm::DenseMap<SemIR::ConstantId, SemIR::TypeId> type_ids_for_type_constants_;
  361. // The list which will form NodeBlockId::Exports.
  362. llvm::SmallVector<SemIR::InstId> exports_;
  363. // Maps CheckIRId to ImportIRId.
  364. llvm::SmallVector<SemIR::ImportIRId> check_ir_map_;
  365. // Per-import constant values. These refer to the main IR and mainly serve as
  366. // a lookup table for quick access.
  367. //
  368. // Inline 0 elements because it's expected to require heap allocation.
  369. llvm::SmallVector<SemIR::ConstantValueStore, 0> import_ir_constant_values_;
  370. };
  371. } // namespace Carbon::Check
  372. #endif // CARBON_TOOLCHAIN_CHECK_CONTEXT_H_