semantics_context.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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_ir.h"
  12. #include "toolchain/semantics/semantics_node.h"
  13. #include "toolchain/semantics/semantics_node_block_stack.h"
  14. #include "toolchain/semantics/semantics_node_stack.h"
  15. namespace Carbon {
  16. // Context and shared functionality for semantics handlers.
  17. class SemanticsContext {
  18. public:
  19. // Stores references for work.
  20. explicit SemanticsContext(const TokenizedBuffer& tokens,
  21. DiagnosticEmitter<ParseTree::Node>& emitter,
  22. const ParseTree& parse_tree, SemanticsIR& semantics,
  23. llvm::raw_ostream* vlog_stream);
  24. // Marks an implementation TODO. Always returns false.
  25. auto TODO(ParseTree::Node parse_node, std::string label) -> bool;
  26. // Runs verification that the processing cleanly finished.
  27. auto VerifyOnFinish() -> void;
  28. // Adds a node to the current block, returning the produced ID.
  29. auto AddNode(SemanticsNode node) -> SemanticsNodeId;
  30. // Adds a node to the given block, returning the produced ID.
  31. auto AddNodeToBlock(SemanticsNodeBlockId block, SemanticsNode node)
  32. -> SemanticsNodeId;
  33. // Pushes a parse tree node onto the stack, storing the SemanticsNode as the
  34. // result.
  35. auto AddNodeAndPush(ParseTree::Node parse_node, SemanticsNode node) -> void;
  36. // Adds a name to name lookup. Prints a diagnostic for name conflicts.
  37. auto AddNameToLookup(ParseTree::Node name_node, SemanticsStringId name_id,
  38. SemanticsNodeId target_id) -> void;
  39. // Lookup up a name, returning the referenced node.
  40. auto LookupName(ParseTree::Node parse_node, llvm::StringRef name)
  41. -> SemanticsNodeId;
  42. // Pushes a new scope onto scope_stack_.
  43. auto PushScope() -> void;
  44. // Pops the top scope from scope_stack_, cleaning up names from name_lookup_.
  45. auto PopScope() -> void;
  46. // Adds a `Branch` node branching to a new node block, and returns the ID of
  47. // the new block. All paths to the branch target must go through the current
  48. // block, though not necessarily through this branch.
  49. auto AddDominatedBlockAndBranch(ParseTree::Node parse_node)
  50. -> SemanticsNodeBlockId;
  51. // Adds a `Branch` node branching to a new node block with a value, and
  52. // returns the ID of the new block. All paths to the branch target must go
  53. // through the current block.
  54. auto AddDominatedBlockAndBranchWithArg(ParseTree::Node parse_node,
  55. SemanticsNodeId arg_id)
  56. -> SemanticsNodeBlockId;
  57. // Adds a `BranchIf` node branching to a new node block, and returns the ID
  58. // of the new block. All paths to the branch target must go through the
  59. // current block.
  60. auto AddDominatedBlockAndBranchIf(ParseTree::Node parse_node,
  61. SemanticsNodeId cond_id)
  62. -> SemanticsNodeBlockId;
  63. // Adds branches from the given list of blocks to a new block, for
  64. // reconvergence of control flow, and pushes the new block onto the node
  65. // block stack.
  66. auto AddConvergenceBlockAndPush(
  67. ParseTree::Node parse_tree,
  68. std::initializer_list<SemanticsNodeBlockId> blocks) -> void;
  69. // Adds branches from the given list of blocks and values to a new block, for
  70. // reconvergence of control flow with a result value, and pushes the new
  71. // block onto the node block stack. Returns a node referring to the result
  72. // value.
  73. auto AddConvergenceBlockWithArgAndPush(
  74. ParseTree::Node parse_node,
  75. std::initializer_list<std::pair<SemanticsNodeBlockId, SemanticsNodeId>>
  76. blocks_and_args) -> SemanticsNodeId;
  77. // Add the current code block to the enclosing function.
  78. auto AddCurrentCodeBlockToFunction() -> void;
  79. // Returns whether the current position in the current block is reachable.
  80. auto is_current_position_reachable() -> bool;
  81. // Runs ImplicitAsImpl for a set of arguments and parameters.
  82. //
  83. // This will eventually need to support checking against multiple possible
  84. // overloads, multiple of which may be possible but not "best". While this can
  85. // currently be done by calling twice, toggling `apply_implicit_as`, in the
  86. // future we may want to remember the right implicit conversions to do for
  87. // valid cases in order to efficiently handle generics.
  88. auto ImplicitAsForArgs(
  89. SemanticsNodeBlockId arg_refs_id, ParseTree::Node param_parse_node,
  90. SemanticsNodeBlockId param_refs_id,
  91. DiagnosticEmitter<ParseTree::Node>::DiagnosticBuilder* diagnostic)
  92. -> bool;
  93. // Runs ImplicitAsImpl for a situation where a cast is required, returning the
  94. // updated `value_id`. Prints a diagnostic and returns an InvalidType if
  95. // unsupported.
  96. auto ImplicitAsRequired(ParseTree::Node parse_node, SemanticsNodeId value_id,
  97. SemanticsTypeId as_type_id) -> SemanticsNodeId;
  98. // Runs ImplicitAsRequired for a conversion to `bool`.
  99. auto ImplicitAsBool(ParseTree::Node parse_node, SemanticsNodeId value_id)
  100. -> SemanticsNodeId;
  101. // Canonicalizes a type which is tracked as a single node.
  102. // TODO: This should eventually return a type ID.
  103. auto CanonicalizeType(SemanticsNodeId node_id) -> SemanticsTypeId;
  104. // Handles canonicalization of struct types. This may create a new struct type
  105. // when it has a new structure, or reference an existing struct type when it
  106. // duplicates a prior type.
  107. //
  108. // Individual struct type fields aren't canonicalized because they may have
  109. // name conflicts or other diagnostics during creation, which can use the
  110. // parse node.
  111. auto CanonicalizeStructType(ParseTree::Node parse_node,
  112. SemanticsNodeBlockId refs_id) -> SemanticsTypeId;
  113. // Converts an expression for use as a type.
  114. // TODO: This should eventually return a type ID.
  115. auto ExpressionAsType(ParseTree::Node parse_node, SemanticsNodeId value_id)
  116. -> SemanticsTypeId {
  117. return CanonicalizeType(
  118. ImplicitAsRequired(parse_node, value_id, SemanticsTypeId::TypeType));
  119. }
  120. // Starts handling parameters or arguments.
  121. auto ParamOrArgStart() -> void;
  122. // On a comma, pushes the entry. On return, the top of node_stack_ will be
  123. // start_kind.
  124. auto ParamOrArgComma(bool for_args) -> void;
  125. // Detects whether there's an entry to push. On return, the top of
  126. // node_stack_ will be start_kind, and the caller should do type-specific
  127. // processing. Returns refs_id.
  128. auto ParamOrArgEnd(bool for_args, ParseNodeKind start_kind)
  129. -> SemanticsNodeBlockId;
  130. // Saves a parameter from the top block in node_stack_ to the top block in
  131. // params_or_args_stack_. If for_args, adds a StubReference of the previous
  132. // node's result to the IR.
  133. //
  134. // This should only be called by other ParamOrArg functions, not directly.
  135. auto ParamOrArgSave(bool for_args) -> void;
  136. // Prints information for a stack dump.
  137. auto PrintForStackDump(llvm::raw_ostream& output) const -> void;
  138. auto tokens() -> const TokenizedBuffer& { return *tokens_; }
  139. auto emitter() -> DiagnosticEmitter<ParseTree::Node>& { return *emitter_; }
  140. auto parse_tree() -> const ParseTree& { return *parse_tree_; }
  141. auto semantics_ir() -> SemanticsIR& { return *semantics_ir_; }
  142. auto node_stack() -> SemanticsNodeStack& { return node_stack_; }
  143. auto node_block_stack() -> SemanticsNodeBlockStack& {
  144. return node_block_stack_;
  145. }
  146. auto args_type_info_stack() -> SemanticsNodeBlockStack& {
  147. return args_type_info_stack_;
  148. }
  149. auto return_scope_stack() -> llvm::SmallVector<SemanticsNodeId>& {
  150. return return_scope_stack_;
  151. }
  152. private:
  153. // For CanImplicitAs, the detected conversion to apply.
  154. enum ImplicitAsKind {
  155. // Incompatible types.
  156. Incompatible,
  157. // No conversion required.
  158. Identical,
  159. // ImplicitAs is required.
  160. Compatible,
  161. };
  162. // A FoldingSet node for a struct type.
  163. class StructTypeNode : public llvm::FastFoldingSetNode {
  164. public:
  165. explicit StructTypeNode(const llvm::FoldingSetNodeID& node_id,
  166. SemanticsTypeId type_id)
  167. : llvm::FastFoldingSetNode(node_id), type_id_(type_id) {}
  168. auto type_id() -> SemanticsTypeId { return type_id_; }
  169. private:
  170. SemanticsTypeId type_id_;
  171. };
  172. // An entry in scope_stack_.
  173. struct ScopeStackEntry {
  174. // Names which are registered with name_lookup_, and will need to be
  175. // deregistered when the scope ends.
  176. llvm::DenseSet<SemanticsStringId> names;
  177. // TODO: This likely needs to track things which need to be destructed.
  178. };
  179. // Runs ImplicitAs behavior to convert `value` to `as_type`, returning the
  180. // result type. The result will be the node to use to replace `value`.
  181. //
  182. // If `output_value_id` is null, then this only checks if the conversion is
  183. // possible.
  184. //
  185. // If `output_value_id` is not null, then it will be set if there is a need to
  186. // cast.
  187. auto ImplicitAsImpl(SemanticsNodeId value_id, SemanticsTypeId as_type_id,
  188. SemanticsNodeId* output_value_id) -> ImplicitAsKind;
  189. auto current_scope() -> ScopeStackEntry& { return scope_stack_.back(); }
  190. // Tokens for getting data on literals.
  191. const TokenizedBuffer* tokens_;
  192. // Handles diagnostics.
  193. DiagnosticEmitter<ParseTree::Node>* emitter_;
  194. // The file's parse tree.
  195. const ParseTree* parse_tree_;
  196. // The SemanticsIR being added to.
  197. SemanticsIR* semantics_ir_;
  198. // Whether to print verbose output.
  199. llvm::raw_ostream* vlog_stream_;
  200. // The stack during Build. Will contain file-level parse nodes on return.
  201. SemanticsNodeStack node_stack_;
  202. // The stack of node blocks being used for general IR generation.
  203. SemanticsNodeBlockStack node_block_stack_;
  204. // The stack of node blocks being used for per-element tracking of nodes in
  205. // parameter and argument node blocks. Versus node_block_stack_, an element
  206. // will have 1 or more nodes in blocks in node_block_stack_, but only ever 1
  207. // node in blocks here.
  208. SemanticsNodeBlockStack params_or_args_stack_;
  209. // The stack of node blocks being used for type information while processing
  210. // arguments. This is used in parallel with params_or_args_stack_. It's
  211. // currently only used for struct literals, where we need to track names
  212. // for a type separate from the literal arguments.
  213. SemanticsNodeBlockStack args_type_info_stack_;
  214. // A stack of return scopes; i.e., targets for `return`. Inside a function,
  215. // this will be a FunctionDeclaration.
  216. llvm::SmallVector<SemanticsNodeId> return_scope_stack_;
  217. // A stack for scope context.
  218. llvm::SmallVector<ScopeStackEntry> scope_stack_;
  219. // Maps identifiers to name lookup results. Values are a stack of name lookup
  220. // results in the ancestor scopes. This offers constant-time lookup of names,
  221. // regardless of how many scopes exist between the name declaration and
  222. // reference.
  223. //
  224. // Names which no longer have lookup results are erased.
  225. llvm::DenseMap<SemanticsStringId, llvm::SmallVector<SemanticsNodeId>>
  226. name_lookup_;
  227. // Tracks types which have been used, so that they aren't repeatedly added to
  228. // SemanticsIR.
  229. llvm::DenseMap<SemanticsNodeId, SemanticsTypeId> canonical_types_;
  230. // Tracks struct type literals which have been defined, so that they aren't
  231. // repeatedly redefined.
  232. llvm::FoldingSet<StructTypeNode> canonical_struct_types_;
  233. // Storage for the nodes in canonical_struct_types_. This stores in pointers
  234. // so that canonical_struct_types_ can have stable pointers.
  235. llvm::SmallVector<std::unique_ptr<StructTypeNode>>
  236. canonical_struct_types_nodes_;
  237. };
  238. // Parse node handlers. Returns false for unrecoverable errors.
  239. #define CARBON_PARSE_NODE_KIND(Name) \
  240. auto SemanticsHandle##Name(SemanticsContext& context, \
  241. ParseTree::Node parse_node) \
  242. ->bool;
  243. #include "toolchain/parser/parse_node_kind.def"
  244. } // namespace Carbon
  245. #endif // CARBON_TOOLCHAIN_SEMANTICS_SEMANTICS_CONTEXT_H_