handle_import_and_package.cpp 9.4 KB

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