typed_nodes.h 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459
  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/lex/token_index.h"
  8. #include "toolchain/parse/node_ids.h"
  9. #include "toolchain/parse/node_kind.h"
  10. namespace Carbon::Parse {
  11. // Helpers for defining different kinds of parse nodes.
  12. // ----------------------------------------------------
  13. // A pair of a list item and its optional following comma.
  14. template <typename Element, typename Comma>
  15. struct ListItem {
  16. Element value;
  17. std::optional<Comma> comma;
  18. };
  19. // A list of items, parameterized by the kind of the elements and comma.
  20. template <typename Element, typename Comma>
  21. using CommaSeparatedList = llvm::SmallVector<ListItem<Element, Comma>>;
  22. // This class provides a shorthand for defining parse node kinds for leaf nodes.
  23. template <const NodeKind& KindT, typename TokenKind,
  24. NodeCategory::RawEnumType Category = NodeCategory::None>
  25. struct LeafNode {
  26. static constexpr auto Kind =
  27. KindT.Define({.category = Category, .child_count = 0});
  28. TokenKind token;
  29. };
  30. // ----------------------------------------------------------------------------
  31. // Each node kind (in node_kind.def) should have a corresponding type defined
  32. // here which describes the expected child structure of that parse node.
  33. //
  34. // Each of these types should start with a `static constexpr Kind` member
  35. // initialized by calling `Define` on the corresponding `NodeKind`, and passing
  36. // in the `NodeCategory` of that kind. This will both associate the category
  37. // with the node kind and create the necessary kind object for the typed node.
  38. //
  39. // This should be followed by field declarations that describe the child nodes,
  40. // in order, that occur in the parse tree. The `Extract...` functions on the
  41. // parse tree use struct reflection on these fields to guide the extraction of
  42. // the child nodes from the tree into an object of this type with these fields
  43. // for convenient access.
  44. //
  45. // The types of these fields are special and describe the specific child node
  46. // structure of the parse node. Many of these types are defined in `node_ids.h`.
  47. //
  48. // Valid primitive types here are:
  49. // - `NodeId` to match any single child node
  50. // - `FooId` to require that child to have kind `NodeKind::Foo`
  51. // - `AnyCatId` to require that child to have a kind in category `Cat`
  52. // - `NodeIdOneOf<A, B>` to require the child to have kind `NodeKind::A` or
  53. // `NodeKind::B`
  54. // - `NodeIdNot<A>` to match any single child whose kind is not `NodeKind::A`
  55. //
  56. // There a few, restricted composite field types allowed that compose types in
  57. // various ways, where all of the `T`s and `U`s below are themselves valid field
  58. // types:
  59. // - `llvm::SmallVector<T>` to match any number of children matching `T`
  60. // - `std::optional<T>` to match 0 or 1 children matching `T`
  61. // - `std::tuple<T...>` to match children matching `T...`
  62. // - Any provided `Aggregate` type that is a simple aggregate type such as
  63. // `struct Aggregate { T x; U y; }`,
  64. // to match children with types `T` and `U`.
  65. //
  66. // In addition to the fields describing the child nodes, each parse node should
  67. // also have exactly one field that describes the token corresponding to the
  68. // parse node itself. This field should have the name `token`. The type of the
  69. // field should be `Lex::*TokenIndex`, describing the kind of the token, such as
  70. // `Lex::SemiTokenIndex` for a `;` token. If the parse node can correspond to
  71. // any kind of token, `Lex::TokenIndex` can be used instead, but should only be
  72. // used when the node kind is either not used in a finished tree, such as
  73. // `Placeholder`, or is always invalid, such as `InvalidParse`. The location of
  74. // the field relative to the child nodes indicates the location within the
  75. // corresponding grammar production where the token appears.
  76. // ----------------------------------------------------------------------------
  77. // Error nodes
  78. // -----------
  79. // An invalid parse. Used to balance the parse tree. This type is here only to
  80. // ensure we have a type for each parse node kind. This node kind always has an
  81. // error, so can never be extracted.
  82. using InvalidParse = LeafNode<NodeKind::InvalidParse, Lex::TokenIndex,
  83. NodeCategory::Decl | NodeCategory::Expr>;
  84. // An invalid subtree. Always has an error so can never be extracted.
  85. using InvalidParseStart =
  86. LeafNode<NodeKind::InvalidParseStart, Lex::TokenIndex>;
  87. struct InvalidParseSubtree {
  88. static constexpr auto Kind = NodeKind::InvalidParseSubtree.Define(
  89. {.category = NodeCategory::Decl,
  90. .bracketed_by = InvalidParseStart::Kind});
  91. InvalidParseStartId start;
  92. llvm::SmallVector<NodeIdNot<InvalidParseStart>> extra;
  93. Lex::TokenIndex token;
  94. };
  95. // A placeholder node to be replaced; it will never exist in a valid parse tree.
  96. // Its token kind is not enforced even when valid.
  97. using Placeholder = LeafNode<NodeKind::Placeholder, Lex::TokenIndex>;
  98. // File nodes
  99. // ----------
  100. // The start of the file.
  101. using FileStart = LeafNode<NodeKind::FileStart, Lex::FileStartTokenIndex>;
  102. // The end of the file.
  103. using FileEnd = LeafNode<NodeKind::FileEnd, Lex::FileEndTokenIndex>;
  104. // General-purpose nodes
  105. // ---------------------
  106. // An empty declaration, such as `;`.
  107. using EmptyDecl =
  108. LeafNode<NodeKind::EmptyDecl, Lex::SemiTokenIndex, NodeCategory::Decl>;
  109. // A name in a non-expression context, such as a declaration, that is known
  110. // to be followed by parameters.
  111. using IdentifierNameBeforeParams =
  112. LeafNode<NodeKind::IdentifierNameBeforeParams, Lex::IdentifierTokenIndex,
  113. NodeCategory::MemberName | NodeCategory::NonExprIdentifierName>;
  114. // A name in a non-expression context, such as a declaration, that is known
  115. // to not be followed by parameters.
  116. using IdentifierNameNotBeforeParams =
  117. LeafNode<NodeKind::IdentifierNameNotBeforeParams, Lex::IdentifierTokenIndex,
  118. NodeCategory::MemberName | NodeCategory::NonExprIdentifierName>;
  119. // A name in an expression context.
  120. using IdentifierNameExpr =
  121. LeafNode<NodeKind::IdentifierNameExpr, Lex::IdentifierTokenIndex,
  122. NodeCategory::Expr>;
  123. // The `self` value and `Self` type identifier keywords. Typically of the form
  124. // `self: Self`.
  125. using SelfValueName =
  126. LeafNode<NodeKind::SelfValueName, Lex::SelfValueIdentifierTokenIndex>;
  127. using SelfValueNameExpr =
  128. LeafNode<NodeKind::SelfValueNameExpr, Lex::SelfValueIdentifierTokenIndex,
  129. NodeCategory::Expr>;
  130. using SelfTypeNameExpr =
  131. LeafNode<NodeKind::SelfTypeNameExpr, Lex::SelfTypeIdentifierTokenIndex,
  132. NodeCategory::Expr>;
  133. // The `base` value keyword, introduced by `base: B`. Typically referenced in
  134. // an expression, as in `x.base` or `{.base = ...}`, but can also be used as a
  135. // declared name, as in `{.base: partial B}`.
  136. using BaseName =
  137. LeafNode<NodeKind::BaseName, Lex::BaseTokenIndex, NodeCategory::MemberName>;
  138. // A name qualifier with parameters, such as `A(T:! type).` or `A[T:! type](N:!
  139. // T).`.
  140. struct NameQualifierWithParams {
  141. static constexpr auto Kind = NodeKind::NameQualifierWithParams.Define(
  142. {.bracketed_by = IdentifierNameBeforeParams::Kind});
  143. IdentifierNameBeforeParamsId name;
  144. std::optional<ImplicitParamListId> implicit_params;
  145. std::optional<TuplePatternId> params;
  146. Lex::PeriodTokenIndex token;
  147. };
  148. // A name qualifier without parameters, such as `A.`.
  149. struct NameQualifierWithoutParams {
  150. static constexpr auto Kind = NodeKind::NameQualifierWithoutParams.Define(
  151. {.bracketed_by = IdentifierNameNotBeforeParams::Kind});
  152. IdentifierNameNotBeforeParamsId name;
  153. Lex::PeriodTokenIndex token;
  154. };
  155. // A complete name in a declaration: `A.C(T:! type).F(n: i32)`.
  156. // Note that this includes the parameters of the entity itself.
  157. struct DeclName {
  158. llvm::SmallVector<
  159. NodeIdOneOf<NameQualifierWithParams, NameQualifierWithoutParams>>
  160. qualifiers;
  161. AnyNonExprIdentifierNameId name;
  162. std::optional<ImplicitParamListId> implicit_params;
  163. std::optional<TuplePatternId> params;
  164. };
  165. // Library, package, import, export
  166. // --------------------------------
  167. // The `package` keyword in an expression.
  168. using PackageExpr =
  169. LeafNode<NodeKind::PackageExpr, Lex::PackageTokenIndex, NodeCategory::Expr>;
  170. // The `Core` keyword in an expression.
  171. using CoreNameExpr =
  172. LeafNode<NodeKind::CoreNameExpr, Lex::CoreTokenIndex, NodeCategory::Expr>;
  173. // The name of a package or library for `package`, `import`, and `library`.
  174. using IdentifierPackageName =
  175. LeafNode<NodeKind::IdentifierPackageName, Lex::IdentifierTokenIndex,
  176. NodeCategory::PackageName>;
  177. using CorePackageName = LeafNode<NodeKind::CorePackageName, Lex::CoreTokenIndex,
  178. NodeCategory::PackageName>;
  179. using LibraryName =
  180. LeafNode<NodeKind::LibraryName, Lex::StringLiteralTokenIndex>;
  181. using DefaultLibrary =
  182. LeafNode<NodeKind::DefaultLibrary, Lex::DefaultTokenIndex>;
  183. using PackageIntroducer =
  184. LeafNode<NodeKind::PackageIntroducer, Lex::PackageTokenIndex>;
  185. // `library` in `package` or `import`.
  186. struct LibrarySpecifier {
  187. static constexpr auto Kind =
  188. NodeKind::LibrarySpecifier.Define({.child_count = 1});
  189. Lex::LibraryTokenIndex token;
  190. NodeIdOneOf<LibraryName, DefaultLibrary> name;
  191. };
  192. // First line of the file, such as:
  193. // `impl package MyPackage library "MyLibrary";`
  194. struct PackageDecl {
  195. static constexpr auto Kind =
  196. NodeKind::PackageDecl.Define({.category = NodeCategory::Decl,
  197. .bracketed_by = PackageIntroducer::Kind});
  198. PackageIntroducerId introducer;
  199. llvm::SmallVector<AnyModifierId> modifiers;
  200. std::optional<AnyPackageNameId> name;
  201. std::optional<LibrarySpecifierId> library;
  202. Lex::SemiTokenIndex token;
  203. };
  204. // `import TheirPackage library "TheirLibrary";`
  205. using ImportIntroducer =
  206. LeafNode<NodeKind::ImportIntroducer, Lex::ImportTokenIndex>;
  207. struct ImportDecl {
  208. static constexpr auto Kind = NodeKind::ImportDecl.Define(
  209. {.category = NodeCategory::Decl, .bracketed_by = ImportIntroducer::Kind});
  210. ImportIntroducerId introducer;
  211. llvm::SmallVector<AnyModifierId> modifiers;
  212. std::optional<AnyPackageNameId> name;
  213. std::optional<LibrarySpecifierId> library;
  214. Lex::SemiTokenIndex token;
  215. };
  216. // `library` as declaration.
  217. using LibraryIntroducer =
  218. LeafNode<NodeKind::LibraryIntroducer, Lex::LibraryTokenIndex>;
  219. struct LibraryDecl {
  220. static constexpr auto Kind =
  221. NodeKind::LibraryDecl.Define({.category = NodeCategory::Decl,
  222. .bracketed_by = LibraryIntroducer::Kind});
  223. LibraryIntroducerId introducer;
  224. llvm::SmallVector<AnyModifierId> modifiers;
  225. NodeIdOneOf<LibraryName, DefaultLibrary> library_name;
  226. Lex::SemiTokenIndex token;
  227. };
  228. // `export` as a declaration.
  229. using ExportIntroducer =
  230. LeafNode<NodeKind::ExportIntroducer, Lex::ExportTokenIndex>;
  231. struct ExportDecl {
  232. static constexpr auto Kind = NodeKind::ExportDecl.Define(
  233. {.category = NodeCategory::Decl, .bracketed_by = ExportIntroducer::Kind});
  234. ExportIntroducerId introducer;
  235. llvm::SmallVector<AnyModifierId> modifiers;
  236. DeclName name;
  237. Lex::SemiTokenIndex token;
  238. };
  239. // Namespace nodes
  240. // ---------------
  241. using NamespaceStart =
  242. LeafNode<NodeKind::NamespaceStart, Lex::NamespaceTokenIndex>;
  243. // A namespace: `namespace N;`.
  244. struct Namespace {
  245. static constexpr auto Kind = NodeKind::Namespace.Define(
  246. {.category = NodeCategory::Decl, .bracketed_by = NamespaceStart::Kind});
  247. NamespaceStartId introducer;
  248. llvm::SmallVector<AnyModifierId> modifiers;
  249. DeclName name;
  250. Lex::SemiTokenIndex token;
  251. };
  252. // Pattern nodes
  253. // -------------
  254. // A pattern binding, such as `name: Type`, that isn't inside a `var` pattern.
  255. struct LetBindingPattern {
  256. static constexpr auto Kind = NodeKind::LetBindingPattern.Define(
  257. {.category = NodeCategory::Pattern, .child_count = 2});
  258. NodeIdOneOf<IdentifierNameNotBeforeParams, SelfValueName> name;
  259. Lex::ColonTokenIndex token;
  260. AnyExprId type;
  261. };
  262. // A pattern binding, such as `name: Type`, that is inside a `var` pattern.
  263. struct VarBindingPattern {
  264. static constexpr auto Kind = NodeKind::VarBindingPattern.Define(
  265. {.category = NodeCategory::Pattern, .child_count = 2});
  266. NodeIdOneOf<IdentifierNameNotBeforeParams, SelfValueName> name;
  267. Lex::ColonTokenIndex token;
  268. AnyExprId type;
  269. };
  270. // `name:! Type`
  271. struct CompileTimeBindingPattern {
  272. static constexpr auto Kind = NodeKind::CompileTimeBindingPattern.Define(
  273. {.category = NodeCategory::Pattern, .child_count = 2});
  274. NodeIdOneOf<IdentifierNameNotBeforeParams, SelfValueName> name;
  275. Lex::ColonExclaimTokenIndex token;
  276. AnyExprId type;
  277. };
  278. // An address-of binding: `addr self: Self*`.
  279. struct Addr {
  280. static constexpr auto Kind = NodeKind::Addr.Define(
  281. {.category = NodeCategory::Pattern, .child_count = 1});
  282. Lex::AddrTokenIndex token;
  283. AnyPatternId inner;
  284. };
  285. // A template binding: `template T:! type`.
  286. struct Template {
  287. static constexpr auto Kind = NodeKind::Template.Define(
  288. {.category = NodeCategory::Pattern, .child_count = 1});
  289. Lex::TemplateTokenIndex token;
  290. // This is a CompileTimeBindingPatternId in any valid program.
  291. // TODO: Should the parser enforce that?
  292. AnyPatternId inner;
  293. };
  294. using TuplePatternStart =
  295. LeafNode<NodeKind::TuplePatternStart, Lex::OpenParenTokenIndex>;
  296. using PatternListComma =
  297. LeafNode<NodeKind::PatternListComma, Lex::CommaTokenIndex>;
  298. // A parameter list or tuple pattern: `(a: i32, b: i32)`.
  299. struct TuplePattern {
  300. static constexpr auto Kind =
  301. NodeKind::TuplePattern.Define({.category = NodeCategory::Pattern,
  302. .bracketed_by = TuplePatternStart::Kind});
  303. TuplePatternStartId left_paren;
  304. CommaSeparatedList<AnyPatternId, PatternListCommaId> params;
  305. Lex::CloseParenTokenIndex token;
  306. };
  307. using ImplicitParamListStart = LeafNode<NodeKind::ImplicitParamListStart,
  308. Lex::OpenSquareBracketTokenIndex>;
  309. // An implicit parameter list: `[T:! type, self: Self]`.
  310. struct ImplicitParamList {
  311. static constexpr auto Kind = NodeKind::ImplicitParamList.Define(
  312. {.bracketed_by = ImplicitParamListStart::Kind});
  313. ImplicitParamListStartId left_square;
  314. CommaSeparatedList<AnyPatternId, PatternListCommaId> params;
  315. Lex::CloseSquareBracketTokenIndex token;
  316. };
  317. // Function nodes
  318. // --------------
  319. using FunctionIntroducer =
  320. LeafNode<NodeKind::FunctionIntroducer, Lex::FnTokenIndex>;
  321. // A return type: `-> i32`.
  322. struct ReturnType {
  323. static constexpr auto Kind = NodeKind::ReturnType.Define({.child_count = 1});
  324. Lex::MinusGreaterTokenIndex token;
  325. AnyExprId type;
  326. };
  327. // A function signature: `fn F() -> i32`.
  328. template <const NodeKind& KindT, typename TokenKind,
  329. NodeCategory::RawEnumType Category>
  330. struct FunctionSignature {
  331. static constexpr auto Kind = KindT.Define(
  332. {.category = Category, .bracketed_by = FunctionIntroducer::Kind});
  333. FunctionIntroducerId introducer;
  334. llvm::SmallVector<AnyModifierId> modifiers;
  335. DeclName name;
  336. std::optional<ReturnTypeId> return_type;
  337. TokenKind token;
  338. };
  339. using FunctionDecl = FunctionSignature<NodeKind::FunctionDecl,
  340. Lex::SemiTokenIndex, NodeCategory::Decl>;
  341. using FunctionDefinitionStart =
  342. FunctionSignature<NodeKind::FunctionDefinitionStart,
  343. Lex::OpenCurlyBraceTokenIndex, NodeCategory::None>;
  344. // A function definition: `fn F() -> i32 { ... }`.
  345. struct FunctionDefinition {
  346. static constexpr auto Kind = NodeKind::FunctionDefinition.Define(
  347. {.category = NodeCategory::Decl,
  348. .bracketed_by = FunctionDefinitionStart::Kind});
  349. FunctionDefinitionStartId signature;
  350. llvm::SmallVector<AnyStatementId> body;
  351. Lex::CloseCurlyBraceTokenIndex token;
  352. };
  353. using BuiltinFunctionDefinitionStart =
  354. FunctionSignature<NodeKind::BuiltinFunctionDefinitionStart,
  355. Lex::EqualTokenIndex, NodeCategory::None>;
  356. using BuiltinName =
  357. LeafNode<NodeKind::BuiltinName, Lex::StringLiteralTokenIndex>;
  358. // A builtin function definition: `fn F() -> i32 = "builtin name";`
  359. struct BuiltinFunctionDefinition {
  360. static constexpr auto Kind = NodeKind::BuiltinFunctionDefinition.Define(
  361. {.category = NodeCategory::Decl,
  362. .bracketed_by = BuiltinFunctionDefinitionStart::Kind});
  363. BuiltinFunctionDefinitionStartId signature;
  364. BuiltinNameId builtin_name;
  365. Lex::SemiTokenIndex token;
  366. };
  367. // `alias` nodes
  368. // -------------
  369. using AliasIntroducer =
  370. LeafNode<NodeKind::AliasIntroducer, Lex::AliasTokenIndex>;
  371. using AliasInitializer =
  372. LeafNode<NodeKind::AliasInitializer, Lex::EqualTokenIndex>;
  373. // An `alias` declaration: `alias a = b;`.
  374. struct Alias {
  375. static constexpr auto Kind = NodeKind::Alias.Define(
  376. {.category = NodeCategory::Decl, .bracketed_by = AliasIntroducer::Kind});
  377. AliasIntroducerId introducer;
  378. llvm::SmallVector<AnyModifierId> modifiers;
  379. DeclName name;
  380. AliasInitializerId equals;
  381. AnyExprId initializer;
  382. Lex::SemiTokenIndex token;
  383. };
  384. // `let` nodes
  385. // -----------
  386. using LetIntroducer = LeafNode<NodeKind::LetIntroducer, Lex::LetTokenIndex>;
  387. using LetInitializer = LeafNode<NodeKind::LetInitializer, Lex::EqualTokenIndex>;
  388. // A `let` declaration: `let a: i32 = 5;`.
  389. struct LetDecl {
  390. static constexpr auto Kind = NodeKind::LetDecl.Define(
  391. {.category = NodeCategory::Decl, .bracketed_by = LetIntroducer::Kind});
  392. LetIntroducerId introducer;
  393. llvm::SmallVector<AnyModifierId> modifiers;
  394. AnyPatternId pattern;
  395. struct Initializer {
  396. LetInitializerId equals;
  397. AnyExprId initializer;
  398. };
  399. std::optional<Initializer> initializer;
  400. Lex::SemiTokenIndex token;
  401. };
  402. // `var` nodes
  403. // -----------
  404. using VariableIntroducer =
  405. LeafNode<NodeKind::VariableIntroducer, Lex::VarTokenIndex>;
  406. using ReturnedModifier =
  407. LeafNode<NodeKind::ReturnedModifier, Lex::ReturnedTokenIndex,
  408. NodeCategory::Modifier>;
  409. using VariableInitializer =
  410. LeafNode<NodeKind::VariableInitializer, Lex::EqualTokenIndex>;
  411. // A `var` declaration: `var a: i32;` or `var a: i32 = 5;`.
  412. struct VariableDecl {
  413. static constexpr auto Kind =
  414. NodeKind::VariableDecl.Define({.category = NodeCategory::Decl,
  415. .bracketed_by = VariableIntroducer::Kind});
  416. VariableIntroducerId introducer;
  417. llvm::SmallVector<AnyModifierId> modifiers;
  418. std::optional<ReturnedModifierId> returned;
  419. VariablePatternId pattern;
  420. struct Initializer {
  421. VariableInitializerId equals;
  422. AnyExprId value;
  423. };
  424. std::optional<Initializer> initializer;
  425. Lex::SemiTokenIndex token;
  426. };
  427. // A `var` pattern.
  428. struct VariablePattern {
  429. static constexpr auto Kind = NodeKind::VariablePattern.Define(
  430. {.category = NodeCategory::Pattern, .child_count = 1});
  431. Lex::VarTokenIndex token;
  432. AnyPatternId inner;
  433. };
  434. // Statement nodes
  435. // ---------------
  436. using CodeBlockStart =
  437. LeafNode<NodeKind::CodeBlockStart, Lex::OpenCurlyBraceTokenIndex>;
  438. // A code block: `{ statement; statement; ... }`.
  439. struct CodeBlock {
  440. static constexpr auto Kind =
  441. NodeKind::CodeBlock.Define({.bracketed_by = CodeBlockStart::Kind});
  442. CodeBlockStartId left_brace;
  443. llvm::SmallVector<AnyStatementId> statements;
  444. Lex::CloseCurlyBraceTokenIndex token;
  445. };
  446. // An expression statement: `F(x);`.
  447. struct ExprStatement {
  448. static constexpr auto Kind = NodeKind::ExprStatement.Define(
  449. {.category = NodeCategory::Statement, .child_count = 1});
  450. AnyExprId expr;
  451. Lex::SemiTokenIndex token;
  452. };
  453. using BreakStatementStart =
  454. LeafNode<NodeKind::BreakStatementStart, Lex::BreakTokenIndex>;
  455. // A break statement: `break;`.
  456. struct BreakStatement {
  457. static constexpr auto Kind = NodeKind::BreakStatement.Define(
  458. {.category = NodeCategory::Statement,
  459. .bracketed_by = BreakStatementStart::Kind,
  460. .child_count = 1});
  461. BreakStatementStartId introducer;
  462. Lex::SemiTokenIndex token;
  463. };
  464. using ContinueStatementStart =
  465. LeafNode<NodeKind::ContinueStatementStart, Lex::ContinueTokenIndex>;
  466. // A continue statement: `continue;`.
  467. struct ContinueStatement {
  468. static constexpr auto Kind = NodeKind::ContinueStatement.Define(
  469. {.category = NodeCategory::Statement,
  470. .bracketed_by = ContinueStatementStart::Kind,
  471. .child_count = 1});
  472. ContinueStatementStartId introducer;
  473. Lex::SemiTokenIndex token;
  474. };
  475. using ReturnStatementStart =
  476. LeafNode<NodeKind::ReturnStatementStart, Lex::ReturnTokenIndex>;
  477. using ReturnVarModifier = LeafNode<NodeKind::ReturnVarModifier,
  478. Lex::VarTokenIndex, NodeCategory::Modifier>;
  479. // A return statement: `return;` or `return expr;` or `return var;`.
  480. struct ReturnStatement {
  481. static constexpr auto Kind = NodeKind::ReturnStatement.Define(
  482. {.category = NodeCategory::Statement,
  483. .bracketed_by = ReturnStatementStart::Kind});
  484. ReturnStatementStartId introducer;
  485. std::optional<AnyExprId> expr;
  486. std::optional<ReturnVarModifierId> var;
  487. Lex::SemiTokenIndex token;
  488. };
  489. using ForHeaderStart =
  490. LeafNode<NodeKind::ForHeaderStart, Lex::OpenParenTokenIndex>;
  491. // The `var ... in` portion of a `for` statement.
  492. struct ForIn {
  493. static constexpr auto Kind = NodeKind::ForIn.Define(
  494. {.bracketed_by = VariableIntroducer::Kind, .child_count = 2});
  495. VariableIntroducerId introducer;
  496. Lex::InTokenIndex token;
  497. AnyPatternId pattern;
  498. };
  499. // The `for (var ... in ...)` portion of a `for` statement.
  500. struct ForHeader {
  501. static constexpr auto Kind =
  502. NodeKind::ForHeader.Define({.bracketed_by = ForHeaderStart::Kind});
  503. ForHeaderStartId introducer;
  504. ForInId var;
  505. AnyExprId range;
  506. Lex::CloseParenTokenIndex token;
  507. };
  508. // A complete `for (...) { ... }` statement.
  509. struct ForStatement {
  510. static constexpr auto Kind =
  511. NodeKind::ForStatement.Define({.category = NodeCategory::Statement,
  512. .bracketed_by = ForHeader::Kind,
  513. .child_count = 2});
  514. Lex::ForTokenIndex token;
  515. ForHeaderId header;
  516. CodeBlockId body;
  517. };
  518. using IfConditionStart =
  519. LeafNode<NodeKind::IfConditionStart, Lex::OpenParenTokenIndex>;
  520. // The condition portion of an `if` statement: `(expr)`.
  521. struct IfCondition {
  522. static constexpr auto Kind = NodeKind::IfCondition.Define(
  523. {.bracketed_by = IfConditionStart::Kind, .child_count = 2});
  524. IfConditionStartId left_paren;
  525. AnyExprId condition;
  526. Lex::CloseParenTokenIndex token;
  527. };
  528. using IfStatementElse =
  529. LeafNode<NodeKind::IfStatementElse, Lex::ElseTokenIndex>;
  530. // An `if` statement: `if (expr) { ... } else { ... }`.
  531. struct IfStatement {
  532. static constexpr auto Kind = NodeKind::IfStatement.Define(
  533. {.category = NodeCategory::Statement, .bracketed_by = IfCondition::Kind});
  534. Lex::IfTokenIndex token;
  535. IfConditionId head;
  536. CodeBlockId then;
  537. struct Else {
  538. IfStatementElseId else_token;
  539. NodeIdOneOf<CodeBlock, IfStatement> body;
  540. };
  541. std::optional<Else> else_clause;
  542. };
  543. using WhileConditionStart =
  544. LeafNode<NodeKind::WhileConditionStart, Lex::OpenParenTokenIndex>;
  545. // The condition portion of a `while` statement: `(expr)`.
  546. struct WhileCondition {
  547. static constexpr auto Kind = NodeKind::WhileCondition.Define(
  548. {.bracketed_by = WhileConditionStart::Kind, .child_count = 2});
  549. WhileConditionStartId left_paren;
  550. AnyExprId condition;
  551. Lex::CloseParenTokenIndex token;
  552. };
  553. // A `while` statement: `while (expr) { ... }`.
  554. struct WhileStatement {
  555. static constexpr auto Kind =
  556. NodeKind::WhileStatement.Define({.category = NodeCategory::Statement,
  557. .bracketed_by = WhileCondition::Kind,
  558. .child_count = 2});
  559. Lex::WhileTokenIndex token;
  560. WhileConditionId head;
  561. CodeBlockId body;
  562. };
  563. using MatchConditionStart =
  564. LeafNode<NodeKind::MatchConditionStart, Lex::OpenParenTokenIndex>;
  565. struct MatchCondition {
  566. static constexpr auto Kind = NodeKind::MatchCondition.Define(
  567. {.bracketed_by = MatchConditionStart::Kind, .child_count = 2});
  568. MatchConditionStartId left_paren;
  569. AnyExprId condition;
  570. Lex::CloseParenTokenIndex token;
  571. };
  572. using MatchIntroducer =
  573. LeafNode<NodeKind::MatchIntroducer, Lex::MatchTokenIndex>;
  574. struct MatchStatementStart {
  575. static constexpr auto Kind = NodeKind::MatchStatementStart.Define(
  576. {.bracketed_by = MatchIntroducer::Kind, .child_count = 2});
  577. MatchIntroducerId introducer;
  578. MatchConditionId condition;
  579. Lex::OpenCurlyBraceTokenIndex token;
  580. };
  581. using MatchCaseIntroducer =
  582. LeafNode<NodeKind::MatchCaseIntroducer, Lex::CaseTokenIndex>;
  583. using MatchCaseGuardIntroducer =
  584. LeafNode<NodeKind::MatchCaseGuardIntroducer, Lex::IfTokenIndex>;
  585. using MatchCaseGuardStart =
  586. LeafNode<NodeKind::MatchCaseGuardStart, Lex::OpenParenTokenIndex>;
  587. struct MatchCaseGuard {
  588. static constexpr auto Kind = NodeKind::MatchCaseGuard.Define(
  589. {.bracketed_by = MatchCaseGuardIntroducer::Kind, .child_count = 3});
  590. MatchCaseGuardIntroducerId introducer;
  591. MatchCaseGuardStartId left_paren;
  592. AnyExprId condition;
  593. Lex::CloseParenTokenIndex token;
  594. };
  595. using MatchCaseEqualGreater =
  596. LeafNode<NodeKind::MatchCaseEqualGreater, Lex::EqualGreaterTokenIndex>;
  597. struct MatchCaseStart {
  598. static constexpr auto Kind = NodeKind::MatchCaseStart.Define(
  599. {.bracketed_by = MatchCaseIntroducer::Kind});
  600. MatchCaseIntroducerId introducer;
  601. AnyPatternId pattern;
  602. std::optional<MatchCaseGuardId> guard;
  603. MatchCaseEqualGreaterId equal_greater_token;
  604. Lex::OpenCurlyBraceTokenIndex token;
  605. };
  606. struct MatchCase {
  607. static constexpr auto Kind =
  608. NodeKind::MatchCase.Define({.bracketed_by = MatchCaseStart::Kind});
  609. MatchCaseStartId head;
  610. llvm::SmallVector<AnyStatementId> statements;
  611. Lex::CloseCurlyBraceTokenIndex token;
  612. };
  613. using MatchDefaultIntroducer =
  614. LeafNode<NodeKind::MatchDefaultIntroducer, Lex::DefaultTokenIndex>;
  615. using MatchDefaultEqualGreater =
  616. LeafNode<NodeKind::MatchDefaultEqualGreater, Lex::EqualGreaterTokenIndex>;
  617. struct MatchDefaultStart {
  618. static constexpr auto Kind = NodeKind::MatchDefaultStart.Define(
  619. {.bracketed_by = MatchDefaultIntroducer::Kind, .child_count = 2});
  620. MatchDefaultIntroducerId introducer;
  621. MatchDefaultEqualGreaterId equal_greater_token;
  622. Lex::OpenCurlyBraceTokenIndex token;
  623. };
  624. struct MatchDefault {
  625. static constexpr auto Kind =
  626. NodeKind::MatchDefault.Define({.bracketed_by = MatchDefaultStart::Kind});
  627. MatchDefaultStartId introducer;
  628. llvm::SmallVector<AnyStatementId> statements;
  629. Lex::CloseCurlyBraceTokenIndex token;
  630. };
  631. // A `match` statement: `match (expr) { case (...) => {...} default => {...}}`.
  632. struct MatchStatement {
  633. static constexpr auto Kind = NodeKind::MatchStatement.Define(
  634. {.category = NodeCategory::Statement,
  635. .bracketed_by = MatchStatementStart::Kind});
  636. MatchStatementStartId head;
  637. llvm::SmallVector<MatchCaseId> cases;
  638. std::optional<MatchDefaultId> default_case;
  639. Lex::CloseCurlyBraceTokenIndex token;
  640. };
  641. // Expression nodes
  642. // ----------------
  643. using ArrayExprStart =
  644. LeafNode<NodeKind::ArrayExprStart, Lex::OpenSquareBracketTokenIndex>;
  645. // The start of an array type, `[i32;`.
  646. //
  647. // TODO: Consider flattening this into `ArrayExpr`.
  648. struct ArrayExprSemi {
  649. static constexpr auto Kind = NodeKind::ArrayExprSemi.Define(
  650. {.bracketed_by = ArrayExprStart::Kind, .child_count = 2});
  651. ArrayExprStartId left_square;
  652. AnyExprId type;
  653. Lex::SemiTokenIndex token;
  654. };
  655. // An array type, such as `[i32; 3]` or `[i32;]`.
  656. struct ArrayExpr {
  657. static constexpr auto Kind = NodeKind::ArrayExpr.Define(
  658. {.category = NodeCategory::Expr, .bracketed_by = ArrayExprSemi::Kind});
  659. ArrayExprSemiId start;
  660. std::optional<AnyExprId> bound;
  661. Lex::CloseSquareBracketTokenIndex token;
  662. };
  663. // The opening portion of an indexing expression: `a[`.
  664. //
  665. // TODO: Consider flattening this into `IndexExpr`.
  666. struct IndexExprStart {
  667. static constexpr auto Kind =
  668. NodeKind::IndexExprStart.Define({.child_count = 1});
  669. AnyExprId sequence;
  670. Lex::OpenSquareBracketTokenIndex token;
  671. };
  672. // An indexing expression, such as `a[1]`.
  673. struct IndexExpr {
  674. static constexpr auto Kind =
  675. NodeKind::IndexExpr.Define({.category = NodeCategory::Expr,
  676. .bracketed_by = IndexExprStart::Kind,
  677. .child_count = 2});
  678. IndexExprStartId start;
  679. AnyExprId index;
  680. Lex::CloseSquareBracketTokenIndex token;
  681. };
  682. using ParenExprStart =
  683. LeafNode<NodeKind::ParenExprStart, Lex::OpenParenTokenIndex>;
  684. // A parenthesized expression: `(a)`.
  685. struct ParenExpr {
  686. static constexpr auto Kind = NodeKind::ParenExpr.Define(
  687. {.category = NodeCategory::Expr | NodeCategory::MemberExpr,
  688. .bracketed_by = ParenExprStart::Kind,
  689. .child_count = 2});
  690. ParenExprStartId start;
  691. AnyExprId expr;
  692. Lex::CloseParenTokenIndex token;
  693. };
  694. using TupleLiteralStart =
  695. LeafNode<NodeKind::TupleLiteralStart, Lex::OpenParenTokenIndex>;
  696. using TupleLiteralComma =
  697. LeafNode<NodeKind::TupleLiteralComma, Lex::CommaTokenIndex>;
  698. // A tuple literal: `()`, `(a, b, c)`, or `(a,)`.
  699. struct TupleLiteral {
  700. static constexpr auto Kind =
  701. NodeKind::TupleLiteral.Define({.category = NodeCategory::Expr,
  702. .bracketed_by = TupleLiteralStart::Kind});
  703. TupleLiteralStartId start;
  704. CommaSeparatedList<AnyExprId, TupleLiteralCommaId> elements;
  705. Lex::CloseParenTokenIndex token;
  706. };
  707. // The opening portion of a call expression: `F(`.
  708. //
  709. // TODO: Consider flattening this into `CallExpr`.
  710. struct CallExprStart {
  711. static constexpr auto Kind =
  712. NodeKind::CallExprStart.Define({.child_count = 1});
  713. AnyExprId callee;
  714. Lex::OpenParenTokenIndex token;
  715. };
  716. using CallExprComma = LeafNode<NodeKind::CallExprComma, Lex::CommaTokenIndex>;
  717. // A call expression: `F(a, b, c)`.
  718. struct CallExpr {
  719. static constexpr auto Kind = NodeKind::CallExpr.Define(
  720. {.category = NodeCategory::Expr, .bracketed_by = CallExprStart::Kind});
  721. CallExprStartId start;
  722. CommaSeparatedList<AnyExprId, CallExprCommaId> arguments;
  723. Lex::CloseParenTokenIndex token;
  724. };
  725. // A member access expression: `a.b` or `a.(b)`.
  726. struct MemberAccessExpr {
  727. static constexpr auto Kind = NodeKind::MemberAccessExpr.Define(
  728. {.category = NodeCategory::Expr, .child_count = 2});
  729. AnyExprId lhs;
  730. Lex::PeriodTokenIndex token;
  731. AnyMemberAccessId rhs;
  732. };
  733. // An indirect member access expression: `a->b` or `a->(b)`.
  734. struct PointerMemberAccessExpr {
  735. static constexpr auto Kind = NodeKind::PointerMemberAccessExpr.Define(
  736. {.category = NodeCategory::Expr, .child_count = 2});
  737. AnyExprId lhs;
  738. Lex::MinusGreaterTokenIndex token;
  739. AnyMemberAccessId rhs;
  740. };
  741. // A prefix operator expression.
  742. template <const NodeKind& KindT, typename TokenKind>
  743. struct PrefixOperator {
  744. static constexpr auto Kind =
  745. KindT.Define({.category = NodeCategory::Expr, .child_count = 1});
  746. TokenKind token;
  747. AnyExprId operand;
  748. };
  749. // An infix operator expression.
  750. template <const NodeKind& KindT, typename TokenKind>
  751. struct InfixOperator {
  752. static constexpr auto Kind =
  753. KindT.Define({.category = NodeCategory::Expr, .child_count = 2});
  754. AnyExprId lhs;
  755. TokenKind token;
  756. AnyExprId rhs;
  757. };
  758. // A postfix operator expression.
  759. template <const NodeKind& KindT, typename TokenKind>
  760. struct PostfixOperator {
  761. static constexpr auto Kind =
  762. KindT.Define({.category = NodeCategory::Expr, .child_count = 1});
  763. AnyExprId operand;
  764. TokenKind token;
  765. };
  766. // Literals, operators, and modifiers
  767. #define CARBON_PARSE_NODE_KIND(...)
  768. #define CARBON_PARSE_NODE_KIND_TOKEN_LITERAL(Name, LexTokenKind) \
  769. using Name = LeafNode<NodeKind::Name, Lex::LexTokenKind##TokenIndex, \
  770. NodeCategory::Expr>;
  771. #define CARBON_PARSE_NODE_KIND_TOKEN_MODIFIER(Name) \
  772. using Name##Modifier = \
  773. LeafNode<NodeKind::Name##Modifier, Lex::Name##TokenIndex, \
  774. NodeCategory::Modifier>;
  775. #define CARBON_PARSE_NODE_KIND_PREFIX_OPERATOR(Name) \
  776. using PrefixOperator##Name = \
  777. PrefixOperator<NodeKind::PrefixOperator##Name, Lex::Name##TokenIndex>;
  778. #define CARBON_PARSE_NODE_KIND_INFIX_OPERATOR(Name) \
  779. using InfixOperator##Name = \
  780. InfixOperator<NodeKind::InfixOperator##Name, Lex::Name##TokenIndex>;
  781. #define CARBON_PARSE_NODE_KIND_POSTFIX_OPERATOR(Name) \
  782. using PostfixOperator##Name = \
  783. PostfixOperator<NodeKind::PostfixOperator##Name, Lex::Name##TokenIndex>;
  784. #include "toolchain/parse/node_kind.def"
  785. using IntLiteral = LeafNode<NodeKind::IntLiteral, Lex::IntLiteralTokenIndex,
  786. NodeCategory::Expr | NodeCategory::IntConst>;
  787. // `extern` as a standalone modifier.
  788. using ExternModifier = LeafNode<NodeKind::ExternModifier, Lex::ExternTokenIndex,
  789. NodeCategory::Modifier>;
  790. // `extern library <owning_library>` modifiers.
  791. struct ExternModifierWithLibrary {
  792. static constexpr auto Kind = NodeKind::ExternModifierWithLibrary.Define(
  793. {.category = NodeCategory::Modifier, .child_count = 1});
  794. Lex::ExternTokenIndex token;
  795. LibrarySpecifierId library;
  796. };
  797. // The first operand of a short-circuiting infix operator: `a and` or `a or`.
  798. // The complete operator expression will be an InfixOperator with this as the
  799. // `lhs`.
  800. // TODO: Make this be a template if we ever need to write generic code to cover
  801. // both cases at once, say in check.
  802. struct ShortCircuitOperandAnd {
  803. static constexpr auto Kind =
  804. NodeKind::ShortCircuitOperandAnd.Define({.child_count = 1});
  805. AnyExprId operand;
  806. // This is a virtual token. The `and` token is owned by the
  807. // ShortCircuitOperatorAnd node.
  808. Lex::AndTokenIndex token;
  809. };
  810. struct ShortCircuitOperandOr {
  811. static constexpr auto Kind =
  812. NodeKind::ShortCircuitOperandOr.Define({.child_count = 1});
  813. AnyExprId operand;
  814. // This is a virtual token. The `or` token is owned by the
  815. // ShortCircuitOperatorOr node.
  816. Lex::OrTokenIndex token;
  817. };
  818. struct ShortCircuitOperatorAnd {
  819. static constexpr auto Kind = NodeKind::ShortCircuitOperatorAnd.Define(
  820. {.category = NodeCategory::Expr,
  821. .bracketed_by = ShortCircuitOperandAnd::Kind,
  822. .child_count = 2});
  823. ShortCircuitOperandAndId lhs;
  824. Lex::AndTokenIndex token;
  825. AnyExprId rhs;
  826. };
  827. struct ShortCircuitOperatorOr {
  828. static constexpr auto Kind = NodeKind::ShortCircuitOperatorOr.Define(
  829. {.category = NodeCategory::Expr,
  830. .bracketed_by = ShortCircuitOperandOr::Kind,
  831. .child_count = 2});
  832. ShortCircuitOperandOrId lhs;
  833. Lex::OrTokenIndex token;
  834. AnyExprId rhs;
  835. };
  836. // The `if` portion of an `if` expression: `if expr`.
  837. struct IfExprIf {
  838. static constexpr auto Kind = NodeKind::IfExprIf.Define({.child_count = 1});
  839. Lex::IfTokenIndex token;
  840. AnyExprId condition;
  841. };
  842. // The `then` portion of an `if` expression: `then expr`.
  843. struct IfExprThen {
  844. static constexpr auto Kind = NodeKind::IfExprThen.Define({.child_count = 1});
  845. Lex::ThenTokenIndex token;
  846. AnyExprId result;
  847. };
  848. // A full `if` expression: `if expr then expr else expr`.
  849. struct IfExprElse {
  850. static constexpr auto Kind =
  851. NodeKind::IfExprElse.Define({.category = NodeCategory::Expr,
  852. .bracketed_by = IfExprIf::Kind,
  853. .child_count = 3});
  854. IfExprIfId start;
  855. IfExprThenId then;
  856. Lex::ElseTokenIndex token;
  857. AnyExprId else_result;
  858. };
  859. // A `where` expression (TODO: `require` and `observe` declarations)
  860. // The `Self` in a context where it is treated as a name rather than an
  861. // expression, such as `.Self`.
  862. using SelfTypeName =
  863. LeafNode<NodeKind::SelfTypeName, Lex::SelfTypeIdentifierTokenIndex>;
  864. // `.Member` or `.Self` in an expression context, used in `where` and `require`
  865. // clauses.
  866. // TODO: Do we want to support `.1`, a designator for accessing a tuple member?
  867. struct DesignatorExpr {
  868. static constexpr auto Kind = NodeKind::DesignatorExpr.Define(
  869. {.category = NodeCategory::Expr, .child_count = 1});
  870. Lex::PeriodTokenIndex token;
  871. NodeIdOneOf<IdentifierNameNotBeforeParams, SelfTypeName> name;
  872. };
  873. struct RequirementEqual {
  874. static constexpr auto Kind = NodeKind::RequirementEqual.Define(
  875. {.category = NodeCategory::Requirement, .child_count = 2});
  876. DesignatorExprId lhs;
  877. Lex::EqualTokenIndex token;
  878. AnyExprId rhs;
  879. };
  880. struct RequirementEqualEqual {
  881. static constexpr auto Kind = NodeKind::RequirementEqualEqual.Define(
  882. {.category = NodeCategory::Requirement, .child_count = 2});
  883. AnyExprId lhs;
  884. Lex::EqualEqualTokenIndex token;
  885. AnyExprId rhs;
  886. };
  887. struct RequirementImpls {
  888. static constexpr auto Kind = NodeKind::RequirementImpls.Define(
  889. {.category = NodeCategory::Requirement, .child_count = 2});
  890. AnyExprId lhs;
  891. Lex::ImplsTokenIndex token;
  892. AnyExprId rhs;
  893. };
  894. // An `and` token separating requirements in a `where` expression.
  895. using RequirementAnd = LeafNode<NodeKind::RequirementAnd, Lex::AndTokenIndex>;
  896. struct WhereOperand {
  897. static constexpr auto Kind =
  898. NodeKind::WhereOperand.Define({.child_count = 1});
  899. AnyExprId type;
  900. // This is a virtual token. The `where` token is owned by the
  901. // WhereExpr node.
  902. Lex::WhereTokenIndex token;
  903. };
  904. struct WhereExpr {
  905. static constexpr auto Kind = NodeKind::WhereExpr.Define(
  906. {.category = NodeCategory::Expr, .bracketed_by = WhereOperand::Kind});
  907. WhereOperandId introducer;
  908. Lex::WhereTokenIndex token;
  909. CommaSeparatedList<AnyRequirementId, RequirementAndId> requirements;
  910. };
  911. // Choice nodes
  912. // ------------
  913. using ChoiceIntroducer =
  914. LeafNode<NodeKind::ChoiceIntroducer, Lex::ChoiceTokenIndex>;
  915. struct ChoiceSignature {
  916. static constexpr auto Kind = NodeKind::ChoiceDefinitionStart.Define(
  917. {.category = NodeCategory::None, .bracketed_by = ChoiceIntroducer::Kind});
  918. ChoiceIntroducerId introducer;
  919. llvm::SmallVector<AnyModifierId> modifiers;
  920. DeclName name;
  921. Lex::OpenCurlyBraceTokenIndex token;
  922. };
  923. using ChoiceDefinitionStart = ChoiceSignature;
  924. using ChoiceAlternativeListComma =
  925. LeafNode<NodeKind::ChoiceAlternativeListComma, Lex::CommaTokenIndex>;
  926. struct ChoiceDefinition {
  927. static constexpr auto Kind = NodeKind::ChoiceDefinition.Define(
  928. {.category = NodeCategory::Decl,
  929. .bracketed_by = ChoiceDefinitionStart::Kind});
  930. ChoiceDefinitionStartId signature;
  931. struct Alternative {
  932. AnyNonExprIdentifierNameId name;
  933. std::optional<TuplePatternId> parameters;
  934. };
  935. CommaSeparatedList<Alternative, ChoiceAlternativeListCommaId> alternatives;
  936. Lex::CloseCurlyBraceTokenIndex token;
  937. };
  938. // Struct type and value literals
  939. // ----------------------------------------
  940. // `{`
  941. using StructLiteralStart =
  942. LeafNode<NodeKind::StructLiteralStart, Lex::OpenCurlyBraceTokenIndex>;
  943. using StructTypeLiteralStart =
  944. LeafNode<NodeKind::StructTypeLiteralStart, Lex::OpenCurlyBraceTokenIndex>;
  945. // `,`
  946. using StructLiteralComma =
  947. LeafNode<NodeKind::StructLiteralComma, Lex::CommaTokenIndex>;
  948. using StructTypeLiteralComma =
  949. LeafNode<NodeKind::StructTypeLiteralComma, Lex::CommaTokenIndex>;
  950. // `.a`
  951. // This is shared for struct literals and type literals in order to reduce
  952. // lookahead for parse (the `=` versus `:` would require lookahead of 2).
  953. struct StructFieldDesignator {
  954. static constexpr auto Kind =
  955. NodeKind::StructFieldDesignator.Define({.child_count = 1});
  956. Lex::PeriodTokenIndex token;
  957. NodeIdOneOf<IdentifierNameNotBeforeParams, BaseName> name;
  958. };
  959. // `.a = 0`
  960. struct StructLiteralField {
  961. static constexpr auto Kind = NodeKind::StructLiteralField.Define(
  962. {.bracketed_by = StructFieldDesignator::Kind, .child_count = 2});
  963. StructFieldDesignatorId designator;
  964. Lex::EqualTokenIndex token;
  965. AnyExprId expr;
  966. };
  967. // `.a: i32`
  968. struct StructTypeLiteralField {
  969. static constexpr auto Kind = NodeKind::StructTypeLiteralField.Define(
  970. {.bracketed_by = StructFieldDesignator::Kind, .child_count = 2});
  971. StructFieldDesignatorId designator;
  972. Lex::ColonTokenIndex token;
  973. AnyExprId type_expr;
  974. };
  975. // Struct literals, such as `{.a = 0}`.
  976. struct StructLiteral {
  977. static constexpr auto Kind = NodeKind::StructLiteral.Define(
  978. {.category = NodeCategory::Expr,
  979. .bracketed_by = StructLiteralStart::Kind});
  980. StructLiteralStartId start;
  981. CommaSeparatedList<StructLiteralFieldId, StructLiteralCommaId> fields;
  982. Lex::CloseCurlyBraceTokenIndex token;
  983. };
  984. // Struct type literals, such as `{.a: i32}`.
  985. struct StructTypeLiteral {
  986. static constexpr auto Kind = NodeKind::StructTypeLiteral.Define(
  987. {.category = NodeCategory::Expr,
  988. .bracketed_by = StructTypeLiteralStart::Kind});
  989. StructTypeLiteralStartId start;
  990. CommaSeparatedList<StructTypeLiteralFieldId, StructTypeLiteralCommaId> fields;
  991. Lex::CloseCurlyBraceTokenIndex token;
  992. };
  993. // `class` declarations and definitions
  994. // ------------------------------------
  995. // `class`
  996. using ClassIntroducer =
  997. LeafNode<NodeKind::ClassIntroducer, Lex::ClassTokenIndex>;
  998. // A class signature `class C`
  999. template <const NodeKind& KindT, typename TokenKind,
  1000. NodeCategory::RawEnumType Category>
  1001. struct ClassSignature {
  1002. static constexpr auto Kind = KindT.Define(
  1003. {.category = Category, .bracketed_by = ClassIntroducer::Kind});
  1004. ClassIntroducerId introducer;
  1005. llvm::SmallVector<AnyModifierId> modifiers;
  1006. DeclName name;
  1007. TokenKind token;
  1008. };
  1009. // `class C;`
  1010. using ClassDecl = ClassSignature<NodeKind::ClassDecl, Lex::SemiTokenIndex,
  1011. NodeCategory::Decl>;
  1012. // `class C {`
  1013. using ClassDefinitionStart =
  1014. ClassSignature<NodeKind::ClassDefinitionStart,
  1015. Lex::OpenCurlyBraceTokenIndex, NodeCategory::None>;
  1016. // `class C { ... }`
  1017. struct ClassDefinition {
  1018. static constexpr auto Kind = NodeKind::ClassDefinition.Define(
  1019. {.category = NodeCategory::Decl,
  1020. .bracketed_by = ClassDefinitionStart::Kind});
  1021. ClassDefinitionStartId signature;
  1022. llvm::SmallVector<AnyDeclId> members;
  1023. Lex::CloseCurlyBraceTokenIndex token;
  1024. };
  1025. // Adapter declaration
  1026. // -------------------
  1027. // `adapt`
  1028. using AdaptIntroducer =
  1029. LeafNode<NodeKind::AdaptIntroducer, Lex::AdaptTokenIndex>;
  1030. // `adapt SomeType;`
  1031. struct AdaptDecl {
  1032. static constexpr auto Kind = NodeKind::AdaptDecl.Define(
  1033. {.category = NodeCategory::Decl, .bracketed_by = AdaptIntroducer::Kind});
  1034. AdaptIntroducerId introducer;
  1035. llvm::SmallVector<AnyModifierId> modifiers;
  1036. AnyExprId adapted_type;
  1037. Lex::SemiTokenIndex token;
  1038. };
  1039. // Base class declaration
  1040. // ----------------------
  1041. // `base`
  1042. using BaseIntroducer = LeafNode<NodeKind::BaseIntroducer, Lex::BaseTokenIndex>;
  1043. using BaseColon = LeafNode<NodeKind::BaseColon, Lex::ColonTokenIndex>;
  1044. // `extend base: BaseClass;`
  1045. struct BaseDecl {
  1046. static constexpr auto Kind = NodeKind::BaseDecl.Define(
  1047. {.category = NodeCategory::Decl, .bracketed_by = BaseIntroducer::Kind});
  1048. BaseIntroducerId introducer;
  1049. llvm::SmallVector<AnyModifierId> modifiers;
  1050. BaseColonId colon;
  1051. AnyExprId base_class;
  1052. Lex::SemiTokenIndex token;
  1053. };
  1054. // Interface declarations and definitions
  1055. // --------------------------------------
  1056. // `interface`
  1057. using InterfaceIntroducer =
  1058. LeafNode<NodeKind::InterfaceIntroducer, Lex::InterfaceTokenIndex>;
  1059. // `interface I`
  1060. template <const NodeKind& KindT, typename TokenKind,
  1061. NodeCategory::RawEnumType Category>
  1062. struct InterfaceSignature {
  1063. static constexpr auto Kind = KindT.Define(
  1064. {.category = Category, .bracketed_by = InterfaceIntroducer::Kind});
  1065. InterfaceIntroducerId introducer;
  1066. llvm::SmallVector<AnyModifierId> modifiers;
  1067. DeclName name;
  1068. TokenKind token;
  1069. };
  1070. // `interface I;`
  1071. using InterfaceDecl =
  1072. InterfaceSignature<NodeKind::InterfaceDecl, Lex::SemiTokenIndex,
  1073. NodeCategory::Decl>;
  1074. // `interface I {`
  1075. using InterfaceDefinitionStart =
  1076. InterfaceSignature<NodeKind::InterfaceDefinitionStart,
  1077. Lex::OpenCurlyBraceTokenIndex, NodeCategory::None>;
  1078. // `interface I { ... }`
  1079. struct InterfaceDefinition {
  1080. static constexpr auto Kind = NodeKind::InterfaceDefinition.Define(
  1081. {.category = NodeCategory::Decl,
  1082. .bracketed_by = InterfaceDefinitionStart::Kind});
  1083. InterfaceDefinitionStartId signature;
  1084. llvm::SmallVector<AnyDeclId> members;
  1085. Lex::CloseCurlyBraceTokenIndex token;
  1086. };
  1087. // `impl`...`as` declarations and definitions
  1088. // ------------------------------------------
  1089. // `impl`
  1090. using ImplIntroducer = LeafNode<NodeKind::ImplIntroducer, Lex::ImplTokenIndex>;
  1091. // `forall [...]`
  1092. struct ImplForall {
  1093. static constexpr auto Kind = NodeKind::ImplForall.Define({.child_count = 1});
  1094. Lex::ForallTokenIndex token;
  1095. ImplicitParamListId params;
  1096. };
  1097. // `as` with no type before it
  1098. using DefaultSelfImplAs = LeafNode<NodeKind::DefaultSelfImplAs,
  1099. Lex::AsTokenIndex, NodeCategory::ImplAs>;
  1100. // `<type> as`
  1101. struct TypeImplAs {
  1102. static constexpr auto Kind = NodeKind::TypeImplAs.Define(
  1103. {.category = NodeCategory::ImplAs, .child_count = 1});
  1104. AnyExprId type_expr;
  1105. Lex::AsTokenIndex token;
  1106. };
  1107. // `impl T as I`
  1108. template <const NodeKind& KindT, typename TokenKind,
  1109. NodeCategory::RawEnumType Category>
  1110. struct ImplSignature {
  1111. static constexpr auto Kind = KindT.Define(
  1112. {.category = Category, .bracketed_by = ImplIntroducer::Kind});
  1113. ImplIntroducerId introducer;
  1114. llvm::SmallVector<AnyModifierId> modifiers;
  1115. std::optional<ImplForallId> forall;
  1116. AnyImplAsId as;
  1117. AnyExprId interface;
  1118. TokenKind token;
  1119. };
  1120. // `impl T as I;`
  1121. using ImplDecl =
  1122. ImplSignature<NodeKind::ImplDecl, Lex::SemiTokenIndex, NodeCategory::Decl>;
  1123. // `impl T as I {`
  1124. using ImplDefinitionStart =
  1125. ImplSignature<NodeKind::ImplDefinitionStart, Lex::OpenCurlyBraceTokenIndex,
  1126. NodeCategory::None>;
  1127. // `impl T as I { ... }`
  1128. struct ImplDefinition {
  1129. static constexpr auto Kind = NodeKind::ImplDefinition.Define(
  1130. {.category = NodeCategory::Decl,
  1131. .bracketed_by = ImplDefinitionStart::Kind});
  1132. ImplDefinitionStartId signature;
  1133. llvm::SmallVector<AnyDeclId> members;
  1134. Lex::CloseCurlyBraceTokenIndex token;
  1135. };
  1136. // Named constraint declarations and definitions
  1137. // ---------------------------------------------
  1138. // `constraint`
  1139. using NamedConstraintIntroducer =
  1140. LeafNode<NodeKind::NamedConstraintIntroducer, Lex::ConstraintTokenIndex>;
  1141. // `constraint NC`
  1142. template <const NodeKind& KindT, typename TokenKind,
  1143. NodeCategory::RawEnumType Category>
  1144. struct NamedConstraintSignature {
  1145. static constexpr auto Kind = KindT.Define(
  1146. {.category = Category, .bracketed_by = NamedConstraintIntroducer::Kind});
  1147. NamedConstraintIntroducerId introducer;
  1148. llvm::SmallVector<AnyModifierId> modifiers;
  1149. DeclName name;
  1150. TokenKind token;
  1151. };
  1152. // `constraint NC;`
  1153. using NamedConstraintDecl =
  1154. NamedConstraintSignature<NodeKind::NamedConstraintDecl, Lex::SemiTokenIndex,
  1155. NodeCategory::Decl>;
  1156. // `constraint NC {`
  1157. using NamedConstraintDefinitionStart =
  1158. NamedConstraintSignature<NodeKind::NamedConstraintDefinitionStart,
  1159. Lex::OpenCurlyBraceTokenIndex, NodeCategory::None>;
  1160. // `constraint NC { ... }`
  1161. struct NamedConstraintDefinition {
  1162. static constexpr auto Kind = NodeKind::NamedConstraintDefinition.Define(
  1163. {.category = NodeCategory::Decl,
  1164. .bracketed_by = NamedConstraintDefinitionStart::Kind});
  1165. NamedConstraintDefinitionStartId signature;
  1166. llvm::SmallVector<AnyDeclId> members;
  1167. Lex::CloseCurlyBraceTokenIndex token;
  1168. };
  1169. // ---------------------------------------------------------------------------
  1170. // A complete source file. Note that there is no corresponding parse node for
  1171. // the file. The file is instead the complete contents of the parse tree.
  1172. struct File {
  1173. FileStartId start;
  1174. llvm::SmallVector<AnyDeclId> decls;
  1175. FileEndId end;
  1176. };
  1177. // Define `Foo` as the node type for the ID type `FooId`.
  1178. #define CARBON_PARSE_NODE_KIND(KindName) \
  1179. template <> \
  1180. struct NodeForId<KindName##Id> { \
  1181. using TypedNode = KindName; \
  1182. };
  1183. #include "toolchain/parse/node_kind.def"
  1184. } // namespace Carbon::Parse
  1185. #endif // CARBON_TOOLCHAIN_PARSE_TYPED_NODES_H_