handle_decl_scope_loop.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  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 OutputInvalidParseSubtree(Context& context, int32_t subtree_start)
  7. -> void {
  8. auto cursor = *context.position();
  9. // Consume to the next `;` or end of line. We ignore the return value since
  10. // we only care how much was consumed, not whether it ended with a `;`.
  11. // TODO: adjust the return of SkipPastLikelyEnd or create a new function
  12. // to avoid going through these hoops.
  13. context.SkipPastLikelyEnd(cursor);
  14. // Set `iter` to the last token consumed, one before the current position.
  15. auto iter = context.position();
  16. --iter;
  17. // Output an invalid parse subtree including everything up to the last token
  18. // consumed.
  19. context.ReplacePlaceholderNode(subtree_start, NodeKind::InvalidParseStart,
  20. cursor, /*has_error=*/true);
  21. context.AddNode(NodeKind::InvalidParseSubtree, *iter, subtree_start,
  22. /*has_error=*/true);
  23. }
  24. // Handles an unrecognized declaration.
  25. static auto HandleUnrecognizedDecl(Context& context, int32_t subtree_start)
  26. -> void {
  27. CARBON_DIAGNOSTIC(UnrecognizedDecl, Error,
  28. "Unrecognized declaration introducer.");
  29. context.emitter().Emit(*context.position(), UnrecognizedDecl);
  30. OutputInvalidParseSubtree(context, subtree_start);
  31. }
  32. static auto TokenIsModifierOrIntroducer(Lex::TokenKind token_kind) -> bool {
  33. switch (token_kind) {
  34. case Lex::TokenKind::Abstract:
  35. case Lex::TokenKind::Base:
  36. case Lex::TokenKind::Class:
  37. case Lex::TokenKind::Constraint:
  38. case Lex::TokenKind::Default:
  39. case Lex::TokenKind::Extend:
  40. case Lex::TokenKind::Final:
  41. case Lex::TokenKind::Fn:
  42. case Lex::TokenKind::Impl:
  43. case Lex::TokenKind::Interface:
  44. case Lex::TokenKind::Let:
  45. case Lex::TokenKind::Namespace:
  46. case Lex::TokenKind::Private:
  47. case Lex::TokenKind::Protected:
  48. case Lex::TokenKind::Var:
  49. case Lex::TokenKind::Virtual:
  50. return true;
  51. default:
  52. return false;
  53. }
  54. }
  55. auto HandleDeclScopeLoop(Context& context) -> void {
  56. // This maintains the current state unless we're at the end of the scope.
  57. switch (context.PositionKind()) {
  58. case Lex::TokenKind::CloseCurlyBrace:
  59. case Lex::TokenKind::FileEnd: {
  60. // This is the end of the scope, so the loop state ends.
  61. context.PopAndDiscardState();
  62. return;
  63. }
  64. // `import`, `library`, and `package` manage their packaging state.
  65. case Lex::TokenKind::Import: {
  66. context.PushState(State::Import);
  67. return;
  68. }
  69. case Lex::TokenKind::Library: {
  70. context.PushState(State::Library);
  71. return;
  72. }
  73. case Lex::TokenKind::Package: {
  74. context.PushState(State::Package);
  75. return;
  76. }
  77. default: {
  78. break;
  79. }
  80. }
  81. // Because a non-packaging keyword was encountered, packaging is complete.
  82. // Misplaced packaging keywords may lead to this being re-triggered.
  83. if (context.packaging_state() !=
  84. Context::PackagingState::AfterNonPackagingDecl) {
  85. if (!context.first_non_packaging_token().is_valid()) {
  86. context.set_first_non_packaging_token(*context.position());
  87. }
  88. context.set_packaging_state(Context::PackagingState::AfterNonPackagingDecl);
  89. }
  90. // Remaining keywords are only valid after imports are complete, and so all
  91. // result in a `set_packaging_state` call. Note, this may not always be
  92. // necessary but is probably cheaper than validating.
  93. // Create a state with the correct starting position, with a dummy kind until
  94. // we see the declaration's introducer.
  95. context.PushState(State::DeclScopeLoop);
  96. auto state = context.PopState();
  97. // Add a placeholder node, to be replaced by the declaration introducer once
  98. // it is found.
  99. context.AddLeafNode(NodeKind::Placeholder, *context.position());
  100. auto introducer = [&](NodeKind node_kind, State next_state) {
  101. context.ReplacePlaceholderNode(state.subtree_start, node_kind,
  102. context.Consume());
  103. // Reuse state here to retain its `subtree_start`
  104. state.state = next_state;
  105. context.PushState(state);
  106. };
  107. bool saw_modifier = false;
  108. while (true) {
  109. switch (context.PositionKind()) {
  110. // If we see a modifier keyword token, add it as a leaf node and loop to
  111. // the next token.
  112. case Lex::TokenKind::Abstract:
  113. context.AddLeafNode(NodeKind::AbstractModifier, context.Consume());
  114. saw_modifier = true;
  115. break;
  116. case Lex::TokenKind::Default:
  117. context.AddLeafNode(NodeKind::DefaultModifier, context.Consume());
  118. saw_modifier = true;
  119. break;
  120. case Lex::TokenKind::Final:
  121. context.AddLeafNode(NodeKind::FinalModifier, context.Consume());
  122. saw_modifier = true;
  123. break;
  124. case Lex::TokenKind::Private:
  125. context.AddLeafNode(NodeKind::PrivateModifier, context.Consume());
  126. saw_modifier = true;
  127. break;
  128. case Lex::TokenKind::Protected:
  129. context.AddLeafNode(NodeKind::ProtectedModifier, context.Consume());
  130. saw_modifier = true;
  131. break;
  132. case Lex::TokenKind::Virtual:
  133. context.AddLeafNode(NodeKind::VirtualModifier, context.Consume());
  134. saw_modifier = true;
  135. break;
  136. case Lex::TokenKind::Base:
  137. // `base` may be followed by:
  138. // - a colon
  139. // => assume it is an introducer, as in `extend base: BaseType;`.
  140. // - a modifier or an introducer
  141. // => assume it is a modifier, as in `base class`; which is handled
  142. // by falling through to the next case.
  143. // Anything else is an error.
  144. if (context.PositionIs(Lex::TokenKind::Colon, Lookahead::NextToken)) {
  145. context.ReplacePlaceholderNode(
  146. state.subtree_start, NodeKind::BaseIntroducer, context.Consume());
  147. // Reuse state here to retain its `subtree_start`
  148. state.state = State::BaseDecl;
  149. context.PushState(state);
  150. context.PushState(State::Expr);
  151. context.AddLeafNode(NodeKind::BaseColon, context.Consume());
  152. return;
  153. } else if (!TokenIsModifierOrIntroducer(
  154. context.PositionKind(Lookahead::NextToken))) {
  155. // TODO: If the next token isn't a colon or `class`, try to recover
  156. // based on whether we're in a class, whether we have an `extend`
  157. // modifier, and the following tokens.
  158. context.AddLeafNode(NodeKind::InvalidParse, context.Consume(),
  159. /*has_error=*/true);
  160. CARBON_DIAGNOSTIC(ExpectedAfterBase, Error,
  161. "`class` or `:` expected after `base`.");
  162. context.emitter().Emit(*context.position(), ExpectedAfterBase);
  163. OutputInvalidParseSubtree(context, state.subtree_start);
  164. return;
  165. }
  166. context.AddLeafNode(NodeKind::BaseModifier, context.Consume());
  167. saw_modifier = true;
  168. break;
  169. case Lex::TokenKind::Impl: {
  170. // `impl` is considered a declaration modifier if it is followed by
  171. // another modifier or an introducer.
  172. if (TokenIsModifierOrIntroducer(
  173. context.PositionKind(Lookahead::NextToken))) {
  174. context.AddLeafNode(NodeKind::ImplModifier, context.Consume());
  175. saw_modifier = true;
  176. } else {
  177. // TODO: Treat this `impl` token as a declaration introducer
  178. HandleUnrecognizedDecl(context, state.subtree_start);
  179. return;
  180. }
  181. break;
  182. }
  183. case Lex::TokenKind::Extend: {
  184. // `extend` is considered a declaration modifier if it is followed by
  185. // another modifier or an introducer.
  186. if (TokenIsModifierOrIntroducer(
  187. context.PositionKind(Lookahead::NextToken))) {
  188. context.AddLeafNode(NodeKind::ExtendModifier, context.Consume());
  189. saw_modifier = true;
  190. } else {
  191. // TODO: Treat this `extend` token as a declaration introducer
  192. HandleUnrecognizedDecl(context, state.subtree_start);
  193. return;
  194. }
  195. break;
  196. }
  197. // If we see a declaration introducer keyword token, replace the
  198. // placeholder node and switch to a state to parse the rest of the
  199. // declaration. We don't allow namespace or empty declarations here since
  200. // they can't have modifiers and don't use bracketing parse nodes that
  201. // would allow a variable number of modifier nodes.
  202. case Lex::TokenKind::Class: {
  203. introducer(NodeKind::ClassIntroducer,
  204. State::TypeAfterIntroducerAsClass);
  205. return;
  206. }
  207. case Lex::TokenKind::Constraint: {
  208. introducer(NodeKind::NamedConstraintIntroducer,
  209. State::TypeAfterIntroducerAsNamedConstraint);
  210. return;
  211. }
  212. case Lex::TokenKind::Fn: {
  213. introducer(NodeKind::FunctionIntroducer, State::FunctionIntroducer);
  214. return;
  215. }
  216. case Lex::TokenKind::Interface: {
  217. introducer(NodeKind::InterfaceIntroducer,
  218. State::TypeAfterIntroducerAsInterface);
  219. return;
  220. }
  221. case Lex::TokenKind::Var: {
  222. introducer(NodeKind::VariableIntroducer, State::VarAsDecl);
  223. return;
  224. }
  225. case Lex::TokenKind::Let: {
  226. introducer(NodeKind::LetIntroducer, State::Let);
  227. return;
  228. }
  229. // We don't allow namespace or empty declarations after a modifier since
  230. // they can't have modifiers and don't use bracketing parse nodes that
  231. // would allow a variable number of modifier nodes.
  232. case Lex::TokenKind::Namespace: {
  233. introducer(NodeKind::NamespaceStart, State::Namespace);
  234. return;
  235. }
  236. case Lex::TokenKind::Semi: {
  237. if (saw_modifier) {
  238. HandleUnrecognizedDecl(context, state.subtree_start);
  239. } else {
  240. context.ReplacePlaceholderNode(
  241. state.subtree_start, NodeKind::EmptyDecl, context.Consume());
  242. }
  243. return;
  244. }
  245. default: {
  246. // For anything else, report an error and output an invalid parse node
  247. // or subtree.
  248. HandleUnrecognizedDecl(context, state.subtree_start);
  249. return;
  250. }
  251. }
  252. }
  253. }
  254. } // namespace Carbon::Parse