semantics_context.h 9.9 KB

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