handle_expr.cpp 16 KB

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