parser_handle_expression.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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/parser/parser_context.h"
  5. namespace Carbon {
  6. CARBON_DIAGNOSTIC(
  7. OperatorRequiresParentheses, Error,
  8. "Parentheses are required to disambiguate operator precedence.");
  9. auto ParserHandleExpression(ParserContext& context) -> void {
  10. auto state = context.PopState();
  11. // Check for a prefix operator.
  12. if (auto operator_precedence =
  13. PrecedenceGroup::ForLeading(context.PositionKind())) {
  14. if (PrecedenceGroup::GetPriority(state.ambient_precedence,
  15. *operator_precedence) !=
  16. OperatorPriority::RightFirst) {
  17. // The precedence rules don't permit this prefix operator in this
  18. // context. Diagnose this, but carry on and parse it anyway.
  19. context.emitter().Emit(*context.position(), OperatorRequiresParentheses);
  20. } else {
  21. // Check that this operator follows the proper whitespace rules.
  22. context.DiagnoseOperatorFixity(ParserContext::OperatorFixity::Prefix);
  23. }
  24. if (context.PositionIs(TokenKind::If)) {
  25. context.PushState(ParserState::IfExpressionFinish);
  26. context.PushState(ParserState::IfExpressionFinishCondition);
  27. } else {
  28. context.PushStateForExpressionLoop(ParserState::ExpressionLoopForPrefix,
  29. state.ambient_precedence,
  30. *operator_precedence);
  31. }
  32. ++context.position();
  33. context.PushStateForExpression(*operator_precedence);
  34. } else {
  35. context.PushStateForExpressionLoop(ParserState::ExpressionLoop,
  36. state.ambient_precedence,
  37. PrecedenceGroup::ForPostfixExpression());
  38. context.PushState(ParserState::ExpressionInPostfix);
  39. }
  40. }
  41. auto ParserHandleExpressionInPostfix(ParserContext& context) -> void {
  42. auto state = context.PopState();
  43. // Continue to the loop state.
  44. state.state = ParserState::ExpressionInPostfixLoop;
  45. // Parses a primary expression, which is either a terminal portion of an
  46. // expression tree, such as an identifier or literal, or a parenthesized
  47. // expression.
  48. switch (context.PositionKind()) {
  49. case TokenKind::Identifier: {
  50. context.AddLeafNode(ParseNodeKind::NameExpression, context.Consume());
  51. context.PushState(state);
  52. break;
  53. }
  54. case TokenKind::False:
  55. case TokenKind::True:
  56. case TokenKind::IntegerLiteral:
  57. case TokenKind::RealLiteral:
  58. case TokenKind::StringLiteral:
  59. case TokenKind::Bool:
  60. case TokenKind::IntegerTypeLiteral:
  61. case TokenKind::UnsignedIntegerTypeLiteral:
  62. case TokenKind::FloatingPointTypeLiteral:
  63. case TokenKind::StringTypeLiteral: {
  64. context.AddLeafNode(ParseNodeKind::Literal, context.Consume());
  65. context.PushState(state);
  66. break;
  67. }
  68. case TokenKind::OpenCurlyBrace: {
  69. context.PushState(state);
  70. context.PushState(ParserState::BraceExpression);
  71. break;
  72. }
  73. case TokenKind::OpenParen: {
  74. context.PushState(state);
  75. context.PushState(ParserState::ParenExpression);
  76. break;
  77. }
  78. case TokenKind::SelfValueIdentifier: {
  79. context.AddLeafNode(ParseNodeKind::SelfValueName, context.Consume());
  80. context.PushState(state);
  81. break;
  82. }
  83. case TokenKind::SelfTypeIdentifier: {
  84. context.AddLeafNode(ParseNodeKind::SelfTypeNameExpression,
  85. context.Consume());
  86. context.PushState(state);
  87. break;
  88. }
  89. default: {
  90. // Add a node to keep the parse tree balanced.
  91. context.AddLeafNode(ParseNodeKind::InvalidParse, *context.position(),
  92. /*has_error=*/true);
  93. CARBON_DIAGNOSTIC(ExpectedExpression, Error, "Expected expression.");
  94. context.emitter().Emit(*context.position(), ExpectedExpression);
  95. context.ReturnErrorOnState();
  96. break;
  97. }
  98. }
  99. }
  100. auto ParserHandleExpressionInPostfixLoop(ParserContext& context) -> void {
  101. // This is a cyclic state that repeats, so this state is typically pushed back
  102. // on.
  103. auto state = context.PopState();
  104. state.token = *context.position();
  105. switch (context.PositionKind()) {
  106. case TokenKind::Period: {
  107. context.PushState(state);
  108. state.state = ParserState::DesignatorAsExpression;
  109. context.PushState(state);
  110. break;
  111. }
  112. case TokenKind::OpenParen: {
  113. context.PushState(state);
  114. state.state = ParserState::CallExpression;
  115. context.PushState(state);
  116. break;
  117. }
  118. default: {
  119. if (state.has_error) {
  120. context.ReturnErrorOnState();
  121. }
  122. break;
  123. }
  124. }
  125. }
  126. auto ParserHandleExpressionLoop(ParserContext& context) -> void {
  127. auto state = context.PopState();
  128. auto operator_kind = context.PositionKind();
  129. auto trailing_operator = PrecedenceGroup::ForTrailing(
  130. operator_kind, context.IsTrailingOperatorInfix());
  131. if (!trailing_operator) {
  132. if (state.has_error) {
  133. context.ReturnErrorOnState();
  134. }
  135. return;
  136. }
  137. auto [operator_precedence, is_binary] = *trailing_operator;
  138. // TODO: If this operator is ambiguous with either the ambient precedence
  139. // or the LHS precedence, and there's a variant with a different fixity
  140. // that would work, use that one instead for error recovery.
  141. if (PrecedenceGroup::GetPriority(state.ambient_precedence,
  142. operator_precedence) !=
  143. OperatorPriority::RightFirst) {
  144. // The precedence rules don't permit this operator in this context. Try
  145. // again in the enclosing expression context.
  146. if (state.has_error) {
  147. context.ReturnErrorOnState();
  148. }
  149. return;
  150. }
  151. if (PrecedenceGroup::GetPriority(state.lhs_precedence, operator_precedence) !=
  152. OperatorPriority::LeftFirst) {
  153. // Either the LHS operator and this operator are ambiguous, or the
  154. // LHS operator is a unary operator that can't be nested within
  155. // this operator. Either way, parentheses are required.
  156. context.emitter().Emit(*context.position(), OperatorRequiresParentheses);
  157. state.has_error = true;
  158. } else {
  159. context.DiagnoseOperatorFixity(
  160. is_binary ? ParserContext::OperatorFixity::Infix
  161. : ParserContext::OperatorFixity::Postfix);
  162. }
  163. state.token = context.Consume();
  164. state.lhs_precedence = operator_precedence;
  165. if (is_binary) {
  166. if (operator_kind == TokenKind::And || operator_kind == TokenKind::Or) {
  167. // For `and` and `or`, wrap the first operand in a virtual parse tree
  168. // node so that semantics can insert control flow here.
  169. context.AddNode(ParseNodeKind::ShortCircuitOperand, state.token,
  170. state.subtree_start, state.has_error);
  171. }
  172. state.state = ParserState::ExpressionLoopForBinary;
  173. context.PushState(state);
  174. context.PushStateForExpression(operator_precedence);
  175. } else {
  176. context.AddNode(ParseNodeKind::PostfixOperator, state.token,
  177. state.subtree_start, state.has_error);
  178. state.has_error = false;
  179. context.PushState(state);
  180. }
  181. }
  182. auto ParserHandleExpressionLoopForBinary(ParserContext& context) -> void {
  183. auto state = context.PopState();
  184. context.AddNode(ParseNodeKind::InfixOperator, state.token,
  185. state.subtree_start, state.has_error);
  186. state.state = ParserState::ExpressionLoop;
  187. state.has_error = false;
  188. context.PushState(state);
  189. }
  190. auto ParserHandleExpressionLoopForPrefix(ParserContext& context) -> void {
  191. auto state = context.PopState();
  192. context.AddNode(ParseNodeKind::PrefixOperator, state.token,
  193. state.subtree_start, state.has_error);
  194. state.state = ParserState::ExpressionLoop;
  195. state.has_error = false;
  196. context.PushState(state);
  197. }
  198. auto ParserHandleIfExpressionFinishCondition(ParserContext& context) -> void {
  199. auto state = context.PopState();
  200. context.AddNode(ParseNodeKind::IfExpressionIf, state.token,
  201. state.subtree_start, state.has_error);
  202. if (context.PositionIs(TokenKind::Then)) {
  203. context.PushState(ParserState::IfExpressionFinishThen);
  204. context.ConsumeChecked(TokenKind::Then);
  205. context.PushStateForExpression(*PrecedenceGroup::ForLeading(TokenKind::If));
  206. } else {
  207. // TODO: Include the location of the `if` token.
  208. CARBON_DIAGNOSTIC(ExpectedThenAfterIf, Error,
  209. "Expected `then` after `if` condition.");
  210. if (!state.has_error) {
  211. context.emitter().Emit(*context.position(), ExpectedThenAfterIf);
  212. }
  213. // Add placeholders for `IfExpressionThen` and final `Expression`.
  214. context.AddLeafNode(ParseNodeKind::InvalidParse, *context.position(),
  215. /*has_error=*/true);
  216. context.AddLeafNode(ParseNodeKind::InvalidParse, *context.position(),
  217. /*has_error=*/true);
  218. context.ReturnErrorOnState();
  219. }
  220. }
  221. auto ParserHandleIfExpressionFinishThen(ParserContext& context) -> void {
  222. auto state = context.PopState();
  223. context.AddNode(ParseNodeKind::IfExpressionThen, state.token,
  224. state.subtree_start, state.has_error);
  225. if (context.PositionIs(TokenKind::Else)) {
  226. context.PushState(ParserState::IfExpressionFinishElse);
  227. context.ConsumeChecked(TokenKind::Else);
  228. context.PushStateForExpression(*PrecedenceGroup::ForLeading(TokenKind::If));
  229. } else {
  230. // TODO: Include the location of the `if` token.
  231. CARBON_DIAGNOSTIC(ExpectedElseAfterIf, Error,
  232. "Expected `else` after `if ... then ...`.");
  233. if (!state.has_error) {
  234. context.emitter().Emit(*context.position(), ExpectedElseAfterIf);
  235. }
  236. // Add placeholder for the final `Expression`.
  237. context.AddLeafNode(ParseNodeKind::InvalidParse, *context.position(),
  238. /*has_error=*/true);
  239. context.ReturnErrorOnState();
  240. }
  241. }
  242. auto ParserHandleIfExpressionFinishElse(ParserContext& context) -> void {
  243. auto else_state = context.PopState();
  244. // Propagate the location of `else`.
  245. auto if_state = context.PopState();
  246. if_state.token = else_state.token;
  247. if_state.has_error |= else_state.has_error;
  248. context.PushState(if_state);
  249. }
  250. auto ParserHandleIfExpressionFinish(ParserContext& context) -> void {
  251. auto state = context.PopState();
  252. context.AddNode(ParseNodeKind::IfExpressionElse, state.token,
  253. state.subtree_start, state.has_error);
  254. }
  255. auto ParserHandleExpressionStatementFinish(ParserContext& context) -> void {
  256. auto state = context.PopState();
  257. if (auto semi = context.ConsumeIf(TokenKind::Semi)) {
  258. context.AddNode(ParseNodeKind::ExpressionStatement, *semi,
  259. state.subtree_start, state.has_error);
  260. return;
  261. }
  262. if (!state.has_error) {
  263. CARBON_DIAGNOSTIC(ExpectedSemiAfterExpression, Error,
  264. "Expected `;` after expression.");
  265. context.emitter().Emit(*context.position(), ExpectedSemiAfterExpression);
  266. }
  267. if (auto semi_token = context.SkipPastLikelyEnd(state.token)) {
  268. context.AddNode(ParseNodeKind::ExpressionStatement, *semi_token,
  269. state.subtree_start,
  270. /*has_error=*/true);
  271. return;
  272. }
  273. // Found junk not even followed by a `;`, no node to add.
  274. context.ReturnErrorOnState();
  275. }
  276. } // namespace Carbon