handle_expr.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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::IdentifierNameExpr, context.Consume());
  67. context.PushState(state);
  68. break;
  69. }
  70. case Lex::TokenKind::False: {
  71. context.AddLeafNode(NodeKind::BoolLiteralFalse, context.Consume());
  72. context.PushState(state);
  73. break;
  74. }
  75. case Lex::TokenKind::True: {
  76. context.AddLeafNode(NodeKind::BoolLiteralTrue, context.Consume());
  77. context.PushState(state);
  78. break;
  79. }
  80. case Lex::TokenKind::IntLiteral: {
  81. context.AddLeafNode(NodeKind::IntLiteral, context.Consume());
  82. context.PushState(state);
  83. break;
  84. }
  85. case Lex::TokenKind::RealLiteral: {
  86. context.AddLeafNode(NodeKind::RealLiteral, context.Consume());
  87. context.PushState(state);
  88. break;
  89. }
  90. case Lex::TokenKind::StringLiteral: {
  91. context.AddLeafNode(NodeKind::StringLiteral, context.Consume());
  92. context.PushState(state);
  93. break;
  94. }
  95. case Lex::TokenKind::Bool: {
  96. context.AddLeafNode(NodeKind::BoolTypeLiteral, context.Consume());
  97. context.PushState(state);
  98. break;
  99. }
  100. case Lex::TokenKind::IntTypeLiteral: {
  101. context.AddLeafNode(NodeKind::IntTypeLiteral, context.Consume());
  102. context.PushState(state);
  103. break;
  104. }
  105. case Lex::TokenKind::UnsignedIntTypeLiteral: {
  106. context.AddLeafNode(NodeKind::UnsignedIntTypeLiteral, context.Consume());
  107. context.PushState(state);
  108. break;
  109. }
  110. case Lex::TokenKind::FloatTypeLiteral: {
  111. context.AddLeafNode(NodeKind::FloatTypeLiteral, context.Consume());
  112. context.PushState(state);
  113. break;
  114. }
  115. case Lex::TokenKind::StringTypeLiteral: {
  116. context.AddLeafNode(NodeKind::StringTypeLiteral, context.Consume());
  117. context.PushState(state);
  118. break;
  119. }
  120. case Lex::TokenKind::Type: {
  121. context.AddLeafNode(NodeKind::TypeTypeLiteral, context.Consume());
  122. context.PushState(state);
  123. break;
  124. }
  125. case Lex::TokenKind::OpenCurlyBrace: {
  126. context.PushState(state);
  127. context.PushState(State::BraceExpr);
  128. break;
  129. }
  130. case Lex::TokenKind::OpenParen: {
  131. context.PushState(state);
  132. context.PushState(State::ParenExpr);
  133. break;
  134. }
  135. case Lex::TokenKind::OpenSquareBracket: {
  136. context.PushState(state);
  137. context.PushState(State::ArrayExpr);
  138. break;
  139. }
  140. case Lex::TokenKind::Package: {
  141. context.AddLeafNode(NodeKind::PackageExpr, context.Consume());
  142. context.PushState(state);
  143. break;
  144. }
  145. case Lex::TokenKind::SelfValueIdentifier: {
  146. context.AddLeafNode(NodeKind::SelfValueNameExpr, context.Consume());
  147. context.PushState(state);
  148. break;
  149. }
  150. case Lex::TokenKind::SelfTypeIdentifier: {
  151. context.AddLeafNode(NodeKind::SelfTypeNameExpr, context.Consume());
  152. context.PushState(state);
  153. break;
  154. }
  155. default: {
  156. // Add a node to keep the parse tree balanced.
  157. context.AddLeafNode(NodeKind::InvalidParse, *context.position(),
  158. /*has_error=*/true);
  159. CARBON_DIAGNOSTIC(ExpectedExpr, Error, "Expected expression.");
  160. context.emitter().Emit(*context.position(), ExpectedExpr);
  161. context.ReturnErrorOnState();
  162. break;
  163. }
  164. }
  165. }
  166. auto HandleExprInPostfixLoop(Context& context) -> void {
  167. // This is a cyclic state that repeats, so this state is typically pushed back
  168. // on.
  169. auto state = context.PopState();
  170. state.token = *context.position();
  171. switch (context.PositionKind()) {
  172. case Lex::TokenKind::Period: {
  173. context.PushState(state);
  174. state.state = State::PeriodAsExpr;
  175. context.PushState(state);
  176. break;
  177. }
  178. case Lex::TokenKind::MinusGreater: {
  179. context.PushState(state);
  180. state.state = State::ArrowExpr;
  181. context.PushState(state);
  182. break;
  183. }
  184. case Lex::TokenKind::OpenParen: {
  185. context.PushState(state);
  186. state.state = State::CallExpr;
  187. context.PushState(state);
  188. break;
  189. }
  190. case Lex::TokenKind::OpenSquareBracket: {
  191. context.PushState(state);
  192. state.state = State::IndexExpr;
  193. context.PushState(state);
  194. break;
  195. }
  196. default: {
  197. if (state.has_error) {
  198. context.ReturnErrorOnState();
  199. }
  200. break;
  201. }
  202. }
  203. }
  204. auto HandleExprLoop(Context& context) -> void {
  205. auto state = context.PopState();
  206. auto operator_kind = context.PositionKind();
  207. auto trailing_operator = PrecedenceGroup::ForTrailing(
  208. operator_kind, context.IsTrailingOperatorInfix());
  209. if (!trailing_operator) {
  210. if (state.has_error) {
  211. context.ReturnErrorOnState();
  212. }
  213. return;
  214. }
  215. auto [operator_precedence, is_binary] = *trailing_operator;
  216. // TODO: If this operator is ambiguous with either the ambient precedence
  217. // or the LHS precedence, and there's a variant with a different fixity
  218. // that would work, use that one instead for error recovery.
  219. if (PrecedenceGroup::GetPriority(state.ambient_precedence,
  220. operator_precedence) !=
  221. OperatorPriority::RightFirst) {
  222. // The precedence rules don't permit this operator in this context. Try
  223. // again in the enclosing expression context.
  224. if (state.has_error) {
  225. context.ReturnErrorOnState();
  226. }
  227. return;
  228. }
  229. if (PrecedenceGroup::GetPriority(state.lhs_precedence, operator_precedence) !=
  230. OperatorPriority::LeftFirst) {
  231. // Either the LHS operator and this operator are ambiguous, or the
  232. // LHS operator is a unary operator that can't be nested within
  233. // this operator. Either way, parentheses are required.
  234. if (PrecedenceGroup::GetPriority(PrecedenceGroup::ForTopLevelExpr(),
  235. operator_precedence) ==
  236. OperatorPriority::RightFirst) {
  237. CARBON_DIAGNOSTIC(
  238. OperatorRequiresParentheses, Error,
  239. "Parentheses are required to disambiguate operator precedence.");
  240. context.emitter().Emit(*context.position(), OperatorRequiresParentheses);
  241. } else {
  242. // This operator wouldn't be allowed even if parenthesized.
  243. DiagnoseStatementOperatorAsSubExpr(context);
  244. }
  245. state.has_error = true;
  246. } else {
  247. context.DiagnoseOperatorFixity(is_binary
  248. ? Context::OperatorFixity::Infix
  249. : Context::OperatorFixity::Postfix);
  250. }
  251. state.token = context.Consume();
  252. state.lhs_precedence = operator_precedence;
  253. if (is_binary) {
  254. if (operator_kind == Lex::TokenKind::And ||
  255. operator_kind == Lex::TokenKind::Or) {
  256. // For `and` and `or`, wrap the first operand in a virtual parse tree
  257. // node so that semantics can insert control flow here.
  258. context.AddNode(NodeKind::ShortCircuitOperand, state.token,
  259. state.subtree_start, state.has_error);
  260. }
  261. state.state = State::ExprLoopForBinary;
  262. context.PushState(state);
  263. context.PushStateForExpr(operator_precedence);
  264. } else {
  265. context.AddNode(NodeKind::PostfixOperator, state.token, state.subtree_start,
  266. state.has_error);
  267. state.has_error = false;
  268. context.PushState(state);
  269. }
  270. }
  271. auto HandleExprLoopForBinary(Context& context) -> void {
  272. auto state = context.PopState();
  273. context.AddNode(NodeKind::InfixOperator, state.token, state.subtree_start,
  274. state.has_error);
  275. state.state = State::ExprLoop;
  276. state.has_error = false;
  277. context.PushState(state);
  278. }
  279. auto HandleExprLoopForPrefix(Context& context) -> void {
  280. auto state = context.PopState();
  281. context.AddNode(NodeKind::PrefixOperator, state.token, state.subtree_start,
  282. state.has_error);
  283. state.state = State::ExprLoop;
  284. state.has_error = false;
  285. context.PushState(state);
  286. }
  287. auto HandleIfExprFinishCondition(Context& context) -> void {
  288. auto state = context.PopState();
  289. context.AddNode(NodeKind::IfExprIf, state.token, state.subtree_start,
  290. state.has_error);
  291. if (context.PositionIs(Lex::TokenKind::Then)) {
  292. context.PushState(State::IfExprFinishThen);
  293. context.ConsumeChecked(Lex::TokenKind::Then);
  294. context.PushStateForExpr(*PrecedenceGroup::ForLeading(Lex::TokenKind::If));
  295. } else {
  296. // TODO: Include the location of the `if` token.
  297. CARBON_DIAGNOSTIC(ExpectedThenAfterIf, Error,
  298. "Expected `then` after `if` condition.");
  299. if (!state.has_error) {
  300. context.emitter().Emit(*context.position(), ExpectedThenAfterIf);
  301. }
  302. // Add placeholders for `IfExprThen` and final `Expr`.
  303. context.AddLeafNode(NodeKind::InvalidParse, *context.position(),
  304. /*has_error=*/true);
  305. context.AddLeafNode(NodeKind::InvalidParse, *context.position(),
  306. /*has_error=*/true);
  307. context.ReturnErrorOnState();
  308. }
  309. }
  310. auto HandleIfExprFinishThen(Context& context) -> void {
  311. auto state = context.PopState();
  312. context.AddNode(NodeKind::IfExprThen, state.token, state.subtree_start,
  313. state.has_error);
  314. if (context.PositionIs(Lex::TokenKind::Else)) {
  315. context.PushState(State::IfExprFinishElse);
  316. context.ConsumeChecked(Lex::TokenKind::Else);
  317. context.PushStateForExpr(*PrecedenceGroup::ForLeading(Lex::TokenKind::If));
  318. } else {
  319. // TODO: Include the location of the `if` token.
  320. CARBON_DIAGNOSTIC(ExpectedElseAfterIf, Error,
  321. "Expected `else` after `if ... then ...`.");
  322. if (!state.has_error) {
  323. context.emitter().Emit(*context.position(), ExpectedElseAfterIf);
  324. }
  325. // Add placeholder for the final `Expr`.
  326. context.AddLeafNode(NodeKind::InvalidParse, *context.position(),
  327. /*has_error=*/true);
  328. context.ReturnErrorOnState();
  329. }
  330. }
  331. auto HandleIfExprFinishElse(Context& context) -> void {
  332. auto else_state = context.PopState();
  333. // Propagate the location of `else`.
  334. auto if_state = context.PopState();
  335. if_state.token = else_state.token;
  336. if_state.has_error |= else_state.has_error;
  337. context.PushState(if_state);
  338. }
  339. auto HandleIfExprFinish(Context& context) -> void {
  340. auto state = context.PopState();
  341. context.AddNode(NodeKind::IfExprElse, state.token, state.subtree_start,
  342. state.has_error);
  343. }
  344. auto HandleExprStatementFinish(Context& context) -> void {
  345. auto state = context.PopState();
  346. if (auto semi = context.ConsumeIf(Lex::TokenKind::Semi)) {
  347. context.AddNode(NodeKind::ExprStatement, *semi, state.subtree_start,
  348. state.has_error);
  349. return;
  350. }
  351. if (!state.has_error) {
  352. CARBON_DIAGNOSTIC(ExpectedExprSemi, Error,
  353. "Expected `;` after expression statement.");
  354. context.emitter().Emit(*context.position(), ExpectedExprSemi);
  355. }
  356. if (auto semi_token = context.SkipPastLikelyEnd(state.token)) {
  357. context.AddNode(NodeKind::ExprStatement, *semi_token, state.subtree_start,
  358. /*has_error=*/true);
  359. return;
  360. }
  361. // Found junk not even followed by a `;`, no node to add.
  362. context.ReturnErrorOnState();
  363. }
  364. } // namespace Carbon::Parse