typed_nodes.h 47 KB

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