semantics_parse_tree_handler.h 7.8 KB

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