context.h 17 KB

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