handle_expr.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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/parse/context.h"
  5. namespace Carbon::Parse {
  6. static auto DiagnoseStatementOperatorAsSubExpr(Context& context) -> void {
  7. CARBON_DIAGNOSTIC(StatementOperatorAsSubExpr, Error,
  8. "Operator `{0}` can only be used as a complete statement.",
  9. Lex::TokenKind);
  10. context.emitter().Emit(*context.position(), StatementOperatorAsSubExpr,
  11. context.PositionKind());
  12. }
  13. auto HandleExpr(Context& context) -> void {
  14. auto state = context.PopState();
  15. // Check for a prefix operator.
  16. if (auto operator_precedence =
  17. PrecedenceGroup::ForLeading(context.PositionKind())) {
  18. if (PrecedenceGroup::GetPriority(state.ambient_precedence,
  19. *operator_precedence) !=
  20. OperatorPriority::RightFirst) {
  21. // The precedence rules don't permit this prefix operator in this
  22. // context. Diagnose this, but carry on and parse it anyway.
  23. if (PrecedenceGroup::GetPriority(PrecedenceGroup::ForTopLevelExpr(),
  24. *operator_precedence) ==
  25. OperatorPriority::RightFirst) {
  26. CARBON_DIAGNOSTIC(
  27. UnaryOperatorRequiresParentheses, Error,
  28. "Parentheses are required around this unary `{0}` operator.",
  29. Lex::TokenKind);
  30. context.emitter().Emit(*context.position(),
  31. UnaryOperatorRequiresParentheses,
  32. context.PositionKind());
  33. } else {
  34. // This operator wouldn't be allowed even if parenthesized.
  35. DiagnoseStatementOperatorAsSubExpr(context);
  36. }
  37. } else {
  38. // Check that this operator follows the proper whitespace rules.
  39. context.DiagnoseOperatorFixity(Context::OperatorFixity::Prefix);
  40. }
  41. if (context.PositionIs(Lex::TokenKind::If)) {
  42. context.PushState(State::IfExprFinish);
  43. context.PushState(State::IfExprFinishCondition);
  44. } else {
  45. context.PushStateForExprLoop(State::ExprLoopForPrefix,
  46. state.ambient_precedence,
  47. *operator_precedence);
  48. }
  49. context.ConsumeAndDiscard();
  50. context.PushStateForExpr(*operator_precedence);
  51. } else {
  52. context.PushStateForExprLoop(State::ExprLoop, state.ambient_precedence,
  53. PrecedenceGroup::ForPostfixExpr());
  54. context.PushState(State::ExprInPostfix);
  55. }
  56. }
  57. auto HandleExprInPostfix(Context& context) -> void {
  58. auto state = context.PopState();
  59. // Continue to the loop state.
  60. state.state = State::ExprInPostfixLoop;
  61. // Parses a primary expression, which is either a terminal portion of an
  62. // expression tree, such as an identifier or literal, or a parenthesized
  63. // expression.
  64. switch (context.PositionKind()) {
  65. case Lex::TokenKind::Identifier: {
  66. context.AddLeafNode(NodeKind::NameExpr, context.Consume());
  67. context.PushState(state);
  68. break;
  69. }
  70. case Lex::TokenKind::False:
  71. case Lex::TokenKind::True:
  72. case Lex::TokenKind::IntegerLiteral:
  73. case Lex::TokenKind::RealLiteral:
  74. case Lex::TokenKind::StringLiteral:
  75. case Lex::TokenKind::Bool:
  76. case Lex::TokenKind::IntegerTypeLiteral:
  77. case Lex::TokenKind::UnsignedIntegerTypeLiteral:
  78. case Lex::TokenKind::FloatingPointTypeLiteral:
  79. case Lex::TokenKind::StringTypeLiteral:
  80. case Lex::TokenKind::Type: {
  81. context.AddLeafNode(NodeKind::Literal, context.Consume());
  82. context.PushState(state);
  83. break;
  84. }
  85. case Lex::TokenKind::OpenCurlyBrace: {
  86. context.PushState(state);
  87. context.PushState(State::BraceExpr);
  88. break;
  89. }
  90. case Lex::TokenKind::OpenParen: {
  91. context.PushState(state);
  92. context.PushState(State::ParenExpr);
  93. break;
  94. }
  95. case Lex::TokenKind::OpenSquareBracket: {
  96. context.PushState(state);
  97. context.PushState(State::ArrayExpr);
  98. break;
  99. }
  100. case Lex::TokenKind::SelfValueIdentifier: {
  101. context.AddLeafNode(NodeKind::SelfValueNameExpr, context.Consume());
  102. context.PushState(state);
  103. break;
  104. }
  105. case Lex::TokenKind::SelfTypeIdentifier: {
  106. context.AddLeafNode(NodeKind::SelfTypeNameExpr, context.Consume());
  107. context.PushState(state);
  108. break;
  109. }
  110. default: {
  111. // Add a node to keep the parse tree balanced.
  112. context.AddLeafNode(NodeKind::InvalidParse, *context.position(),
  113. /*has_error=*/true);
  114. CARBON_DIAGNOSTIC(ExpectedExpr, Error, "Expected expression.");
  115. context.emitter().Emit(*context.position(), ExpectedExpr);
  116. context.ReturnErrorOnState();
  117. break;
  118. }
  119. }
  120. }
  121. auto HandleExprInPostfixLoop(Context& context) -> void {
  122. // This is a cyclic state that repeats, so this state is typically pushed back
  123. // on.
  124. auto state = context.PopState();
  125. state.token = *context.position();
  126. switch (context.PositionKind()) {
  127. case Lex::TokenKind::Period: {
  128. context.PushState(state);
  129. state.state = State::PeriodAsExpr;
  130. context.PushState(state);
  131. break;
  132. }
  133. case Lex::TokenKind::MinusGreater: {
  134. context.PushState(state);
  135. state.state = State::ArrowExpr;
  136. context.PushState(state);
  137. break;
  138. }
  139. case Lex::TokenKind::OpenParen: {
  140. context.PushState(state);
  141. state.state = State::CallExpr;
  142. context.PushState(state);
  143. break;
  144. }
  145. case Lex::TokenKind::OpenSquareBracket: {
  146. context.PushState(state);
  147. state.state = State::IndexExpr;
  148. context.PushState(state);
  149. break;
  150. }
  151. default: {
  152. if (state.has_error) {
  153. context.ReturnErrorOnState();
  154. }
  155. break;
  156. }
  157. }
  158. }
  159. auto HandleExprLoop(Context& context) -> void {
  160. auto state = context.PopState();
  161. auto operator_kind = context.PositionKind();
  162. auto trailing_operator = PrecedenceGroup::ForTrailing(
  163. operator_kind, context.IsTrailingOperatorInfix());
  164. if (!trailing_operator) {
  165. if (state.has_error) {
  166. context.ReturnErrorOnState();
  167. }
  168. return;
  169. }
  170. auto [operator_precedence, is_binary] = *trailing_operator;
  171. // TODO: If this operator is ambiguous with either the ambient precedence
  172. // or the LHS precedence, and there's a variant with a different fixity
  173. // that would work, use that one instead for error recovery.
  174. if (PrecedenceGroup::GetPriority(state.ambient_precedence,
  175. operator_precedence) !=
  176. OperatorPriority::RightFirst) {
  177. // The precedence rules don't permit this operator in this context. Try
  178. // again in the enclosing expression context.
  179. if (state.has_error) {
  180. context.ReturnErrorOnState();
  181. }
  182. return;
  183. }
  184. if (PrecedenceGroup::GetPriority(state.lhs_precedence, operator_precedence) !=
  185. OperatorPriority::LeftFirst) {
  186. // Either the LHS operator and this operator are ambiguous, or the
  187. // LHS operator is a unary operator that can't be nested within
  188. // this operator. Either way, parentheses are required.
  189. if (PrecedenceGroup::GetPriority(PrecedenceGroup::ForTopLevelExpr(),
  190. operator_precedence) ==
  191. OperatorPriority::RightFirst) {
  192. CARBON_DIAGNOSTIC(
  193. OperatorRequiresParentheses, Error,
  194. "Parentheses are required to disambiguate operator precedence.");
  195. context.emitter().Emit(*context.position(), OperatorRequiresParentheses);
  196. } else {
  197. // This operator wouldn't be allowed even if parenthesized.
  198. DiagnoseStatementOperatorAsSubExpr(context);
  199. }
  200. state.has_error = true;
  201. } else {
  202. context.DiagnoseOperatorFixity(is_binary
  203. ? Context::OperatorFixity::Infix
  204. : Context::OperatorFixity::Postfix);
  205. }
  206. state.token = context.Consume();
  207. state.lhs_precedence = operator_precedence;
  208. if (is_binary) {
  209. if (operator_kind == Lex::TokenKind::And ||
  210. operator_kind == Lex::TokenKind::Or) {
  211. // For `and` and `or`, wrap the first operand in a virtual parse tree
  212. // node so that semantics can insert control flow here.
  213. context.AddNode(NodeKind::ShortCircuitOperand, state.token,
  214. state.subtree_start, state.has_error);
  215. }
  216. state.state = State::ExprLoopForBinary;
  217. context.PushState(state);
  218. context.PushStateForExpr(operator_precedence);
  219. } else {
  220. context.AddNode(NodeKind::PostfixOperator, state.token, state.subtree_start,
  221. state.has_error);
  222. state.has_error = false;
  223. context.PushState(state);
  224. }
  225. }
  226. auto HandleExprLoopForBinary(Context& context) -> void {
  227. auto state = context.PopState();
  228. context.AddNode(NodeKind::InfixOperator, state.token, state.subtree_start,
  229. state.has_error);
  230. state.state = State::ExprLoop;
  231. state.has_error = false;
  232. context.PushState(state);
  233. }
  234. auto HandleExprLoopForPrefix(Context& context) -> void {
  235. auto state = context.PopState();
  236. context.AddNode(NodeKind::PrefixOperator, state.token, state.subtree_start,
  237. state.has_error);
  238. state.state = State::ExprLoop;
  239. state.has_error = false;
  240. context.PushState(state);
  241. }
  242. auto HandleIfExprFinishCondition(Context& context) -> void {
  243. auto state = context.PopState();
  244. context.AddNode(NodeKind::IfExprIf, state.token, state.subtree_start,
  245. state.has_error);
  246. if (context.PositionIs(Lex::TokenKind::Then)) {
  247. context.PushState(State::IfExprFinishThen);
  248. context.ConsumeChecked(Lex::TokenKind::Then);
  249. context.PushStateForExpr(*PrecedenceGroup::ForLeading(Lex::TokenKind::If));
  250. } else {
  251. // TODO: Include the location of the `if` token.
  252. CARBON_DIAGNOSTIC(ExpectedThenAfterIf, Error,
  253. "Expected `then` after `if` condition.");
  254. if (!state.has_error) {
  255. context.emitter().Emit(*context.position(), ExpectedThenAfterIf);
  256. }
  257. // Add placeholders for `IfExprThen` and final `Expr`.
  258. context.AddLeafNode(NodeKind::InvalidParse, *context.position(),
  259. /*has_error=*/true);
  260. context.AddLeafNode(NodeKind::InvalidParse, *context.position(),
  261. /*has_error=*/true);
  262. context.ReturnErrorOnState();
  263. }
  264. }
  265. auto HandleIfExprFinishThen(Context& context) -> void {
  266. auto state = context.PopState();
  267. context.AddNode(NodeKind::IfExprThen, state.token, state.subtree_start,
  268. state.has_error);
  269. if (context.PositionIs(Lex::TokenKind::Else)) {
  270. context.PushState(State::IfExprFinishElse);
  271. context.ConsumeChecked(Lex::TokenKind::Else);
  272. context.PushStateForExpr(*PrecedenceGroup::ForLeading(Lex::TokenKind::If));
  273. } else {
  274. // TODO: Include the location of the `if` token.
  275. CARBON_DIAGNOSTIC(ExpectedElseAfterIf, Error,
  276. "Expected `else` after `if ... then ...`.");
  277. if (!state.has_error) {
  278. context.emitter().Emit(*context.position(), ExpectedElseAfterIf);
  279. }
  280. // Add placeholder for the final `Expr`.
  281. context.AddLeafNode(NodeKind::InvalidParse, *context.position(),
  282. /*has_error=*/true);
  283. context.ReturnErrorOnState();
  284. }
  285. }
  286. auto HandleIfExprFinishElse(Context& context) -> void {
  287. auto else_state = context.PopState();
  288. // Propagate the location of `else`.
  289. auto if_state = context.PopState();
  290. if_state.token = else_state.token;
  291. if_state.has_error |= else_state.has_error;
  292. context.PushState(if_state);
  293. }
  294. auto HandleIfExprFinish(Context& context) -> void {
  295. auto state = context.PopState();
  296. context.AddNode(NodeKind::IfExprElse, state.token, state.subtree_start,
  297. state.has_error);
  298. }
  299. auto HandleExprStatementFinish(Context& context) -> void {
  300. auto state = context.PopState();
  301. if (auto semi = context.ConsumeIf(Lex::TokenKind::Semi)) {
  302. context.AddNode(NodeKind::ExprStatement, *semi, state.subtree_start,
  303. state.has_error);
  304. return;
  305. }
  306. if (!state.has_error) {
  307. CARBON_DIAGNOSTIC(ExpectedExprSemi, Error,
  308. "Expected `;` after expression statement.");
  309. context.emitter().Emit(*context.position(), ExpectedExprSemi);
  310. }
  311. if (auto semi_token = context.SkipPastLikelyEnd(state.token)) {
  312. context.AddNode(NodeKind::ExprStatement, *semi_token, state.subtree_start,
  313. /*has_error=*/true);
  314. return;
  315. }
  316. // Found junk not even followed by a `;`, no node to add.
  317. context.ReturnErrorOnState();
  318. }
  319. } // namespace Carbon::Parse