handle_import_and_package.cpp 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  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/base/value_store.h"
  5. #include "toolchain/lex/tokenized_buffer.h"
  6. #include "toolchain/parse/context.h"
  7. #include "toolchain/parse/node_kind.h"
  8. namespace Carbon::Parse {
  9. // Provides common error exiting logic that skips to the semi, if present.
  10. static auto OnParseError(Context& context, Context::StateStackEntry state,
  11. NodeKind directive) -> void {
  12. auto semi_token = context.SkipPastLikelyEnd(state.token);
  13. return context.AddNode(directive, semi_token ? *semi_token : state.token,
  14. state.subtree_start,
  15. /*has_error=*/true);
  16. }
  17. // Handles parsing of the library name. Returns the name's ID on success, which
  18. // may be invalid for `default`.
  19. static auto HandleLibraryName(Context& context, bool accept_default)
  20. -> std::optional<StringLiteralId> {
  21. if (auto library_name_token =
  22. context.ConsumeIf(Lex::TokenKind::StringLiteral)) {
  23. context.AddLeafNode(NodeKind::LibraryName, *library_name_token);
  24. return context.tokens().GetStringLiteral(*library_name_token);
  25. }
  26. if (accept_default) {
  27. if (auto default_token = context.ConsumeIf(Lex::TokenKind::Default)) {
  28. context.AddLeafNode(NodeKind::DefaultLibrary, *default_token);
  29. return StringLiteralId::Invalid;
  30. }
  31. }
  32. CARBON_DIAGNOSTIC(
  33. ExpectedLibraryNameOrDefault, Error,
  34. "Expected `default` or a string literal to specify the library name.");
  35. CARBON_DIAGNOSTIC(ExpectedLibraryName, Error,
  36. "Expected a string literal to specify the library name.");
  37. context.emitter().Emit(*context.position(), accept_default
  38. ? ExpectedLibraryNameOrDefault
  39. : ExpectedLibraryName);
  40. return std::nullopt;
  41. }
  42. // Returns whether `api` or `impl` is provided, or prints an error and returns
  43. // nullopt.
  44. static auto HandleApiOrImpl(Context& context)
  45. -> std::optional<Tree::ApiOrImpl> {
  46. switch (context.PositionKind()) {
  47. case Lex::TokenKind::Api: {
  48. context.AddLeafNode(NodeKind::PackageApi,
  49. context.ConsumeChecked(Lex::TokenKind::Api));
  50. return Tree::ApiOrImpl::Api;
  51. break;
  52. }
  53. case Lex::TokenKind::Impl: {
  54. context.AddLeafNode(NodeKind::PackageImpl,
  55. context.ConsumeChecked(Lex::TokenKind::Impl));
  56. return Tree::ApiOrImpl::Impl;
  57. break;
  58. }
  59. default: {
  60. CARBON_DIAGNOSTIC(ExpectedApiOrImpl, Error, "Expected `api` or `impl`.");
  61. context.emitter().Emit(*context.position(), ExpectedApiOrImpl);
  62. return std::nullopt;
  63. }
  64. }
  65. }
  66. // Handles everything after the directive's introducer.
  67. static auto HandleDirectiveContent(Context& context,
  68. Context::StateStackEntry state,
  69. NodeKind directive,
  70. llvm::function_ref<void()> on_parse_error)
  71. -> void {
  72. Tree::PackagingNames names{.node = Node(state.subtree_start)};
  73. if (directive != NodeKind::LibraryDirective) {
  74. if (auto package_name_token =
  75. context.ConsumeIf(Lex::TokenKind::Identifier)) {
  76. names.package_id = context.tokens().GetIdentifier(*package_name_token);
  77. context.AddLeafNode(NodeKind::PackageName, *package_name_token);
  78. } else if (directive == NodeKind::PackageDirective ||
  79. !context.PositionIs(Lex::TokenKind::Library)) {
  80. CARBON_DIAGNOSTIC(ExpectedIdentifierAfterPackage, Error,
  81. "Expected identifier after `package`.");
  82. CARBON_DIAGNOSTIC(ExpectedIdentifierAfterImport, Error,
  83. "Expected identifier or `library` after `import`.");
  84. context.emitter().Emit(*context.position(),
  85. directive == NodeKind::PackageDirective
  86. ? ExpectedIdentifierAfterPackage
  87. : ExpectedIdentifierAfterImport);
  88. on_parse_error();
  89. return;
  90. }
  91. }
  92. // Parse the optional library keyword.
  93. bool accept_default = !names.package_id.is_valid();
  94. if (directive == NodeKind::LibraryDirective) {
  95. auto library_id = HandleLibraryName(context, accept_default);
  96. if (!library_id) {
  97. on_parse_error();
  98. return;
  99. }
  100. names.library_id = *library_id;
  101. } else {
  102. auto next_kind = context.PositionKind();
  103. if (next_kind == Lex::TokenKind::Library) {
  104. auto library_token = context.ConsumeChecked(Lex::TokenKind::Library);
  105. auto library_subtree_start = context.tree().size();
  106. auto library_id = HandleLibraryName(context, accept_default);
  107. if (!library_id) {
  108. on_parse_error();
  109. return;
  110. }
  111. names.library_id = *library_id;
  112. context.AddNode(NodeKind::LibrarySpecifier, library_token,
  113. library_subtree_start,
  114. /*has_error=*/false);
  115. } else if (next_kind == Lex::TokenKind::StringLiteral ||
  116. (accept_default && next_kind == Lex::TokenKind::Default)) {
  117. // If we come across a string literal and we didn't parse `library
  118. // "..."` yet, then most probably the user forgot to add `library`
  119. // before the library name.
  120. CARBON_DIAGNOSTIC(MissingLibraryKeyword, Error,
  121. "Missing `library` keyword.");
  122. context.emitter().Emit(*context.position(), MissingLibraryKeyword);
  123. on_parse_error();
  124. return;
  125. }
  126. }
  127. std::optional<Tree::ApiOrImpl> api_or_impl;
  128. if (directive != NodeKind::ImportDirective) {
  129. api_or_impl = HandleApiOrImpl(context);
  130. if (!api_or_impl) {
  131. on_parse_error();
  132. return;
  133. }
  134. }
  135. if (auto semi = context.ConsumeIf(Lex::TokenKind::Semi)) {
  136. if (directive == NodeKind::ImportDirective) {
  137. context.AddImport(names);
  138. } else {
  139. context.set_packaging_directive(names, *api_or_impl);
  140. }
  141. context.AddNode(directive, *semi, state.subtree_start, state.has_error);
  142. } else {
  143. context.EmitExpectedDeclSemi(context.tokens().GetKind(state.token));
  144. on_parse_error();
  145. }
  146. }
  147. auto HandleImport(Context& context) -> void {
  148. auto state = context.PopState();
  149. auto directive = NodeKind::ImportDirective;
  150. auto on_parse_error = [&] { OnParseError(context, state, directive); };
  151. auto intro_token = context.ConsumeChecked(Lex::TokenKind::Import);
  152. context.AddLeafNode(NodeKind::ImportIntroducer, intro_token);
  153. switch (context.packaging_state()) {
  154. case Context::PackagingState::StartOfFile:
  155. // `package` is no longer allowed, but `import` may repeat.
  156. context.set_packaging_state(Context::PackagingState::InImports);
  157. [[clang::fallthrough]];
  158. case Context::PackagingState::InImports:
  159. HandleDirectiveContent(context, state, directive, on_parse_error);
  160. break;
  161. case Context::PackagingState::AfterNonPackagingDecl: {
  162. context.set_packaging_state(
  163. Context::PackagingState::InImportsAfterNonPackagingDecl);
  164. CARBON_DIAGNOSTIC(
  165. ImportTooLate, Error,
  166. "`import` directives must come after the `package` directive (if "
  167. "present) and before any other entities in the file.");
  168. CARBON_DIAGNOSTIC(FirstDecl, Note, "First declaration is here.");
  169. context.emitter()
  170. .Build(intro_token, ImportTooLate)
  171. .Note(context.first_non_packaging_token(), FirstDecl)
  172. .Emit();
  173. on_parse_error();
  174. break;
  175. }
  176. case Context::PackagingState::InImportsAfterNonPackagingDecl:
  177. // There is a sequential block of misplaced `import` statements, which can
  178. // occur if a declaration is added above `import`s. Avoid duplicate
  179. // warnings.
  180. on_parse_error();
  181. break;
  182. }
  183. }
  184. // Handles common logic for `package` and `library`.
  185. static auto HandlePackageAndLibraryDirectives(Context& context,
  186. Lex::TokenKind intro_token_kind,
  187. NodeKind intro,
  188. NodeKind directive) -> void {
  189. auto state = context.PopState();
  190. auto on_parse_error = [&] { OnParseError(context, state, directive); };
  191. auto intro_token = context.ConsumeChecked(intro_token_kind);
  192. context.AddLeafNode(intro, intro_token);
  193. if (intro_token != Lex::Token::FirstNonCommentToken) {
  194. CARBON_DIAGNOSTIC(PackageTooLate, Error,
  195. "The `{0}` directive must be the first non-comment line.",
  196. Lex::TokenKind);
  197. CARBON_DIAGNOSTIC(FirstNonCommentLine, Note,
  198. "First non-comment line is here.");
  199. context.emitter()
  200. .Build(intro_token, PackageTooLate, intro_token_kind)
  201. .Note(Lex::Token::FirstNonCommentToken, FirstNonCommentLine)
  202. .Emit();
  203. on_parse_error();
  204. return;
  205. }
  206. // `package`/`library` is no longer allowed, but `import` may repeat.
  207. context.set_packaging_state(Context::PackagingState::InImports);
  208. HandleDirectiveContent(context, state, directive, on_parse_error);
  209. }
  210. auto HandlePackage(Context& context) -> void {
  211. HandlePackageAndLibraryDirectives(context, Lex::TokenKind::Package,
  212. NodeKind::PackageIntroducer,
  213. NodeKind::PackageDirective);
  214. }
  215. auto HandleLibrary(Context& context) -> void {
  216. HandlePackageAndLibraryDirectives(context, Lex::TokenKind::Library,
  217. NodeKind::LibraryIntroducer,
  218. NodeKind::LibraryDirective);
  219. }
  220. } // namespace Carbon::Parse