typed_nodes.h 51 KB

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