typed_nodes.h 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084
  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, export
  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. // `library` in `package` or `import`.
  129. struct LibrarySpecifier {
  130. static constexpr auto Kind = NodeKind::LibrarySpecifier.Define();
  131. NodeIdOneOf<LibraryName, DefaultLibrary> name;
  132. };
  133. // First line of the file, such as:
  134. // `impl package MyPackage library "MyLibrary";`
  135. struct PackageDecl {
  136. static constexpr auto Kind = NodeKind::PackageDecl.Define(NodeCategory::Decl);
  137. PackageIntroducerId introducer;
  138. llvm::SmallVector<AnyModifierId> modifiers;
  139. std::optional<PackageNameId> name;
  140. std::optional<LibrarySpecifierId> library;
  141. };
  142. // `import TheirPackage library "TheirLibrary";`
  143. using ImportIntroducer = LeafNode<NodeKind::ImportIntroducer>;
  144. struct ImportDecl {
  145. static constexpr auto Kind = NodeKind::ImportDecl.Define(NodeCategory::Decl);
  146. ImportIntroducerId introducer;
  147. llvm::SmallVector<AnyModifierId> modifiers;
  148. std::optional<PackageNameId> name;
  149. std::optional<LibrarySpecifierId> library;
  150. };
  151. // `library` as declaration.
  152. using LibraryIntroducer = LeafNode<NodeKind::LibraryIntroducer>;
  153. struct LibraryDecl {
  154. static constexpr auto Kind = NodeKind::LibraryDecl.Define(NodeCategory::Decl);
  155. LibraryIntroducerId introducer;
  156. llvm::SmallVector<AnyModifierId> modifiers;
  157. NodeIdOneOf<LibraryName, DefaultLibrary> library_name;
  158. };
  159. // `export` as a declaration.
  160. using ExportIntroducer = LeafNode<NodeKind::ExportIntroducer>;
  161. struct ExportDecl {
  162. static constexpr auto Kind = NodeKind::ExportDecl.Define(NodeCategory::Decl);
  163. ExportIntroducerId introducer;
  164. llvm::SmallVector<AnyModifierId> modifiers;
  165. AnyNameComponentId name;
  166. };
  167. // Namespace nodes
  168. // ---------------
  169. using NamespaceStart = LeafNode<NodeKind::NamespaceStart>;
  170. // A namespace: `namespace N;`.
  171. struct Namespace {
  172. static constexpr auto Kind = NodeKind::Namespace.Define(NodeCategory::Decl);
  173. NamespaceStartId introducer;
  174. llvm::SmallVector<AnyModifierId> modifiers;
  175. AnyNameComponentId name;
  176. };
  177. // Pattern nodes
  178. // -------------
  179. // A pattern binding, such as `name: Type`.
  180. struct BindingPattern {
  181. static constexpr auto Kind =
  182. NodeKind::BindingPattern.Define(NodeCategory::Pattern);
  183. NodeIdOneOf<IdentifierName, SelfValueName> name;
  184. AnyExprId type;
  185. };
  186. // `name:! Type`
  187. struct CompileTimeBindingPattern {
  188. static constexpr auto Kind =
  189. NodeKind::CompileTimeBindingPattern.Define(NodeCategory::Pattern);
  190. NodeIdOneOf<IdentifierName, SelfValueName> name;
  191. AnyExprId type;
  192. };
  193. // An address-of binding: `addr self: Self*`.
  194. struct Addr {
  195. static constexpr auto Kind = NodeKind::Addr.Define(NodeCategory::Pattern);
  196. AnyPatternId inner;
  197. };
  198. // A template binding: `template T:! type`.
  199. struct Template {
  200. static constexpr auto Kind = NodeKind::Template.Define(NodeCategory::Pattern);
  201. // This is a CompileTimeBindingPatternId in any valid program.
  202. // TODO: Should the parser enforce that?
  203. AnyPatternId inner;
  204. };
  205. using TuplePatternStart = LeafNode<NodeKind::TuplePatternStart>;
  206. using PatternListComma = LeafNode<NodeKind::PatternListComma>;
  207. // A parameter list or tuple pattern: `(a: i32, b: i32)`.
  208. struct TuplePattern {
  209. static constexpr auto Kind =
  210. NodeKind::TuplePattern.Define(NodeCategory::Pattern);
  211. TuplePatternStartId left_paren;
  212. CommaSeparatedList<AnyPatternId, PatternListCommaId> params;
  213. };
  214. using ImplicitParamListStart = LeafNode<NodeKind::ImplicitParamListStart>;
  215. // An implicit parameter list: `[T:! type, self: Self]`.
  216. struct ImplicitParamList {
  217. static constexpr auto Kind = NodeKind::ImplicitParamList.Define();
  218. ImplicitParamListStartId left_square;
  219. CommaSeparatedList<AnyPatternId, PatternListCommaId> params;
  220. };
  221. // Function nodes
  222. // --------------
  223. using FunctionIntroducer = LeafNode<NodeKind::FunctionIntroducer>;
  224. // A return type: `-> i32`.
  225. struct ReturnType {
  226. static constexpr auto Kind = NodeKind::ReturnType.Define();
  227. AnyExprId type;
  228. };
  229. // A function signature: `fn F() -> i32`.
  230. template <const NodeKind& KindT, NodeCategory Category>
  231. struct FunctionSignature {
  232. static constexpr auto Kind = KindT.Define(Category);
  233. FunctionIntroducerId introducer;
  234. llvm::SmallVector<AnyModifierId> modifiers;
  235. // For now, this is either an IdentifierName or a QualifiedName.
  236. AnyNameComponentId name;
  237. std::optional<ImplicitParamListId> implicit_params;
  238. TuplePatternId params;
  239. std::optional<ReturnTypeId> return_type;
  240. };
  241. using FunctionDecl =
  242. FunctionSignature<NodeKind::FunctionDecl, NodeCategory::Decl>;
  243. using FunctionDefinitionStart =
  244. FunctionSignature<NodeKind::FunctionDefinitionStart, NodeCategory::None>;
  245. // A function definition: `fn F() -> i32 { ... }`.
  246. struct FunctionDefinition {
  247. static constexpr auto Kind =
  248. NodeKind::FunctionDefinition.Define(NodeCategory::Decl);
  249. FunctionDefinitionStartId signature;
  250. llvm::SmallVector<AnyStatementId> body;
  251. };
  252. using BuiltinFunctionDefinitionStart =
  253. FunctionSignature<NodeKind::BuiltinFunctionDefinitionStart,
  254. NodeCategory::None>;
  255. using BuiltinName = LeafNode<NodeKind::BuiltinName>;
  256. // A builtin function definition: `fn F() -> i32 = "builtin name";`
  257. struct BuiltinFunctionDefinition {
  258. static constexpr auto Kind =
  259. NodeKind::BuiltinFunctionDefinition.Define(NodeCategory::Decl);
  260. BuiltinFunctionDefinitionStartId signature;
  261. BuiltinNameId builtin_name;
  262. };
  263. // `alias` nodes
  264. // -------------
  265. using AliasIntroducer = LeafNode<NodeKind::AliasIntroducer>;
  266. using AliasInitializer = LeafNode<NodeKind::AliasInitializer>;
  267. // An `alias` declaration: `alias a = b;`.
  268. struct Alias {
  269. static constexpr auto Kind =
  270. NodeKind::Alias.Define(NodeCategory::Decl | NodeCategory::Statement);
  271. AliasIntroducerId introducer;
  272. llvm::SmallVector<AnyModifierId> modifiers;
  273. // For now, this is either an IdentifierName or a QualifiedName.
  274. AnyNameComponentId name;
  275. AliasInitializerId equals;
  276. AnyExprId initializer;
  277. };
  278. // `let` nodes
  279. // -----------
  280. using LetIntroducer = LeafNode<NodeKind::LetIntroducer>;
  281. using LetInitializer = LeafNode<NodeKind::LetInitializer>;
  282. // A `let` declaration: `let a: i32 = 5;`.
  283. struct LetDecl {
  284. static constexpr auto Kind =
  285. NodeKind::LetDecl.Define(NodeCategory::Decl | NodeCategory::Statement);
  286. LetIntroducerId introducer;
  287. llvm::SmallVector<AnyModifierId> modifiers;
  288. AnyPatternId pattern;
  289. struct Initializer {
  290. LetInitializerId equals;
  291. AnyExprId initializer;
  292. };
  293. std::optional<Initializer> initializer;
  294. };
  295. // `var` nodes
  296. // -----------
  297. using VariableIntroducer = LeafNode<NodeKind::VariableIntroducer>;
  298. using ReturnedModifier = LeafNode<NodeKind::ReturnedModifier>;
  299. using VariableInitializer = LeafNode<NodeKind::VariableInitializer>;
  300. // A `var` declaration: `var a: i32;` or `var a: i32 = 5;`.
  301. struct VariableDecl {
  302. static constexpr auto Kind = NodeKind::VariableDecl.Define(
  303. NodeCategory::Decl | NodeCategory::Statement);
  304. VariableIntroducerId introducer;
  305. llvm::SmallVector<AnyModifierId> modifiers;
  306. std::optional<ReturnedModifierId> returned;
  307. AnyPatternId pattern;
  308. struct Initializer {
  309. VariableInitializerId equals;
  310. AnyExprId value;
  311. };
  312. std::optional<Initializer> initializer;
  313. };
  314. // Statement nodes
  315. // ---------------
  316. using CodeBlockStart = LeafNode<NodeKind::CodeBlockStart>;
  317. // A code block: `{ statement; statement; ... }`.
  318. struct CodeBlock {
  319. static constexpr auto Kind = NodeKind::CodeBlock.Define();
  320. CodeBlockStartId left_brace;
  321. llvm::SmallVector<AnyStatementId> statements;
  322. };
  323. // An expression statement: `F(x);`.
  324. struct ExprStatement {
  325. static constexpr auto Kind =
  326. NodeKind::ExprStatement.Define(NodeCategory::Statement);
  327. AnyExprId expr;
  328. };
  329. using BreakStatementStart = LeafNode<NodeKind::BreakStatementStart>;
  330. // A break statement: `break;`.
  331. struct BreakStatement {
  332. static constexpr auto Kind =
  333. NodeKind::BreakStatement.Define(NodeCategory::Statement);
  334. BreakStatementStartId introducer;
  335. };
  336. using ContinueStatementStart = LeafNode<NodeKind::ContinueStatementStart>;
  337. // A continue statement: `continue;`.
  338. struct ContinueStatement {
  339. static constexpr auto Kind =
  340. NodeKind::ContinueStatement.Define(NodeCategory::Statement);
  341. ContinueStatementStartId introducer;
  342. };
  343. using ReturnStatementStart = LeafNode<NodeKind::ReturnStatementStart>;
  344. using ReturnVarModifier = LeafNode<NodeKind::ReturnVarModifier>;
  345. // A return statement: `return;` or `return expr;` or `return var;`.
  346. struct ReturnStatement {
  347. static constexpr auto Kind =
  348. NodeKind::ReturnStatement.Define(NodeCategory::Statement);
  349. ReturnStatementStartId introducer;
  350. std::optional<AnyExprId> expr;
  351. std::optional<ReturnVarModifierId> var;
  352. };
  353. using ForHeaderStart = LeafNode<NodeKind::ForHeaderStart>;
  354. // The `var ... in` portion of a `for` statement.
  355. struct ForIn {
  356. static constexpr auto Kind = NodeKind::ForIn.Define();
  357. VariableIntroducerId introducer;
  358. AnyPatternId pattern;
  359. };
  360. // The `for (var ... in ...)` portion of a `for` statement.
  361. struct ForHeader {
  362. static constexpr auto Kind = NodeKind::ForHeader.Define();
  363. ForHeaderStartId introducer;
  364. ForInId var;
  365. AnyExprId range;
  366. };
  367. // A complete `for (...) { ... }` statement.
  368. struct ForStatement {
  369. static constexpr auto Kind =
  370. NodeKind::ForStatement.Define(NodeCategory::Statement);
  371. ForHeaderId header;
  372. CodeBlockId body;
  373. };
  374. using IfConditionStart = LeafNode<NodeKind::IfConditionStart>;
  375. // The condition portion of an `if` statement: `(expr)`.
  376. struct IfCondition {
  377. static constexpr auto Kind = NodeKind::IfCondition.Define();
  378. IfConditionStartId left_paren;
  379. AnyExprId condition;
  380. };
  381. using IfStatementElse = LeafNode<NodeKind::IfStatementElse>;
  382. // An `if` statement: `if (expr) { ... } else { ... }`.
  383. struct IfStatement {
  384. static constexpr auto Kind =
  385. NodeKind::IfStatement.Define(NodeCategory::Statement);
  386. IfConditionId head;
  387. CodeBlockId then;
  388. struct Else {
  389. IfStatementElseId else_token;
  390. NodeIdOneOf<CodeBlock, IfStatement> body;
  391. };
  392. std::optional<Else> else_clause;
  393. };
  394. using WhileConditionStart = LeafNode<NodeKind::WhileConditionStart>;
  395. // The condition portion of a `while` statement: `(expr)`.
  396. struct WhileCondition {
  397. static constexpr auto Kind = NodeKind::WhileCondition.Define();
  398. WhileConditionStartId left_paren;
  399. AnyExprId condition;
  400. };
  401. // A `while` statement: `while (expr) { ... }`.
  402. struct WhileStatement {
  403. static constexpr auto Kind =
  404. NodeKind::WhileStatement.Define(NodeCategory::Statement);
  405. WhileConditionId head;
  406. CodeBlockId body;
  407. };
  408. using MatchConditionStart = LeafNode<NodeKind::MatchConditionStart>;
  409. struct MatchCondition {
  410. static constexpr auto Kind = NodeKind::MatchCondition.Define();
  411. MatchConditionStartId left_paren;
  412. AnyExprId condition;
  413. };
  414. using MatchIntroducer = LeafNode<NodeKind::MatchIntroducer>;
  415. struct MatchStatementStart {
  416. static constexpr auto Kind = NodeKind::MatchStatementStart.Define();
  417. MatchIntroducerId introducer;
  418. MatchConditionId left_brace;
  419. };
  420. using MatchCaseIntroducer = LeafNode<NodeKind::MatchCaseIntroducer>;
  421. using MatchCaseGuardIntroducer = LeafNode<NodeKind::MatchCaseGuardIntroducer>;
  422. using MatchCaseGuardStart = LeafNode<NodeKind::MatchCaseGuardStart>;
  423. struct MatchCaseGuard {
  424. static constexpr auto Kind = NodeKind::MatchCaseGuard.Define();
  425. MatchCaseGuardIntroducerId introducer;
  426. MatchCaseGuardStartId left_paren;
  427. AnyExprId condition;
  428. };
  429. using MatchCaseEqualGreater = LeafNode<NodeKind::MatchCaseEqualGreater>;
  430. struct MatchCaseStart {
  431. static constexpr auto Kind = NodeKind::MatchCaseStart.Define();
  432. MatchCaseIntroducerId introducer;
  433. AnyPatternId pattern;
  434. std::optional<MatchCaseGuardId> guard;
  435. MatchCaseEqualGreaterId equal_greater_token;
  436. };
  437. struct MatchCase {
  438. static constexpr auto Kind = NodeKind::MatchCase.Define();
  439. MatchCaseStartId head;
  440. llvm::SmallVector<AnyStatementId> statements;
  441. };
  442. using MatchDefaultIntroducer = LeafNode<NodeKind::MatchDefaultIntroducer>;
  443. using MatchDefaultEqualGreater = LeafNode<NodeKind::MatchDefaultEqualGreater>;
  444. struct MatchDefaultStart {
  445. static constexpr auto Kind = NodeKind::MatchDefaultStart.Define();
  446. MatchDefaultIntroducerId introducer;
  447. MatchDefaultEqualGreaterId equal_greater_token;
  448. };
  449. struct MatchDefault {
  450. static constexpr auto Kind = NodeKind::MatchDefault.Define();
  451. MatchDefaultStartId introducer;
  452. llvm::SmallVector<AnyStatementId> statements;
  453. };
  454. // A `match` statement: `match (expr) { case (...) => {...} default => {...}}`.
  455. struct MatchStatement {
  456. static constexpr auto Kind =
  457. NodeKind::MatchStatement.Define(NodeCategory::Statement);
  458. MatchStatementStartId head;
  459. llvm::SmallVector<MatchCaseId> cases;
  460. std::optional<MatchDefaultId> default_case;
  461. };
  462. // Expression nodes
  463. // ----------------
  464. using ArrayExprStart = LeafNode<NodeKind::ArrayExprStart>;
  465. // The start of an array type, `[i32;`.
  466. //
  467. // TODO: Consider flattening this into `ArrayExpr`.
  468. struct ArrayExprSemi {
  469. static constexpr auto Kind = NodeKind::ArrayExprSemi.Define();
  470. ArrayExprStartId left_square;
  471. AnyExprId type;
  472. };
  473. // An array type, such as `[i32; 3]` or `[i32;]`.
  474. struct ArrayExpr {
  475. static constexpr auto Kind = NodeKind::ArrayExpr.Define(NodeCategory::Expr);
  476. ArrayExprSemiId start;
  477. std::optional<AnyExprId> bound;
  478. };
  479. // The opening portion of an indexing expression: `a[`.
  480. //
  481. // TODO: Consider flattening this into `IndexExpr`.
  482. struct IndexExprStart {
  483. static constexpr auto Kind = NodeKind::IndexExprStart.Define();
  484. AnyExprId sequence;
  485. };
  486. // An indexing expression, such as `a[1]`.
  487. struct IndexExpr {
  488. static constexpr auto Kind = NodeKind::IndexExpr.Define(NodeCategory::Expr);
  489. IndexExprStartId start;
  490. AnyExprId index;
  491. };
  492. using ParenExprStart = LeafNode<NodeKind::ParenExprStart>;
  493. // A parenthesized expression: `(a)`.
  494. struct ParenExpr {
  495. static constexpr auto Kind =
  496. NodeKind::ParenExpr.Define(NodeCategory::Expr | NodeCategory::MemberExpr);
  497. ParenExprStartId start;
  498. AnyExprId expr;
  499. };
  500. using TupleLiteralStart = LeafNode<NodeKind::TupleLiteralStart>;
  501. using TupleLiteralComma = LeafNode<NodeKind::TupleLiteralComma>;
  502. // A tuple literal: `()`, `(a, b, c)`, or `(a,)`.
  503. struct TupleLiteral {
  504. static constexpr auto Kind =
  505. NodeKind::TupleLiteral.Define(NodeCategory::Expr);
  506. TupleLiteralStartId start;
  507. CommaSeparatedList<AnyExprId, TupleLiteralCommaId> elements;
  508. };
  509. // The opening portion of a call expression: `F(`.
  510. //
  511. // TODO: Consider flattening this into `CallExpr`.
  512. struct CallExprStart {
  513. static constexpr auto Kind = NodeKind::CallExprStart.Define();
  514. AnyExprId callee;
  515. };
  516. using CallExprComma = LeafNode<NodeKind::CallExprComma>;
  517. // A call expression: `F(a, b, c)`.
  518. struct CallExpr {
  519. static constexpr auto Kind = NodeKind::CallExpr.Define(NodeCategory::Expr);
  520. CallExprStartId start;
  521. CommaSeparatedList<AnyExprId, CallExprCommaId> arguments;
  522. };
  523. // A member access expression: `a.b` or `a.(b)`.
  524. struct MemberAccessExpr {
  525. static constexpr auto Kind =
  526. NodeKind::MemberAccessExpr.Define(NodeCategory::Expr);
  527. AnyExprId lhs;
  528. AnyMemberNameOrMemberExprId rhs;
  529. };
  530. // An indirect member access expression: `a->b` or `a->(b)`.
  531. struct PointerMemberAccessExpr {
  532. static constexpr auto Kind =
  533. NodeKind::PointerMemberAccessExpr.Define(NodeCategory::Expr);
  534. AnyExprId lhs;
  535. AnyMemberNameOrMemberExprId rhs;
  536. };
  537. // A prefix operator expression.
  538. template <const NodeKind& KindT>
  539. struct PrefixOperator {
  540. static constexpr auto Kind = KindT.Define(NodeCategory::Expr);
  541. AnyExprId operand;
  542. };
  543. // An infix operator expression.
  544. template <const NodeKind& KindT>
  545. struct InfixOperator {
  546. static constexpr auto Kind = KindT.Define(NodeCategory::Expr);
  547. AnyExprId lhs;
  548. AnyExprId rhs;
  549. };
  550. // A postfix operator expression.
  551. template <const NodeKind& KindT>
  552. struct PostfixOperator {
  553. static constexpr auto Kind = KindT.Define(NodeCategory::Expr);
  554. AnyExprId operand;
  555. };
  556. // Literals, operators, and modifiers
  557. #define CARBON_PARSE_NODE_KIND(...)
  558. #define CARBON_PARSE_NODE_KIND_TOKEN_LITERAL(Name, ...) \
  559. using Name = LeafNode<NodeKind::Name, NodeCategory::Expr>;
  560. #define CARBON_PARSE_NODE_KIND_TOKEN_MODIFIER(Name, ...) \
  561. using Name##Modifier = \
  562. LeafNode<NodeKind::Name##Modifier, NodeCategory::Modifier>;
  563. #define CARBON_PARSE_NODE_KIND_PREFIX_OPERATOR(Name, ...) \
  564. using PrefixOperator##Name = PrefixOperator<NodeKind::PrefixOperator##Name>;
  565. #define CARBON_PARSE_NODE_KIND_INFIX_OPERATOR(Name, ...) \
  566. using InfixOperator##Name = InfixOperator<NodeKind::InfixOperator##Name>;
  567. #define CARBON_PARSE_NODE_KIND_POSTFIX_OPERATOR(Name, ...) \
  568. using PostfixOperator##Name = \
  569. PostfixOperator<NodeKind::PostfixOperator##Name>;
  570. #include "toolchain/parse/node_kind.def"
  571. // The first operand of a short-circuiting infix operator: `a and` or `a or`.
  572. // The complete operator expression will be an InfixOperator with this as the
  573. // `lhs`.
  574. // TODO: Make this be a template if we ever need to write generic code to cover
  575. // both cases at once, say in check.
  576. struct ShortCircuitOperandAnd {
  577. static constexpr auto Kind = NodeKind::ShortCircuitOperandAnd.Define();
  578. AnyExprId operand;
  579. };
  580. struct ShortCircuitOperandOr {
  581. static constexpr auto Kind = NodeKind::ShortCircuitOperandOr.Define();
  582. AnyExprId operand;
  583. };
  584. struct ShortCircuitOperatorAnd {
  585. static constexpr auto Kind =
  586. NodeKind::ShortCircuitOperatorAnd.Define(NodeCategory::Expr);
  587. ShortCircuitOperandAndId lhs;
  588. AnyExprId rhs;
  589. };
  590. struct ShortCircuitOperatorOr {
  591. static constexpr auto Kind =
  592. NodeKind::ShortCircuitOperatorOr.Define(NodeCategory::Expr);
  593. ShortCircuitOperandOrId lhs;
  594. AnyExprId rhs;
  595. };
  596. // The `if` portion of an `if` expression: `if expr`.
  597. struct IfExprIf {
  598. static constexpr auto Kind = NodeKind::IfExprIf.Define();
  599. AnyExprId condition;
  600. };
  601. // The `then` portion of an `if` expression: `then expr`.
  602. struct IfExprThen {
  603. static constexpr auto Kind = NodeKind::IfExprThen.Define();
  604. AnyExprId result;
  605. };
  606. // A full `if` expression: `if expr then expr else expr`.
  607. struct IfExprElse {
  608. static constexpr auto Kind = NodeKind::IfExprElse.Define(NodeCategory::Expr);
  609. IfExprIfId start;
  610. IfExprThenId then;
  611. AnyExprId else_result;
  612. };
  613. // Choice nodes
  614. // ------------
  615. using ChoiceIntroducer = LeafNode<NodeKind::ChoiceIntroducer>;
  616. struct ChoiceSignature {
  617. static constexpr auto Kind =
  618. NodeKind::ChoiceDefinitionStart.Define(NodeCategory::None);
  619. ChoiceIntroducerId introducer;
  620. llvm::SmallVector<AnyModifierId> modifiers;
  621. AnyNameComponentId name;
  622. std::optional<ImplicitParamListId> implicit_params;
  623. std::optional<TuplePatternId> params;
  624. };
  625. using ChoiceDefinitionStart = ChoiceSignature;
  626. using ChoiceAlternativeListComma =
  627. LeafNode<NodeKind::ChoiceAlternativeListComma>;
  628. struct ChoiceDefinition {
  629. static constexpr auto Kind =
  630. NodeKind::ChoiceDefinition.Define(NodeCategory::Decl);
  631. ChoiceDefinitionStartId signature;
  632. struct Alternative {
  633. IdentifierNameId name;
  634. std::optional<TuplePatternId> parameters;
  635. };
  636. CommaSeparatedList<Alternative, ChoiceAlternativeListCommaId> alternatives;
  637. };
  638. // Struct type and value literals
  639. // ----------------------------------------
  640. // `{`
  641. using StructLiteralStart = LeafNode<NodeKind::StructLiteralStart>;
  642. using StructTypeLiteralStart = LeafNode<NodeKind::StructTypeLiteralStart>;
  643. // `,`
  644. using StructComma = LeafNode<NodeKind::StructComma>;
  645. // `.a`
  646. struct StructFieldDesignator {
  647. static constexpr auto Kind = NodeKind::StructFieldDesignator.Define();
  648. NodeIdOneOf<IdentifierName, BaseName> name;
  649. };
  650. // `.a = 0`
  651. struct StructField {
  652. static constexpr auto Kind = NodeKind::StructField.Define();
  653. StructFieldDesignatorId designator;
  654. AnyExprId expr;
  655. };
  656. // `.a: i32`
  657. struct StructTypeField {
  658. static constexpr auto Kind = NodeKind::StructTypeField.Define();
  659. StructFieldDesignatorId designator;
  660. AnyExprId type_expr;
  661. };
  662. // Struct literals, such as `{.a = 0}`.
  663. struct StructLiteral {
  664. static constexpr auto Kind =
  665. NodeKind::StructLiteral.Define(NodeCategory::Expr);
  666. StructLiteralStartId start;
  667. CommaSeparatedList<StructFieldId, StructCommaId> fields;
  668. };
  669. // Struct type literals, such as `{.a: i32}`.
  670. struct StructTypeLiteral {
  671. static constexpr auto Kind =
  672. NodeKind::StructTypeLiteral.Define(NodeCategory::Expr);
  673. StructTypeLiteralStartId start;
  674. CommaSeparatedList<StructTypeFieldId, StructCommaId> fields;
  675. };
  676. // `class` declarations and definitions
  677. // ------------------------------------
  678. // `class`
  679. using ClassIntroducer = LeafNode<NodeKind::ClassIntroducer>;
  680. // A class signature `class C`
  681. template <const NodeKind& KindT, NodeCategory Category>
  682. struct ClassSignature {
  683. static constexpr auto Kind = KindT.Define(Category);
  684. ClassIntroducerId introducer;
  685. llvm::SmallVector<AnyModifierId> modifiers;
  686. AnyNameComponentId name;
  687. std::optional<ImplicitParamListId> implicit_params;
  688. std::optional<TuplePatternId> params;
  689. };
  690. // `class C;`
  691. using ClassDecl = ClassSignature<NodeKind::ClassDecl, NodeCategory::Decl>;
  692. // `class C {`
  693. using ClassDefinitionStart =
  694. ClassSignature<NodeKind::ClassDefinitionStart, NodeCategory::None>;
  695. // `class C { ... }`
  696. struct ClassDefinition {
  697. static constexpr auto Kind =
  698. NodeKind::ClassDefinition.Define(NodeCategory::Decl);
  699. ClassDefinitionStartId signature;
  700. llvm::SmallVector<AnyDeclId> members;
  701. };
  702. // Adapter declaration
  703. // -------------------
  704. // `adapt`
  705. using AdaptIntroducer = LeafNode<NodeKind::AdaptIntroducer>;
  706. // `adapt SomeType;`
  707. struct AdaptDecl {
  708. static constexpr auto Kind = NodeKind::AdaptDecl.Define(NodeCategory::Decl);
  709. AdaptIntroducerId introducer;
  710. llvm::SmallVector<AnyModifierId> modifiers;
  711. AnyExprId adapted_type;
  712. };
  713. // Base class declaration
  714. // ----------------------
  715. // `base`
  716. using BaseIntroducer = LeafNode<NodeKind::BaseIntroducer>;
  717. using BaseColon = LeafNode<NodeKind::BaseColon>;
  718. // `extend base: BaseClass;`
  719. struct BaseDecl {
  720. static constexpr auto Kind = NodeKind::BaseDecl.Define(NodeCategory::Decl);
  721. BaseIntroducerId introducer;
  722. llvm::SmallVector<AnyModifierId> modifiers;
  723. BaseColonId colon;
  724. AnyExprId base_class;
  725. };
  726. // Interface declarations and definitions
  727. // --------------------------------------
  728. // `interface`
  729. using InterfaceIntroducer = LeafNode<NodeKind::InterfaceIntroducer>;
  730. // `interface I`
  731. template <const NodeKind& KindT, NodeCategory Category>
  732. struct InterfaceSignature {
  733. static constexpr auto Kind = KindT.Define(Category);
  734. InterfaceIntroducerId introducer;
  735. llvm::SmallVector<AnyModifierId> modifiers;
  736. AnyNameComponentId name;
  737. std::optional<ImplicitParamListId> implicit_params;
  738. std::optional<TuplePatternId> params;
  739. };
  740. // `interface I;`
  741. using InterfaceDecl =
  742. InterfaceSignature<NodeKind::InterfaceDecl, NodeCategory::Decl>;
  743. // `interface I {`
  744. using InterfaceDefinitionStart =
  745. InterfaceSignature<NodeKind::InterfaceDefinitionStart, NodeCategory::None>;
  746. // `interface I { ... }`
  747. struct InterfaceDefinition {
  748. static constexpr auto Kind =
  749. NodeKind::InterfaceDefinition.Define(NodeCategory::Decl);
  750. InterfaceDefinitionStartId signature;
  751. llvm::SmallVector<AnyDeclId> members;
  752. };
  753. // `impl`...`as` declarations and definitions
  754. // ------------------------------------------
  755. // `impl`
  756. using ImplIntroducer = LeafNode<NodeKind::ImplIntroducer>;
  757. // `forall [...]`
  758. struct ImplForall {
  759. static constexpr auto Kind = NodeKind::ImplForall.Define();
  760. ImplicitParamListId params;
  761. };
  762. // `as` with no type before it
  763. using DefaultSelfImplAs =
  764. LeafNode<NodeKind::DefaultSelfImplAs, NodeCategory::ImplAs>;
  765. // `<type> as`
  766. struct TypeImplAs {
  767. static constexpr auto Kind =
  768. NodeKind::TypeImplAs.Define(NodeCategory::ImplAs);
  769. AnyExprId type_expr;
  770. };
  771. // `impl T as I`
  772. template <const NodeKind& KindT, NodeCategory Category>
  773. struct ImplSignature {
  774. static constexpr auto Kind = KindT.Define(Category);
  775. ImplIntroducerId introducer;
  776. llvm::SmallVector<AnyModifierId> modifiers;
  777. std::optional<ImplForallId> forall;
  778. AnyImplAsId as;
  779. AnyExprId interface;
  780. };
  781. // `impl T as I;`
  782. using ImplDecl = ImplSignature<NodeKind::ImplDecl, NodeCategory::Decl>;
  783. // `impl T as I {`
  784. using ImplDefinitionStart =
  785. ImplSignature<NodeKind::ImplDefinitionStart, NodeCategory::None>;
  786. // `impl T as I { ... }`
  787. struct ImplDefinition {
  788. static constexpr auto Kind =
  789. NodeKind::ImplDefinition.Define(NodeCategory::Decl);
  790. ImplDefinitionStartId signature;
  791. llvm::SmallVector<AnyDeclId> members;
  792. };
  793. // Named constraint declarations and definitions
  794. // ---------------------------------------------
  795. // `constraint`
  796. using NamedConstraintIntroducer = LeafNode<NodeKind::NamedConstraintIntroducer>;
  797. // `constraint NC`
  798. template <const NodeKind& KindT, NodeCategory Category>
  799. struct NamedConstraintSignature {
  800. static constexpr auto Kind = KindT.Define(Category);
  801. NamedConstraintIntroducerId introducer;
  802. llvm::SmallVector<AnyModifierId> modifiers;
  803. AnyNameComponentId name;
  804. std::optional<ImplicitParamListId> implicit_params;
  805. std::optional<TuplePatternId> params;
  806. };
  807. // `constraint NC;`
  808. using NamedConstraintDecl =
  809. NamedConstraintSignature<NodeKind::NamedConstraintDecl, NodeCategory::Decl>;
  810. // `constraint NC {`
  811. using NamedConstraintDefinitionStart =
  812. NamedConstraintSignature<NodeKind::NamedConstraintDefinitionStart,
  813. NodeCategory::None>;
  814. // `constraint NC { ... }`
  815. struct NamedConstraintDefinition {
  816. static constexpr auto Kind =
  817. NodeKind::NamedConstraintDefinition.Define(NodeCategory::Decl);
  818. NamedConstraintDefinitionStartId signature;
  819. llvm::SmallVector<AnyDeclId> members;
  820. };
  821. // ---------------------------------------------------------------------------
  822. // A complete source file. Note that there is no corresponding parse node for
  823. // the file. The file is instead the complete contents of the parse tree.
  824. struct File {
  825. FileStartId start;
  826. llvm::SmallVector<AnyDeclId> decls;
  827. FileEndId end;
  828. };
  829. // Define `Foo` as the node type for the ID type `FooId`.
  830. #define CARBON_PARSE_NODE_KIND(KindName) \
  831. template <> \
  832. struct NodeForId<KindName##Id> { \
  833. using TypedNode = KindName; \
  834. };
  835. #include "toolchain/parse/node_kind.def"
  836. } // namespace Carbon::Parse
  837. #endif // CARBON_TOOLCHAIN_PARSE_TYPED_NODES_H_