context.h 17 KB

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