context.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  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/inst_block_stack.h"
  12. #include "toolchain/check/node_stack.h"
  13. #include "toolchain/check/scope_stack.h"
  14. #include "toolchain/parse/node_ids.h"
  15. #include "toolchain/parse/tree.h"
  16. #include "toolchain/parse/tree_node_location_translator.h"
  17. #include "toolchain/sem_ir/file.h"
  18. #include "toolchain/sem_ir/ids.h"
  19. #include "toolchain/sem_ir/inst.h"
  20. namespace Carbon::Check {
  21. // Diagnostic locations produced by checking may be either a parse node
  22. // directly, or an inst ID which is later translated to a parse node.
  23. struct SemIRLocation {
  24. // NOLINTNEXTLINE(google-explicit-constructor)
  25. SemIRLocation(SemIR::InstId inst_id) : inst_id(inst_id), is_inst_id(true) {}
  26. // NOLINTNEXTLINE(google-explicit-constructor)
  27. SemIRLocation(Parse::NodeLocation node_location)
  28. : node_location(node_location), is_inst_id(false) {}
  29. // NOLINTNEXTLINE(google-explicit-constructor)
  30. SemIRLocation(Parse::NodeId node_id)
  31. : SemIRLocation(Parse::NodeLocation(node_id)) {}
  32. union {
  33. SemIR::InstId inst_id;
  34. Parse::NodeLocation node_location;
  35. };
  36. bool is_inst_id;
  37. };
  38. // Context and shared functionality for semantics handlers.
  39. class Context {
  40. public:
  41. using DiagnosticEmitter = Carbon::DiagnosticEmitter<SemIRLocation>;
  42. using DiagnosticBuilder = DiagnosticEmitter::DiagnosticBuilder;
  43. // Stores references for work.
  44. explicit Context(const Lex::TokenizedBuffer& tokens,
  45. DiagnosticEmitter& emitter, const Parse::Tree& parse_tree,
  46. SemIR::File& sem_ir, llvm::raw_ostream* vlog_stream);
  47. // Marks an implementation TODO. Always returns false.
  48. auto TODO(Parse::NodeId parse_node, std::string label) -> bool;
  49. // Runs verification that the processing cleanly finished.
  50. auto VerifyOnFinish() -> void;
  51. // Adds an instruction to the current block, returning the produced ID.
  52. auto AddInst(SemIR::ParseNodeAndInst parse_node_and_inst) -> SemIR::InstId;
  53. // Adds an instruction in no block, returning the produced ID. Should be used
  54. // rarely.
  55. auto AddInstInNoBlock(SemIR::ParseNodeAndInst parse_node_and_inst)
  56. -> SemIR::InstId;
  57. // Adds an instruction to the current block, returning the produced ID. The
  58. // instruction is a placeholder that is expected to be replaced by
  59. // `ReplaceInstBeforeConstantUse`.
  60. auto AddPlaceholderInst(SemIR::ParseNodeAndInst parse_node_and_inst)
  61. -> SemIR::InstId;
  62. // Adds an instruction in no block, returning the produced ID. Should be used
  63. // rarely. The instruction is a placeholder that is expected to be replaced by
  64. // `ReplaceInstBeforeConstantUse`.
  65. auto AddPlaceholderInstInNoBlock(SemIR::ParseNodeAndInst parse_node_and_inst)
  66. -> SemIR::InstId;
  67. // Adds an instruction to the constants block, returning the produced ID.
  68. auto AddConstant(SemIR::Inst inst, bool is_symbolic) -> SemIR::ConstantId;
  69. // Pushes a parse tree node onto the stack, storing the SemIR::Inst as the
  70. // result.
  71. auto AddInstAndPush(SemIR::ParseNodeAndInst parse_node_and_inst) -> void;
  72. // Replaces the value of the instruction `inst_id` with `parse_node_and_inst`.
  73. // The instruction is required to not have been used in any constant
  74. // evaluation, either because it's newly created and entirely unused, or
  75. // because it's only used in a position that constant evaluation ignores, such
  76. // as a return slot.
  77. auto ReplaceInstBeforeConstantUse(SemIR::InstId inst_id,
  78. SemIR::ParseNodeAndInst parse_node_and_inst)
  79. -> void;
  80. // Sets only the parse node of an instruction. This is only used when setting
  81. // the parse node of an imported namespace. Versus
  82. // ReplaceInstBeforeConstantUse, it is safe to use after the namespace is used
  83. // in constant evaluation. It's exposed this way mainly so that `insts()` can
  84. // remain const.
  85. auto SetNamespaceParseNode(SemIR::InstId inst_id, Parse::NodeId parse_node)
  86. -> void {
  87. sem_ir().insts().SetParseNode(inst_id, parse_node);
  88. }
  89. // Adds a package's imports to name lookup, with all libraries together.
  90. // sem_irs will all be non-null; has_load_error must be used for any errors.
  91. auto AddPackageImports(Parse::NodeId import_node, IdentifierId package_id,
  92. llvm::ArrayRef<const SemIR::File*> sem_irs,
  93. bool has_load_error) -> void;
  94. // Adds a name to name lookup. Prints a diagnostic for name conflicts.
  95. auto AddNameToLookup(SemIR::NameId name_id, SemIR::InstId target_id) -> void;
  96. // Performs name lookup in a specified scope for a name appearing in a
  97. // declaration, returning the referenced instruction. If scope_id is invalid,
  98. // uses the current contextual scope.
  99. auto LookupNameInDecl(Parse::NodeId parse_node, SemIR::NameId name_id,
  100. SemIR::NameScopeId scope_id) -> SemIR::InstId;
  101. // Performs an unqualified name lookup, returning the referenced instruction.
  102. auto LookupUnqualifiedName(Parse::NodeId parse_node, SemIR::NameId name_id)
  103. -> SemIR::InstId;
  104. // Performs a name lookup in a specified scope, returning the referenced
  105. // instruction. Does not look into extended scopes. Returns an invalid
  106. // instruction if the name is not found.
  107. auto LookupNameInExactScope(SemIR::NameId name_id,
  108. const SemIR::NameScope& scope) -> SemIR::InstId;
  109. // Performs a qualified name lookup in a specified scope and in scopes that
  110. // it extends, returning the referenced instruction.
  111. auto LookupQualifiedName(Parse::NodeId parse_node, SemIR::NameId name_id,
  112. SemIR::NameScopeId scope_id, bool required = true)
  113. -> SemIR::InstId;
  114. // Prints a diagnostic for a duplicate name.
  115. auto DiagnoseDuplicateName(SemIR::InstId dup_def_id,
  116. SemIR::InstId prev_def_id) -> void;
  117. // Prints a diagnostic for a missing name.
  118. auto DiagnoseNameNotFound(Parse::NodeId parse_node, SemIR::NameId name_id)
  119. -> void;
  120. // Adds a note to a diagnostic explaining that a class is incomplete.
  121. auto NoteIncompleteClass(SemIR::ClassId class_id, DiagnosticBuilder& builder)
  122. -> void;
  123. // Adds a note to a diagnostic explaining that an interface is not defined.
  124. auto NoteUndefinedInterface(SemIR::InterfaceId interface_id,
  125. DiagnosticBuilder& builder) -> void;
  126. // Returns the current scope, if it is of the specified kind. Otherwise,
  127. // returns nullopt.
  128. template <typename InstT>
  129. auto GetCurrentScopeAs() -> std::optional<InstT> {
  130. return scope_stack().GetCurrentScopeAs<InstT>(sem_ir());
  131. }
  132. // Adds a `Branch` instruction branching to a new instruction block, and
  133. // returns the ID of the new block. All paths to the branch target must go
  134. // through the current block, though not necessarily through this branch.
  135. auto AddDominatedBlockAndBranch(Parse::NodeId parse_node)
  136. -> SemIR::InstBlockId;
  137. // Adds a `Branch` instruction branching to a new instruction block with a
  138. // value, and returns the ID of the new block. All paths to the branch target
  139. // must go through the current block.
  140. auto AddDominatedBlockAndBranchWithArg(Parse::NodeId parse_node,
  141. SemIR::InstId arg_id)
  142. -> SemIR::InstBlockId;
  143. // Adds a `BranchIf` instruction branching to a new instruction block, and
  144. // returns the ID of the new block. All paths to the branch target must go
  145. // through the current block.
  146. auto AddDominatedBlockAndBranchIf(Parse::NodeId parse_node,
  147. SemIR::InstId cond_id)
  148. -> SemIR::InstBlockId;
  149. // Handles recovergence of control flow. Adds branches from the top
  150. // `num_blocks` on the instruction block stack to a new block, pops the
  151. // existing blocks, and pushes the new block onto the instruction block stack.
  152. auto AddConvergenceBlockAndPush(Parse::NodeId parse_node, int num_blocks)
  153. -> void;
  154. // Handles recovergence of control flow with a result value. Adds branches
  155. // from the top few blocks on the instruction block stack to a new block, pops
  156. // the existing blocks, and pushes the new block onto the instruction block
  157. // stack. The number of blocks popped is the size of `block_args`, and the
  158. // corresponding result values are the elements of `block_args`. Returns an
  159. // instruction referring to the result value.
  160. auto AddConvergenceBlockWithArgAndPush(
  161. Parse::NodeId parse_node, std::initializer_list<SemIR::InstId> block_args)
  162. -> SemIR::InstId;
  163. // Add the current code block to the enclosing function.
  164. // TODO: The parse_node is taken for expressions, which can occur in
  165. // non-function contexts. This should be refactored to support non-function
  166. // contexts, and parse_node removed.
  167. auto AddCurrentCodeBlockToFunction(
  168. Parse::NodeId parse_node = Parse::NodeId::Invalid) -> void;
  169. // Returns whether the current position in the current block is reachable.
  170. auto is_current_position_reachable() -> bool;
  171. // Returns the type ID for a constant of type `type`.
  172. auto GetTypeIdForTypeConstant(SemIR::ConstantId constant_id) -> SemIR::TypeId;
  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 a builtin type. The returned type will be complete.
  195. auto GetBuiltinType(SemIR::BuiltinKind kind) -> SemIR::TypeId;
  196. // Returns a pointer type whose pointee type is `pointee_type_id`.
  197. auto GetPointerType(SemIR::TypeId pointee_type_id) -> SemIR::TypeId;
  198. // Returns a struct type with the given fields, which should be a block of
  199. // `StructTypeField`s.
  200. auto GetStructType(SemIR::InstBlockId refs_id) -> SemIR::TypeId;
  201. // Returns a tuple type with the given element types.
  202. auto GetTupleType(llvm::ArrayRef<SemIR::TypeId> type_ids) -> SemIR::TypeId;
  203. // Returns an unbound element type.
  204. auto GetUnboundElementType(SemIR::TypeId class_type_id,
  205. SemIR::TypeId element_type_id) -> SemIR::TypeId;
  206. // Removes any top-level `const` qualifiers from a type.
  207. auto GetUnqualifiedType(SemIR::TypeId type_id) -> SemIR::TypeId;
  208. // Starts handling parameters or arguments.
  209. auto ParamOrArgStart() -> void;
  210. // On a comma, pushes the entry. On return, the top of node_stack_ will be
  211. // start_kind.
  212. auto ParamOrArgComma() -> void;
  213. // Detects whether there's an entry to push from the end of a parameter or
  214. // argument list, and if so, moves it to the current parameter or argument
  215. // list. Does not pop the list. `start_kind` is the node kind at the start
  216. // of the parameter or argument list, and will be at the top of the parse node
  217. // stack when this function returns.
  218. auto ParamOrArgEndNoPop(Parse::NodeKind start_kind) -> void;
  219. // Pops the current parameter or argument list. Should only be called after
  220. // `ParamOrArgEndNoPop`.
  221. auto ParamOrArgPop() -> SemIR::InstBlockId;
  222. // Detects whether there's an entry to push. Pops and returns the argument
  223. // list. This is the same as `ParamOrArgEndNoPop` followed by `ParamOrArgPop`.
  224. auto ParamOrArgEnd(Parse::NodeKind start_kind) -> SemIR::InstBlockId;
  225. // Saves a parameter from the top block in node_stack_ to the top block in
  226. // params_or_args_stack_.
  227. auto ParamOrArgSave(SemIR::InstId inst_id) -> void {
  228. params_or_args_stack_.AddInstId(inst_id);
  229. }
  230. // Adds an exported name.
  231. auto AddExport(SemIR::InstId inst_id) -> void { exports_.push_back(inst_id); }
  232. // Finalizes the list of exports on the IR.
  233. auto FinalizeExports() -> void {
  234. inst_blocks().Set(SemIR::InstBlockId::Exports, exports_);
  235. }
  236. // Finalizes the initialization function (__global_init).
  237. auto FinalizeGlobalInit() -> void;
  238. // Prints information for a stack dump.
  239. auto PrintForStackDump(llvm::raw_ostream& output) const -> void;
  240. // Get the Lex::TokenKind of a node for diagnostics.
  241. auto token_kind(Parse::NodeId parse_node) -> Lex::TokenKind {
  242. return tokens().GetKind(parse_tree().node_token(parse_node));
  243. }
  244. auto tokens() -> const Lex::TokenizedBuffer& { return *tokens_; }
  245. auto emitter() -> DiagnosticEmitter& { return *emitter_; }
  246. auto parse_tree() -> const Parse::Tree& { return *parse_tree_; }
  247. auto sem_ir() -> SemIR::File& { return *sem_ir_; }
  248. auto node_stack() -> NodeStack& { return node_stack_; }
  249. auto inst_block_stack() -> InstBlockStack& { return inst_block_stack_; }
  250. auto params_or_args_stack() -> InstBlockStack& {
  251. return params_or_args_stack_;
  252. }
  253. auto args_type_info_stack() -> InstBlockStack& {
  254. return args_type_info_stack_;
  255. }
  256. auto decl_name_stack() -> DeclNameStack& { return decl_name_stack_; }
  257. auto decl_state_stack() -> DeclStateStack& { return decl_state_stack_; }
  258. auto scope_stack() -> ScopeStack& { return scope_stack_; }
  259. auto return_scope_stack() -> llvm::SmallVector<ScopeStack::ReturnScope>& {
  260. return scope_stack().return_scope_stack();
  261. }
  262. auto break_continue_stack()
  263. -> llvm::SmallVector<ScopeStack::BreakContinueScope>& {
  264. return scope_stack().break_continue_stack();
  265. }
  266. auto import_ir_constant_values()
  267. -> llvm::SmallVector<SemIR::ConstantValueStore, 0>& {
  268. return import_ir_constant_values_;
  269. }
  270. // Directly expose SemIR::File data accessors for brevity in calls.
  271. auto identifiers() -> StringStoreWrapper<IdentifierId>& {
  272. return sem_ir().identifiers();
  273. }
  274. auto ints() -> ValueStore<IntId>& { return sem_ir().ints(); }
  275. auto reals() -> ValueStore<RealId>& { return sem_ir().reals(); }
  276. auto string_literal_values() -> StringStoreWrapper<StringLiteralValueId>& {
  277. return sem_ir().string_literal_values();
  278. }
  279. auto bind_names() -> ValueStore<SemIR::BindNameId>& {
  280. return sem_ir().bind_names();
  281. }
  282. auto functions() -> ValueStore<SemIR::FunctionId>& {
  283. return sem_ir().functions();
  284. }
  285. auto classes() -> ValueStore<SemIR::ClassId>& { return sem_ir().classes(); }
  286. auto interfaces() -> ValueStore<SemIR::InterfaceId>& {
  287. return sem_ir().interfaces();
  288. }
  289. auto impls() -> SemIR::ImplStore& { return sem_ir().impls(); }
  290. auto import_irs() -> ValueStore<SemIR::ImportIRId>& {
  291. return sem_ir().import_irs();
  292. }
  293. auto names() -> SemIR::NameStoreWrapper { return sem_ir().names(); }
  294. auto name_scopes() -> SemIR::NameScopeStore& {
  295. return sem_ir().name_scopes();
  296. }
  297. auto types() -> SemIR::TypeStore& { return sem_ir().types(); }
  298. auto type_blocks() -> SemIR::BlockValueStore<SemIR::TypeBlockId>& {
  299. return sem_ir().type_blocks();
  300. }
  301. // Instructions should be added with `AddInst` or `AddInstInNoBlock`. This is
  302. // `const` to prevent accidental misuse.
  303. auto insts() -> const SemIR::InstStore& { return sem_ir().insts(); }
  304. auto constant_values() -> SemIR::ConstantValueStore& {
  305. return sem_ir().constant_values();
  306. }
  307. auto inst_blocks() -> SemIR::InstBlockStore& {
  308. return sem_ir().inst_blocks();
  309. }
  310. auto constants() -> SemIR::ConstantStore& { return sem_ir().constants(); }
  311. private:
  312. // A FoldingSet node for a type.
  313. class TypeNode : public llvm::FastFoldingSetNode {
  314. public:
  315. explicit TypeNode(const llvm::FoldingSetNodeID& node_id,
  316. SemIR::TypeId type_id)
  317. : llvm::FastFoldingSetNode(node_id), type_id_(type_id) {}
  318. auto type_id() -> SemIR::TypeId { return type_id_; }
  319. private:
  320. SemIR::TypeId type_id_;
  321. };
  322. // Tokens for getting data on literals.
  323. const Lex::TokenizedBuffer* tokens_;
  324. // Handles diagnostics.
  325. DiagnosticEmitter* emitter_;
  326. // The file's parse tree.
  327. const Parse::Tree* parse_tree_;
  328. // The SemIR::File being added to.
  329. SemIR::File* sem_ir_;
  330. // Whether to print verbose output.
  331. llvm::raw_ostream* vlog_stream_;
  332. // The stack during Build. Will contain file-level parse nodes on return.
  333. NodeStack node_stack_;
  334. // The stack of instruction blocks being used for general IR generation.
  335. InstBlockStack inst_block_stack_;
  336. // The stack of instruction blocks being used for per-element tracking of
  337. // instructions in parameter and argument instruction blocks. Versus
  338. // inst_block_stack_, an element will have 1 or more instructions in blocks in
  339. // inst_block_stack_, but only ever 1 instruction in blocks here.
  340. InstBlockStack params_or_args_stack_;
  341. // The stack of instruction blocks being used for type information while
  342. // processing arguments. This is used in parallel with params_or_args_stack_.
  343. // It's currently only used for struct literals, where we need to track names
  344. // for a type separate from the literal 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. // Per-import constant values. These refer to the main IR and mainly serve as
  364. // a lookup table for quick access.
  365. //
  366. // Inline 0 elements because it's expected to require heap allocation.
  367. llvm::SmallVector<SemIR::ConstantValueStore, 0> import_ir_constant_values_;
  368. };
  369. } // namespace Carbon::Check
  370. #endif // CARBON_TOOLCHAIN_CHECK_CONTEXT_H_