typed_nodes.h 45 KB

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