semantics_context.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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_declaration_name_stack.h"
  12. #include "toolchain/semantics/semantics_ir.h"
  13. #include "toolchain/semantics/semantics_node.h"
  14. #include "toolchain/semantics/semantics_node_block_stack.h"
  15. #include "toolchain/semantics/semantics_node_stack.h"
  16. namespace Carbon {
  17. // Context and shared functionality for semantics handlers.
  18. class SemanticsContext {
  19. public:
  20. // Stores references for work.
  21. explicit SemanticsContext(const TokenizedBuffer& tokens,
  22. DiagnosticEmitter<ParseTree::Node>& emitter,
  23. const ParseTree& parse_tree, SemanticsIR& semantics,
  24. llvm::raw_ostream* vlog_stream);
  25. // Marks an implementation TODO. Always returns false.
  26. auto TODO(ParseTree::Node parse_node, std::string label) -> bool;
  27. // Runs verification that the processing cleanly finished.
  28. auto VerifyOnFinish() -> void;
  29. // Adds a node to the current block, returning the produced ID.
  30. auto AddNode(SemanticsNode node) -> SemanticsNodeId;
  31. // Adds a node to the given block, returning the produced ID.
  32. auto AddNodeToBlock(SemanticsNodeBlockId block, SemanticsNode node)
  33. -> SemanticsNodeId;
  34. // Pushes a parse tree node onto the stack, storing the SemanticsNode as the
  35. // result.
  36. auto AddNodeAndPush(ParseTree::Node parse_node, SemanticsNode node) -> void;
  37. // Adds a name to name lookup. Prints a diagnostic for name conflicts.
  38. auto AddNameToLookup(ParseTree::Node name_node, SemanticsStringId name_id,
  39. SemanticsNodeId target_id) -> void;
  40. // Performs name lookup in a specified scope, returning the referenced node.
  41. // If scope_id is invalid, uses the current contextual scope.
  42. auto LookupName(ParseTree::Node parse_node, SemanticsStringId name_id,
  43. SemanticsNameScopeId scope_id, bool print_diagnostics)
  44. -> SemanticsNodeId;
  45. // Prints a diagnostic for a duplicate name.
  46. auto DiagnoseDuplicateName(ParseTree::Node parse_node,
  47. SemanticsNodeId prev_def_id) -> void;
  48. // Prints a diagnostic for a missing name.
  49. auto DiagnoseNameNotFound(ParseTree::Node parse_node,
  50. SemanticsStringId name_id) -> void;
  51. // Pushes a new scope onto scope_stack_.
  52. auto PushScope() -> void;
  53. // Pops the top scope from scope_stack_, cleaning up names from name_lookup_.
  54. auto PopScope() -> void;
  55. // Adds a `Branch` node branching to a new node block, and returns the ID of
  56. // the new block. All paths to the branch target must go through the current
  57. // block, though not necessarily through this branch.
  58. auto AddDominatedBlockAndBranch(ParseTree::Node parse_node)
  59. -> SemanticsNodeBlockId;
  60. // Adds a `Branch` node branching to a new node block with a value, and
  61. // returns the ID of the new block. All paths to the branch target must go
  62. // through the current block.
  63. auto AddDominatedBlockAndBranchWithArg(ParseTree::Node parse_node,
  64. SemanticsNodeId arg_id)
  65. -> SemanticsNodeBlockId;
  66. // Adds a `BranchIf` node branching to a new node block, and returns the ID
  67. // of the new block. All paths to the branch target must go through the
  68. // current block.
  69. auto AddDominatedBlockAndBranchIf(ParseTree::Node parse_node,
  70. SemanticsNodeId cond_id)
  71. -> SemanticsNodeBlockId;
  72. // Adds branches from the given list of blocks to a new block, for
  73. // reconvergence of control flow, and pushes the new block onto the node
  74. // block stack.
  75. auto AddConvergenceBlockAndPush(
  76. ParseTree::Node parse_tree,
  77. std::initializer_list<SemanticsNodeBlockId> blocks) -> void;
  78. // Adds branches from the given list of blocks and values to a new block, for
  79. // reconvergence of control flow with a result value, and pushes the new
  80. // block onto the node block stack. Returns a node referring to the result
  81. // value.
  82. auto AddConvergenceBlockWithArgAndPush(
  83. ParseTree::Node parse_node,
  84. std::initializer_list<std::pair<SemanticsNodeBlockId, SemanticsNodeId>>
  85. blocks_and_args) -> SemanticsNodeId;
  86. // Add the current code block to the enclosing function.
  87. auto AddCurrentCodeBlockToFunction() -> void;
  88. // Returns whether the current position in the current block is reachable.
  89. auto is_current_position_reachable() -> bool;
  90. // Runs ImplicitAsImpl for a set of arguments and parameters.
  91. //
  92. // This will eventually need to support checking against multiple possible
  93. // overloads, multiple of which may be possible but not "best". While this can
  94. // currently be done by calling twice, toggling `apply_implicit_as`, in the
  95. // future we may want to remember the right implicit conversions to do for
  96. // valid cases in order to efficiently handle generics.
  97. auto ImplicitAsForArgs(
  98. SemanticsNodeBlockId arg_refs_id, ParseTree::Node param_parse_node,
  99. SemanticsNodeBlockId param_refs_id,
  100. DiagnosticEmitter<ParseTree::Node>::DiagnosticBuilder* diagnostic)
  101. -> bool;
  102. // Runs ImplicitAsImpl for a situation where a cast is required, returning the
  103. // updated `value_id`. Prints a diagnostic and returns an Error if
  104. // unsupported.
  105. auto ImplicitAsRequired(ParseTree::Node parse_node, SemanticsNodeId value_id,
  106. SemanticsTypeId as_type_id) -> SemanticsNodeId;
  107. // Runs ImplicitAsRequired for a conversion to `bool`.
  108. auto ImplicitAsBool(ParseTree::Node parse_node, SemanticsNodeId value_id)
  109. -> SemanticsNodeId;
  110. // Canonicalizes a type which is tracked as a single node.
  111. // TODO: This should eventually return a type ID.
  112. auto CanonicalizeType(SemanticsNodeId node_id) -> SemanticsTypeId;
  113. // Handles canonicalization of struct types. This may create a new struct type
  114. // when it has a new structure, or reference an existing struct type when it
  115. // duplicates a prior type.
  116. //
  117. // Individual struct type fields aren't canonicalized because they may have
  118. // name conflicts or other diagnostics during creation, which can use the
  119. // parse node.
  120. auto CanonicalizeStructType(ParseTree::Node parse_node,
  121. SemanticsNodeBlockId refs_id) -> SemanticsTypeId;
  122. // Handles canonicalization of tuple types. This may create a new tuple type
  123. // if the `type_ids` doesn't match an existing tuple type.
  124. auto CanonicalizeTupleType(ParseTree::Node parse_node,
  125. llvm::SmallVector<SemanticsTypeId>&& type_ids)
  126. -> SemanticsTypeId;
  127. // Converts an expression for use as a type.
  128. // TODO: This should eventually return a type ID.
  129. auto ExpressionAsType(ParseTree::Node parse_node, SemanticsNodeId value_id)
  130. -> SemanticsTypeId {
  131. auto node = semantics_ir_->GetNode(value_id);
  132. if (node.kind() == SemanticsNodeKind::StubReference) {
  133. value_id = node.GetAsStubReference();
  134. CARBON_CHECK(semantics_ir_->GetNode(value_id).kind() !=
  135. SemanticsNodeKind::StubReference)
  136. << "Stub reference should not point to another stub reference";
  137. }
  138. return CanonicalizeType(
  139. ImplicitAsRequired(parse_node, value_id, SemanticsTypeId::TypeType));
  140. }
  141. // Starts handling parameters or arguments.
  142. auto ParamOrArgStart() -> void;
  143. // On a comma, pushes the entry. On return, the top of node_stack_ will be
  144. // start_kind.
  145. auto ParamOrArgComma(bool for_args) -> void;
  146. // Detects whether there's an entry to push. On return, the top of
  147. // node_stack_ will be start_kind, and the caller should do type-specific
  148. // processing. Returns refs_id.
  149. auto ParamOrArgEnd(bool for_args, ParseNodeKind start_kind)
  150. -> SemanticsNodeBlockId;
  151. // Saves a parameter from the top block in node_stack_ to the top block in
  152. // params_or_args_stack_. If for_args, adds a StubReference of the previous
  153. // node's result to the IR.
  154. //
  155. // This should only be called by other ParamOrArg functions, not directly.
  156. auto ParamOrArgSave(bool for_args) -> void;
  157. // Prints information for a stack dump.
  158. auto PrintForStackDump(llvm::raw_ostream& output) const -> void;
  159. auto tokens() -> const TokenizedBuffer& { return *tokens_; }
  160. auto emitter() -> DiagnosticEmitter<ParseTree::Node>& { return *emitter_; }
  161. auto parse_tree() -> const ParseTree& { return *parse_tree_; }
  162. auto semantics_ir() -> SemanticsIR& { return *semantics_ir_; }
  163. auto node_stack() -> SemanticsNodeStack& { return node_stack_; }
  164. auto node_block_stack() -> SemanticsNodeBlockStack& {
  165. return node_block_stack_;
  166. }
  167. auto args_type_info_stack() -> SemanticsNodeBlockStack& {
  168. return args_type_info_stack_;
  169. }
  170. auto return_scope_stack() -> llvm::SmallVector<SemanticsNodeId>& {
  171. return return_scope_stack_;
  172. }
  173. auto declaration_name_stack() -> SemanticsDeclarationNameStack& {
  174. return declaration_name_stack_;
  175. }
  176. private:
  177. // For CanImplicitAs, the detected conversion to apply.
  178. enum ImplicitAsKind {
  179. // Incompatible types.
  180. Incompatible,
  181. // No conversion required.
  182. Identical,
  183. // ImplicitAs is required.
  184. Compatible,
  185. };
  186. // A FoldingSet node for a struct or tuple type.
  187. class TypeNode : public llvm::FastFoldingSetNode {
  188. public:
  189. explicit TypeNode(const llvm::FoldingSetNodeID& node_id,
  190. SemanticsTypeId type_id)
  191. : llvm::FastFoldingSetNode(node_id), type_id_(type_id) {}
  192. auto type_id() -> SemanticsTypeId { return type_id_; }
  193. private:
  194. SemanticsTypeId type_id_;
  195. };
  196. // An entry in scope_stack_.
  197. struct ScopeStackEntry {
  198. // Names which are registered with name_lookup_, and will need to be
  199. // deregistered when the scope ends.
  200. llvm::DenseSet<SemanticsStringId> names;
  201. // TODO: This likely needs to track things which need to be destructed.
  202. };
  203. // Runs ImplicitAs behavior to convert `value` to `as_type`, returning the
  204. // result type. The result will be the node to use to replace `value`.
  205. //
  206. // If `output_value_id` is null, then this only checks if the conversion is
  207. // possible.
  208. //
  209. // If `output_value_id` is not null, then it will be set if there is a need to
  210. // cast.
  211. auto ImplicitAsImpl(SemanticsNodeId value_id, SemanticsTypeId as_type_id,
  212. SemanticsNodeId* output_value_id) -> ImplicitAsKind;
  213. auto current_scope() -> ScopeStackEntry& { return scope_stack_.back(); }
  214. // Tokens for getting data on literals.
  215. const TokenizedBuffer* tokens_;
  216. // Handles diagnostics.
  217. DiagnosticEmitter<ParseTree::Node>* emitter_;
  218. // The file's parse tree.
  219. const ParseTree* parse_tree_;
  220. // The SemanticsIR being added to.
  221. SemanticsIR* semantics_ir_;
  222. // Whether to print verbose output.
  223. llvm::raw_ostream* vlog_stream_;
  224. // The stack during Build. Will contain file-level parse nodes on return.
  225. SemanticsNodeStack node_stack_;
  226. // The stack of node blocks being used for general IR generation.
  227. SemanticsNodeBlockStack node_block_stack_;
  228. // The stack of node blocks being used for per-element tracking of nodes in
  229. // parameter and argument node blocks. Versus node_block_stack_, an element
  230. // will have 1 or more nodes in blocks in node_block_stack_, but only ever 1
  231. // node in blocks here.
  232. SemanticsNodeBlockStack params_or_args_stack_;
  233. // The stack of node blocks being used for type information while processing
  234. // arguments. This is used in parallel with params_or_args_stack_. It's
  235. // currently only used for struct literals, where we need to track names
  236. // for a type separate from the literal arguments.
  237. SemanticsNodeBlockStack args_type_info_stack_;
  238. // A stack of return scopes; i.e., targets for `return`. Inside a function,
  239. // this will be a FunctionDeclaration.
  240. llvm::SmallVector<SemanticsNodeId> return_scope_stack_;
  241. // A stack for scope context.
  242. llvm::SmallVector<ScopeStackEntry> scope_stack_;
  243. // The stack used for qualified declaration name construction.
  244. SemanticsDeclarationNameStack declaration_name_stack_;
  245. // Maps identifiers to name lookup results. Values are a stack of name lookup
  246. // results in the ancestor scopes. This offers constant-time lookup of names,
  247. // regardless of how many scopes exist between the name declaration and
  248. // reference.
  249. //
  250. // Names which no longer have lookup results are erased.
  251. llvm::DenseMap<SemanticsStringId, llvm::SmallVector<SemanticsNodeId>>
  252. name_lookup_;
  253. // Tracks types which have been used, so that they aren't repeatedly added to
  254. // SemanticsIR.
  255. llvm::DenseMap<SemanticsNodeId, SemanticsTypeId> canonical_types_;
  256. // Tracks struct type literals which have been defined, so that they aren't
  257. // repeatedly redefined.
  258. llvm::FoldingSet<TypeNode> canonical_struct_types_;
  259. // Tracks tuple type literals which have been defined, so that they aren't
  260. // repeatedly redefined.
  261. llvm::FoldingSet<TypeNode> canonical_tuple_types_;
  262. // Storage for the nodes in canonical_struct_types_ and
  263. // canonical_tuple_types_. This stores in pointers so that FoldingSet can have
  264. // stable pointers.
  265. llvm::SmallVector<std::unique_ptr<TypeNode>> canonical_types_nodes_;
  266. };
  267. // Parse node handlers. Returns false for unrecoverable errors.
  268. #define CARBON_PARSE_NODE_KIND(Name) \
  269. auto SemanticsHandle##Name(SemanticsContext& context, \
  270. ParseTree::Node parse_node) \
  271. ->bool;
  272. #include "toolchain/parser/parse_node_kind.def"
  273. } // namespace Carbon
  274. #endif // CARBON_TOOLCHAIN_SEMANTICS_SEMANTICS_CONTEXT_H_