semantics_parse_tree_handler.h 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  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_PARSE_TREE_HANDLER_H_
  5. #define CARBON_TOOLCHAIN_SEMANTICS_SEMANTICS_PARSE_TREE_HANDLER_H_
  6. #include "llvm/ADT/DenseMap.h"
  7. #include "llvm/ADT/DenseSet.h"
  8. #include "llvm/ADT/SmallVector.h"
  9. #include "toolchain/parser/parse_tree.h"
  10. #include "toolchain/semantics/semantics_ir.h"
  11. #include "toolchain/semantics/semantics_node.h"
  12. #include "toolchain/semantics/semantics_node_block_stack.h"
  13. #include "toolchain/semantics/semantics_node_stack.h"
  14. namespace Carbon {
  15. // Handles processing of a ParseTree for semantics.
  16. class SemanticsParseTreeHandler {
  17. public:
  18. // Stores references for work.
  19. explicit SemanticsParseTreeHandler(
  20. const TokenizedBuffer& tokens,
  21. DiagnosticEmitter<ParseTree::Node>& emitter, const ParseTree& parse_tree,
  22. SemanticsIR& semantics, llvm::raw_ostream* vlog_stream)
  23. : tokens_(&tokens),
  24. emitter_(&emitter),
  25. parse_tree_(&parse_tree),
  26. semantics_(&semantics),
  27. vlog_stream_(vlog_stream),
  28. node_stack_(parse_tree, vlog_stream),
  29. node_block_stack_("node_block_stack_", semantics.node_blocks_,
  30. vlog_stream),
  31. params_or_args_stack_("params_or_args_stack_", semantics.node_blocks_,
  32. vlog_stream),
  33. args_type_info_stack_("args_type_info_stack_", semantics.node_blocks_,
  34. vlog_stream) {}
  35. // Outputs the ParseTree information into SemanticsIR.
  36. auto Build() -> void;
  37. private:
  38. // Prints the node_stack_ on stack dumps.
  39. class PrettyStackTraceNodeStack;
  40. // Prints the node_block_stack_ on stack dumps.
  41. class PrettyStackTraceNodeBlockStack;
  42. // For CanImplicitAs, the detected conversion to apply.
  43. enum ImplicitAsKind {
  44. // Incompatible types.
  45. Incompatible,
  46. // No conversion required.
  47. Identical,
  48. // ImplicitAs is required.
  49. Compatible,
  50. };
  51. // Provides DenseMapInfo for SemanticsStringId.
  52. struct SemanticsStringIdMapInfo {
  53. static inline auto getEmptyKey() -> SemanticsStringId {
  54. return SemanticsStringId(llvm::DenseMapInfo<int32_t>::getEmptyKey());
  55. }
  56. static inline auto getTombstoneKey() -> SemanticsStringId {
  57. return SemanticsStringId(llvm::DenseMapInfo<int32_t>::getTombstoneKey());
  58. }
  59. static auto getHashValue(const SemanticsStringId& val) -> unsigned {
  60. return llvm::DenseMapInfo<int32_t>::getHashValue(val.index);
  61. }
  62. static auto isEqual(const SemanticsStringId& lhs,
  63. const SemanticsStringId& rhs) -> bool {
  64. return lhs == rhs;
  65. }
  66. };
  67. // An entry in scope_stack_.
  68. struct ScopeStackEntry {
  69. // Names which are registered with name_lookup_, and will need to be
  70. // deregistered when the scope ends.
  71. llvm::DenseSet<SemanticsStringId, SemanticsStringIdMapInfo> names;
  72. // TODO: This likely needs to track things which need to be destructed.
  73. };
  74. // Adds a node to the current block, returning the produced ID.
  75. auto AddNode(SemanticsNode node) -> SemanticsNodeId;
  76. // Pushes a parse tree node onto the stack, storing the SemanticsNode as the
  77. // result.
  78. auto AddNodeAndPush(ParseTree::Node parse_node, SemanticsNode node) -> void;
  79. // Adds a name to name lookup.
  80. auto AddNameToLookup(ParseTree::Node name_node, SemanticsStringId name_id,
  81. SemanticsNodeId target_id) -> void;
  82. // Re-adds a name to name lookup. This is typically done through BindName, but
  83. // can also be used to restore removed names.
  84. auto ReaddNameToLookup(SemanticsStringId name_id, SemanticsNodeId storage_id)
  85. -> void {
  86. name_lookup_[name_id].push_back(storage_id);
  87. }
  88. // Binds a DeclaredName to a target node with the given type.
  89. auto BindName(ParseTree::Node name_node, SemanticsNodeId type_id,
  90. SemanticsNodeId target_id) -> SemanticsStringId;
  91. // Pushes a new scope onto scope_stack_.
  92. auto PushScope() -> void;
  93. // Pops the top scope from scope_stack_, cleaning up names from name_lookup_.
  94. auto PopScope() -> void;
  95. // Runs ImplicitAsImpl for a set of arguments and parameters.
  96. //
  97. // This will eventually need to support checking against multiple possible
  98. // overloads, multiple of which may be possible but not "best". While this can
  99. // currently be done by calling twice, toggling `apply_implicit_as`, in the
  100. // future we may want to remember the right implicit conversions to do for
  101. // valid cases in order to efficiently handle generics.
  102. auto ImplicitAsForArgs(
  103. SemanticsNodeBlockId arg_ir_id, SemanticsNodeBlockId arg_refs_id,
  104. ParseTree::Node param_parse_node, SemanticsNodeBlockId param_refs_id,
  105. DiagnosticEmitter<ParseTree::Node>::DiagnosticBuilder* diagnostic)
  106. -> bool;
  107. // Runs ImplicitAsImpl for a situation where a cast is required, returning the
  108. // updated `value_id`. Prints a diagnostic and returns an InvalidType if
  109. // unsupported.
  110. auto ImplicitAsRequired(ParseTree::Node parse_node, SemanticsNodeId value_id,
  111. SemanticsNodeId as_type_id) -> SemanticsNodeId;
  112. // Runs ImplicitAs behavior to convert `value` to `as_type`, returning the
  113. // result type. The result will be the node to use to replace `value`.
  114. //
  115. // If `output_value_id` is null, then this only checks if the conversion is
  116. // possible.
  117. //
  118. // If `output_value_id` is not null, then it will be set if there is a need to
  119. // cast.
  120. auto ImplicitAsImpl(SemanticsNodeId value_id, SemanticsNodeId as_type_id,
  121. SemanticsNodeId* output_value_id) -> ImplicitAsKind;
  122. // Returns true if the ImplicitAs can use struct conversion.
  123. // TODO: This currently only supports struct types that precisely match.
  124. auto CanImplicitAsStruct(SemanticsNode value_type, SemanticsNode as_type)
  125. -> bool;
  126. // Starts handling parameters or arguments.
  127. auto ParamOrArgStart() -> void;
  128. // On a comma, pushes the entry. On return, the top of node_stack_ will be
  129. // start_kind.
  130. auto ParamOrArgComma(bool for_args) -> void;
  131. // Detects whether there's an entry to push. On return, the top of
  132. // node_stack_ will be start_kind, and the caller should do type-specific
  133. // processing. Returns a pair of {ir_id, refs_id}.
  134. auto ParamOrArgEnd(bool for_args, ParseNodeKind start_kind)
  135. -> std::pair<SemanticsNodeBlockId, SemanticsNodeBlockId>;
  136. // Saves a parameter from the top block in node_stack_ to the top block in
  137. // params_or_args_stack_. If for_args, adds a StubReference of the previous
  138. // node's result to the IR.
  139. //
  140. // This should only be called by other ParamOrArg functions, not directly.
  141. auto ParamOrArgSave(bool for_args) -> void;
  142. // Parse node handlers. Returns false for unrecoverable errors.
  143. #define CARBON_PARSE_NODE_KIND(Name) \
  144. auto Handle##Name(ParseTree::Node parse_node)->bool;
  145. #include "toolchain/parser/parse_node_kind.def"
  146. auto current_scope() -> ScopeStackEntry& { return scope_stack_.back(); }
  147. // Tokens for getting data on literals.
  148. const TokenizedBuffer* tokens_;
  149. // Handles diagnostics.
  150. DiagnosticEmitter<ParseTree::Node>* emitter_;
  151. // The file's parse tree.
  152. const ParseTree* parse_tree_;
  153. // The SemanticsIR being added to.
  154. SemanticsIR* semantics_;
  155. // Whether to print verbose output.
  156. llvm::raw_ostream* vlog_stream_;
  157. // The stack during Build. Will contain file-level parse nodes on return.
  158. SemanticsNodeStack node_stack_;
  159. // The stack of node blocks being used for general IR generation.
  160. SemanticsNodeBlockStack node_block_stack_;
  161. // The stack of node blocks being used for per-element tracking of nodes in
  162. // parameter and argument node blocks. Versus node_block_stack_, an element
  163. // will have 1 or more nodes in blocks in node_block_stack_, but only ever 1
  164. // node in blocks here.
  165. SemanticsNodeBlockStack params_or_args_stack_;
  166. // The stack of node blocks being used for type information while processing
  167. // arguments. This is used in parallel with params_or_args_stack_. It's
  168. // currently only used for struct literals, where we need to track names
  169. // for a type separate from the literal arguments.
  170. SemanticsNodeBlockStack args_type_info_stack_;
  171. // Completed parameters that are held temporarily on a side-channel for a
  172. // function. This can't use node_stack_ because it has space for only one
  173. // value, whereas parameters return two values.
  174. llvm::SmallVector<std::pair<SemanticsNodeBlockId, SemanticsNodeBlockId>>
  175. finished_params_stack_;
  176. // A stack of return scopes; i.e., targets for `return`. Inside a function,
  177. // this will be a FunctionDeclaration.
  178. llvm::SmallVector<SemanticsNodeId> return_scope_stack_;
  179. // A stack for scope context.
  180. llvm::SmallVector<ScopeStackEntry> scope_stack_;
  181. // Maps identifiers to name lookup results. Values are a stack of name lookup
  182. // results in the ancestor scopes. This offers constant-time lookup of names,
  183. // regardless of how many scopes exist between the name declaration and
  184. // reference.
  185. //
  186. // Names which no longer have lookup results are erased.
  187. llvm::DenseMap<SemanticsStringId, llvm::SmallVector<SemanticsNodeId>,
  188. SemanticsStringIdMapInfo>
  189. name_lookup_;
  190. };
  191. } // namespace Carbon
  192. #endif // CARBON_TOOLCHAIN_SEMANTICS_SEMANTICS_PARSE_TREE_HANDLER_H_