typed_nodes.h 48 KB

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