handle_import_and_package.cpp 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  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/shared_value_stores.h"
  5. #include "toolchain/lex/token_kind.h"
  6. #include "toolchain/lex/tokenized_buffer.h"
  7. #include "toolchain/parse/context.h"
  8. #include "toolchain/parse/handle.h"
  9. #include "toolchain/parse/node_ids.h"
  10. #include "toolchain/parse/node_kind.h"
  11. namespace Carbon::Parse {
  12. // Provides common error exiting logic that skips to the semi, if present.
  13. static auto OnParseError(Context& context, Context::State state,
  14. NodeKind declaration) -> void {
  15. context.AddNode(declaration, context.SkipPastLikelyEnd(state.token),
  16. /*has_error=*/true);
  17. }
  18. // Determines whether the specified modifier appears within the introducer of
  19. // the given declaration.
  20. // TODO: Restructure how we handle packaging declarations to avoid the need to
  21. // do this.
  22. static auto HasModifier(Context& context, Context::State state,
  23. Lex::TokenKind modifier) -> bool {
  24. for (Lex::TokenIterator it(state.token); it != context.position(); ++it) {
  25. if (context.tokens().GetKind(*it) == modifier) {
  26. return true;
  27. }
  28. }
  29. return false;
  30. }
  31. // Handles everything after the declaration's introducer.
  32. template <const Parse::NodeKind& DeclKind>
  33. static auto HandleDeclContent(Context& context, Context::State state,
  34. bool is_export, bool is_impl,
  35. llvm::function_ref<auto()->void> on_parse_error)
  36. -> void {
  37. Tree::PackagingNames names = {.is_export = is_export};
  38. // Parse the package name.
  39. if (DeclKind == NodeKind::LibraryDecl ||
  40. (DeclKind == NodeKind::ImportDecl &&
  41. context.PositionIs(Lex::TokenKind::Library))) {
  42. // This is either `library ...` or `import library ...`, so no package name
  43. // is expected.
  44. } else {
  45. // We require a package name. This is either an identifier or the `Core`
  46. // keyword.
  47. auto package_name_position = *context.position();
  48. if (auto ident = context.ConsumeIf(Lex::TokenKind::Identifier)) {
  49. names.package_id =
  50. PackageNameId::ForIdentifier(context.tokens().GetIdentifier(*ident));
  51. context.AddLeafNode(NodeKind::IdentifierPackageName, *ident);
  52. } else if (auto core = context.ConsumeIf(Lex::TokenKind::Core)) {
  53. names.package_id = PackageNameId::Core;
  54. context.AddLeafNode(NodeKind::CorePackageName, *core);
  55. } else {
  56. CARBON_DIAGNOSTIC(ExpectedIdentifierAfterPackage, Error,
  57. "expected identifier after `package`");
  58. CARBON_DIAGNOSTIC(ExpectedIdentifierAfterImport, Error,
  59. "expected identifier or `library` after `import`");
  60. context.emitter().Emit(package_name_position,
  61. DeclKind == NodeKind::PackageDecl
  62. ? ExpectedIdentifierAfterPackage
  63. : ExpectedIdentifierAfterImport);
  64. on_parse_error();
  65. return;
  66. }
  67. if (names.is_export) {
  68. names.is_export = false;
  69. state.has_error = true;
  70. CARBON_DIAGNOSTIC(ExportImportPackage, Error,
  71. "`export` cannot be used when importing a package");
  72. context.emitter().Emit(package_name_position, ExportImportPackage);
  73. }
  74. }
  75. // Parse the optional library keyword.
  76. bool accept_default = !names.package_id.has_value();
  77. if constexpr (DeclKind == NodeKind::LibraryDecl) {
  78. auto library_id = context.ParseLibraryName(accept_default);
  79. if (!library_id) {
  80. on_parse_error();
  81. return;
  82. }
  83. names.library_id = *library_id;
  84. } else {
  85. auto next_kind = context.PositionKind();
  86. if (next_kind == Lex::TokenKind::Library) {
  87. if (auto library_id = context.ParseLibrarySpecifier(accept_default)) {
  88. names.library_id = *library_id;
  89. } else {
  90. on_parse_error();
  91. return;
  92. }
  93. } else if (next_kind == Lex::TokenKind::StringLiteral ||
  94. (accept_default && next_kind == Lex::TokenKind::Default)) {
  95. // If we come across a string literal and we didn't parse `library
  96. // "..."` yet, then most probably the user forgot to add `library`
  97. // before the library name.
  98. CARBON_DIAGNOSTIC(MissingLibraryKeyword, Error,
  99. "missing `library` keyword");
  100. context.emitter().Emit(*context.position(), MissingLibraryKeyword);
  101. on_parse_error();
  102. return;
  103. }
  104. }
  105. if (auto semi = context.ConsumeIf(Lex::TokenKind::Semi)) {
  106. names.node_id = context.AddNode<DeclKind>(*semi, state.has_error);
  107. if constexpr (DeclKind == NodeKind::ImportDecl) {
  108. context.AddImport(names);
  109. } else {
  110. context.set_packaging_decl(names, is_impl);
  111. }
  112. } else {
  113. context.DiagnoseExpectedDeclSemi(context.tokens().GetKind(state.token));
  114. on_parse_error();
  115. }
  116. }
  117. // Returns true if currently in a valid state for imports, false otherwise. May
  118. // update the packaging state respectively.
  119. static auto VerifyInImports(Context& context, Lex::TokenIndex intro_token)
  120. -> bool {
  121. switch (context.packaging_state()) {
  122. case Context::PackagingState::FileStart:
  123. // `package` is no longer allowed, but `import` may repeat.
  124. context.set_packaging_state(Context::PackagingState::InImports);
  125. return true;
  126. case Context::PackagingState::InImports:
  127. return true;
  128. case Context::PackagingState::AfterNonPackagingDecl: {
  129. context.set_packaging_state(
  130. Context::PackagingState::InImportsAfterNonPackagingDecl);
  131. CARBON_DIAGNOSTIC(ImportTooLate, Error,
  132. "`import` declarations must come after the `package` "
  133. "declaration (if present) and before any other "
  134. "entities in the file");
  135. CARBON_DIAGNOSTIC(FirstDecl, Note, "first declaration is here");
  136. context.emitter()
  137. .Build(intro_token, ImportTooLate)
  138. .Note(context.first_non_packaging_token(), FirstDecl)
  139. .Emit();
  140. return false;
  141. }
  142. case Context::PackagingState::InImportsAfterNonPackagingDecl:
  143. // There is a sequential block of misplaced `import` statements, which can
  144. // occur if a declaration is added above `import`s. Avoid duplicate
  145. // warnings.
  146. return false;
  147. }
  148. }
  149. // Diagnoses if `export` is used in an `impl` file.
  150. static auto RestrictExportToApi(Context& context, Context::State& state)
  151. -> void {
  152. // Error for both Main//default and every implementation file.
  153. auto packaging = context.tree().packaging_decl();
  154. if (!packaging || packaging->is_impl) {
  155. CARBON_DIAGNOSTIC(ExportFromImpl, Error,
  156. "`export` is only allowed in API files");
  157. context.emitter().Emit(state.token, ExportFromImpl);
  158. state.has_error = true;
  159. }
  160. }
  161. auto HandleImport(Context& context) -> void {
  162. auto state = context.PopState();
  163. auto on_parse_error = [&] {
  164. OnParseError(context, state, NodeKind::ImportDecl);
  165. };
  166. if (VerifyInImports(context, state.token)) {
  167. // Scan the modifiers to see if this import declaration is exported.
  168. bool is_export = HasModifier(context, state, Lex::TokenKind::Export);
  169. if (is_export) {
  170. RestrictExportToApi(context, state);
  171. }
  172. HandleDeclContent<NodeKind::ImportDecl>(context, state, is_export,
  173. /*is_impl=*/false, on_parse_error);
  174. } else {
  175. on_parse_error();
  176. }
  177. }
  178. auto HandleExportName(Context& context) -> void {
  179. auto state = context.PopState();
  180. RestrictExportToApi(context, state);
  181. context.PushState(state, StateKind::ExportNameFinish);
  182. context.PushState(StateKind::DeclNameAndParams, state.token);
  183. }
  184. auto HandleExportNameFinish(Context& context) -> void {
  185. auto state = context.PopState();
  186. context.AddNodeExpectingDeclSemi(state, NodeKind::ExportDecl,
  187. Lex::TokenKind::Export,
  188. /*is_def_allowed=*/false);
  189. }
  190. // Handles common logic for `package` and `library`.
  191. template <const Parse::NodeKind& DeclKind>
  192. static auto HandlePackageAndLibraryDecls(Context& context,
  193. Lex::TokenKind intro_token_kind)
  194. -> void {
  195. auto state = context.PopState();
  196. bool is_impl = HasModifier(context, state, Lex::TokenKind::Impl);
  197. auto on_parse_error = [&] { OnParseError(context, state, DeclKind); };
  198. if (state.token != Lex::TokenIndex::FirstNonCommentToken) {
  199. CARBON_DIAGNOSTIC(
  200. PackageTooLate, Error,
  201. "the `{0}` declaration must be the first non-comment line",
  202. Lex::TokenKind);
  203. CARBON_DIAGNOSTIC(FirstNonCommentLine, Note,
  204. "first non-comment line is here");
  205. context.emitter()
  206. .Build(state.token, PackageTooLate, intro_token_kind)
  207. .Note(Lex::TokenIndex::FirstNonCommentToken, FirstNonCommentLine)
  208. .Emit();
  209. on_parse_error();
  210. return;
  211. }
  212. // `package`/`library` is no longer allowed, but `import` may repeat.
  213. context.set_packaging_state(Context::PackagingState::InImports);
  214. HandleDeclContent<DeclKind>(context, state, /*is_export=*/false, is_impl,
  215. on_parse_error);
  216. }
  217. auto HandlePackage(Context& context) -> void {
  218. HandlePackageAndLibraryDecls<NodeKind::PackageDecl>(context,
  219. Lex::TokenKind::Package);
  220. }
  221. auto HandleLibrary(Context& context) -> void {
  222. HandlePackageAndLibraryDecls<NodeKind::LibraryDecl>(context,
  223. Lex::TokenKind::Library);
  224. }
  225. } // namespace Carbon::Parse