handle_function.cpp 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. auto HandleFunctionIntroducer(Context& context) -> void {
  7. auto state = context.PopState();
  8. context.PushState(state, State::FunctionAfterParams);
  9. context.PushState(State::DeclNameAndParamsAsRequired, state.token);
  10. }
  11. auto HandleFunctionAfterParams(Context& context) -> void {
  12. auto state = context.PopState();
  13. // Regardless of whether there's a return type, we'll finish the signature.
  14. context.PushState(state, State::FunctionSignatureFinish);
  15. // If there is a return type, parse the expression before adding the return
  16. // type node.
  17. if (context.PositionIs(Lex::TokenKind::MinusGreater)) {
  18. context.PushState(State::FunctionReturnTypeFinish);
  19. context.ConsumeAndDiscard();
  20. context.PushStateForExpr(PrecedenceGroup::ForType());
  21. }
  22. }
  23. auto HandleFunctionReturnTypeFinish(Context& context) -> void {
  24. auto state = context.PopState();
  25. context.AddNode(NodeKind::ReturnType, state.token, state.subtree_start,
  26. state.has_error);
  27. }
  28. auto HandleFunctionSignatureFinish(Context& context) -> void {
  29. auto state = context.PopState();
  30. switch (context.PositionKind()) {
  31. case Lex::TokenKind::Semi: {
  32. context.AddNode(NodeKind::FunctionDecl, context.Consume(),
  33. state.subtree_start, state.has_error);
  34. break;
  35. }
  36. case Lex::TokenKind::OpenCurlyBrace: {
  37. context.AddNode(NodeKind::FunctionDefinitionStart, context.Consume(),
  38. state.subtree_start, state.has_error);
  39. // Any error is recorded on the FunctionDefinitionStart.
  40. state.has_error = false;
  41. context.PushState(state, State::FunctionDefinitionFinish);
  42. context.PushState(State::StatementScopeLoop);
  43. break;
  44. }
  45. default: {
  46. if (!state.has_error) {
  47. context.EmitExpectedDeclSemiOrDefinition(Lex::TokenKind::Fn);
  48. }
  49. // Only need to skip if we've not already found a new line.
  50. bool skip_past_likely_end =
  51. context.tokens().GetLine(*context.position()) ==
  52. context.tokens().GetLine(state.token);
  53. context.RecoverFromDeclError(state, NodeKind::FunctionDecl,
  54. skip_past_likely_end);
  55. break;
  56. }
  57. }
  58. }
  59. auto HandleFunctionDefinitionFinish(Context& context) -> void {
  60. auto state = context.PopState();
  61. context.AddNode(NodeKind::FunctionDefinition, context.Consume(),
  62. state.subtree_start, state.has_error);
  63. }
  64. } // namespace Carbon::Parse