typed_nodes.h 50 KB

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