typed_nodes.h 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351
  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. // Choice nodes
  826. // ------------
  827. using ChoiceIntroducer =
  828. LeafNode<NodeKind::ChoiceIntroducer, Lex::ChoiceTokenIndex>;
  829. struct ChoiceSignature {
  830. static constexpr auto Kind = NodeKind::ChoiceDefinitionStart.Define(
  831. {.category = NodeCategory::None, .bracketed_by = ChoiceIntroducer::Kind});
  832. ChoiceIntroducerId introducer;
  833. llvm::SmallVector<AnyModifierId> modifiers;
  834. DeclName name;
  835. Lex::OpenCurlyBraceTokenIndex token;
  836. };
  837. using ChoiceDefinitionStart = ChoiceSignature;
  838. using ChoiceAlternativeListComma =
  839. LeafNode<NodeKind::ChoiceAlternativeListComma, Lex::CommaTokenIndex>;
  840. struct ChoiceDefinition {
  841. static constexpr auto Kind = NodeKind::ChoiceDefinition.Define(
  842. {.category = NodeCategory::Decl,
  843. .bracketed_by = ChoiceDefinitionStart::Kind});
  844. ChoiceDefinitionStartId signature;
  845. struct Alternative {
  846. IdentifierNameId name;
  847. std::optional<TuplePatternId> parameters;
  848. };
  849. CommaSeparatedList<Alternative, ChoiceAlternativeListCommaId> alternatives;
  850. Lex::CloseCurlyBraceTokenIndex token;
  851. };
  852. // Struct type and value literals
  853. // ----------------------------------------
  854. // `{`
  855. using StructLiteralStart =
  856. LeafNode<NodeKind::StructLiteralStart, Lex::OpenCurlyBraceTokenIndex>;
  857. using StructTypeLiteralStart =
  858. LeafNode<NodeKind::StructTypeLiteralStart, Lex::OpenCurlyBraceTokenIndex>;
  859. // `,`
  860. using StructComma = LeafNode<NodeKind::StructComma, Lex::CommaTokenIndex>;
  861. // `.a`
  862. struct StructFieldDesignator {
  863. static constexpr auto Kind =
  864. NodeKind::StructFieldDesignator.Define({.child_count = 1});
  865. Lex::PeriodTokenIndex token;
  866. NodeIdOneOf<IdentifierName, BaseName> name;
  867. };
  868. // `.a = 0`
  869. struct StructField {
  870. static constexpr auto Kind = NodeKind::StructField.Define(
  871. {.bracketed_by = StructFieldDesignator::Kind, .child_count = 2});
  872. StructFieldDesignatorId designator;
  873. Lex::EqualTokenIndex token;
  874. AnyExprId expr;
  875. };
  876. // `.a: i32`
  877. struct StructTypeField {
  878. static constexpr auto Kind = NodeKind::StructTypeField.Define(
  879. {.bracketed_by = StructFieldDesignator::Kind, .child_count = 2});
  880. StructFieldDesignatorId designator;
  881. Lex::ColonTokenIndex token;
  882. AnyExprId type_expr;
  883. };
  884. // Struct literals, such as `{.a = 0}`.
  885. struct StructLiteral {
  886. static constexpr auto Kind = NodeKind::StructLiteral.Define(
  887. {.category = NodeCategory::Expr,
  888. .bracketed_by = StructLiteralStart::Kind});
  889. StructLiteralStartId start;
  890. CommaSeparatedList<StructFieldId, StructCommaId> fields;
  891. Lex::CloseCurlyBraceTokenIndex token;
  892. };
  893. // Struct type literals, such as `{.a: i32}`.
  894. struct StructTypeLiteral {
  895. static constexpr auto Kind = NodeKind::StructTypeLiteral.Define(
  896. {.category = NodeCategory::Expr,
  897. .bracketed_by = StructTypeLiteralStart::Kind});
  898. StructTypeLiteralStartId start;
  899. CommaSeparatedList<StructTypeFieldId, StructCommaId> fields;
  900. Lex::CloseCurlyBraceTokenIndex token;
  901. };
  902. // `class` declarations and definitions
  903. // ------------------------------------
  904. // `class`
  905. using ClassIntroducer =
  906. LeafNode<NodeKind::ClassIntroducer, Lex::ClassTokenIndex>;
  907. // A class signature `class C`
  908. template <const NodeKind& KindT, typename TokenKind,
  909. NodeCategory::RawEnumType Category>
  910. struct ClassSignature {
  911. static constexpr auto Kind = KindT.Define(
  912. {.category = Category, .bracketed_by = ClassIntroducer::Kind});
  913. ClassIntroducerId introducer;
  914. llvm::SmallVector<AnyModifierId> modifiers;
  915. DeclName name;
  916. TokenKind token;
  917. };
  918. // `class C;`
  919. using ClassDecl = ClassSignature<NodeKind::ClassDecl, Lex::SemiTokenIndex,
  920. NodeCategory::Decl>;
  921. // `class C {`
  922. using ClassDefinitionStart =
  923. ClassSignature<NodeKind::ClassDefinitionStart,
  924. Lex::OpenCurlyBraceTokenIndex, NodeCategory::None>;
  925. // `class C { ... }`
  926. struct ClassDefinition {
  927. static constexpr auto Kind = NodeKind::ClassDefinition.Define(
  928. {.category = NodeCategory::Decl,
  929. .bracketed_by = ClassDefinitionStart::Kind});
  930. ClassDefinitionStartId signature;
  931. llvm::SmallVector<AnyDeclId> members;
  932. Lex::CloseCurlyBraceTokenIndex token;
  933. };
  934. // Adapter declaration
  935. // -------------------
  936. // `adapt`
  937. using AdaptIntroducer =
  938. LeafNode<NodeKind::AdaptIntroducer, Lex::AdaptTokenIndex>;
  939. // `adapt SomeType;`
  940. struct AdaptDecl {
  941. static constexpr auto Kind = NodeKind::AdaptDecl.Define(
  942. {.category = NodeCategory::Decl, .bracketed_by = AdaptIntroducer::Kind});
  943. AdaptIntroducerId introducer;
  944. llvm::SmallVector<AnyModifierId> modifiers;
  945. AnyExprId adapted_type;
  946. Lex::SemiTokenIndex token;
  947. };
  948. // Base class declaration
  949. // ----------------------
  950. // `base`
  951. using BaseIntroducer = LeafNode<NodeKind::BaseIntroducer, Lex::BaseTokenIndex>;
  952. using BaseColon = LeafNode<NodeKind::BaseColon, Lex::ColonTokenIndex>;
  953. // `extend base: BaseClass;`
  954. struct BaseDecl {
  955. static constexpr auto Kind = NodeKind::BaseDecl.Define(
  956. {.category = NodeCategory::Decl, .bracketed_by = BaseIntroducer::Kind});
  957. BaseIntroducerId introducer;
  958. llvm::SmallVector<AnyModifierId> modifiers;
  959. BaseColonId colon;
  960. AnyExprId base_class;
  961. Lex::SemiTokenIndex token;
  962. };
  963. // Interface declarations and definitions
  964. // --------------------------------------
  965. // `interface`
  966. using InterfaceIntroducer =
  967. LeafNode<NodeKind::InterfaceIntroducer, Lex::InterfaceTokenIndex>;
  968. // `interface I`
  969. template <const NodeKind& KindT, typename TokenKind,
  970. NodeCategory::RawEnumType Category>
  971. struct InterfaceSignature {
  972. static constexpr auto Kind = KindT.Define(
  973. {.category = Category, .bracketed_by = InterfaceIntroducer::Kind});
  974. InterfaceIntroducerId introducer;
  975. llvm::SmallVector<AnyModifierId> modifiers;
  976. DeclName name;
  977. TokenKind token;
  978. };
  979. // `interface I;`
  980. using InterfaceDecl =
  981. InterfaceSignature<NodeKind::InterfaceDecl, Lex::SemiTokenIndex,
  982. NodeCategory::Decl>;
  983. // `interface I {`
  984. using InterfaceDefinitionStart =
  985. InterfaceSignature<NodeKind::InterfaceDefinitionStart,
  986. Lex::OpenCurlyBraceTokenIndex, NodeCategory::None>;
  987. // `interface I { ... }`
  988. struct InterfaceDefinition {
  989. static constexpr auto Kind = NodeKind::InterfaceDefinition.Define(
  990. {.category = NodeCategory::Decl,
  991. .bracketed_by = InterfaceDefinitionStart::Kind});
  992. InterfaceDefinitionStartId signature;
  993. llvm::SmallVector<AnyDeclId> members;
  994. Lex::CloseCurlyBraceTokenIndex token;
  995. };
  996. // `impl`...`as` declarations and definitions
  997. // ------------------------------------------
  998. // `impl`
  999. using ImplIntroducer = LeafNode<NodeKind::ImplIntroducer, Lex::ImplTokenIndex>;
  1000. // `forall [...]`
  1001. struct ImplForall {
  1002. static constexpr auto Kind = NodeKind::ImplForall.Define({.child_count = 1});
  1003. Lex::ForallTokenIndex token;
  1004. ImplicitParamListId params;
  1005. };
  1006. // `as` with no type before it
  1007. using DefaultSelfImplAs = LeafNode<NodeKind::DefaultSelfImplAs,
  1008. Lex::AsTokenIndex, NodeCategory::ImplAs>;
  1009. // `<type> as`
  1010. struct TypeImplAs {
  1011. static constexpr auto Kind = NodeKind::TypeImplAs.Define(
  1012. {.category = NodeCategory::ImplAs, .child_count = 1});
  1013. AnyExprId type_expr;
  1014. Lex::AsTokenIndex token;
  1015. };
  1016. // `impl T as I`
  1017. template <const NodeKind& KindT, typename TokenKind,
  1018. NodeCategory::RawEnumType Category>
  1019. struct ImplSignature {
  1020. static constexpr auto Kind = KindT.Define(
  1021. {.category = Category, .bracketed_by = ImplIntroducer::Kind});
  1022. ImplIntroducerId introducer;
  1023. llvm::SmallVector<AnyModifierId> modifiers;
  1024. std::optional<ImplForallId> forall;
  1025. AnyImplAsId as;
  1026. AnyExprId interface;
  1027. TokenKind token;
  1028. };
  1029. // `impl T as I;`
  1030. using ImplDecl =
  1031. ImplSignature<NodeKind::ImplDecl, Lex::SemiTokenIndex, NodeCategory::Decl>;
  1032. // `impl T as I {`
  1033. using ImplDefinitionStart =
  1034. ImplSignature<NodeKind::ImplDefinitionStart, Lex::OpenCurlyBraceTokenIndex,
  1035. NodeCategory::None>;
  1036. // `impl T as I { ... }`
  1037. struct ImplDefinition {
  1038. static constexpr auto Kind = NodeKind::ImplDefinition.Define(
  1039. {.category = NodeCategory::Decl,
  1040. .bracketed_by = ImplDefinitionStart::Kind});
  1041. ImplDefinitionStartId signature;
  1042. llvm::SmallVector<AnyDeclId> members;
  1043. Lex::CloseCurlyBraceTokenIndex token;
  1044. };
  1045. // Named constraint declarations and definitions
  1046. // ---------------------------------------------
  1047. // `constraint`
  1048. using NamedConstraintIntroducer =
  1049. LeafNode<NodeKind::NamedConstraintIntroducer, Lex::ConstraintTokenIndex>;
  1050. // `constraint NC`
  1051. template <const NodeKind& KindT, typename TokenKind,
  1052. NodeCategory::RawEnumType Category>
  1053. struct NamedConstraintSignature {
  1054. static constexpr auto Kind = KindT.Define(
  1055. {.category = Category, .bracketed_by = NamedConstraintIntroducer::Kind});
  1056. NamedConstraintIntroducerId introducer;
  1057. llvm::SmallVector<AnyModifierId> modifiers;
  1058. DeclName name;
  1059. TokenKind token;
  1060. };
  1061. // `constraint NC;`
  1062. using NamedConstraintDecl =
  1063. NamedConstraintSignature<NodeKind::NamedConstraintDecl, Lex::SemiTokenIndex,
  1064. NodeCategory::Decl>;
  1065. // `constraint NC {`
  1066. using NamedConstraintDefinitionStart =
  1067. NamedConstraintSignature<NodeKind::NamedConstraintDefinitionStart,
  1068. Lex::OpenCurlyBraceTokenIndex, NodeCategory::None>;
  1069. // `constraint NC { ... }`
  1070. struct NamedConstraintDefinition {
  1071. static constexpr auto Kind = NodeKind::NamedConstraintDefinition.Define(
  1072. {.category = NodeCategory::Decl,
  1073. .bracketed_by = NamedConstraintDefinitionStart::Kind});
  1074. NamedConstraintDefinitionStartId signature;
  1075. llvm::SmallVector<AnyDeclId> members;
  1076. Lex::CloseCurlyBraceTokenIndex token;
  1077. };
  1078. // ---------------------------------------------------------------------------
  1079. // A complete source file. Note that there is no corresponding parse node for
  1080. // the file. The file is instead the complete contents of the parse tree.
  1081. struct File {
  1082. FileStartId start;
  1083. llvm::SmallVector<AnyDeclId> decls;
  1084. FileEndId end;
  1085. };
  1086. // Define `Foo` as the node type for the ID type `FooId`.
  1087. #define CARBON_PARSE_NODE_KIND(KindName) \
  1088. template <> \
  1089. struct NodeForId<KindName##Id> { \
  1090. using TypedNode = KindName; \
  1091. };
  1092. #include "toolchain/parse/node_kind.def"
  1093. } // namespace Carbon::Parse
  1094. #endif // CARBON_TOOLCHAIN_PARSE_TYPED_NODES_H_