semantics_context.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  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_node,
  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. // Returns a pointer type whose pointee type is `pointee_type_id`.
  128. auto GetPointerType(ParseTree::Node parse_node,
  129. SemanticsTypeId pointee_type_id) -> SemanticsTypeId;
  130. // Converts an expression for use as a type.
  131. // TODO: This should eventually return a type ID.
  132. auto ExpressionAsType(ParseTree::Node parse_node, SemanticsNodeId value_id)
  133. -> SemanticsTypeId {
  134. auto node = semantics_ir_->GetNode(value_id);
  135. if (node.kind() == SemanticsNodeKind::StubReference) {
  136. value_id = node.GetAsStubReference();
  137. CARBON_CHECK(semantics_ir_->GetNode(value_id).kind() !=
  138. SemanticsNodeKind::StubReference)
  139. << "Stub reference should not point to another stub reference";
  140. }
  141. return CanonicalizeType(
  142. ImplicitAsRequired(parse_node, value_id, SemanticsTypeId::TypeType));
  143. }
  144. // Removes any top-level `const` qualifiers from a type.
  145. auto GetUnqualifiedType(SemanticsTypeId type_id) -> SemanticsTypeId;
  146. // Starts handling parameters or arguments.
  147. auto ParamOrArgStart() -> void;
  148. // On a comma, pushes the entry. On return, the top of node_stack_ will be
  149. // start_kind.
  150. auto ParamOrArgComma(bool for_args) -> void;
  151. // Detects whether there's an entry to push. On return, the top of
  152. // node_stack_ will be start_kind, and the caller should do type-specific
  153. // processing. Returns refs_id.
  154. auto ParamOrArgEnd(bool for_args, ParseNodeKind start_kind)
  155. -> SemanticsNodeBlockId;
  156. // Saves a parameter from the top block in node_stack_ to the top block in
  157. // params_or_args_stack_. If for_args, adds a StubReference of the previous
  158. // node's result to the IR.
  159. //
  160. // This should only be called by other ParamOrArg functions, not directly.
  161. auto ParamOrArgSave(bool for_args) -> void;
  162. // Prints information for a stack dump.
  163. auto PrintForStackDump(llvm::raw_ostream& output) const -> void;
  164. auto tokens() -> const TokenizedBuffer& { return *tokens_; }
  165. auto emitter() -> DiagnosticEmitter<ParseTree::Node>& { return *emitter_; }
  166. auto parse_tree() -> const ParseTree& { return *parse_tree_; }
  167. auto semantics_ir() -> SemanticsIR& { return *semantics_ir_; }
  168. auto node_stack() -> SemanticsNodeStack& { return node_stack_; }
  169. auto node_block_stack() -> SemanticsNodeBlockStack& {
  170. return node_block_stack_;
  171. }
  172. auto args_type_info_stack() -> SemanticsNodeBlockStack& {
  173. return args_type_info_stack_;
  174. }
  175. auto return_scope_stack() -> llvm::SmallVector<SemanticsNodeId>& {
  176. return return_scope_stack_;
  177. }
  178. auto declaration_name_stack() -> SemanticsDeclarationNameStack& {
  179. return declaration_name_stack_;
  180. }
  181. private:
  182. // For CanImplicitAs, the detected conversion to apply.
  183. enum ImplicitAsKind {
  184. // Incompatible types.
  185. Incompatible,
  186. // No conversion required.
  187. Identical,
  188. // ImplicitAs is required.
  189. Compatible,
  190. };
  191. // A FoldingSet node for a type.
  192. class TypeNode : public llvm::FastFoldingSetNode {
  193. public:
  194. explicit TypeNode(const llvm::FoldingSetNodeID& node_id,
  195. SemanticsTypeId type_id)
  196. : llvm::FastFoldingSetNode(node_id), type_id_(type_id) {}
  197. auto type_id() -> SemanticsTypeId { return type_id_; }
  198. private:
  199. SemanticsTypeId type_id_;
  200. };
  201. // An entry in scope_stack_.
  202. struct ScopeStackEntry {
  203. // Names which are registered with name_lookup_, and will need to be
  204. // deregistered when the scope ends.
  205. llvm::DenseSet<SemanticsStringId> names;
  206. // TODO: This likely needs to track things which need to be destructed.
  207. };
  208. // Runs ImplicitAs behavior to convert `value` to `as_type`, returning the
  209. // result type. The result will be the node to use to replace `value`.
  210. //
  211. // If `output_value_id` is null, then this only checks if the conversion is
  212. // possible.
  213. //
  214. // If `output_value_id` is not null, then it will be set if there is a need to
  215. // cast.
  216. auto ImplicitAsImpl(SemanticsNodeId value_id, SemanticsTypeId as_type_id,
  217. SemanticsNodeId* output_value_id) -> ImplicitAsKind;
  218. // Forms a canonical type ID for a type. This function is given two
  219. // callbacks:
  220. //
  221. // `profile_type(canonical_id)` is called to build a fingerprint for this
  222. // type. The ID should be distinct for all distinct type values with the same
  223. // `kind`.
  224. //
  225. // `make_node()` is called to obtain a `SemanticsNodeId` that describes the
  226. // type. It is only called if the type does not already exist, so can be used
  227. // to lazily build the `SemanticsNode`. `make_node()` is not permitted to
  228. // directly or indirectly canonicalize any types.
  229. auto CanonicalizeTypeImpl(
  230. SemanticsNodeKind kind,
  231. llvm::function_ref<void(llvm::FoldingSetNodeID& canonical_id)>
  232. profile_type,
  233. llvm::function_ref<SemanticsNodeId()> make_node) -> SemanticsTypeId;
  234. // Forms a canonical type ID for a type. If the type is new, adds the node to
  235. // the current block.
  236. auto CanonicalizeTypeAndAddNodeIfNew(SemanticsNode node) -> SemanticsTypeId;
  237. auto current_scope() -> ScopeStackEntry& { return scope_stack_.back(); }
  238. // Tokens for getting data on literals.
  239. const TokenizedBuffer* tokens_;
  240. // Handles diagnostics.
  241. DiagnosticEmitter<ParseTree::Node>* emitter_;
  242. // The file's parse tree.
  243. const ParseTree* parse_tree_;
  244. // The SemanticsIR being added to.
  245. SemanticsIR* semantics_ir_;
  246. // Whether to print verbose output.
  247. llvm::raw_ostream* vlog_stream_;
  248. // The stack during Build. Will contain file-level parse nodes on return.
  249. SemanticsNodeStack node_stack_;
  250. // The stack of node blocks being used for general IR generation.
  251. SemanticsNodeBlockStack node_block_stack_;
  252. // The stack of node blocks being used for per-element tracking of nodes in
  253. // parameter and argument node blocks. Versus node_block_stack_, an element
  254. // will have 1 or more nodes in blocks in node_block_stack_, but only ever 1
  255. // node in blocks here.
  256. SemanticsNodeBlockStack params_or_args_stack_;
  257. // The stack of node blocks being used for type information while processing
  258. // arguments. This is used in parallel with params_or_args_stack_. It's
  259. // currently only used for struct literals, where we need to track names
  260. // for a type separate from the literal arguments.
  261. SemanticsNodeBlockStack args_type_info_stack_;
  262. // A stack of return scopes; i.e., targets for `return`. Inside a function,
  263. // this will be a FunctionDeclaration.
  264. llvm::SmallVector<SemanticsNodeId> return_scope_stack_;
  265. // A stack for scope context.
  266. llvm::SmallVector<ScopeStackEntry> scope_stack_;
  267. // The stack used for qualified declaration name construction.
  268. SemanticsDeclarationNameStack declaration_name_stack_;
  269. // Maps identifiers to name lookup results. Values are a stack of name lookup
  270. // results in the ancestor scopes. This offers constant-time lookup of names,
  271. // regardless of how many scopes exist between the name declaration and
  272. // reference.
  273. //
  274. // Names which no longer have lookup results are erased.
  275. llvm::DenseMap<SemanticsStringId, llvm::SmallVector<SemanticsNodeId>>
  276. name_lookup_;
  277. // Cache of the mapping from nodes to types, to avoid recomputing the folding
  278. // set ID.
  279. llvm::DenseMap<SemanticsNodeId, SemanticsTypeId> canonical_types_;
  280. // Tracks the canonical representation of types that have been defined.
  281. llvm::FoldingSet<TypeNode> canonical_type_nodes_;
  282. // Storage for the nodes in canonical_type_nodes_. This stores in pointers so
  283. // that FoldingSet can have stable pointers.
  284. llvm::SmallVector<std::unique_ptr<TypeNode>> type_node_storage_;
  285. };
  286. // Parse node handlers. Returns false for unrecoverable errors.
  287. #define CARBON_PARSE_NODE_KIND(Name) \
  288. auto SemanticsHandle##Name(SemanticsContext& context, \
  289. ParseTree::Node parse_node) \
  290. ->bool;
  291. #include "toolchain/parser/parse_node_kind.def"
  292. } // namespace Carbon
  293. #endif // CARBON_TOOLCHAIN_SEMANTICS_SEMANTICS_CONTEXT_H_