parser.ypp 27 KB

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