parser.ypp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964
  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. // -----------------------------------------------------------------------------
  5. // Bison Configuration
  6. // -----------------------------------------------------------------------------
  7. %require "3.2"
  8. %language "c++"
  9. // We don't need a separate header for Bison locations.
  10. %define api.location.file none
  11. // Use a type-safe C++ variant for semantic values
  12. %define api.value.type variant
  13. // Have Bison generate the functions ‘make_TEXT’ and ‘make_NUMBER’, but also
  14. // ‘make_YYEOF’, for the end of input.
  15. %define api.token.constructor
  16. // Generate the parser as `::Carbon::Parser`.
  17. %define api.namespace { Carbon }
  18. %define api.parser.class { Parser }
  19. // Make parse error messages more detailed
  20. %define parse.error verbose
  21. // Enable support for parser debugging
  22. %define parse.trace true
  23. // Generate location structs.
  24. %locations
  25. // Parameters to the parser and lexer.
  26. //
  27. // Parameters to the parser are stored therein as protected data members, and
  28. // thus available to its methods.
  29. // "inout" parameters passed to both the parser and the lexer.
  30. %param {Nonnull<Arena*> arena}
  31. %param {yyscan_t yyscanner}
  32. %param {ParseAndLexContext& context}
  33. // "out" parameter passed to the parser, where the AST is written.
  34. %parse-param {std::optional<AST>* ast}
  35. // No shift-reduce conflicts are expected.
  36. // See README.md#precedence-and-associativity for a description of how
  37. // operator precedence is expressed.
  38. %expect 0
  39. // -----------------------------------------------------------------------------
  40. %code top {
  41. #include <algorithm>
  42. #include <cstdarg>
  43. #include <cstdio>
  44. #include <cstdlib>
  45. #include <vector>
  46. #include "common/check.h"
  47. #include "explorer/syntax/parse_and_lex_context.h"
  48. #include "llvm/ADT/StringExtras.h"
  49. #include "llvm/Support/raw_ostream.h"
  50. } // %code top
  51. %code requires {
  52. #include <optional>
  53. #include "explorer/ast/ast.h"
  54. #include "explorer/ast/declaration.h"
  55. #include "explorer/ast/expression.h"
  56. #include "explorer/ast/paren_contents.h"
  57. #include "explorer/ast/pattern.h"
  58. #include "explorer/ast/value_category.h"
  59. #include "explorer/common/arena.h"
  60. #include "explorer/common/nonnull.h"
  61. #include "explorer/syntax/bison_wrap.h"
  62. namespace Carbon {
  63. class ParseAndLexContext;
  64. } // namespace Carbon
  65. typedef void* yyscan_t;
  66. } // %code requires
  67. %code {
  68. void Carbon::Parser::error(const location_type&, const std::string& message) {
  69. context.RecordSyntaxError(message);
  70. }
  71. } // %code
  72. %token <int> integer_literal
  73. %token <std::string> identifier
  74. %token <IntrinsicExpression::Intrinsic> intrinsic_identifier
  75. %token <std::string> sized_type_literal
  76. %token <std::string> string_literal
  77. %type <std::string> designator
  78. %type <ImplKind> impl_kind
  79. %type <Nonnull<Expression*>> impl_type
  80. %type <std::pair<LibraryName, bool>> package_directive
  81. %type <LibraryName> import_directive
  82. %type <std::vector<LibraryName>> import_directives
  83. %type <std::string> optional_library_path
  84. %type <bool> api_or_impl
  85. %type <Nonnull<Declaration*>> declaration
  86. %type <Nonnull<FunctionDeclaration*>> function_declaration
  87. %type <std::vector<Nonnull<Declaration*>>> declaration_list
  88. %type <Nonnull<Statement*>> statement
  89. %type <Nonnull<If*>> if_statement
  90. %type <std::optional<Nonnull<Block*>>> optional_else
  91. %type <std::pair<Nonnull<Expression*>, bool>> return_expression
  92. %type <Nonnull<Block*>> nonempty_block
  93. %type <Nonnull<Block*>> block
  94. %type <std::vector<Nonnull<Statement*>>> statement_list
  95. %type <Nonnull<Expression*>> primary_expression
  96. %type <Nonnull<Expression*>> postfix_expression
  97. %type <Nonnull<Expression*>> ref_deref_expression
  98. %type <Nonnull<Expression*>> type_expression
  99. %type <Nonnull<Expression*>> fn_type_expression
  100. %type <Nonnull<Expression*>> minus_expression
  101. %type <Nonnull<Expression*>> multiplicative_operand
  102. %type <Nonnull<Expression*>> multiplicative_lhs
  103. %type <Nonnull<Expression*>> multiplicative_expression
  104. %type <Nonnull<Expression*>> additive_operand
  105. %type <Nonnull<Expression*>> additive_lhs
  106. %type <Nonnull<Expression*>> additive_expression
  107. %type <Nonnull<Expression*>> unimpl_expression
  108. %type <Nonnull<Expression*>> value_expression
  109. %type <Nonnull<Expression*>> comparison_operand
  110. %type <Nonnull<Expression*>> comparison_expression
  111. %type <Nonnull<Expression*>> not_expression
  112. %type <Nonnull<Expression*>> predicate_expression
  113. %type <Nonnull<Expression*>> and_or_operand
  114. %type <Nonnull<Expression*>> and_lhs
  115. %type <Nonnull<Expression*>> and_expression
  116. %type <Nonnull<Expression*>> or_lhs
  117. %type <Nonnull<Expression*>> or_expression
  118. %type <Nonnull<Expression*>> statement_expression
  119. %type <Nonnull<Expression*>> if_expression
  120. %type <Nonnull<Expression*>> expression
  121. %type <Nonnull<GenericBinding*>> generic_binding
  122. %type <std::vector<Nonnull<AstNode*>>> deduced_params
  123. %type <std::vector<Nonnull<AstNode*>>> impl_deduced_params
  124. %type <std::vector<Nonnull<AstNode*>>> deduced_param_list
  125. %type <Nonnull<Pattern*>> pattern
  126. %type <Nonnull<Pattern*>> non_expression_pattern
  127. %type <BisonWrap<ReturnTerm>> return_term
  128. %type <Nonnull<Expression*>> paren_expression
  129. %type <Nonnull<StructLiteral*>> struct_literal
  130. %type <std::vector<FieldInitializer>> struct_literal_contents
  131. %type <Nonnull<StructTypeLiteral*>> struct_type_literal
  132. %type <std::vector<FieldInitializer>> struct_type_literal_contents
  133. %type <Nonnull<TupleLiteral*>> tuple
  134. %type <std::string> binding_lhs
  135. %type <std::optional<Nonnull<BindingPattern*>>> receiver
  136. %type <Nonnull<BindingPattern*>> variable_declaration
  137. %type <ParenContents<Expression>> paren_expression_base
  138. %type <ParenContents<Expression>> paren_expression_contents
  139. %type <Nonnull<Pattern*>> paren_pattern
  140. %type <Nonnull<TuplePattern*>> tuple_pattern
  141. %type <Nonnull<TuplePattern*>> maybe_empty_tuple_pattern
  142. %type <std::optional<Nonnull<TuplePattern*>>> type_params
  143. %type <ParenContents<Pattern>> paren_pattern_base
  144. %type <ParenContents<Pattern>> paren_pattern_contents
  145. %type <Nonnull<AlternativeSignature*>> alternative
  146. %type <std::vector<Nonnull<AlternativeSignature*>>> alternative_list
  147. %type <std::vector<Nonnull<AlternativeSignature*>>> alternative_list_contents
  148. %type <BisonWrap<Match::Clause>> clause
  149. %type <std::vector<Match::Clause>> clause_list
  150. %token
  151. // Most tokens have their spelling defined in lexer.lpp.
  152. // table-begin
  153. AMPERSAND
  154. AND
  155. API
  156. ARROW
  157. AS
  158. AUTO
  159. AWAIT
  160. BOOL
  161. BREAK
  162. CASE
  163. CHOICE
  164. CLASS
  165. COLON
  166. COLON_BANG
  167. COMMA
  168. CONTINUATION
  169. CONTINUATION_TYPE
  170. CONTINUE
  171. DEFAULT
  172. DOUBLE_ARROW
  173. ELSE
  174. EQUAL
  175. EQUAL_EQUAL
  176. EXTERNAL
  177. FALSE
  178. FN
  179. FN_TYPE
  180. FORALL
  181. IF
  182. IMPL
  183. IMPORT
  184. INTERFACE
  185. LEFT_CURLY_BRACE
  186. LEFT_PARENTHESIS
  187. LEFT_SQUARE_BRACKET
  188. LET
  189. LIBRARY
  190. MATCH
  191. MINUS
  192. NOT
  193. OR
  194. PACKAGE
  195. PERIOD
  196. PLUS
  197. RETURN
  198. RIGHT_CURLY_BRACE
  199. RIGHT_PARENTHESIS
  200. RIGHT_SQUARE_BRACKET
  201. RUN
  202. SELF
  203. SEMICOLON
  204. SLASH
  205. STRING
  206. THEN
  207. TRUE
  208. TYPE
  209. UNDERSCORE
  210. UNIMPL_EXAMPLE
  211. VAR
  212. WHILE
  213. // table-end
  214. // Used to track EOF.
  215. END_OF_FILE 0
  216. // Only used for precedence.
  217. FNARROW "-> in return type"
  218. // The lexer determines the arity and fixity of each `*` based on whitespace
  219. // and adjacent tokens. UNARY_STAR indicates that the operator is unary but
  220. // could be either prefix or postfix.
  221. UNARY_STAR "unary *"
  222. PREFIX_STAR "prefix *"
  223. POSTFIX_STAR "postfix *"
  224. BINARY_STAR "binary *"
  225. ;
  226. %start input
  227. %%
  228. input: package_directive import_directives declaration_list
  229. {
  230. *ast = AST({.package = $1.first,
  231. .is_api = $1.second,
  232. .imports = std::move($2),
  233. .declarations = std::move($3)});
  234. }
  235. ;
  236. package_directive:
  237. PACKAGE identifier optional_library_path api_or_impl SEMICOLON
  238. { $$ = {LibraryName({.package = $2, .path = $3}), $4}; }
  239. ;
  240. import_directive:
  241. IMPORT identifier optional_library_path SEMICOLON
  242. { $$ = LibraryName({.package = $2, .path = $3}); }
  243. ;
  244. import_directives:
  245. // Empty
  246. { $$ = std::vector<LibraryName>(); }
  247. | import_directives import_directive
  248. {
  249. $$ = std::move($1);
  250. $$.push_back($2);
  251. }
  252. ;
  253. optional_library_path:
  254. // Empty
  255. { $$ = ""; }
  256. | LIBRARY string_literal
  257. { $$ = $2; }
  258. ;
  259. api_or_impl:
  260. API
  261. { $$ = true; }
  262. | IMPL
  263. { $$ = false; }
  264. ;
  265. primary_expression:
  266. identifier
  267. { $$ = arena->New<IdentifierExpression>(context.source_loc(), $1); }
  268. | integer_literal
  269. { $$ = arena->New<IntLiteral>(context.source_loc(), $1); }
  270. | string_literal
  271. { $$ = arena->New<StringLiteral>(context.source_loc(), $1); }
  272. | TRUE
  273. { $$ = arena->New<BoolLiteral>(context.source_loc(), true); }
  274. | FALSE
  275. { $$ = arena->New<BoolLiteral>(context.source_loc(), false); }
  276. | sized_type_literal
  277. {
  278. int val;
  279. CARBON_CHECK(llvm::to_integer(llvm::StringRef($1).substr(1), val));
  280. CARBON_CHECK($1[0] == 'i' && val == 32)
  281. << "Only i32 is supported for now: " << $1;
  282. $$ = arena->New<IntTypeLiteral>(context.source_loc());
  283. }
  284. | SELF
  285. // FIXME: Should we create a new TypeLiteral for `Self`?
  286. { $$ = arena->New<IdentifierExpression>(context.source_loc(), "Self"); }
  287. | STRING
  288. { $$ = arena->New<StringTypeLiteral>(context.source_loc()); }
  289. | BOOL
  290. { $$ = arena->New<BoolTypeLiteral>(context.source_loc()); }
  291. | TYPE
  292. { $$ = arena->New<TypeTypeLiteral>(context.source_loc()); }
  293. | CONTINUATION_TYPE
  294. { $$ = arena->New<ContinuationTypeLiteral>(context.source_loc()); }
  295. | paren_expression { $$ = $1; }
  296. | struct_literal { $$ = $1; }
  297. | struct_type_literal { $$ = $1; }
  298. | LEFT_SQUARE_BRACKET expression SEMICOLON expression RIGHT_SQUARE_BRACKET
  299. { $$ = arena->New<ArrayTypeLiteral>(context.source_loc(), $2, $4); }
  300. ;
  301. postfix_expression:
  302. primary_expression
  303. | postfix_expression designator
  304. { $$ = arena->New<FieldAccessExpression>(context.source_loc(), $1, $2); }
  305. | postfix_expression LEFT_SQUARE_BRACKET expression RIGHT_SQUARE_BRACKET
  306. { $$ = arena->New<IndexExpression>(context.source_loc(), $1, $3); }
  307. | intrinsic_identifier tuple
  308. { $$ = arena->New<IntrinsicExpression>($1, $2, context.source_loc()); }
  309. | postfix_expression tuple
  310. { $$ = arena->New<CallExpression>(context.source_loc(), $1, $2); }
  311. | postfix_expression POSTFIX_STAR
  312. {
  313. $$ = arena->New<PrimitiveOperatorExpression>(
  314. context.source_loc(), Operator::Ptr,
  315. std::vector<Nonnull<Expression*>>({$1}));
  316. }
  317. | postfix_expression UNARY_STAR
  318. {
  319. $$ = arena->New<PrimitiveOperatorExpression>(
  320. context.source_loc(), Operator::Ptr,
  321. std::vector<Nonnull<Expression*>>({$1}));
  322. }
  323. ;
  324. ref_deref_expression:
  325. postfix_expression
  326. | PREFIX_STAR ref_deref_expression
  327. {
  328. $$ = arena->New<PrimitiveOperatorExpression>(
  329. context.source_loc(), Operator::Deref,
  330. std::vector<Nonnull<Expression*>>({$2}));
  331. }
  332. | UNARY_STAR ref_deref_expression
  333. {
  334. $$ = arena->New<PrimitiveOperatorExpression>(
  335. context.source_loc(), Operator::Deref,
  336. std::vector<Nonnull<Expression*>>({$2}));
  337. }
  338. | AMPERSAND ref_deref_expression
  339. {
  340. $$ = arena->New<PrimitiveOperatorExpression>(
  341. context.source_loc(), Operator::AddressOf,
  342. std::vector<Nonnull<Expression*>>({$2}));
  343. }
  344. ;
  345. fn_type_expression:
  346. FN_TYPE tuple ARROW type_expression
  347. { $$ = arena->New<FunctionTypeLiteral>(context.source_loc(), $2, $4); }
  348. ;
  349. type_expression:
  350. ref_deref_expression
  351. | fn_type_expression
  352. ;
  353. minus_expression:
  354. // ref_deref_expression excluded due to precedence diamond.
  355. MINUS ref_deref_expression
  356. {
  357. $$ = arena->New<PrimitiveOperatorExpression>(
  358. context.source_loc(), Operator::Neg,
  359. std::vector<Nonnull<Expression*>>({$2}));
  360. }
  361. ;
  362. multiplicative_operand:
  363. ref_deref_expression
  364. | minus_expression
  365. ;
  366. multiplicative_lhs:
  367. ref_deref_expression
  368. | multiplicative_expression
  369. ;
  370. multiplicative_expression:
  371. minus_expression
  372. | multiplicative_lhs BINARY_STAR multiplicative_operand
  373. {
  374. $$ = arena->New<PrimitiveOperatorExpression>(
  375. context.source_loc(), Operator::Mul,
  376. std::vector<Nonnull<Expression*>>({$1, $3}));
  377. }
  378. ;
  379. additive_operand:
  380. ref_deref_expression
  381. | multiplicative_expression
  382. ;
  383. additive_lhs:
  384. ref_deref_expression
  385. | additive_expression
  386. ;
  387. additive_expression:
  388. multiplicative_expression
  389. | additive_lhs PLUS additive_operand
  390. {
  391. $$ = arena->New<PrimitiveOperatorExpression>(
  392. context.source_loc(), Operator::Add,
  393. std::vector<Nonnull<Expression*>>({$1, $3}));
  394. }
  395. | additive_lhs MINUS additive_operand
  396. {
  397. $$ = arena->New<PrimitiveOperatorExpression>(
  398. context.source_loc(), Operator::Sub,
  399. std::vector<Nonnull<Expression*>>({$1, $3}));
  400. }
  401. ;
  402. unimpl_expression:
  403. // ref_deref_expression excluded due to precedence diamond.
  404. ref_deref_expression UNIMPL_EXAMPLE ref_deref_expression
  405. {
  406. $$ = arena->New<UnimplementedExpression>(context.source_loc(),
  407. "ExampleInfix", $1, $3);
  408. }
  409. ;
  410. value_expression:
  411. // ref_deref_expression excluded due to precedence diamond.
  412. additive_expression
  413. | fn_type_expression
  414. | unimpl_expression
  415. ;
  416. comparison_operand:
  417. ref_deref_expression
  418. | value_expression
  419. ;
  420. comparison_expression:
  421. value_expression
  422. | comparison_operand EQUAL_EQUAL comparison_operand
  423. {
  424. $$ = arena->New<PrimitiveOperatorExpression>(
  425. context.source_loc(), Operator::Eq,
  426. std::vector<Nonnull<Expression*>>({$1, $3}));
  427. }
  428. ;
  429. not_expression:
  430. NOT ref_deref_expression
  431. {
  432. $$ = arena->New<PrimitiveOperatorExpression>(
  433. context.source_loc(), Operator::Not,
  434. std::vector<Nonnull<Expression*>>({$2}));
  435. }
  436. ;
  437. predicate_expression:
  438. // ref_deref_expression excluded due to precedence diamond.
  439. not_expression
  440. | comparison_expression
  441. ;
  442. and_or_operand:
  443. ref_deref_expression
  444. | predicate_expression
  445. ;
  446. and_lhs:
  447. and_or_operand
  448. | and_expression
  449. ;
  450. and_expression:
  451. // predicate_expression excluded due to precedence diamond.
  452. and_lhs AND and_or_operand
  453. {
  454. $$ = arena->New<PrimitiveOperatorExpression>(
  455. context.source_loc(), Operator::And,
  456. std::vector<Nonnull<Expression*>>({$1, $3}));
  457. }
  458. ;
  459. or_lhs:
  460. and_or_operand
  461. | or_expression
  462. ;
  463. or_expression:
  464. // predicate_expression excluded due to precedence diamond.
  465. or_lhs OR and_or_operand
  466. {
  467. $$ = arena->New<PrimitiveOperatorExpression>(
  468. context.source_loc(), Operator::Or,
  469. std::vector<Nonnull<Expression*>>({$1, $3}));
  470. }
  471. ;
  472. statement_expression:
  473. ref_deref_expression
  474. | predicate_expression
  475. | and_expression
  476. | or_expression
  477. ;
  478. if_expression:
  479. statement_expression
  480. | IF expression THEN if_expression ELSE if_expression
  481. { $$ = arena->New<IfExpression>(context.source_loc(), $2, $4, $6); }
  482. ;
  483. expression:
  484. if_expression
  485. ;
  486. designator: PERIOD identifier { $$ = $2; }
  487. ;
  488. paren_expression: paren_expression_base
  489. { $$ = ExpressionFromParenContents(arena, context.source_loc(), $1); }
  490. ;
  491. tuple: paren_expression_base
  492. { $$ = TupleExpressionFromParenContents(arena, context.source_loc(), $1); }
  493. ;
  494. paren_expression_base:
  495. LEFT_PARENTHESIS RIGHT_PARENTHESIS
  496. { $$ = {.elements = {}, .has_trailing_comma = false}; }
  497. | LEFT_PARENTHESIS paren_expression_contents RIGHT_PARENTHESIS
  498. { $$ = $2; }
  499. | LEFT_PARENTHESIS paren_expression_contents COMMA RIGHT_PARENTHESIS
  500. {
  501. $$ = $2;
  502. $$.has_trailing_comma = true;
  503. }
  504. ;
  505. paren_expression_contents:
  506. expression
  507. { $$ = {.elements = {$1}, .has_trailing_comma = false}; }
  508. | paren_expression_contents COMMA expression
  509. {
  510. $$ = $1;
  511. $$.elements.push_back($3);
  512. }
  513. ;
  514. struct_literal:
  515. LEFT_CURLY_BRACE struct_literal_contents RIGHT_CURLY_BRACE
  516. { $$ = arena->New<StructLiteral>(context.source_loc(), $2); }
  517. | LEFT_CURLY_BRACE struct_literal_contents COMMA RIGHT_CURLY_BRACE
  518. { $$ = arena->New<StructLiteral>(context.source_loc(), $2); }
  519. ;
  520. struct_literal_contents:
  521. designator EQUAL expression
  522. { $$ = {FieldInitializer($1, $3)}; }
  523. | struct_literal_contents COMMA designator EQUAL expression
  524. {
  525. $$ = $1;
  526. $$.push_back(FieldInitializer($3, $5));
  527. }
  528. ;
  529. struct_type_literal:
  530. LEFT_CURLY_BRACE RIGHT_CURLY_BRACE
  531. { $$ = arena->New<StructTypeLiteral>(context.source_loc()); }
  532. | LEFT_CURLY_BRACE struct_type_literal_contents RIGHT_CURLY_BRACE
  533. { $$ = arena->New<StructTypeLiteral>(context.source_loc(), $2); }
  534. | LEFT_CURLY_BRACE struct_type_literal_contents COMMA RIGHT_CURLY_BRACE
  535. { $$ = arena->New<StructTypeLiteral>(context.source_loc(), $2); }
  536. ;
  537. struct_type_literal_contents:
  538. designator COLON expression
  539. { $$ = {FieldInitializer($1, $3)}; }
  540. | struct_type_literal_contents COMMA designator COLON expression
  541. {
  542. $$ = $1;
  543. $$.push_back(FieldInitializer($3, $5));
  544. }
  545. ;
  546. // In many cases, using `pattern` recursively will result in ambiguities.
  547. // When that happens, it's necessary to factor out two separate productions,
  548. // one for when the sub-pattern is an expression, and one for when it is not.
  549. // To facilitate this, non-terminals besides `pattern` whose names contain
  550. // `pattern` are structured to be disjoint from `expression`, unless otherwise
  551. // specified.
  552. pattern:
  553. non_expression_pattern
  554. { $$ = $1; }
  555. | expression
  556. { $$ = arena->New<ExpressionPattern>($1); }
  557. ;
  558. non_expression_pattern:
  559. AUTO
  560. { $$ = arena->New<AutoPattern>(context.source_loc()); }
  561. | binding_lhs COLON pattern
  562. {
  563. $$ = arena->New<BindingPattern>(context.source_loc(), $1, $3,
  564. std::nullopt);
  565. }
  566. | binding_lhs COLON_BANG expression
  567. { $$ = arena->New<GenericBinding>(context.source_loc(), $1, $3); }
  568. | paren_pattern
  569. { $$ = $1; }
  570. | postfix_expression tuple_pattern
  571. {
  572. ErrorOr<Nonnull<AlternativePattern*>> alternative_pattern =
  573. AlternativePattern::Create(arena, context.source_loc(), $1, $2);
  574. if (alternative_pattern.ok()) {
  575. $$ = *alternative_pattern;
  576. } else {
  577. context.RecordSyntaxError(alternative_pattern.error().message());
  578. YYERROR;
  579. }
  580. }
  581. | VAR non_expression_pattern
  582. { $$ = arena->New<VarPattern>(context.source_loc(), $2); }
  583. ;
  584. binding_lhs:
  585. identifier { $$ = $1; }
  586. | UNDERSCORE { $$ = AnonymousName; }
  587. ;
  588. paren_pattern: paren_pattern_base
  589. { $$ = PatternFromParenContents(arena, context.source_loc(), $1); }
  590. ;
  591. paren_pattern_base:
  592. LEFT_PARENTHESIS paren_pattern_contents RIGHT_PARENTHESIS
  593. { $$ = $2; }
  594. | LEFT_PARENTHESIS paren_pattern_contents COMMA RIGHT_PARENTHESIS
  595. {
  596. $$ = $2;
  597. $$.has_trailing_comma = true;
  598. }
  599. ;
  600. // paren_pattern is analogous to paren_expression, but in order to avoid
  601. // ambiguities, it must be disjoint from paren_expression, meaning it must
  602. // contain at least one non_expression_pattern. The structure of this rule
  603. // is very different from the corresponding expression rule because is has to
  604. // enforce that requirement.
  605. paren_pattern_contents:
  606. non_expression_pattern
  607. { $$ = {.elements = {$1}, .has_trailing_comma = false}; }
  608. | paren_expression_contents COMMA non_expression_pattern
  609. {
  610. $$ = ParenExpressionToParenPattern(arena, $1);
  611. $$.elements.push_back($3);
  612. }
  613. | paren_pattern_contents COMMA expression
  614. {
  615. $$ = $1;
  616. $$.elements.push_back(arena->New<ExpressionPattern>($3));
  617. }
  618. | paren_pattern_contents COMMA non_expression_pattern
  619. {
  620. $$ = $1;
  621. $$.elements.push_back($3);
  622. }
  623. ;
  624. tuple_pattern: paren_pattern_base
  625. { $$ = TuplePatternFromParenContents(arena, context.source_loc(), $1); }
  626. ;
  627. // Unlike most `pattern` nonterminals, this one overlaps with `expression`,
  628. // so it should be used only when prior context (such as an introducer)
  629. // rules out the possibility of an `expression` at this point.
  630. maybe_empty_tuple_pattern:
  631. LEFT_PARENTHESIS RIGHT_PARENTHESIS
  632. {
  633. $$ = arena->New<TuplePattern>(context.source_loc(),
  634. std::vector<Nonnull<Pattern*>>());
  635. }
  636. | tuple_pattern
  637. { $$ = $1; }
  638. ;
  639. clause:
  640. CASE pattern DOUBLE_ARROW statement
  641. { $$ = Match::Clause($2, $4); }
  642. | DEFAULT DOUBLE_ARROW statement
  643. {
  644. $$ = Match::Clause(arena->New<BindingPattern>(
  645. context.source_loc(), std::string(AnonymousName),
  646. arena->New<AutoPattern>(context.source_loc()),
  647. ValueCategory::Let),
  648. $3);
  649. }
  650. ;
  651. clause_list:
  652. // Empty
  653. { $$ = {}; }
  654. | clause_list clause
  655. {
  656. $$ = $1;
  657. $$.push_back($2);
  658. }
  659. ;
  660. statement:
  661. statement_expression EQUAL expression SEMICOLON
  662. { $$ = arena->New<Assign>(context.source_loc(), $1, $3); }
  663. | VAR pattern EQUAL expression SEMICOLON
  664. {
  665. $$ = arena->New<VariableDefinition>(context.source_loc(), $2, $4,
  666. ValueCategory::Var);
  667. }
  668. | LET pattern EQUAL expression SEMICOLON
  669. {
  670. $$ = arena->New<VariableDefinition>(context.source_loc(), $2, $4,
  671. ValueCategory::Let);
  672. }
  673. | statement_expression SEMICOLON
  674. { $$ = arena->New<ExpressionStatement>(context.source_loc(), $1); }
  675. | if_statement
  676. { $$ = $1; }
  677. | WHILE LEFT_PARENTHESIS expression RIGHT_PARENTHESIS block
  678. { $$ = arena->New<While>(context.source_loc(), $3, $5); }
  679. | BREAK SEMICOLON
  680. { $$ = arena->New<Break>(context.source_loc()); }
  681. | CONTINUE SEMICOLON
  682. { $$ = arena->New<Continue>(context.source_loc()); }
  683. | RETURN return_expression SEMICOLON
  684. {
  685. auto [return_exp, is_omitted_exp] = $2;
  686. $$ = arena->New<Return>(context.source_loc(), return_exp, is_omitted_exp);
  687. }
  688. // We disallow empty blocks in places where an arbitrary statement can occur
  689. // in order to avoid ambiguity with the empty struct literal `{}`. We can
  690. // allow non-empty blocks because a non-empty struct literal always starts with
  691. // a designator, and a block never does, so one token of lookahead suffices
  692. // to disambiguate. As of this writing, the "official" resolution of this
  693. // ambiguity is an open question (see
  694. // https://github.com/carbon-language/carbon-lang/blob/trunk/docs/design/classes.md#literals)
  695. | nonempty_block
  696. { $$ = $1; }
  697. | MATCH LEFT_PARENTHESIS expression RIGHT_PARENTHESIS LEFT_CURLY_BRACE
  698. clause_list RIGHT_CURLY_BRACE
  699. { $$ = arena->New<Match>(context.source_loc(), $3, $6); }
  700. | CONTINUATION identifier block
  701. { $$ = arena->New<Continuation>(context.source_loc(), $2, $3); }
  702. | RUN expression SEMICOLON
  703. { $$ = arena->New<Run>(context.source_loc(), $2); }
  704. | AWAIT SEMICOLON
  705. { $$ = arena->New<Await>(context.source_loc()); }
  706. ;
  707. if_statement:
  708. IF LEFT_PARENTHESIS expression RIGHT_PARENTHESIS block optional_else
  709. { $$ = arena->New<If>(context.source_loc(), $3, $5, $6); }
  710. ;
  711. optional_else:
  712. // Empty
  713. { $$ = std::nullopt; }
  714. | ELSE if_statement
  715. {
  716. $$ = arena->New<Block>(context.source_loc(),
  717. std::vector<Nonnull<Statement*>>({$2}));
  718. }
  719. | ELSE block
  720. { $$ = $2; }
  721. ;
  722. return_expression:
  723. // Empty
  724. { $$ = {arena->New<TupleLiteral>(context.source_loc()), true}; }
  725. | expression
  726. { $$ = {$1, false}; }
  727. ;
  728. statement_list:
  729. // Empty
  730. { $$ = {}; }
  731. | statement_list statement
  732. {
  733. $$ = std::move($1);
  734. $$.push_back($2);
  735. }
  736. ;
  737. block:
  738. LEFT_CURLY_BRACE statement_list RIGHT_CURLY_BRACE
  739. { $$ = arena->New<Block>(context.source_loc(), std::move($2)); }
  740. ;
  741. nonempty_block:
  742. LEFT_CURLY_BRACE statement_list statement RIGHT_CURLY_BRACE
  743. {
  744. $2.push_back($3);
  745. $$ = arena->New<Block>(context.source_loc(), std::move($2));
  746. }
  747. ;
  748. return_term:
  749. // Empty
  750. { $$ = ReturnTerm::Omitted(context.source_loc()); }
  751. | ARROW AUTO
  752. { $$ = ReturnTerm::Auto(context.source_loc()); }
  753. | ARROW expression
  754. { $$ = ReturnTerm::Explicit($2); }
  755. ;
  756. generic_binding:
  757. identifier COLON_BANG expression
  758. {
  759. $$ = arena->New<GenericBinding>(context.source_loc(), std::move($1), $3);
  760. }
  761. ;
  762. deduced_param_list:
  763. // Empty
  764. { $$ = std::vector<Nonnull<AstNode*>>(); }
  765. | generic_binding
  766. {
  767. $$ = std::vector<Nonnull<AstNode*>>();
  768. $$.push_back($1);
  769. }
  770. | deduced_param_list COMMA generic_binding
  771. {
  772. $$ = $1;
  773. $$.push_back($3);
  774. }
  775. | variable_declaration
  776. {
  777. $$ = std::vector<Nonnull<AstNode*>>();
  778. $$.push_back($1);
  779. }
  780. | deduced_param_list COMMA variable_declaration
  781. {
  782. $$ = $1;
  783. $$.push_back($3);
  784. }
  785. ;
  786. deduced_params:
  787. // Empty
  788. { $$ = std::vector<Nonnull<AstNode*>>(); }
  789. | LEFT_SQUARE_BRACKET deduced_param_list RIGHT_SQUARE_BRACKET
  790. { $$ = $2; }
  791. ;
  792. impl_deduced_params:
  793. // Empty
  794. { $$ = std::vector<Nonnull<AstNode*>>(); }
  795. | FORALL LEFT_SQUARE_BRACKET deduced_param_list RIGHT_SQUARE_BRACKET
  796. { $$ = $3; }
  797. ;
  798. receiver:
  799. // Empty
  800. { $$ = std::nullopt; }
  801. | LEFT_CURLY_BRACE variable_declaration RIGHT_CURLY_BRACE
  802. { $$ = $2; }
  803. ;
  804. function_declaration:
  805. FN identifier deduced_params receiver maybe_empty_tuple_pattern return_term block
  806. {
  807. ErrorOr<FunctionDeclaration*> fn = FunctionDeclaration::Create(
  808. arena, context.source_loc(), $2, $3, $4, $5, $6, $7);
  809. if (fn.ok()) {
  810. $$ = *fn;
  811. } else {
  812. context.RecordSyntaxError(fn.error().message());
  813. YYERROR;
  814. }
  815. }
  816. | FN identifier deduced_params receiver maybe_empty_tuple_pattern return_term SEMICOLON
  817. {
  818. ErrorOr<FunctionDeclaration*> fn = FunctionDeclaration::Create(
  819. arena, context.source_loc(), $2, $3, $4, $5, $6, std::nullopt);
  820. if (fn.ok()) {
  821. $$ = *fn;
  822. } else {
  823. context.RecordSyntaxError(fn.error().message());
  824. YYERROR;
  825. }
  826. }
  827. ;
  828. variable_declaration: identifier COLON pattern
  829. {
  830. $$ = arena->New<BindingPattern>(context.source_loc(), $1, $3,
  831. std::nullopt);
  832. }
  833. ;
  834. alternative:
  835. identifier tuple
  836. { $$ = arena->New<AlternativeSignature>(context.source_loc(), $1, $2); }
  837. | identifier
  838. {
  839. $$ = arena->New<AlternativeSignature>(
  840. context.source_loc(), $1,
  841. arena->New<TupleLiteral>(context.source_loc()));
  842. }
  843. ;
  844. alternative_list:
  845. // Empty
  846. { $$ = {}; }
  847. | alternative_list_contents
  848. { $$ = $1; }
  849. | alternative_list_contents COMMA
  850. { $$ = $1; }
  851. ;
  852. alternative_list_contents:
  853. alternative
  854. { $$ = {std::move($1)}; }
  855. | alternative_list_contents COMMA alternative
  856. {
  857. $$ = $1;
  858. $$.push_back(std::move($3));
  859. }
  860. ;
  861. type_params:
  862. // Empty
  863. { $$ = std::nullopt; }
  864. | tuple_pattern
  865. { $$ = $1; }
  866. ;
  867. declaration:
  868. function_declaration
  869. { $$ = $1; }
  870. | CLASS identifier type_params LEFT_CURLY_BRACE declaration_list RIGHT_CURLY_BRACE
  871. {
  872. $$ = arena->New<ClassDeclaration>(
  873. context.source_loc(), $2,
  874. arena->New<SelfDeclaration>(context.source_loc()), $3, $5);
  875. }
  876. | CHOICE identifier LEFT_CURLY_BRACE alternative_list RIGHT_CURLY_BRACE
  877. { $$ = arena->New<ChoiceDeclaration>(context.source_loc(), $2, $4); }
  878. | VAR variable_declaration SEMICOLON
  879. {
  880. $$ = arena->New<VariableDeclaration>(context.source_loc(), $2,
  881. std::nullopt, ValueCategory::Var);
  882. }
  883. | VAR variable_declaration EQUAL expression SEMICOLON
  884. {
  885. $$ = arena->New<VariableDeclaration>(context.source_loc(), $2, $4,
  886. ValueCategory::Var);
  887. }
  888. | LET variable_declaration EQUAL expression SEMICOLON
  889. {
  890. $$ = arena->New<VariableDeclaration>(context.source_loc(), $2, $4,
  891. ValueCategory::Let);
  892. }
  893. | INTERFACE identifier type_params LEFT_CURLY_BRACE declaration_list RIGHT_CURLY_BRACE
  894. {
  895. // TODO: Type of `Self` should be the interface being declared, not
  896. // `Type`.
  897. auto ty_ty = arena -> New<TypeTypeLiteral>(context.source_loc());
  898. // FIXME: Should this be switched to use a `SelfDeclaration` instead?
  899. auto self =
  900. arena -> New<GenericBinding>(context.source_loc(), "Self", ty_ty);
  901. $$ = arena->New<InterfaceDeclaration>(context.source_loc(), $2, $3, self,
  902. $5);
  903. }
  904. | impl_kind IMPL impl_deduced_params impl_type AS expression LEFT_CURLY_BRACE declaration_list RIGHT_CURLY_BRACE
  905. {
  906. ErrorOr<ImplDeclaration*> impl = ImplDeclaration::Create(
  907. arena, context.source_loc(), $1, $4, $6, $3, $8);
  908. if (impl.ok()) {
  909. $$ = *impl;
  910. } else {
  911. context.RecordSyntaxError(impl.error().message());
  912. YYERROR;
  913. }
  914. }
  915. ;
  916. impl_kind:
  917. // Internal
  918. { $$ = Carbon::ImplKind::InternalImpl; }
  919. | EXTERNAL
  920. { $$ = Carbon::ImplKind::ExternalImpl; }
  921. ;
  922. impl_type:
  923. // Self
  924. { $$ = arena->New<IdentifierExpression>(context.source_loc(), "Self"); }
  925. | expression
  926. ;
  927. declaration_list:
  928. // Empty
  929. { $$ = {}; }
  930. | declaration_list declaration
  931. {
  932. $$ = $1;
  933. $$.push_back(Nonnull<Declaration*>($2));
  934. }
  935. ;
  936. %%