semantics_parse_tree_handler.h 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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. // Provides DenseMapInfo for SemanticsStringId.
  43. struct SemanticsStringIdMapInfo {
  44. static inline auto getEmptyKey() -> SemanticsStringId {
  45. return SemanticsStringId(llvm::DenseMapInfo<int32_t>::getEmptyKey());
  46. }
  47. static inline auto getTombstoneKey() -> SemanticsStringId {
  48. return SemanticsStringId(llvm::DenseMapInfo<int32_t>::getTombstoneKey());
  49. }
  50. static auto getHashValue(const SemanticsStringId& val) -> unsigned {
  51. return llvm::DenseMapInfo<int32_t>::getHashValue(val.index);
  52. }
  53. static auto isEqual(const SemanticsStringId& lhs,
  54. const SemanticsStringId& rhs) -> bool {
  55. return lhs == rhs;
  56. }
  57. };
  58. // An entry in scope_stack_.
  59. struct ScopeStackEntry {
  60. // Names which are registered with name_lookup_, and will need to be
  61. // deregistered when the scope ends.
  62. llvm::DenseSet<SemanticsStringId, SemanticsStringIdMapInfo> names;
  63. // TODO: This likely needs to track things which need to be destructed.
  64. };
  65. // Adds a node to the current block, returning the produced ID.
  66. auto AddNode(SemanticsNode node) -> SemanticsNodeId;
  67. // Pushes a parse tree node onto the stack, storing the SemanticsNode as the
  68. // result.
  69. auto AddNodeAndPush(ParseTree::Node parse_node, SemanticsNode node) -> void;
  70. // Adds a name to name lookup.
  71. auto AddNameToLookup(ParseTree::Node name_node, SemanticsStringId name_id,
  72. SemanticsNodeId target_id) -> void;
  73. // Re-adds a name to name lookup. This is typically done through BindName, but
  74. // can also be used to restore removed names.
  75. auto ReaddNameToLookup(SemanticsStringId name_id, SemanticsNodeId storage_id)
  76. -> void {
  77. name_lookup_[name_id].push_back(storage_id);
  78. }
  79. // Binds a DeclaredName to a target node with the given type.
  80. auto BindName(ParseTree::Node name_node, SemanticsNodeId type_id,
  81. SemanticsNodeId target_id) -> SemanticsStringId;
  82. // Pushes a new scope onto scope_stack_.
  83. auto PushScope() -> void;
  84. // Pops the top scope from scope_stack_, cleaning up names from name_lookup_.
  85. auto PopScope() -> void;
  86. // Attempts a type conversion between two types. Returns:
  87. // - The result type if valid.
  88. // - BuiltinInvalidType if either lhs_id or rhs_id is BuiltinInvalidType.
  89. // - Invalid if no conversion is supported.
  90. //
  91. // The caller might choose to print a diagnostic if Invalid is returned,
  92. // whereas BuiltinInvalidType means there was a previous error that may be
  93. // related and another diagnostic is undesirable.
  94. auto CanTypeConvert(SemanticsNodeId from_type, SemanticsNodeId to_type)
  95. -> SemanticsNodeId;
  96. // Attempts a type conversion between two arguments, returning the result
  97. // type. The result type will be BuiltinInvalidType for errors; this handles
  98. // printing diagnostics.
  99. auto TryTypeConversion(ParseTree::Node parse_node, SemanticsNodeId lhs_id,
  100. SemanticsNodeId rhs_id, bool can_convert_lhs)
  101. -> SemanticsNodeId;
  102. // Attempts a type conversion between arguments and parameters. Returns true
  103. // on success. arg_parse_node and param_parse_node are only used for
  104. // diagnostic locations.
  105. auto TryTypeConversionOnArgs(ParseTree::Node arg_parse_node,
  106. SemanticsNodeBlockId arg_ir_id,
  107. SemanticsNodeBlockId arg_refs_id,
  108. ParseTree::Node param_parse_node,
  109. SemanticsNodeBlockId param_refs_id) -> bool;
  110. // Runs ImplicitAs behavior to convert `value` to `as_type`, returning the
  111. // result type. The result will be the node to use to replace `value`. The
  112. // result will be BuiltinInvalidType for errors; this handles printing
  113. // diagnostics.
  114. auto ImplicitAs(ParseTree::Node parse_node, SemanticsNodeId value,
  115. SemanticsNodeId as_type) -> SemanticsNodeId;
  116. // Returns true if the ImplicitAs can use struct conversion.
  117. // TODO: This currently only supports struct types that precisely match.
  118. auto CanImplicitAsStruct(SemanticsNode value_type, SemanticsNode as_type)
  119. -> bool;
  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 a pair of {ir_id, refs_id}.
  128. auto ParamOrArgEnd(bool for_args, ParseNodeKind start_kind)
  129. -> std::pair<SemanticsNodeBlockId, 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. // Parse node handlers. Returns false for unrecoverable errors.
  137. #define CARBON_PARSE_NODE_KIND(Name) \
  138. auto Handle##Name(ParseTree::Node parse_node)->bool;
  139. #include "toolchain/parser/parse_node_kind.def"
  140. auto current_scope() -> ScopeStackEntry& { return scope_stack_.back(); }
  141. // Tokens for getting data on literals.
  142. const TokenizedBuffer* tokens_;
  143. // Handles diagnostics.
  144. DiagnosticEmitter<ParseTree::Node>* emitter_;
  145. // The file's parse tree.
  146. const ParseTree* parse_tree_;
  147. // The SemanticsIR being added to.
  148. SemanticsIR* semantics_;
  149. // Whether to print verbose output.
  150. llvm::raw_ostream* vlog_stream_;
  151. // The stack during Build. Will contain file-level parse nodes on return.
  152. SemanticsNodeStack node_stack_;
  153. // The stack of node blocks being used for general IR generation.
  154. SemanticsNodeBlockStack node_block_stack_;
  155. // The stack of node blocks being used for per-element tracking of nodes in
  156. // parameter and argument node blocks. Versus node_block_stack_, an element
  157. // will have 1 or more nodes in blocks in node_block_stack_, but only ever 1
  158. // node in blocks here.
  159. SemanticsNodeBlockStack params_or_args_stack_;
  160. // The stack of node blocks being used for type information while processing
  161. // arguments. This is used in parallel with params_or_args_stack_. It's
  162. // currently only used for struct literals, where we need to track names
  163. // for a type separate from the literal arguments.
  164. SemanticsNodeBlockStack args_type_info_stack_;
  165. // Completed parameters that are held temporarily on a side-channel for a
  166. // function. This can't use node_stack_ because it has space for only one
  167. // value, whereas parameters return two values.
  168. llvm::SmallVector<std::pair<SemanticsNodeBlockId, SemanticsNodeBlockId>>
  169. finished_params_stack_;
  170. // A stack of return scopes; i.e., targets for `return`. Inside a function,
  171. // this will be a FunctionDeclaration.
  172. llvm::SmallVector<SemanticsNodeId> return_scope_stack_;
  173. // A stack for scope context.
  174. llvm::SmallVector<ScopeStackEntry> scope_stack_;
  175. // Maps identifiers to name lookup results. Values are a stack of name lookup
  176. // results in the ancestor scopes. This offers constant-time lookup of names,
  177. // regardless of how many scopes exist between the name declaration and
  178. // reference.
  179. //
  180. // Names which no longer have lookup results are erased.
  181. llvm::DenseMap<SemanticsStringId, llvm::SmallVector<SemanticsNodeId>,
  182. SemanticsStringIdMapInfo>
  183. name_lookup_;
  184. };
  185. } // namespace Carbon
  186. #endif // CARBON_TOOLCHAIN_SEMANTICS_SEMANTICS_PARSE_TREE_HANDLER_H_