semantics_context.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  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_SEMANTICS_SEMANTICS_CONTEXT_H_
  5. #define CARBON_TOOLCHAIN_SEMANTICS_SEMANTICS_CONTEXT_H_
  6. #include "llvm/ADT/DenseMap.h"
  7. #include "llvm/ADT/DenseSet.h"
  8. #include "llvm/ADT/FoldingSet.h"
  9. #include "llvm/ADT/SmallVector.h"
  10. #include "toolchain/parser/parse_tree.h"
  11. #include "toolchain/semantics/semantics_declaration_name_stack.h"
  12. #include "toolchain/semantics/semantics_ir.h"
  13. #include "toolchain/semantics/semantics_node.h"
  14. #include "toolchain/semantics/semantics_node_block_stack.h"
  15. #include "toolchain/semantics/semantics_node_stack.h"
  16. namespace Carbon::Check {
  17. // Context and shared functionality for semantics handlers.
  18. class Context {
  19. public:
  20. // Stores references for work.
  21. explicit Context(const TokenizedBuffer& tokens,
  22. DiagnosticEmitter<ParseTree::Node>& emitter,
  23. const ParseTree& parse_tree, SemIR::File& semantics,
  24. llvm::raw_ostream* vlog_stream);
  25. // Marks an implementation TODO. Always returns false.
  26. auto TODO(ParseTree::Node parse_node, std::string label) -> bool;
  27. // Runs verification that the processing cleanly finished.
  28. auto VerifyOnFinish() -> void;
  29. // Adds a node to the current block, returning the produced ID.
  30. auto AddNode(SemIR::Node node) -> SemIR::NodeId;
  31. // Adds a node to the given block, returning the produced ID.
  32. auto AddNodeToBlock(SemIR::NodeBlockId block, SemIR::Node node)
  33. -> SemIR::NodeId;
  34. // Pushes a parse tree node onto the stack, storing the SemIR::Node as the
  35. // result.
  36. auto AddNodeAndPush(ParseTree::Node parse_node, SemIR::Node node) -> void;
  37. // Adds a name to name lookup. Prints a diagnostic for name conflicts.
  38. auto AddNameToLookup(ParseTree::Node name_node, SemIR::StringId name_id,
  39. SemIR::NodeId target_id) -> void;
  40. // Performs name lookup in a specified scope, returning the referenced node.
  41. // If scope_id is invalid, uses the current contextual scope.
  42. auto LookupName(ParseTree::Node parse_node, SemIR::StringId name_id,
  43. SemIR::NameScopeId scope_id, bool print_diagnostics)
  44. -> SemIR::NodeId;
  45. // Prints a diagnostic for a duplicate name.
  46. auto DiagnoseDuplicateName(ParseTree::Node parse_node,
  47. SemIR::NodeId prev_def_id) -> void;
  48. // Prints a diagnostic for a missing name.
  49. auto DiagnoseNameNotFound(ParseTree::Node parse_node, SemIR::StringId name_id)
  50. -> void;
  51. // Pushes a new scope onto scope_stack_.
  52. auto PushScope() -> void;
  53. // Pops the top scope from scope_stack_, cleaning up names from name_lookup_.
  54. auto PopScope() -> void;
  55. // Adds a `Branch` node branching to a new node block, and returns the ID of
  56. // the new block. All paths to the branch target must go through the current
  57. // block, though not necessarily through this branch.
  58. auto AddDominatedBlockAndBranch(ParseTree::Node parse_node)
  59. -> SemIR::NodeBlockId;
  60. // Adds a `Branch` node branching to a new node block with a value, and
  61. // returns the ID of the new block. All paths to the branch target must go
  62. // through the current block.
  63. auto AddDominatedBlockAndBranchWithArg(ParseTree::Node parse_node,
  64. SemIR::NodeId arg_id)
  65. -> SemIR::NodeBlockId;
  66. // Adds a `BranchIf` node branching to a new node block, and returns the ID
  67. // of the new block. All paths to the branch target must go through the
  68. // current block.
  69. auto AddDominatedBlockAndBranchIf(ParseTree::Node parse_node,
  70. SemIR::NodeId cond_id)
  71. -> SemIR::NodeBlockId;
  72. // Adds branches from the given list of blocks to a new block, for
  73. // reconvergence of control flow, and pushes the new block onto the node
  74. // block stack.
  75. auto AddConvergenceBlockAndPush(
  76. ParseTree::Node parse_node,
  77. std::initializer_list<SemIR::NodeBlockId> blocks) -> void;
  78. // Adds branches from the given list of blocks and values to a new block, for
  79. // reconvergence of control flow with a result value, and pushes the new
  80. // block onto the node block stack. Returns a node referring to the result
  81. // value.
  82. auto AddConvergenceBlockWithArgAndPush(
  83. ParseTree::Node parse_node,
  84. std::initializer_list<std::pair<SemIR::NodeBlockId, SemIR::NodeId>>
  85. blocks_and_args) -> SemIR::NodeId;
  86. // Add the current code block to the enclosing function.
  87. auto AddCurrentCodeBlockToFunction() -> void;
  88. // Returns whether the current position in the current block is reachable.
  89. auto is_current_position_reachable() -> bool;
  90. // Converts the given expression to an ephemeral reference to a temporary if
  91. // it is an initializing expression.
  92. auto MaterializeIfInitializing(SemIR::NodeId expr_id) -> SemIR::NodeId {
  93. if (GetExpressionCategory(semantics_ir(), expr_id) ==
  94. SemIR::ExpressionCategory::Initializing) {
  95. return FinalizeTemporary(expr_id, /*discarded=*/false);
  96. }
  97. return expr_id;
  98. }
  99. // Convert the given expression to a value expression of the same type.
  100. auto ConvertToValueExpression(SemIR::NodeId expr_id) -> SemIR::NodeId;
  101. // Performs initialization of `target_id` from `value_id`.
  102. auto Initialize(ParseTree::Node parse_node, SemIR::NodeId target_id,
  103. SemIR::NodeId value_id) -> void;
  104. // Converts `value_id` to a value expression of type `type_id`.
  105. auto ConvertToValueOfType(ParseTree::Node parse_node, SemIR::NodeId value_id,
  106. SemIR::TypeId type_id) -> SemIR::NodeId {
  107. return ConvertToValueExpression(
  108. ImplicitAsRequired(parse_node, value_id, type_id));
  109. }
  110. // Converts `value_id` to a value expression of type `bool`.
  111. auto ConvertToBoolValue(ParseTree::Node parse_node, SemIR::NodeId value_id)
  112. -> SemIR::NodeId {
  113. return ConvertToValueOfType(
  114. parse_node, value_id, CanonicalizeType(SemIR::NodeId::BuiltinBoolType));
  115. }
  116. // Handles an expression whose result is discarded.
  117. auto HandleDiscardedExpression(SemIR::NodeId id) -> void;
  118. // Runs ImplicitAsImpl for a set of arguments and parameters.
  119. //
  120. // This will eventually need to support checking against multiple possible
  121. // overloads, multiple of which may be possible but not "best". While this can
  122. // currently be done by calling twice, toggling `apply_implicit_as`, in the
  123. // future we may want to remember the right implicit conversions to do for
  124. // valid cases in order to efficiently handle generics.
  125. auto ImplicitAsForArgs(
  126. SemIR::NodeBlockId arg_refs_id, ParseTree::Node param_parse_node,
  127. SemIR::NodeBlockId param_refs_id,
  128. DiagnosticEmitter<ParseTree::Node>::DiagnosticBuilder* diagnostic)
  129. -> bool;
  130. // Runs ImplicitAsImpl for a situation where a cast is required, returning the
  131. // updated `value_id`. Prints a diagnostic and returns an Error if
  132. // unsupported.
  133. auto ImplicitAsRequired(ParseTree::Node parse_node, SemIR::NodeId value_id,
  134. SemIR::TypeId as_type_id) -> SemIR::NodeId;
  135. // Canonicalizes a type which is tracked as a single node.
  136. // TODO: This should eventually return a type ID.
  137. auto CanonicalizeType(SemIR::NodeId node_id) -> SemIR::TypeId;
  138. // Handles canonicalization of struct types. This may create a new struct type
  139. // when it has a new structure, or reference an existing struct type when it
  140. // duplicates a prior type.
  141. //
  142. // Individual struct type fields aren't canonicalized because they may have
  143. // name conflicts or other diagnostics during creation, which can use the
  144. // parse node.
  145. auto CanonicalizeStructType(ParseTree::Node parse_node,
  146. SemIR::NodeBlockId refs_id) -> SemIR::TypeId;
  147. // Handles canonicalization of tuple types. This may create a new tuple type
  148. // if the `type_ids` doesn't match an existing tuple type.
  149. auto CanonicalizeTupleType(ParseTree::Node parse_node,
  150. llvm::SmallVector<SemIR::TypeId>&& type_ids)
  151. -> SemIR::TypeId;
  152. // Returns a pointer type whose pointee type is `pointee_type_id`.
  153. auto GetPointerType(ParseTree::Node parse_node, SemIR::TypeId pointee_type_id)
  154. -> SemIR::TypeId;
  155. // Converts an expression for use as a type.
  156. // TODO: This should eventually return a type ID.
  157. auto ExpressionAsType(ParseTree::Node parse_node, SemIR::NodeId value_id)
  158. -> SemIR::TypeId {
  159. auto node = semantics_ir_->GetNode(value_id);
  160. if (node.kind() == SemIR::NodeKind::StubReference) {
  161. value_id = node.GetAsStubReference();
  162. CARBON_CHECK(semantics_ir_->GetNode(value_id).kind() !=
  163. SemIR::NodeKind::StubReference)
  164. << "Stub reference should not point to another stub reference";
  165. }
  166. return CanonicalizeType(
  167. ConvertToValueOfType(parse_node, value_id, SemIR::TypeId::TypeType));
  168. }
  169. // Removes any top-level `const` qualifiers from a type.
  170. auto GetUnqualifiedType(SemIR::TypeId type_id) -> SemIR::TypeId;
  171. // Starts handling parameters or arguments.
  172. auto ParamOrArgStart() -> void;
  173. // On a comma, pushes the entry. On return, the top of node_stack_ will be
  174. // start_kind.
  175. auto ParamOrArgComma(bool for_args) -> void;
  176. // Detects whether there's an entry to push. On return, the top of
  177. // node_stack_ will be start_kind, and the caller should do type-specific
  178. // processing. Returns refs_id.
  179. auto ParamOrArgEnd(bool for_args, ParseNodeKind start_kind)
  180. -> SemIR::NodeBlockId;
  181. // Saves a parameter from the top block in node_stack_ to the top block in
  182. // params_or_args_stack_. If for_args, adds a StubReference of the previous
  183. // node's result to the IR.
  184. //
  185. // This should only be called by other ParamOrArg functions, not directly.
  186. auto ParamOrArgSave(bool for_args) -> void;
  187. // Prints information for a stack dump.
  188. auto PrintForStackDump(llvm::raw_ostream& output) const -> void;
  189. auto tokens() -> const TokenizedBuffer& { return *tokens_; }
  190. auto emitter() -> DiagnosticEmitter<ParseTree::Node>& { return *emitter_; }
  191. auto parse_tree() -> const ParseTree& { return *parse_tree_; }
  192. auto semantics_ir() -> SemIR::File& { return *semantics_ir_; }
  193. auto node_stack() -> NodeStack& { return node_stack_; }
  194. auto node_block_stack() -> NodeBlockStack& { return node_block_stack_; }
  195. auto args_type_info_stack() -> NodeBlockStack& {
  196. return args_type_info_stack_;
  197. }
  198. auto return_scope_stack() -> llvm::SmallVector<SemIR::NodeId>& {
  199. return return_scope_stack_;
  200. }
  201. auto declaration_name_stack() -> DeclarationNameStack& {
  202. return declaration_name_stack_;
  203. }
  204. private:
  205. // For CanImplicitAs, the detected conversion to apply.
  206. enum ImplicitAsKind : int8_t {
  207. // Incompatible types.
  208. Incompatible,
  209. // No conversion required.
  210. Identical,
  211. // ImplicitAs is required.
  212. Compatible,
  213. };
  214. // A FoldingSet node for a type.
  215. class TypeNode : public llvm::FastFoldingSetNode {
  216. public:
  217. explicit TypeNode(const llvm::FoldingSetNodeID& node_id,
  218. SemIR::TypeId type_id)
  219. : llvm::FastFoldingSetNode(node_id), type_id_(type_id) {}
  220. auto type_id() -> SemIR::TypeId { return type_id_; }
  221. private:
  222. SemIR::TypeId type_id_;
  223. };
  224. // An entry in scope_stack_.
  225. struct ScopeStackEntry {
  226. // Names which are registered with name_lookup_, and will need to be
  227. // deregistered when the scope ends.
  228. llvm::DenseSet<SemIR::StringId> names;
  229. // TODO: This likely needs to track things which need to be destructed.
  230. };
  231. // Commits to using a temporary to store the result of the initializing
  232. // expression described by `init_id`, and returns the location of the
  233. // temporary. If `discarded` is `true`, the result is discarded, and no
  234. // temporary will be created if possible; if no temporary is created, the
  235. // return value will be `SemIR::NodeId::Invalid`.
  236. auto FinalizeTemporary(SemIR::NodeId init_id, bool discarded)
  237. -> SemIR::NodeId;
  238. // Marks the initializer `init_id` as initializing `target_id`.
  239. auto MarkInitializerFor(SemIR::NodeId init_id, SemIR::NodeId target_id)
  240. -> void;
  241. // Runs ImplicitAs behavior to convert `value` to `as_type`, returning the
  242. // result type. The result will be the node to use to replace `value`.
  243. //
  244. // If `output_value_id` is null, then this only checks if the conversion is
  245. // possible.
  246. //
  247. // If `output_value_id` is not null, then it will be set if there is a need to
  248. // cast.
  249. auto ImplicitAsImpl(SemIR::NodeId value_id, SemIR::TypeId as_type_id,
  250. SemIR::NodeId* output_value_id) -> ImplicitAsKind;
  251. // Forms a canonical type ID for a type. This function is given two
  252. // callbacks:
  253. //
  254. // `profile_type(canonical_id)` is called to build a fingerprint for this
  255. // type. The ID should be distinct for all distinct type values with the same
  256. // `kind`.
  257. //
  258. // `make_node()` is called to obtain a `SemIR::NodeId` that describes the
  259. // type. It is only called if the type does not already exist, so can be used
  260. // to lazily build the `SemIR::Node`. `make_node()` is not permitted to
  261. // directly or indirectly canonicalize any types.
  262. auto CanonicalizeTypeImpl(
  263. SemIR::NodeKind kind,
  264. llvm::function_ref<void(llvm::FoldingSetNodeID& canonical_id)>
  265. profile_type,
  266. llvm::function_ref<SemIR::NodeId()> make_node) -> SemIR::TypeId;
  267. // Forms a canonical type ID for a type. If the type is new, adds the node to
  268. // the current block.
  269. auto CanonicalizeTypeAndAddNodeIfNew(SemIR::Node node) -> SemIR::TypeId;
  270. auto current_scope() -> ScopeStackEntry& { return scope_stack_.back(); }
  271. // Tokens for getting data on literals.
  272. const TokenizedBuffer* tokens_;
  273. // Handles diagnostics.
  274. DiagnosticEmitter<ParseTree::Node>* emitter_;
  275. // The file's parse tree.
  276. const ParseTree* parse_tree_;
  277. // The SemIR::File being added to.
  278. SemIR::File* semantics_ir_;
  279. // Whether to print verbose output.
  280. llvm::raw_ostream* vlog_stream_;
  281. // The stack during Build. Will contain file-level parse nodes on return.
  282. NodeStack node_stack_;
  283. // The stack of node blocks being used for general IR generation.
  284. NodeBlockStack node_block_stack_;
  285. // The stack of node blocks being used for per-element tracking of nodes in
  286. // parameter and argument node blocks. Versus node_block_stack_, an element
  287. // will have 1 or more nodes in blocks in node_block_stack_, but only ever 1
  288. // node in blocks here.
  289. NodeBlockStack params_or_args_stack_;
  290. // The stack of node blocks being used for type information while processing
  291. // arguments. This is used in parallel with params_or_args_stack_. It's
  292. // currently only used for struct literals, where we need to track names
  293. // for a type separate from the literal arguments.
  294. NodeBlockStack args_type_info_stack_;
  295. // A stack of return scopes; i.e., targets for `return`. Inside a function,
  296. // this will be a FunctionDeclaration.
  297. llvm::SmallVector<SemIR::NodeId> return_scope_stack_;
  298. // A stack for scope context.
  299. llvm::SmallVector<ScopeStackEntry> scope_stack_;
  300. // The stack used for qualified declaration name construction.
  301. DeclarationNameStack declaration_name_stack_;
  302. // Maps identifiers to name lookup results. Values are a stack of name lookup
  303. // results in the ancestor scopes. This offers constant-time lookup of names,
  304. // regardless of how many scopes exist between the name declaration and
  305. // reference.
  306. //
  307. // Names which no longer have lookup results are erased.
  308. llvm::DenseMap<SemIR::StringId, llvm::SmallVector<SemIR::NodeId>>
  309. name_lookup_;
  310. // Cache of the mapping from nodes to types, to avoid recomputing the folding
  311. // set ID.
  312. llvm::DenseMap<SemIR::NodeId, SemIR::TypeId> canonical_types_;
  313. // Tracks the canonical representation of types that have been defined.
  314. llvm::FoldingSet<TypeNode> canonical_type_nodes_;
  315. // Storage for the nodes in canonical_type_nodes_. This stores in pointers so
  316. // that FoldingSet can have stable pointers.
  317. llvm::SmallVector<std::unique_ptr<TypeNode>> type_node_storage_;
  318. };
  319. // Parse node handlers. Returns false for unrecoverable errors.
  320. #define CARBON_PARSE_NODE_KIND(Name) \
  321. auto Handle##Name(Context& context, ParseTree::Node parse_node)->bool;
  322. #include "toolchain/parser/parse_node_kind.def"
  323. } // namespace Carbon::Check
  324. #endif // CARBON_TOOLCHAIN_SEMANTICS_SEMANTICS_CONTEXT_H_