semantics_parse_tree_handler.h 7.6 KB

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