typed_nodes.h 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064
  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_PARSE_TYPED_NODES_H_
  5. #define CARBON_TOOLCHAIN_PARSE_TYPED_NODES_H_
  6. #include <optional>
  7. #include "toolchain/parse/node_ids.h"
  8. #include "toolchain/parse/node_kind.h"
  9. namespace Carbon::Parse {
  10. // Helpers for defining different kinds of parse nodes.
  11. // ----------------------------------------------------
  12. // A pair of a list item and its optional following comma.
  13. template <typename Element, typename Comma>
  14. struct ListItem {
  15. Element value;
  16. std::optional<Comma> comma;
  17. };
  18. // A list of items, parameterized by the kind of the elements and comma.
  19. template <typename Element, typename Comma>
  20. using CommaSeparatedList = llvm::SmallVector<ListItem<Element, Comma>>;
  21. // This class provides a shorthand for defining parse node kinds for leaf nodes.
  22. template <const NodeKind& KindT, NodeCategory Category = NodeCategory::None>
  23. struct LeafNode {
  24. static constexpr auto Kind = KindT.Define(Category);
  25. };
  26. // ----------------------------------------------------------------------------
  27. // Each node kind (in node_kind.def) should have a corresponding type defined
  28. // here which describes the expected child structure of that parse node.
  29. //
  30. // Each of these types should start with a `static constexpr Kind` member
  31. // initialized by calling `Define` on the corresponding `NodeKind`, and passing
  32. // in the `NodeCategory` of that kind. This will both associate the category
  33. // with the node kind and create the necessary kind object for the typed node.
  34. //
  35. // This should be followed by field declarations that describe the child nodes,
  36. // in order, that occur in the parse tree. The `Extract...` functions on the
  37. // parse tree use struct reflection on these fields to guide the extraction of
  38. // the child nodes from the tree into an object of this type with these fields
  39. // for convenient access.
  40. //
  41. // The types of these fields are special and describe the specific child node
  42. // structure of the parse node. Many of these types are defined in `node_ids.h`.
  43. //
  44. // Valid primitive types here are:
  45. // - `NodeId` to match any single child node
  46. // - `FooId` to require that child to have kind `NodeKind::Foo`
  47. // - `AnyCatId` to require that child to have a kind in category `Cat`
  48. // - `NodeIdOneOf<A, B>` to require the child to have kind `NodeKind::A` or
  49. // `NodeKind::B`
  50. // - `NodeIdNot<A>` to match any single child whose kind is not `NodeKind::A`
  51. //
  52. // There a few, restricted composite field types allowed that compose types in
  53. // various ways, where all of the `T`s and `U`s below are themselves valid field
  54. // types:
  55. // - `llvm::SmallVector<T>` to match any number of children matching `T`
  56. // - `std::optional<T>` to match 0 or 1 children matching `T`
  57. // - `std::tuple<T...>` to match children matching `T...`
  58. // - Any provided `Aggregate` type that is a simple aggregate type such as
  59. // `struct Aggregate { T x; U y; }`,
  60. // to match children with types `T` and `U`.
  61. // ----------------------------------------------------------------------------
  62. // Error nodes
  63. // -----------
  64. // An invalid parse. Used to balance the parse tree. This type is here only to
  65. // ensure we have a type for each parse node kind. This node kind always has an
  66. // error, so can never be extracted.
  67. using InvalidParse =
  68. LeafNode<NodeKind::InvalidParse, NodeCategory::Decl | NodeCategory::Expr>;
  69. // An invalid subtree. Always has an error so can never be extracted.
  70. using InvalidParseStart = LeafNode<NodeKind::InvalidParseStart>;
  71. struct InvalidParseSubtree {
  72. static constexpr auto Kind =
  73. NodeKind::InvalidParseSubtree.Define(NodeCategory::Decl);
  74. InvalidParseStartId start;
  75. llvm::SmallVector<NodeIdNot<InvalidParseStart>> extra;
  76. };
  77. // A placeholder node to be replaced; it will never exist in a valid parse tree.
  78. // Its token kind is not enforced even when valid.
  79. using Placeholder = LeafNode<NodeKind::Placeholder>;
  80. // File nodes
  81. // ----------
  82. // The start of the file.
  83. using FileStart = LeafNode<NodeKind::FileStart>;
  84. // The end of the file.
  85. using FileEnd = LeafNode<NodeKind::FileEnd>;
  86. // General-purpose nodes
  87. // ---------------------
  88. // An empty declaration, such as `;`.
  89. using EmptyDecl =
  90. LeafNode<NodeKind::EmptyDecl, NodeCategory::Decl | NodeCategory::Statement>;
  91. // A name in a non-expression context, such as a declaration.
  92. using IdentifierName =
  93. LeafNode<NodeKind::IdentifierName,
  94. NodeCategory::NameComponent | NodeCategory::MemberName>;
  95. // A name in an expression context.
  96. using IdentifierNameExpr =
  97. LeafNode<NodeKind::IdentifierNameExpr, NodeCategory::Expr>;
  98. // The `self` value and `Self` type identifier keywords. Typically of the form
  99. // `self: Self`.
  100. using SelfValueName = LeafNode<NodeKind::SelfValueName>;
  101. using SelfValueNameExpr =
  102. LeafNode<NodeKind::SelfValueNameExpr, NodeCategory::Expr>;
  103. using SelfTypeNameExpr =
  104. LeafNode<NodeKind::SelfTypeNameExpr, NodeCategory::Expr>;
  105. // The `base` value keyword, introduced by `base: B`. Typically referenced in
  106. // an expression, as in `x.base` or `{.base = ...}`, but can also be used as a
  107. // declared name, as in `{.base: partial B}`.
  108. using BaseName = LeafNode<NodeKind::BaseName, NodeCategory::MemberName>;
  109. // A qualified name: `A.B`.
  110. struct QualifiedName {
  111. static constexpr auto Kind =
  112. NodeKind::QualifiedName.Define(NodeCategory::NameComponent);
  113. // For now, this is either an IdentifierName or a QualifiedName.
  114. AnyNameComponentId lhs;
  115. // TODO: This will eventually need to support more general expressions, for
  116. // example `GenericType(type_args).ChildType(child_type_args).Name`.
  117. IdentifierNameId rhs;
  118. };
  119. // Library, package, import
  120. // ------------------------
  121. // The `package` keyword in an expression.
  122. using PackageExpr = LeafNode<NodeKind::PackageExpr, NodeCategory::Expr>;
  123. // The name of a package or library for `package`, `import`, and `library`.
  124. using PackageName = LeafNode<NodeKind::PackageName>;
  125. using LibraryName = LeafNode<NodeKind::LibraryName>;
  126. using DefaultLibrary = LeafNode<NodeKind::DefaultLibrary>;
  127. using PackageIntroducer = LeafNode<NodeKind::PackageIntroducer>;
  128. using PackageApi = LeafNode<NodeKind::PackageApi>;
  129. using PackageImpl = LeafNode<NodeKind::PackageImpl>;
  130. // `library` in `package` or `import`.
  131. struct LibrarySpecifier {
  132. static constexpr auto Kind = NodeKind::LibrarySpecifier.Define();
  133. NodeIdOneOf<LibraryName, DefaultLibrary> name;
  134. };
  135. // First line of the file, such as:
  136. // `package MyPackage library "MyLibrary" impl;`
  137. struct PackageDirective {
  138. static constexpr auto Kind =
  139. NodeKind::PackageDirective.Define(NodeCategory::Decl);
  140. PackageIntroducerId introducer;
  141. std::optional<PackageNameId> name;
  142. std::optional<LibrarySpecifierId> library;
  143. NodeIdOneOf<PackageApi, PackageImpl> api_or_impl;
  144. };
  145. // `import TheirPackage library "TheirLibrary";`
  146. using ImportIntroducer = LeafNode<NodeKind::ImportIntroducer>;
  147. struct ImportDirective {
  148. static constexpr auto Kind =
  149. NodeKind::ImportDirective.Define(NodeCategory::Decl);
  150. ImportIntroducerId introducer;
  151. std::optional<PackageNameId> name;
  152. std::optional<LibrarySpecifierId> library;
  153. };
  154. // `library` as directive.
  155. using LibraryIntroducer = LeafNode<NodeKind::LibraryIntroducer>;
  156. struct LibraryDirective {
  157. static constexpr auto Kind =
  158. NodeKind::LibraryDirective.Define(NodeCategory::Decl);
  159. LibraryIntroducerId introducer;
  160. NodeIdOneOf<LibraryName, DefaultLibrary> library_name;
  161. NodeIdOneOf<PackageApi, PackageImpl> api_or_impl;
  162. };
  163. // Namespace nodes
  164. // ---------------
  165. using NamespaceStart = LeafNode<NodeKind::NamespaceStart>;
  166. // A namespace: `namespace N;`.
  167. struct Namespace {
  168. static constexpr auto Kind = NodeKind::Namespace.Define(NodeCategory::Decl);
  169. NamespaceStartId introducer;
  170. llvm::SmallVector<AnyModifierId> modifiers;
  171. NodeIdOneOf<IdentifierName, QualifiedName> name;
  172. };
  173. // Pattern nodes
  174. // -------------
  175. // A pattern binding, such as `name: Type`.
  176. struct BindingPattern {
  177. static constexpr auto Kind =
  178. NodeKind::BindingPattern.Define(NodeCategory::Pattern);
  179. NodeIdOneOf<IdentifierName, SelfValueName> name;
  180. AnyExprId type;
  181. };
  182. // `name:! Type`
  183. struct CompileTimeBindingPattern {
  184. static constexpr auto Kind =
  185. NodeKind::CompileTimeBindingPattern.Define(NodeCategory::Pattern);
  186. NodeIdOneOf<IdentifierName, SelfValueName> name;
  187. AnyExprId type;
  188. };
  189. // An address-of binding: `addr self: Self*`.
  190. struct Addr {
  191. static constexpr auto Kind = NodeKind::Addr.Define(NodeCategory::Pattern);
  192. AnyPatternId inner;
  193. };
  194. // A template binding: `template T:! type`.
  195. struct Template {
  196. static constexpr auto Kind = NodeKind::Template.Define(NodeCategory::Pattern);
  197. // This is a CompileTimeBindingPatternId in any valid program.
  198. // TODO: Should the parser enforce that?
  199. AnyPatternId inner;
  200. };
  201. using TuplePatternStart = LeafNode<NodeKind::TuplePatternStart>;
  202. using PatternListComma = LeafNode<NodeKind::PatternListComma>;
  203. // A parameter list or tuple pattern: `(a: i32, b: i32)`.
  204. struct TuplePattern {
  205. static constexpr auto Kind =
  206. NodeKind::TuplePattern.Define(NodeCategory::Pattern);
  207. TuplePatternStartId left_paren;
  208. CommaSeparatedList<AnyPatternId, PatternListCommaId> params;
  209. };
  210. using ImplicitParamListStart = LeafNode<NodeKind::ImplicitParamListStart>;
  211. // An implicit parameter list: `[T:! type, self: Self]`.
  212. struct ImplicitParamList {
  213. static constexpr auto Kind = NodeKind::ImplicitParamList.Define();
  214. ImplicitParamListStartId left_square;
  215. CommaSeparatedList<AnyPatternId, PatternListCommaId> params;
  216. };
  217. // Function nodes
  218. // --------------
  219. using FunctionIntroducer = LeafNode<NodeKind::FunctionIntroducer>;
  220. // A return type: `-> i32`.
  221. struct ReturnType {
  222. static constexpr auto Kind = NodeKind::ReturnType.Define();
  223. AnyExprId type;
  224. };
  225. // A function signature: `fn F() -> i32`.
  226. template <const NodeKind& KindT, NodeCategory Category>
  227. struct FunctionSignature {
  228. static constexpr auto Kind = KindT.Define(Category);
  229. FunctionIntroducerId introducer;
  230. llvm::SmallVector<AnyModifierId> modifiers;
  231. // For now, this is either an IdentifierName or a QualifiedName.
  232. AnyNameComponentId name;
  233. std::optional<ImplicitParamListId> implicit_params;
  234. TuplePatternId params;
  235. std::optional<ReturnTypeId> return_type;
  236. };
  237. using FunctionDecl =
  238. FunctionSignature<NodeKind::FunctionDecl, NodeCategory::Decl>;
  239. using FunctionDefinitionStart =
  240. FunctionSignature<NodeKind::FunctionDefinitionStart, NodeCategory::None>;
  241. // A function definition: `fn F() -> i32 { ... }`.
  242. struct FunctionDefinition {
  243. static constexpr auto Kind =
  244. NodeKind::FunctionDefinition.Define(NodeCategory::Decl);
  245. FunctionDefinitionStartId signature;
  246. llvm::SmallVector<AnyStatementId> body;
  247. };
  248. using BuiltinFunctionDefinitionStart =
  249. FunctionSignature<NodeKind::BuiltinFunctionDefinitionStart,
  250. NodeCategory::None>;
  251. using BuiltinName = LeafNode<NodeKind::BuiltinName>;
  252. // A builtin function definition: `fn F() -> i32 = "builtin name";`
  253. struct BuiltinFunctionDefinition {
  254. static constexpr auto Kind =
  255. NodeKind::BuiltinFunctionDefinition.Define(NodeCategory::Decl);
  256. BuiltinFunctionDefinitionStartId signature;
  257. BuiltinNameId builtin_name;
  258. };
  259. // `alias` nodes
  260. // -------------
  261. using AliasIntroducer = LeafNode<NodeKind::AliasIntroducer>;
  262. using AliasInitializer = LeafNode<NodeKind::AliasInitializer>;
  263. // An `alias` declaration: `alias a = b;`.
  264. struct Alias {
  265. static constexpr auto Kind =
  266. NodeKind::Alias.Define(NodeCategory::Decl | NodeCategory::Statement);
  267. AliasIntroducerId introducer;
  268. llvm::SmallVector<AnyModifierId> modifiers;
  269. // For now, this is either an IdentifierName or a QualifiedName.
  270. AnyNameComponentId name;
  271. AliasInitializerId equals;
  272. AnyExprId initializer;
  273. };
  274. // `let` nodes
  275. // -----------
  276. using LetIntroducer = LeafNode<NodeKind::LetIntroducer>;
  277. using LetInitializer = LeafNode<NodeKind::LetInitializer>;
  278. // A `let` declaration: `let a: i32 = 5;`.
  279. struct LetDecl {
  280. static constexpr auto Kind =
  281. NodeKind::LetDecl.Define(NodeCategory::Decl | NodeCategory::Statement);
  282. LetIntroducerId introducer;
  283. llvm::SmallVector<AnyModifierId> modifiers;
  284. AnyPatternId pattern;
  285. struct Initializer {
  286. LetInitializerId equals;
  287. AnyExprId initializer;
  288. };
  289. std::optional<Initializer> initializer;
  290. };
  291. // `var` nodes
  292. // -----------
  293. using VariableIntroducer = LeafNode<NodeKind::VariableIntroducer>;
  294. using ReturnedModifier = LeafNode<NodeKind::ReturnedModifier>;
  295. using VariableInitializer = LeafNode<NodeKind::VariableInitializer>;
  296. // A `var` declaration: `var a: i32;` or `var a: i32 = 5;`.
  297. struct VariableDecl {
  298. static constexpr auto Kind = NodeKind::VariableDecl.Define(
  299. NodeCategory::Decl | NodeCategory::Statement);
  300. VariableIntroducerId introducer;
  301. llvm::SmallVector<AnyModifierId> modifiers;
  302. std::optional<ReturnedModifierId> returned;
  303. AnyPatternId pattern;
  304. struct Initializer {
  305. VariableInitializerId equals;
  306. AnyExprId value;
  307. };
  308. std::optional<Initializer> initializer;
  309. };
  310. // Statement nodes
  311. // ---------------
  312. using CodeBlockStart = LeafNode<NodeKind::CodeBlockStart>;
  313. // A code block: `{ statement; statement; ... }`.
  314. struct CodeBlock {
  315. static constexpr auto Kind = NodeKind::CodeBlock.Define();
  316. CodeBlockStartId left_brace;
  317. llvm::SmallVector<AnyStatementId> statements;
  318. };
  319. // An expression statement: `F(x);`.
  320. struct ExprStatement {
  321. static constexpr auto Kind =
  322. NodeKind::ExprStatement.Define(NodeCategory::Statement);
  323. AnyExprId expr;
  324. };
  325. using BreakStatementStart = LeafNode<NodeKind::BreakStatementStart>;
  326. // A break statement: `break;`.
  327. struct BreakStatement {
  328. static constexpr auto Kind =
  329. NodeKind::BreakStatement.Define(NodeCategory::Statement);
  330. BreakStatementStartId introducer;
  331. };
  332. using ContinueStatementStart = LeafNode<NodeKind::ContinueStatementStart>;
  333. // A continue statement: `continue;`.
  334. struct ContinueStatement {
  335. static constexpr auto Kind =
  336. NodeKind::ContinueStatement.Define(NodeCategory::Statement);
  337. ContinueStatementStartId introducer;
  338. };
  339. using ReturnStatementStart = LeafNode<NodeKind::ReturnStatementStart>;
  340. using ReturnVarModifier = LeafNode<NodeKind::ReturnVarModifier>;
  341. // A return statement: `return;` or `return expr;` or `return var;`.
  342. struct ReturnStatement {
  343. static constexpr auto Kind =
  344. NodeKind::ReturnStatement.Define(NodeCategory::Statement);
  345. ReturnStatementStartId introducer;
  346. std::optional<AnyExprId> expr;
  347. std::optional<ReturnVarModifierId> var;
  348. };
  349. using ForHeaderStart = LeafNode<NodeKind::ForHeaderStart>;
  350. // The `var ... in` portion of a `for` statement.
  351. struct ForIn {
  352. static constexpr auto Kind = NodeKind::ForIn.Define();
  353. VariableIntroducerId introducer;
  354. AnyPatternId pattern;
  355. };
  356. // The `for (var ... in ...)` portion of a `for` statement.
  357. struct ForHeader {
  358. static constexpr auto Kind = NodeKind::ForHeader.Define();
  359. ForHeaderStartId introducer;
  360. ForInId var;
  361. AnyExprId range;
  362. };
  363. // A complete `for (...) { ... }` statement.
  364. struct ForStatement {
  365. static constexpr auto Kind =
  366. NodeKind::ForStatement.Define(NodeCategory::Statement);
  367. ForHeaderId header;
  368. CodeBlockId body;
  369. };
  370. using IfConditionStart = LeafNode<NodeKind::IfConditionStart>;
  371. // The condition portion of an `if` statement: `(expr)`.
  372. struct IfCondition {
  373. static constexpr auto Kind = NodeKind::IfCondition.Define();
  374. IfConditionStartId left_paren;
  375. AnyExprId condition;
  376. };
  377. using IfStatementElse = LeafNode<NodeKind::IfStatementElse>;
  378. // An `if` statement: `if (expr) { ... } else { ... }`.
  379. struct IfStatement {
  380. static constexpr auto Kind =
  381. NodeKind::IfStatement.Define(NodeCategory::Statement);
  382. IfConditionId head;
  383. CodeBlockId then;
  384. struct Else {
  385. IfStatementElseId else_token;
  386. NodeIdOneOf<CodeBlock, IfStatement> body;
  387. };
  388. std::optional<Else> else_clause;
  389. };
  390. using WhileConditionStart = LeafNode<NodeKind::WhileConditionStart>;
  391. // The condition portion of a `while` statement: `(expr)`.
  392. struct WhileCondition {
  393. static constexpr auto Kind = NodeKind::WhileCondition.Define();
  394. WhileConditionStartId left_paren;
  395. AnyExprId condition;
  396. };
  397. // A `while` statement: `while (expr) { ... }`.
  398. struct WhileStatement {
  399. static constexpr auto Kind =
  400. NodeKind::WhileStatement.Define(NodeCategory::Statement);
  401. WhileConditionId head;
  402. CodeBlockId body;
  403. };
  404. using MatchConditionStart = LeafNode<NodeKind::MatchConditionStart>;
  405. struct MatchCondition {
  406. static constexpr auto Kind = NodeKind::MatchCondition.Define();
  407. MatchConditionStartId left_paren;
  408. AnyExprId condition;
  409. };
  410. using MatchIntroducer = LeafNode<NodeKind::MatchIntroducer>;
  411. struct MatchStatementStart {
  412. static constexpr auto Kind = NodeKind::MatchStatementStart.Define();
  413. MatchIntroducerId introducer;
  414. MatchConditionId left_brace;
  415. };
  416. using MatchCaseIntroducer = LeafNode<NodeKind::MatchCaseIntroducer>;
  417. using MatchCaseGuardIntroducer = LeafNode<NodeKind::MatchCaseGuardIntroducer>;
  418. using MatchCaseGuardStart = LeafNode<NodeKind::MatchCaseGuardStart>;
  419. struct MatchCaseGuard {
  420. static constexpr auto Kind = NodeKind::MatchCaseGuard.Define();
  421. MatchCaseGuardIntroducerId introducer;
  422. MatchCaseGuardStartId left_paren;
  423. AnyExprId condition;
  424. };
  425. using MatchCaseEqualGreater = LeafNode<NodeKind::MatchCaseEqualGreater>;
  426. struct MatchCaseStart {
  427. static constexpr auto Kind = NodeKind::MatchCaseStart.Define();
  428. MatchCaseIntroducerId introducer;
  429. AnyPatternId pattern;
  430. std::optional<MatchCaseGuardId> guard;
  431. MatchCaseEqualGreaterId equal_greater_token;
  432. };
  433. struct MatchCase {
  434. static constexpr auto Kind = NodeKind::MatchCase.Define();
  435. MatchCaseStartId head;
  436. llvm::SmallVector<AnyStatementId> statements;
  437. };
  438. using MatchDefaultIntroducer = LeafNode<NodeKind::MatchDefaultIntroducer>;
  439. using MatchDefaultEqualGreater = LeafNode<NodeKind::MatchDefaultEqualGreater>;
  440. struct MatchDefaultStart {
  441. static constexpr auto Kind = NodeKind::MatchDefaultStart.Define();
  442. MatchDefaultIntroducerId introducer;
  443. MatchDefaultEqualGreaterId equal_greater_token;
  444. };
  445. struct MatchDefault {
  446. static constexpr auto Kind = NodeKind::MatchDefault.Define();
  447. MatchDefaultStartId introducer;
  448. llvm::SmallVector<AnyStatementId> statements;
  449. };
  450. // A `match` statement: `match (expr) { case (...) => {...} default => {...}}`.
  451. struct MatchStatement {
  452. static constexpr auto Kind =
  453. NodeKind::MatchStatement.Define(NodeCategory::Statement);
  454. MatchStatementStartId head;
  455. llvm::SmallVector<MatchCaseId> cases;
  456. std::optional<MatchDefaultId> default_case;
  457. };
  458. // Expression nodes
  459. // ----------------
  460. using ArrayExprStart = LeafNode<NodeKind::ArrayExprStart>;
  461. // The start of an array type, `[i32;`.
  462. //
  463. // TODO: Consider flattening this into `ArrayExpr`.
  464. struct ArrayExprSemi {
  465. static constexpr auto Kind = NodeKind::ArrayExprSemi.Define();
  466. ArrayExprStartId left_square;
  467. AnyExprId type;
  468. };
  469. // An array type, such as `[i32; 3]` or `[i32;]`.
  470. struct ArrayExpr {
  471. static constexpr auto Kind = NodeKind::ArrayExpr.Define(NodeCategory::Expr);
  472. ArrayExprSemiId start;
  473. std::optional<AnyExprId> bound;
  474. };
  475. // The opening portion of an indexing expression: `a[`.
  476. //
  477. // TODO: Consider flattening this into `IndexExpr`.
  478. struct IndexExprStart {
  479. static constexpr auto Kind = NodeKind::IndexExprStart.Define();
  480. AnyExprId sequence;
  481. };
  482. // An indexing expression, such as `a[1]`.
  483. struct IndexExpr {
  484. static constexpr auto Kind = NodeKind::IndexExpr.Define(NodeCategory::Expr);
  485. IndexExprStartId start;
  486. AnyExprId index;
  487. };
  488. using ParenExprStart = LeafNode<NodeKind::ParenExprStart>;
  489. // A parenthesized expression: `(a)`.
  490. struct ParenExpr {
  491. static constexpr auto Kind =
  492. NodeKind::ParenExpr.Define(NodeCategory::Expr | NodeCategory::MemberExpr);
  493. ParenExprStartId start;
  494. AnyExprId expr;
  495. };
  496. using TupleLiteralStart = LeafNode<NodeKind::TupleLiteralStart>;
  497. using TupleLiteralComma = LeafNode<NodeKind::TupleLiteralComma>;
  498. // A tuple literal: `()`, `(a, b, c)`, or `(a,)`.
  499. struct TupleLiteral {
  500. static constexpr auto Kind =
  501. NodeKind::TupleLiteral.Define(NodeCategory::Expr);
  502. TupleLiteralStartId start;
  503. CommaSeparatedList<AnyExprId, TupleLiteralCommaId> elements;
  504. };
  505. // The opening portion of a call expression: `F(`.
  506. //
  507. // TODO: Consider flattening this into `CallExpr`.
  508. struct CallExprStart {
  509. static constexpr auto Kind = NodeKind::CallExprStart.Define();
  510. AnyExprId callee;
  511. };
  512. using CallExprComma = LeafNode<NodeKind::CallExprComma>;
  513. // A call expression: `F(a, b, c)`.
  514. struct CallExpr {
  515. static constexpr auto Kind = NodeKind::CallExpr.Define(NodeCategory::Expr);
  516. CallExprStartId start;
  517. CommaSeparatedList<AnyExprId, CallExprCommaId> arguments;
  518. };
  519. // A member access expression: `a.b` or `a.(b)`.
  520. struct MemberAccessExpr {
  521. static constexpr auto Kind =
  522. NodeKind::MemberAccessExpr.Define(NodeCategory::Expr);
  523. AnyExprId lhs;
  524. AnyMemberNameOrMemberExprId rhs;
  525. };
  526. // An indirect member access expression: `a->b` or `a->(b)`.
  527. struct PointerMemberAccessExpr {
  528. static constexpr auto Kind =
  529. NodeKind::PointerMemberAccessExpr.Define(NodeCategory::Expr);
  530. AnyExprId lhs;
  531. AnyMemberNameOrMemberExprId rhs;
  532. };
  533. // A prefix operator expression.
  534. template <const NodeKind& KindT>
  535. struct PrefixOperator {
  536. static constexpr auto Kind = KindT.Define(NodeCategory::Expr);
  537. AnyExprId operand;
  538. };
  539. // An infix operator expression.
  540. template <const NodeKind& KindT>
  541. struct InfixOperator {
  542. static constexpr auto Kind = KindT.Define(NodeCategory::Expr);
  543. AnyExprId lhs;
  544. AnyExprId rhs;
  545. };
  546. // A postfix operator expression.
  547. template <const NodeKind& KindT>
  548. struct PostfixOperator {
  549. static constexpr auto Kind = KindT.Define(NodeCategory::Expr);
  550. AnyExprId operand;
  551. };
  552. // Literals, operators, and modifiers
  553. #define CARBON_PARSE_NODE_KIND(...)
  554. #define CARBON_PARSE_NODE_KIND_TOKEN_LITERAL(Name, ...) \
  555. using Name = LeafNode<NodeKind::Name, NodeCategory::Expr>;
  556. #define CARBON_PARSE_NODE_KIND_TOKEN_MODIFIER(Name, ...) \
  557. using Name##Modifier = \
  558. LeafNode<NodeKind::Name##Modifier, NodeCategory::Modifier>;
  559. #define CARBON_PARSE_NODE_KIND_PREFIX_OPERATOR(Name, ...) \
  560. using PrefixOperator##Name = PrefixOperator<NodeKind::PrefixOperator##Name>;
  561. #define CARBON_PARSE_NODE_KIND_INFIX_OPERATOR(Name, ...) \
  562. using InfixOperator##Name = InfixOperator<NodeKind::InfixOperator##Name>;
  563. #define CARBON_PARSE_NODE_KIND_POSTFIX_OPERATOR(Name, ...) \
  564. using PostfixOperator##Name = \
  565. PostfixOperator<NodeKind::PostfixOperator##Name>;
  566. #include "toolchain/parse/node_kind.def"
  567. // The first operand of a short-circuiting infix operator: `a and` or `a or`.
  568. // The complete operator expression will be an InfixOperator with this as the
  569. // `lhs`.
  570. // TODO: Make this be a template if we ever need to write generic code to cover
  571. // both cases at once, say in check.
  572. struct ShortCircuitOperandAnd {
  573. static constexpr auto Kind = NodeKind::ShortCircuitOperandAnd.Define();
  574. AnyExprId operand;
  575. };
  576. struct ShortCircuitOperandOr {
  577. static constexpr auto Kind = NodeKind::ShortCircuitOperandOr.Define();
  578. AnyExprId operand;
  579. };
  580. struct ShortCircuitOperatorAnd {
  581. static constexpr auto Kind =
  582. NodeKind::ShortCircuitOperatorAnd.Define(NodeCategory::Expr);
  583. ShortCircuitOperandAndId lhs;
  584. AnyExprId rhs;
  585. };
  586. struct ShortCircuitOperatorOr {
  587. static constexpr auto Kind =
  588. NodeKind::ShortCircuitOperatorOr.Define(NodeCategory::Expr);
  589. ShortCircuitOperandOrId lhs;
  590. AnyExprId rhs;
  591. };
  592. // The `if` portion of an `if` expression: `if expr`.
  593. struct IfExprIf {
  594. static constexpr auto Kind = NodeKind::IfExprIf.Define();
  595. AnyExprId condition;
  596. };
  597. // The `then` portion of an `if` expression: `then expr`.
  598. struct IfExprThen {
  599. static constexpr auto Kind = NodeKind::IfExprThen.Define();
  600. AnyExprId result;
  601. };
  602. // A full `if` expression: `if expr then expr else expr`.
  603. struct IfExprElse {
  604. static constexpr auto Kind = NodeKind::IfExprElse.Define(NodeCategory::Expr);
  605. IfExprIfId start;
  606. IfExprThenId then;
  607. AnyExprId else_result;
  608. };
  609. // Choice nodes
  610. // ------------
  611. using ChoiceIntroducer = LeafNode<NodeKind::ChoiceIntroducer>;
  612. struct ChoiceSignature {
  613. static constexpr auto Kind =
  614. NodeKind::ChoiceDefinitionStart.Define(NodeCategory::None);
  615. ChoiceIntroducerId introducer;
  616. llvm::SmallVector<AnyModifierId> modifiers;
  617. AnyNameComponentId name;
  618. std::optional<ImplicitParamListId> implicit_params;
  619. std::optional<TuplePatternId> params;
  620. };
  621. using ChoiceDefinitionStart = ChoiceSignature;
  622. using ChoiceAlternativeListComma =
  623. LeafNode<NodeKind::ChoiceAlternativeListComma>;
  624. struct ChoiceDefinition {
  625. static constexpr auto Kind =
  626. NodeKind::ChoiceDefinition.Define(NodeCategory::Decl);
  627. ChoiceDefinitionStartId signature;
  628. struct Alternative {
  629. IdentifierNameId name;
  630. std::optional<TuplePatternId> parameters;
  631. };
  632. CommaSeparatedList<Alternative, ChoiceAlternativeListCommaId> alternatives;
  633. };
  634. // Struct type and value literals
  635. // ----------------------------------------
  636. // `{`
  637. using StructLiteralStart = LeafNode<NodeKind::StructLiteralStart>;
  638. using StructTypeLiteralStart = LeafNode<NodeKind::StructTypeLiteralStart>;
  639. // `,`
  640. using StructComma = LeafNode<NodeKind::StructComma>;
  641. // `.a`
  642. struct StructFieldDesignator {
  643. static constexpr auto Kind = NodeKind::StructFieldDesignator.Define();
  644. NodeIdOneOf<IdentifierName, BaseName> name;
  645. };
  646. // `.a = 0`
  647. struct StructField {
  648. static constexpr auto Kind = NodeKind::StructField.Define();
  649. StructFieldDesignatorId designator;
  650. AnyExprId expr;
  651. };
  652. // `.a: i32`
  653. struct StructTypeField {
  654. static constexpr auto Kind = NodeKind::StructTypeField.Define();
  655. StructFieldDesignatorId designator;
  656. AnyExprId type_expr;
  657. };
  658. // Struct literals, such as `{.a = 0}`.
  659. struct StructLiteral {
  660. static constexpr auto Kind =
  661. NodeKind::StructLiteral.Define(NodeCategory::Expr);
  662. StructLiteralStartId start;
  663. CommaSeparatedList<StructFieldId, StructCommaId> fields;
  664. };
  665. // Struct type literals, such as `{.a: i32}`.
  666. struct StructTypeLiteral {
  667. static constexpr auto Kind =
  668. NodeKind::StructTypeLiteral.Define(NodeCategory::Expr);
  669. StructTypeLiteralStartId start;
  670. CommaSeparatedList<StructTypeFieldId, StructCommaId> fields;
  671. };
  672. // `class` declarations and definitions
  673. // ------------------------------------
  674. // `class`
  675. using ClassIntroducer = LeafNode<NodeKind::ClassIntroducer>;
  676. // A class signature `class C`
  677. template <const NodeKind& KindT, NodeCategory Category>
  678. struct ClassSignature {
  679. static constexpr auto Kind = KindT.Define(Category);
  680. ClassIntroducerId introducer;
  681. llvm::SmallVector<AnyModifierId> modifiers;
  682. AnyNameComponentId name;
  683. std::optional<ImplicitParamListId> implicit_params;
  684. std::optional<TuplePatternId> params;
  685. };
  686. // `class C;`
  687. using ClassDecl = ClassSignature<NodeKind::ClassDecl, NodeCategory::Decl>;
  688. // `class C {`
  689. using ClassDefinitionStart =
  690. ClassSignature<NodeKind::ClassDefinitionStart, NodeCategory::None>;
  691. // `class C { ... }`
  692. struct ClassDefinition {
  693. static constexpr auto Kind =
  694. NodeKind::ClassDefinition.Define(NodeCategory::Decl);
  695. ClassDefinitionStartId signature;
  696. llvm::SmallVector<AnyDeclId> members;
  697. };
  698. // Base class declaration
  699. // ----------------------
  700. // `base`
  701. using BaseIntroducer = LeafNode<NodeKind::BaseIntroducer>;
  702. using BaseColon = LeafNode<NodeKind::BaseColon>;
  703. // `extend base: BaseClass;`
  704. struct BaseDecl {
  705. static constexpr auto Kind = NodeKind::BaseDecl.Define(NodeCategory::Decl);
  706. BaseIntroducerId introducer;
  707. llvm::SmallVector<AnyModifierId> modifiers;
  708. BaseColonId colon;
  709. AnyExprId base_class;
  710. };
  711. // Interface declarations and definitions
  712. // --------------------------------------
  713. // `interface`
  714. using InterfaceIntroducer = LeafNode<NodeKind::InterfaceIntroducer>;
  715. // `interface I`
  716. template <const NodeKind& KindT, NodeCategory Category>
  717. struct InterfaceSignature {
  718. static constexpr auto Kind = KindT.Define(Category);
  719. InterfaceIntroducerId introducer;
  720. llvm::SmallVector<AnyModifierId> modifiers;
  721. AnyNameComponentId name;
  722. std::optional<ImplicitParamListId> implicit_params;
  723. std::optional<TuplePatternId> params;
  724. };
  725. // `interface I;`
  726. using InterfaceDecl =
  727. InterfaceSignature<NodeKind::InterfaceDecl, NodeCategory::Decl>;
  728. // `interface I {`
  729. using InterfaceDefinitionStart =
  730. InterfaceSignature<NodeKind::InterfaceDefinitionStart, NodeCategory::None>;
  731. // `interface I { ... }`
  732. struct InterfaceDefinition {
  733. static constexpr auto Kind =
  734. NodeKind::InterfaceDefinition.Define(NodeCategory::Decl);
  735. InterfaceDefinitionStartId signature;
  736. llvm::SmallVector<AnyDeclId> members;
  737. };
  738. // `impl`...`as` declarations and definitions
  739. // ------------------------------------------
  740. // `impl`
  741. using ImplIntroducer = LeafNode<NodeKind::ImplIntroducer>;
  742. // `forall [...]`
  743. struct ImplForall {
  744. static constexpr auto Kind = NodeKind::ImplForall.Define();
  745. ImplicitParamListId params;
  746. };
  747. // `as` with no type before it
  748. using DefaultSelfImplAs =
  749. LeafNode<NodeKind::DefaultSelfImplAs, NodeCategory::ImplAs>;
  750. // `<type> as`
  751. struct TypeImplAs {
  752. static constexpr auto Kind =
  753. NodeKind::TypeImplAs.Define(NodeCategory::ImplAs);
  754. AnyExprId type_expr;
  755. };
  756. // `impl T as I`
  757. template <const NodeKind& KindT, NodeCategory Category>
  758. struct ImplSignature {
  759. static constexpr auto Kind = KindT.Define(Category);
  760. ImplIntroducerId introducer;
  761. llvm::SmallVector<AnyModifierId> modifiers;
  762. std::optional<ImplForallId> forall;
  763. AnyImplAsId as;
  764. AnyExprId interface;
  765. };
  766. // `impl T as I;`
  767. using ImplDecl = ImplSignature<NodeKind::ImplDecl, NodeCategory::Decl>;
  768. // `impl T as I {`
  769. using ImplDefinitionStart =
  770. ImplSignature<NodeKind::ImplDefinitionStart, NodeCategory::None>;
  771. // `impl T as I { ... }`
  772. struct ImplDefinition {
  773. static constexpr auto Kind =
  774. NodeKind::ImplDefinition.Define(NodeCategory::Decl);
  775. ImplDefinitionStartId signature;
  776. llvm::SmallVector<AnyDeclId> members;
  777. };
  778. // Named constraint declarations and definitions
  779. // ---------------------------------------------
  780. // `constraint`
  781. using NamedConstraintIntroducer = LeafNode<NodeKind::NamedConstraintIntroducer>;
  782. // `constraint NC`
  783. template <const NodeKind& KindT, NodeCategory Category>
  784. struct NamedConstraintSignature {
  785. static constexpr auto Kind = KindT.Define(Category);
  786. NamedConstraintIntroducerId introducer;
  787. llvm::SmallVector<AnyModifierId> modifiers;
  788. AnyNameComponentId name;
  789. std::optional<ImplicitParamListId> implicit_params;
  790. std::optional<TuplePatternId> params;
  791. };
  792. // `constraint NC;`
  793. using NamedConstraintDecl =
  794. NamedConstraintSignature<NodeKind::NamedConstraintDecl, NodeCategory::Decl>;
  795. // `constraint NC {`
  796. using NamedConstraintDefinitionStart =
  797. NamedConstraintSignature<NodeKind::NamedConstraintDefinitionStart,
  798. NodeCategory::None>;
  799. // `constraint NC { ... }`
  800. struct NamedConstraintDefinition {
  801. static constexpr auto Kind =
  802. NodeKind::NamedConstraintDefinition.Define(NodeCategory::Decl);
  803. NamedConstraintDefinitionStartId signature;
  804. llvm::SmallVector<AnyDeclId> members;
  805. };
  806. // ---------------------------------------------------------------------------
  807. // A complete source file. Note that there is no corresponding parse node for
  808. // the file. The file is instead the complete contents of the parse tree.
  809. struct File {
  810. FileStartId start;
  811. llvm::SmallVector<AnyDeclId> decls;
  812. FileEndId end;
  813. };
  814. // Define `Foo` as the node type for the ID type `FooId`.
  815. #define CARBON_PARSE_NODE_KIND(KindName) \
  816. template <> \
  817. struct NodeForId<KindName##Id> { \
  818. using TypedNode = KindName; \
  819. };
  820. #include "toolchain/parse/node_kind.def"
  821. } // namespace Carbon::Parse
  822. #endif // CARBON_TOOLCHAIN_PARSE_TYPED_NODES_H_