handle_import_and_package.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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. // TODO: Model `Cpp` as a keyword too.
  54. names.package_id = PackageNameId::Core;
  55. context.AddLeafNode(NodeKind::CorePackageName, *core);
  56. } else {
  57. CARBON_DIAGNOSTIC(ExpectedIdentifierAfterPackage, Error,
  58. "expected identifier after `package`");
  59. CARBON_DIAGNOSTIC(ExpectedIdentifierAfterImport, Error,
  60. "expected identifier or `library` after `import`");
  61. context.emitter().Emit(package_name_position,
  62. DeclKind == NodeKind::PackageDecl
  63. ? ExpectedIdentifierAfterPackage
  64. : ExpectedIdentifierAfterImport);
  65. on_parse_error();
  66. return;
  67. }
  68. if (names.is_export) {
  69. names.is_export = false;
  70. state.has_error = true;
  71. CARBON_DIAGNOSTIC(ExportImportPackage, Error,
  72. "`export` cannot be used when importing a package");
  73. context.emitter().Emit(package_name_position, ExportImportPackage);
  74. }
  75. }
  76. // Parse the optional library keyword.
  77. bool accept_default = !names.package_id.has_value();
  78. if constexpr (DeclKind == NodeKind::LibraryDecl) {
  79. auto library_id = context.ParseLibraryName(accept_default);
  80. if (!library_id) {
  81. on_parse_error();
  82. return;
  83. }
  84. names.library_id = *library_id;
  85. } else {
  86. auto next_kind = context.PositionKind();
  87. if (next_kind == Lex::TokenKind::Library) {
  88. if (auto library_id = context.ParseLibrarySpecifier(accept_default)) {
  89. names.library_id = *library_id;
  90. } else {
  91. on_parse_error();
  92. return;
  93. }
  94. } else if (DeclKind == NodeKind::ImportDecl &&
  95. next_kind == Lex::TokenKind::Inline) {
  96. auto inline_token = context.ConsumeChecked(Lex::TokenKind::Inline);
  97. auto body_position = *context.position();
  98. auto inline_body_token = context.ConsumeIf(Lex::TokenKind::StringLiteral);
  99. names.inline_body_id = context.AddNode<NodeKind::InlineImportBody>(
  100. body_position, /*has_error=*/!inline_body_token);
  101. context.AddNode(NodeKind::InlineImportSpecifier, inline_token,
  102. /*has_error=*/false);
  103. if (!inline_body_token) {
  104. CARBON_DIAGNOSTIC(ExpectedStringAfterInline, Error,
  105. "expected string literal after `inline`");
  106. context.emitter().Emit(body_position, ExpectedStringAfterInline);
  107. on_parse_error();
  108. return;
  109. }
  110. } else if (next_kind == Lex::TokenKind::StringLiteral ||
  111. (accept_default && next_kind == Lex::TokenKind::Default)) {
  112. // If we come across a string literal and we didn't parse `library
  113. // "..."` yet, then most probably the user forgot to add `library`
  114. // before the library name.
  115. CARBON_DIAGNOSTIC(MissingLibraryKeyword, Error,
  116. "missing `library` keyword");
  117. context.emitter().Emit(*context.position(), MissingLibraryKeyword);
  118. on_parse_error();
  119. return;
  120. }
  121. }
  122. if (auto semi = context.ConsumeIf(Lex::TokenKind::Semi)) {
  123. names.node_id = context.AddNode<DeclKind>(*semi, state.has_error);
  124. if constexpr (DeclKind == NodeKind::ImportDecl) {
  125. context.AddImport(names);
  126. } else {
  127. context.set_packaging_decl(names, is_impl);
  128. }
  129. } else {
  130. context.DiagnoseExpectedDeclSemi(context.tokens().GetKind(state.token));
  131. on_parse_error();
  132. }
  133. }
  134. // Returns true if currently in a valid state for imports, false otherwise. May
  135. // update the packaging state respectively.
  136. static auto VerifyInImports(Context& context, Lex::TokenIndex intro_token)
  137. -> bool {
  138. switch (context.packaging_state()) {
  139. case Context::PackagingState::FileStart:
  140. // `package` is no longer allowed, but `import` may repeat.
  141. context.set_packaging_state(Context::PackagingState::InImports);
  142. return true;
  143. case Context::PackagingState::InImports:
  144. return true;
  145. case Context::PackagingState::AfterNonPackagingDecl: {
  146. context.set_packaging_state(
  147. Context::PackagingState::InImportsAfterNonPackagingDecl);
  148. CARBON_DIAGNOSTIC(ImportTooLate, Error,
  149. "`import` declarations must come after the `package` "
  150. "declaration (if present) and before any other "
  151. "entities in the file");
  152. CARBON_DIAGNOSTIC(FirstDecl, Note, "first declaration is here");
  153. context.emitter()
  154. .Build(intro_token, ImportTooLate)
  155. .Note(context.first_non_packaging_token(), FirstDecl)
  156. .Emit();
  157. return false;
  158. }
  159. case Context::PackagingState::InImportsAfterNonPackagingDecl:
  160. // There is a sequential block of misplaced `import` statements, which can
  161. // occur if a declaration is added above `import`s. Avoid duplicate
  162. // warnings.
  163. return false;
  164. }
  165. }
  166. // Diagnoses if `export` is used in an `impl` file.
  167. static auto RestrictExportToApi(Context& context, Context::State& state)
  168. -> void {
  169. // Error for both Main//default and every implementation file.
  170. auto packaging = context.tree().packaging_decl();
  171. if (!packaging || packaging->is_impl) {
  172. CARBON_DIAGNOSTIC(ExportFromImpl, Error,
  173. "`export` is only allowed in API files");
  174. context.emitter().Emit(state.token, ExportFromImpl);
  175. state.has_error = true;
  176. }
  177. }
  178. auto HandleImport(Context& context) -> void {
  179. auto state = context.PopState();
  180. auto on_parse_error = [&] {
  181. OnParseError(context, state, NodeKind::ImportDecl);
  182. };
  183. if (VerifyInImports(context, state.token)) {
  184. // Scan the modifiers to see if this import declaration is exported.
  185. bool is_export = HasModifier(context, state, Lex::TokenKind::Export);
  186. if (is_export) {
  187. RestrictExportToApi(context, state);
  188. }
  189. HandleDeclContent<NodeKind::ImportDecl>(context, state, is_export,
  190. /*is_impl=*/false, on_parse_error);
  191. } else {
  192. on_parse_error();
  193. }
  194. }
  195. auto HandleExportName(Context& context) -> void {
  196. auto state = context.PopState();
  197. RestrictExportToApi(context, state);
  198. context.PushState(state, StateKind::ExportNameFinish);
  199. context.PushState(StateKind::DeclNameAndParams, state.token);
  200. }
  201. auto HandleExportNameFinish(Context& context) -> void {
  202. auto state = context.PopState();
  203. context.AddNodeExpectingDeclSemi(state, NodeKind::ExportDecl,
  204. Lex::TokenKind::Export,
  205. /*is_def_allowed=*/false);
  206. }
  207. // Handles common logic for `package` and `library`.
  208. template <const Parse::NodeKind& DeclKind>
  209. static auto HandlePackageAndLibraryDecls(Context& context,
  210. Lex::TokenKind intro_token_kind)
  211. -> void {
  212. auto state = context.PopState();
  213. bool is_impl = HasModifier(context, state, Lex::TokenKind::Impl);
  214. auto on_parse_error = [&] { OnParseError(context, state, DeclKind); };
  215. if (state.token != Lex::TokenIndex::FirstNonCommentToken) {
  216. CARBON_DIAGNOSTIC(
  217. PackageTooLate, Error,
  218. "the `{0}` declaration must be the first non-comment line",
  219. Lex::TokenKind);
  220. CARBON_DIAGNOSTIC(FirstNonCommentLine, Note,
  221. "first non-comment line is here");
  222. context.emitter()
  223. .Build(state.token, PackageTooLate, intro_token_kind)
  224. .Note(Lex::TokenIndex::FirstNonCommentToken, FirstNonCommentLine)
  225. .Emit();
  226. on_parse_error();
  227. return;
  228. }
  229. // `package`/`library` is no longer allowed, but `import` may repeat.
  230. context.set_packaging_state(Context::PackagingState::InImports);
  231. HandleDeclContent<DeclKind>(context, state, /*is_export=*/false, is_impl,
  232. on_parse_error);
  233. }
  234. auto HandlePackage(Context& context) -> void {
  235. HandlePackageAndLibraryDecls<NodeKind::PackageDecl>(context,
  236. Lex::TokenKind::Package);
  237. }
  238. auto HandleLibrary(Context& context) -> void {
  239. HandlePackageAndLibraryDecls<NodeKind::LibraryDecl>(context,
  240. Lex::TokenKind::Library);
  241. }
  242. } // namespace Carbon::Parse