handle_expr.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  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(StateKind::IfExprFinish);
  45. context.PushState(StateKind::IfExprFinishCondition);
  46. } else {
  47. context.PushStateForExprLoop(StateKind::ExprLoopForPrefixOperator,
  48. state.ambient_precedence,
  49. *operator_precedence);
  50. }
  51. context.ConsumeAndDiscard();
  52. context.PushStateForExpr(*operator_precedence);
  53. } else {
  54. context.PushStateForExprLoop(StateKind::ExprLoop, state.ambient_precedence,
  55. PrecedenceGroup::ForPostfixExpr());
  56. context.PushState(StateKind::ExprInPostfix);
  57. }
  58. }
  59. auto HandleExprInPostfix(Context& context) -> void {
  60. auto state = context.PopState();
  61. // Continue to the loop state.
  62. state.kind = StateKind::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 (auto token_kind = 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::CharLiteral: {
  83. context.AddLeafNode(NodeKind::CharLiteral, context.Consume());
  84. context.PushState(state);
  85. break;
  86. }
  87. case Lex::TokenKind::IntLiteral: {
  88. context.AddLeafNode(NodeKind::IntLiteral, context.Consume());
  89. context.PushState(state);
  90. break;
  91. }
  92. case Lex::TokenKind::RealLiteral: {
  93. context.AddLeafNode(NodeKind::RealLiteral, context.Consume());
  94. context.PushState(state);
  95. break;
  96. }
  97. case Lex::TokenKind::StringLiteral: {
  98. context.AddLeafNode(NodeKind::StringLiteral, context.Consume());
  99. context.PushState(state);
  100. break;
  101. }
  102. case Lex::TokenKind::Bool: {
  103. context.AddLeafNode(NodeKind::BoolTypeLiteral, context.Consume());
  104. context.PushState(state);
  105. break;
  106. }
  107. case Lex::TokenKind::Char: {
  108. context.AddLeafNode(NodeKind::CharTypeLiteral, context.Consume());
  109. context.PushState(state);
  110. break;
  111. }
  112. case Lex::TokenKind::IntTypeLiteral: {
  113. context.AddLeafNode(NodeKind::IntTypeLiteral, context.Consume());
  114. context.PushState(state);
  115. break;
  116. }
  117. case Lex::TokenKind::UnsignedIntTypeLiteral: {
  118. context.AddLeafNode(NodeKind::UnsignedIntTypeLiteral, context.Consume());
  119. context.PushState(state);
  120. break;
  121. }
  122. case Lex::TokenKind::FloatTypeLiteral: {
  123. context.AddLeafNode(NodeKind::FloatTypeLiteral, context.Consume());
  124. context.PushState(state);
  125. break;
  126. }
  127. case Lex::TokenKind::Str: {
  128. context.AddLeafNode(NodeKind::StringTypeLiteral, context.Consume());
  129. context.PushState(state);
  130. break;
  131. }
  132. case Lex::TokenKind::Type: {
  133. context.AddLeafNode(NodeKind::TypeTypeLiteral, context.Consume());
  134. context.PushState(state);
  135. break;
  136. }
  137. case Lex::TokenKind::Auto: {
  138. context.AddLeafNode(NodeKind::AutoTypeLiteral, context.Consume());
  139. context.PushState(state);
  140. break;
  141. }
  142. case Lex::TokenKind::OpenCurlyBrace: {
  143. context.PushState(state);
  144. context.PushState(StateKind::BraceExpr);
  145. break;
  146. }
  147. case Lex::TokenKind::OpenParen: {
  148. context.PushState(state);
  149. context.PushState(StateKind::ParenExpr);
  150. break;
  151. }
  152. case Lex::TokenKind::Array: {
  153. context.PushState(state);
  154. context.PushState(StateKind::ArrayExpr);
  155. break;
  156. }
  157. case Lex::TokenKind::Package: {
  158. context.AddLeafNode(NodeKind::PackageExpr, context.Consume());
  159. if (context.PositionKind() != Lex::TokenKind::Period) {
  160. CARBON_DIAGNOSTIC(ExpectedPeriodAfterPackage, Error,
  161. "expected `.` after `package` expression");
  162. context.emitter().Emit(*context.position(), ExpectedPeriodAfterPackage);
  163. state.has_error = true;
  164. }
  165. context.PushState(state);
  166. break;
  167. }
  168. case Lex::TokenKind::Core: {
  169. context.AddLeafNode(NodeKind::CoreNameExpr, context.Consume());
  170. context.PushState(state);
  171. break;
  172. }
  173. case Lex::TokenKind::Cpp: {
  174. context.AddLeafNode(NodeKind::CppNameExpr, context.Consume());
  175. context.PushState(state);
  176. break;
  177. }
  178. case Lex::TokenKind::SelfValueIdentifier: {
  179. context.AddLeafNode(NodeKind::SelfValueNameExpr, context.Consume());
  180. context.PushState(state);
  181. break;
  182. }
  183. case Lex::TokenKind::SelfTypeIdentifier: {
  184. context.AddLeafNode(NodeKind::SelfTypeNameExpr, context.Consume());
  185. context.PushState(state);
  186. break;
  187. }
  188. case Lex::TokenKind::Period: {
  189. // For periods, we look at the next token to form a designator like
  190. // `.Member` or `.Self`.
  191. auto period = context.Consume();
  192. if (context.ConsumeAndAddLeafNodeIf(
  193. Lex::TokenKind::Identifier,
  194. NodeKind::IdentifierNameNotBeforeParams)) {
  195. // OK, `.` identifier.
  196. } else if (context.ConsumeAndAddLeafNodeIf(
  197. Lex::TokenKind::SelfTypeIdentifier,
  198. NodeKind::SelfTypeName)) {
  199. // OK, `.Self`.
  200. } else {
  201. CARBON_DIAGNOSTIC(ExpectedIdentifierOrSelfAfterPeriod, Error,
  202. "expected identifier or `Self` after `.`");
  203. context.emitter().Emit(*context.position(),
  204. ExpectedIdentifierOrSelfAfterPeriod);
  205. // Only consume if it is a number or word.
  206. if (context.PositionKind().is_keyword()) {
  207. context.AddLeafNode(NodeKind::IdentifierNameNotBeforeParams,
  208. context.Consume(), /*has_error=*/true);
  209. } else if (context.PositionIs(Lex::TokenKind::IntLiteral)) {
  210. context.AddInvalidParse(context.Consume());
  211. } else {
  212. context.AddInvalidParse(*context.position());
  213. // Indicate the error to the parent state so that it can avoid
  214. // producing more errors. We only do this on this path where we don't
  215. // consume the token after the period, where we expect further errors
  216. // since we likely haven't recovered.
  217. context.ReturnErrorOnState();
  218. }
  219. state.has_error = true;
  220. }
  221. context.AddNode(NodeKind::DesignatorExpr, period, state.has_error);
  222. context.PushState(state);
  223. break;
  224. }
  225. default: {
  226. // If not already diagnosed in the lexer, diagnose it here.
  227. if (token_kind != Lex::TokenKind::Error) {
  228. CARBON_DIAGNOSTIC(ExpectedExpr, Error, "expected expression");
  229. context.emitter().Emit(*context.position(), ExpectedExpr);
  230. }
  231. // Add a node to keep the parse tree balanced.
  232. context.AddInvalidParse(*context.position());
  233. context.ReturnErrorOnState();
  234. break;
  235. }
  236. }
  237. }
  238. auto HandleExprInPostfixLoop(Context& context) -> void {
  239. // This is a cyclic state that repeats, so this state is typically pushed back
  240. // on.
  241. auto state = context.PopState();
  242. state.token = *context.position();
  243. switch (context.PositionKind()) {
  244. case Lex::TokenKind::Period: {
  245. context.PushState(state);
  246. context.PushState(state, StateKind::PeriodAsExpr);
  247. break;
  248. }
  249. case Lex::TokenKind::MinusGreater: {
  250. context.PushState(state);
  251. context.PushState(state, StateKind::ArrowExpr);
  252. break;
  253. }
  254. case Lex::TokenKind::OpenParen: {
  255. context.PushState(state);
  256. context.PushState(state, StateKind::CallExpr);
  257. break;
  258. }
  259. case Lex::TokenKind::OpenSquareBracket: {
  260. context.PushState(state);
  261. context.PushState(state, StateKind::IndexExpr);
  262. break;
  263. }
  264. default: {
  265. if (state.has_error) {
  266. context.ReturnErrorOnState();
  267. }
  268. break;
  269. }
  270. }
  271. }
  272. auto HandleExprLoop(Context& context) -> void {
  273. auto state = context.PopState();
  274. auto operator_kind = context.PositionKind();
  275. auto trailing_operator = PrecedenceGroup::ForTrailing(
  276. operator_kind, context.IsTrailingOperatorInfix());
  277. if (!trailing_operator) {
  278. // TODO: Generalize this to handle a sequence of operator modifiers once we
  279. // have more than one.
  280. if (context.PositionIs(Lex::TokenKind::Unsafe)) {
  281. operator_kind = context.PositionKind(Lookahead::NextToken);
  282. trailing_operator = PrecedenceGroup::ForTrailing(
  283. operator_kind, context.IsTrailingOperatorInfix());
  284. }
  285. if (!trailing_operator) {
  286. if (state.has_error) {
  287. context.ReturnErrorOnState();
  288. }
  289. return;
  290. }
  291. }
  292. auto [operator_precedence, is_binary] = *trailing_operator;
  293. // TODO: If this operator is ambiguous with either the ambient precedence
  294. // or the LHS precedence, and there's a variant with a different fixity
  295. // that would work, use that one instead for error recovery.
  296. if (PrecedenceGroup::GetPriority(state.ambient_precedence,
  297. operator_precedence) !=
  298. OperatorPriority::RightFirst) {
  299. // The precedence rules don't permit this operator in this context. Try
  300. // again in the enclosing expression context.
  301. if (state.has_error) {
  302. context.ReturnErrorOnState();
  303. }
  304. return;
  305. }
  306. if (PrecedenceGroup::GetPriority(state.lhs_precedence, operator_precedence) !=
  307. OperatorPriority::LeftFirst) {
  308. // Either the LHS operator and this operator are ambiguous, or the
  309. // LHS operator is a unary operator that can't be nested within
  310. // this operator. Either way, parentheses are required.
  311. if (PrecedenceGroup::GetPriority(PrecedenceGroup::ForTopLevelExpr(),
  312. operator_precedence) ==
  313. OperatorPriority::RightFirst) {
  314. CARBON_DIAGNOSTIC(
  315. OperatorRequiresParentheses, Error,
  316. "parentheses are required to disambiguate operator precedence");
  317. context.emitter().Emit(*context.position(), OperatorRequiresParentheses);
  318. } else {
  319. // This operator wouldn't be allowed even if parenthesized.
  320. DiagnoseStatementOperatorAsSubExpr(context);
  321. }
  322. state.has_error = true;
  323. } else {
  324. context.DiagnoseOperatorFixity(is_binary
  325. ? Context::OperatorFixity::Infix
  326. : Context::OperatorFixity::Postfix);
  327. }
  328. // For operator modifiers, wrap the first operand in the modifier.
  329. if (context.PositionIs(Lex::TokenKind::Unsafe)) {
  330. if (context.PositionIs(Lex::TokenKind::As, Lookahead::NextToken)) {
  331. context.AddNode<NodeKind::UnsafeModifier>(context.Consume(),
  332. state.has_error);
  333. } else {
  334. CARBON_DIAGNOSTIC(ModifierNotAllowedOnOperator, Error,
  335. "`{0}` not allowed on operator `{1}`", Lex::TokenKind,
  336. Lex::TokenKind);
  337. context.emitter().Emit(*context.position(), ModifierNotAllowedOnOperator,
  338. context.PositionKind(),
  339. context.PositionKind(Lookahead::NextToken));
  340. context.Consume();
  341. state.has_error = true;
  342. }
  343. }
  344. state.token = context.Consume();
  345. state.lhs_precedence = operator_precedence;
  346. if (is_binary) {
  347. switch (operator_kind) {
  348. // For `and` and `or`, wrap the first operand in a virtual parse tree
  349. // node so that checking can insert control flow here.
  350. case Lex::TokenKind::And:
  351. context.AddNode(NodeKind::ShortCircuitOperandAnd, state.token,
  352. state.has_error);
  353. state.kind = StateKind::ExprLoopForShortCircuitOperatorAsAnd;
  354. break;
  355. case Lex::TokenKind::Or:
  356. context.AddNode(NodeKind::ShortCircuitOperandOr, state.token,
  357. state.has_error);
  358. state.kind = StateKind::ExprLoopForShortCircuitOperatorAsOr;
  359. break;
  360. // `where` also needs a virtual parse tree node, and parses its right
  361. // argument in a mode where it can handle requirement operators like
  362. // `impls` and `=`.
  363. case Lex::TokenKind::Where:
  364. context.AddNode(NodeKind::WhereOperand, state.token, state.has_error);
  365. context.PushState(state, StateKind::WhereFinish);
  366. context.PushState(StateKind::RequirementBegin);
  367. return;
  368. default:
  369. state.kind = StateKind::ExprLoopForInfixOperator;
  370. break;
  371. }
  372. context.PushState(state);
  373. context.PushStateForExpr(operator_precedence);
  374. } else {
  375. NodeKind node_kind;
  376. switch (operator_kind) {
  377. #define CARBON_PARSE_NODE_KIND(Name)
  378. #define CARBON_PARSE_NODE_KIND_POSTFIX_OPERATOR(Name) \
  379. case Lex::TokenKind::Name: \
  380. node_kind = NodeKind::PostfixOperator##Name; \
  381. break;
  382. #include "toolchain/parse/node_kind.def"
  383. default:
  384. CARBON_FATAL("Unexpected token kind for postfix operator: {0}",
  385. operator_kind);
  386. }
  387. context.AddNode(node_kind, state.token, state.has_error);
  388. state.has_error = false;
  389. context.PushState(state);
  390. }
  391. }
  392. // Adds the operator node and returns the main expression loop.
  393. static auto HandleExprLoopForOperator(Context& context, Context::State state,
  394. NodeKind node_kind) -> void {
  395. context.AddNode(node_kind, state.token, state.has_error);
  396. state.has_error = false;
  397. context.PushState(state, StateKind::ExprLoop);
  398. }
  399. auto HandleExprLoopForInfixOperator(Context& context) -> void {
  400. auto state = context.PopState();
  401. switch (auto token_kind = context.tokens().GetKind(state.token)) {
  402. #define CARBON_PARSE_NODE_KIND(Name)
  403. #define CARBON_PARSE_NODE_KIND_INFIX_OPERATOR(Name) \
  404. case Lex::TokenKind::Name: \
  405. HandleExprLoopForOperator(context, state, NodeKind::InfixOperator##Name); \
  406. break;
  407. #include "toolchain/parse/node_kind.def"
  408. default:
  409. CARBON_FATAL("Unexpected token kind for infix operator: {0}", token_kind);
  410. }
  411. }
  412. auto HandleExprLoopForPrefixOperator(Context& context) -> void {
  413. auto state = context.PopState();
  414. switch (auto token_kind = context.tokens().GetKind(state.token)) {
  415. #define CARBON_PARSE_NODE_KIND(Name)
  416. #define CARBON_PARSE_NODE_KIND_PREFIX_OPERATOR(Name) \
  417. case Lex::TokenKind::Name: \
  418. HandleExprLoopForOperator(context, state, NodeKind::PrefixOperator##Name); \
  419. break;
  420. #include "toolchain/parse/node_kind.def"
  421. default:
  422. CARBON_FATAL("Unexpected token kind for prefix operator: {0}",
  423. token_kind);
  424. }
  425. }
  426. auto HandleExprLoopForShortCircuitOperatorAsAnd(Context& context) -> void {
  427. auto state = context.PopState();
  428. HandleExprLoopForOperator(context, state, NodeKind::ShortCircuitOperatorAnd);
  429. }
  430. auto HandleExprLoopForShortCircuitOperatorAsOr(Context& context) -> void {
  431. auto state = context.PopState();
  432. HandleExprLoopForOperator(context, state, NodeKind::ShortCircuitOperatorOr);
  433. }
  434. auto HandleExprStatementFinish(Context& context) -> void {
  435. auto state = context.PopState();
  436. if (auto semi = context.ConsumeIf(Lex::TokenKind::Semi)) {
  437. context.AddNode(NodeKind::ExprStatement, *semi, state.has_error);
  438. return;
  439. }
  440. if (!state.has_error) {
  441. CARBON_DIAGNOSTIC(ExpectedExprSemi, Error,
  442. "expected `;` after expression statement");
  443. context.emitter().Emit(*context.position(), ExpectedExprSemi);
  444. }
  445. context.AddNode(NodeKind::ExprStatement,
  446. context.SkipPastLikelyEnd(state.token), /*has_error=*/true);
  447. }
  448. } // namespace Carbon::Parse