handle_expr.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  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. #include "toolchain/lex/token_kind.h"
  5. #include "toolchain/parse/context.h"
  6. namespace Carbon::Parse {
  7. static auto DiagnoseStatementOperatorAsSubExpr(Context& context) -> void {
  8. CARBON_DIAGNOSTIC(StatementOperatorAsSubExpr, Error,
  9. "Operator `{0}` can only be used as a complete statement.",
  10. Lex::TokenKind);
  11. context.emitter().Emit(*context.position(), StatementOperatorAsSubExpr,
  12. context.PositionKind());
  13. }
  14. auto HandleExpr(Context& context) -> void {
  15. auto state = context.PopState();
  16. // Check for a prefix operator.
  17. if (auto operator_precedence =
  18. PrecedenceGroup::ForLeading(context.PositionKind())) {
  19. if (PrecedenceGroup::GetPriority(state.ambient_precedence,
  20. *operator_precedence) !=
  21. OperatorPriority::RightFirst) {
  22. // The precedence rules don't permit this prefix operator in this
  23. // context. Diagnose this, but carry on and parse it anyway.
  24. if (PrecedenceGroup::GetPriority(PrecedenceGroup::ForTopLevelExpr(),
  25. *operator_precedence) ==
  26. OperatorPriority::RightFirst) {
  27. CARBON_DIAGNOSTIC(
  28. UnaryOperatorRequiresParentheses, Error,
  29. "Parentheses are required around this unary `{0}` operator.",
  30. Lex::TokenKind);
  31. context.emitter().Emit(*context.position(),
  32. UnaryOperatorRequiresParentheses,
  33. context.PositionKind());
  34. } else {
  35. // This operator wouldn't be allowed even if parenthesized.
  36. DiagnoseStatementOperatorAsSubExpr(context);
  37. }
  38. } else {
  39. // Check that this operator follows the proper whitespace rules.
  40. context.DiagnoseOperatorFixity(Context::OperatorFixity::Prefix);
  41. }
  42. if (context.PositionIs(Lex::TokenKind::If)) {
  43. context.PushState(State::IfExprFinish);
  44. context.PushState(State::IfExprFinishCondition);
  45. } else {
  46. context.PushStateForExprLoop(State::ExprLoopForPrefixOperator,
  47. state.ambient_precedence,
  48. *operator_precedence);
  49. }
  50. context.ConsumeAndDiscard();
  51. context.PushStateForExpr(*operator_precedence);
  52. } else {
  53. context.PushStateForExprLoop(State::ExprLoop, state.ambient_precedence,
  54. PrecedenceGroup::ForPostfixExpr());
  55. context.PushState(State::ExprInPostfix);
  56. }
  57. }
  58. auto HandleExprInPostfix(Context& context) -> void {
  59. auto state = context.PopState();
  60. // Continue to the loop state.
  61. state.state = State::ExprInPostfixLoop;
  62. // Parses a primary expression, which is either a terminal portion of an
  63. // expression tree, such as an identifier or literal, or a parenthesized
  64. // expression.
  65. switch (context.PositionKind()) {
  66. case Lex::TokenKind::Identifier: {
  67. context.AddLeafNode(NodeKind::IdentifierNameExpr, context.Consume());
  68. context.PushState(state);
  69. break;
  70. }
  71. case Lex::TokenKind::False: {
  72. context.AddLeafNode(NodeKind::BoolLiteralFalse, context.Consume());
  73. context.PushState(state);
  74. break;
  75. }
  76. case Lex::TokenKind::True: {
  77. context.AddLeafNode(NodeKind::BoolLiteralTrue, context.Consume());
  78. context.PushState(state);
  79. break;
  80. }
  81. case Lex::TokenKind::IntLiteral: {
  82. context.AddLeafNode(NodeKind::IntLiteral, context.Consume());
  83. context.PushState(state);
  84. break;
  85. }
  86. case Lex::TokenKind::RealLiteral: {
  87. context.AddLeafNode(NodeKind::RealLiteral, context.Consume());
  88. context.PushState(state);
  89. break;
  90. }
  91. case Lex::TokenKind::StringLiteral: {
  92. context.AddLeafNode(NodeKind::StringLiteral, context.Consume());
  93. context.PushState(state);
  94. break;
  95. }
  96. case Lex::TokenKind::Bool: {
  97. context.AddLeafNode(NodeKind::BoolTypeLiteral, context.Consume());
  98. context.PushState(state);
  99. break;
  100. }
  101. case Lex::TokenKind::IntTypeLiteral: {
  102. context.AddLeafNode(NodeKind::IntTypeLiteral, context.Consume());
  103. context.PushState(state);
  104. break;
  105. }
  106. case Lex::TokenKind::UnsignedIntTypeLiteral: {
  107. context.AddLeafNode(NodeKind::UnsignedIntTypeLiteral, context.Consume());
  108. context.PushState(state);
  109. break;
  110. }
  111. case Lex::TokenKind::FloatTypeLiteral: {
  112. context.AddLeafNode(NodeKind::FloatTypeLiteral, context.Consume());
  113. context.PushState(state);
  114. break;
  115. }
  116. case Lex::TokenKind::StringTypeLiteral: {
  117. context.AddLeafNode(NodeKind::StringTypeLiteral, context.Consume());
  118. context.PushState(state);
  119. break;
  120. }
  121. case Lex::TokenKind::Type: {
  122. context.AddLeafNode(NodeKind::TypeTypeLiteral, context.Consume());
  123. context.PushState(state);
  124. break;
  125. }
  126. case Lex::TokenKind::Auto: {
  127. context.AddLeafNode(NodeKind::AutoTypeLiteral, context.Consume());
  128. context.PushState(state);
  129. break;
  130. }
  131. case Lex::TokenKind::OpenCurlyBrace: {
  132. context.PushState(state);
  133. context.PushState(State::BraceExpr);
  134. break;
  135. }
  136. case Lex::TokenKind::OpenParen: {
  137. context.PushState(state);
  138. context.PushState(State::ParenExpr);
  139. break;
  140. }
  141. case Lex::TokenKind::OpenSquareBracket: {
  142. context.PushState(state);
  143. context.PushState(State::ArrayExpr);
  144. break;
  145. }
  146. case Lex::TokenKind::Package: {
  147. context.AddLeafNode(NodeKind::PackageExpr, context.Consume());
  148. context.PushState(state);
  149. break;
  150. }
  151. case Lex::TokenKind::SelfValueIdentifier: {
  152. context.AddLeafNode(NodeKind::SelfValueNameExpr, context.Consume());
  153. context.PushState(state);
  154. break;
  155. }
  156. case Lex::TokenKind::SelfTypeIdentifier: {
  157. context.AddLeafNode(NodeKind::SelfTypeNameExpr, context.Consume());
  158. context.PushState(state);
  159. break;
  160. }
  161. default: {
  162. // Add a node to keep the parse tree balanced.
  163. context.AddLeafNode(NodeKind::InvalidParse, *context.position(),
  164. /*has_error=*/true);
  165. CARBON_DIAGNOSTIC(ExpectedExpr, Error, "Expected expression.");
  166. context.emitter().Emit(*context.position(), ExpectedExpr);
  167. context.ReturnErrorOnState();
  168. break;
  169. }
  170. }
  171. }
  172. auto HandleExprInPostfixLoop(Context& context) -> void {
  173. // This is a cyclic state that repeats, so this state is typically pushed back
  174. // on.
  175. auto state = context.PopState();
  176. state.token = *context.position();
  177. switch (context.PositionKind()) {
  178. case Lex::TokenKind::Period: {
  179. context.PushState(state);
  180. context.PushState(state, State::PeriodAsExpr);
  181. break;
  182. }
  183. case Lex::TokenKind::MinusGreater: {
  184. context.PushState(state);
  185. context.PushState(state, State::ArrowExpr);
  186. break;
  187. }
  188. case Lex::TokenKind::OpenParen: {
  189. context.PushState(state);
  190. context.PushState(state, State::CallExpr);
  191. break;
  192. }
  193. case Lex::TokenKind::OpenSquareBracket: {
  194. context.PushState(state);
  195. context.PushState(state, State::IndexExpr);
  196. break;
  197. }
  198. default: {
  199. if (state.has_error) {
  200. context.ReturnErrorOnState();
  201. }
  202. break;
  203. }
  204. }
  205. }
  206. auto HandleExprLoop(Context& context) -> void {
  207. auto state = context.PopState();
  208. auto operator_kind = context.PositionKind();
  209. auto trailing_operator = PrecedenceGroup::ForTrailing(
  210. operator_kind, context.IsTrailingOperatorInfix());
  211. if (!trailing_operator) {
  212. if (state.has_error) {
  213. context.ReturnErrorOnState();
  214. }
  215. return;
  216. }
  217. auto [operator_precedence, is_binary] = *trailing_operator;
  218. // TODO: If this operator is ambiguous with either the ambient precedence
  219. // or the LHS precedence, and there's a variant with a different fixity
  220. // that would work, use that one instead for error recovery.
  221. if (PrecedenceGroup::GetPriority(state.ambient_precedence,
  222. operator_precedence) !=
  223. OperatorPriority::RightFirst) {
  224. // The precedence rules don't permit this operator in this context. Try
  225. // again in the enclosing expression context.
  226. if (state.has_error) {
  227. context.ReturnErrorOnState();
  228. }
  229. return;
  230. }
  231. if (PrecedenceGroup::GetPriority(state.lhs_precedence, operator_precedence) !=
  232. OperatorPriority::LeftFirst) {
  233. // Either the LHS operator and this operator are ambiguous, or the
  234. // LHS operator is a unary operator that can't be nested within
  235. // this operator. Either way, parentheses are required.
  236. if (PrecedenceGroup::GetPriority(PrecedenceGroup::ForTopLevelExpr(),
  237. operator_precedence) ==
  238. OperatorPriority::RightFirst) {
  239. CARBON_DIAGNOSTIC(
  240. OperatorRequiresParentheses, Error,
  241. "Parentheses are required to disambiguate operator precedence.");
  242. context.emitter().Emit(*context.position(), OperatorRequiresParentheses);
  243. } else {
  244. // This operator wouldn't be allowed even if parenthesized.
  245. DiagnoseStatementOperatorAsSubExpr(context);
  246. }
  247. state.has_error = true;
  248. } else {
  249. context.DiagnoseOperatorFixity(is_binary
  250. ? Context::OperatorFixity::Infix
  251. : Context::OperatorFixity::Postfix);
  252. }
  253. state.token = context.Consume();
  254. state.lhs_precedence = operator_precedence;
  255. if (is_binary) {
  256. switch (operator_kind) {
  257. // For `and` and `or`, wrap the first operand in a virtual parse tree
  258. // node so that checking can insert control flow here.
  259. case Lex::TokenKind::And:
  260. context.AddNode(NodeKind::ShortCircuitOperandAnd, state.token,
  261. state.subtree_start, state.has_error);
  262. state.state = State::ExprLoopForShortCircuitOperatorAsAnd;
  263. break;
  264. case Lex::TokenKind::Or:
  265. context.AddNode(NodeKind::ShortCircuitOperandOr, state.token,
  266. state.subtree_start, state.has_error);
  267. state.state = State::ExprLoopForShortCircuitOperatorAsOr;
  268. break;
  269. default:
  270. state.state = State::ExprLoopForInfixOperator;
  271. break;
  272. }
  273. context.PushState(state);
  274. context.PushStateForExpr(operator_precedence);
  275. } else {
  276. NodeKind node_kind;
  277. switch (operator_kind) {
  278. #define CARBON_PARSE_NODE_KIND(...)
  279. #define CARBON_PARSE_NODE_KIND_POSTFIX_OPERATOR(Name, ...) \
  280. case Lex::TokenKind::Name: \
  281. node_kind = NodeKind::PostfixOperator##Name; \
  282. break;
  283. #include "toolchain/parse/node_kind.def"
  284. default:
  285. CARBON_FATAL() << "Unexpected token kind for postfix operator: "
  286. << operator_kind;
  287. }
  288. context.AddNode(node_kind, state.token, state.subtree_start,
  289. state.has_error);
  290. state.has_error = false;
  291. context.PushState(state);
  292. }
  293. }
  294. // Adds the operator node and returns the main expression loop.
  295. static auto HandleExprLoopForOperator(Context& context,
  296. Context::StateStackEntry state,
  297. NodeKind node_kind) -> void {
  298. context.AddNode(node_kind, state.token, state.subtree_start, state.has_error);
  299. state.has_error = false;
  300. context.PushState(state, State::ExprLoop);
  301. }
  302. auto HandleExprLoopForInfixOperator(Context& context) -> void {
  303. auto state = context.PopState();
  304. switch (auto token_kind = context.tokens().GetKind(state.token)) {
  305. #define CARBON_PARSE_NODE_KIND(...)
  306. #define CARBON_PARSE_NODE_KIND_INFIX_OPERATOR(Name, ...) \
  307. case Lex::TokenKind::Name: \
  308. HandleExprLoopForOperator(context, state, NodeKind::InfixOperator##Name); \
  309. break;
  310. #include "toolchain/parse/node_kind.def"
  311. default:
  312. CARBON_FATAL() << "Unexpected token kind for infix operator: "
  313. << token_kind;
  314. }
  315. }
  316. auto HandleExprLoopForPrefixOperator(Context& context) -> void {
  317. auto state = context.PopState();
  318. switch (auto token_kind = context.tokens().GetKind(state.token)) {
  319. #define CARBON_PARSE_NODE_KIND(...)
  320. #define CARBON_PARSE_NODE_KIND_PREFIX_OPERATOR(Name, ...) \
  321. case Lex::TokenKind::Name: \
  322. HandleExprLoopForOperator(context, state, NodeKind::PrefixOperator##Name); \
  323. break;
  324. #include "toolchain/parse/node_kind.def"
  325. default:
  326. CARBON_FATAL() << "Unexpected token kind for prefix operator: "
  327. << token_kind;
  328. }
  329. }
  330. auto HandleExprLoopForShortCircuitOperatorAsAnd(Context& context) -> void {
  331. auto state = context.PopState();
  332. HandleExprLoopForOperator(context, state, NodeKind::ShortCircuitOperatorAnd);
  333. }
  334. auto HandleExprLoopForShortCircuitOperatorAsOr(Context& context) -> void {
  335. auto state = context.PopState();
  336. HandleExprLoopForOperator(context, state, NodeKind::ShortCircuitOperatorOr);
  337. }
  338. auto HandleIfExprFinishCondition(Context& context) -> void {
  339. auto state = context.PopState();
  340. context.AddNode(NodeKind::IfExprIf, state.token, state.subtree_start,
  341. state.has_error);
  342. if (context.PositionIs(Lex::TokenKind::Then)) {
  343. context.PushState(State::IfExprFinishThen);
  344. context.ConsumeChecked(Lex::TokenKind::Then);
  345. context.PushStateForExpr(*PrecedenceGroup::ForLeading(Lex::TokenKind::If));
  346. } else {
  347. // TODO: Include the location of the `if` token.
  348. CARBON_DIAGNOSTIC(ExpectedThenAfterIf, Error,
  349. "Expected `then` after `if` condition.");
  350. if (!state.has_error) {
  351. context.emitter().Emit(*context.position(), ExpectedThenAfterIf);
  352. }
  353. // Add placeholders for `IfExprThen` and final `Expr`.
  354. context.AddLeafNode(NodeKind::InvalidParse, *context.position(),
  355. /*has_error=*/true);
  356. context.AddLeafNode(NodeKind::InvalidParse, *context.position(),
  357. /*has_error=*/true);
  358. context.ReturnErrorOnState();
  359. }
  360. }
  361. auto HandleIfExprFinishThen(Context& context) -> void {
  362. auto state = context.PopState();
  363. context.AddNode(NodeKind::IfExprThen, state.token, state.subtree_start,
  364. state.has_error);
  365. if (context.PositionIs(Lex::TokenKind::Else)) {
  366. context.PushState(State::IfExprFinishElse);
  367. context.ConsumeChecked(Lex::TokenKind::Else);
  368. context.PushStateForExpr(*PrecedenceGroup::ForLeading(Lex::TokenKind::If));
  369. } else {
  370. // TODO: Include the location of the `if` token.
  371. CARBON_DIAGNOSTIC(ExpectedElseAfterIf, Error,
  372. "Expected `else` after `if ... then ...`.");
  373. if (!state.has_error) {
  374. context.emitter().Emit(*context.position(), ExpectedElseAfterIf);
  375. }
  376. // Add placeholder for the final `Expr`.
  377. context.AddLeafNode(NodeKind::InvalidParse, *context.position(),
  378. /*has_error=*/true);
  379. context.ReturnErrorOnState();
  380. }
  381. }
  382. auto HandleIfExprFinishElse(Context& context) -> void {
  383. auto else_state = context.PopState();
  384. // Propagate the location of `else`.
  385. auto if_state = context.PopState();
  386. if_state.token = else_state.token;
  387. if_state.has_error |= else_state.has_error;
  388. context.PushState(if_state);
  389. }
  390. auto HandleIfExprFinish(Context& context) -> void {
  391. auto state = context.PopState();
  392. context.AddNode(NodeKind::IfExprElse, state.token, state.subtree_start,
  393. state.has_error);
  394. }
  395. auto HandleExprStatementFinish(Context& context) -> void {
  396. auto state = context.PopState();
  397. if (auto semi = context.ConsumeIf(Lex::TokenKind::Semi)) {
  398. context.AddNode(NodeKind::ExprStatement, *semi, state.subtree_start,
  399. state.has_error);
  400. return;
  401. }
  402. if (!state.has_error) {
  403. CARBON_DIAGNOSTIC(ExpectedExprSemi, Error,
  404. "Expected `;` after expression statement.");
  405. context.emitter().Emit(*context.position(), ExpectedExprSemi);
  406. }
  407. context.AddNode(NodeKind::ExprStatement,
  408. context.SkipPastLikelyEnd(state.token), state.subtree_start,
  409. /*has_error=*/true);
  410. }
  411. } // namespace Carbon::Parse