handle_import_and_package.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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/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::StateStackEntry state,
  14. NodeKind declaration) -> void {
  15. return context.AddNode(declaration, context.SkipPastLikelyEnd(state.token),
  16. state.subtree_start, /*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::StateStackEntry state,
  23. Lex::TokenKind modifier) -> bool {
  24. for (auto it = Lex::TokenIterator(state.token); it != context.position();
  25. ++it) {
  26. if (context.tokens().GetKind(*it) == modifier) {
  27. return true;
  28. }
  29. }
  30. return false;
  31. }
  32. // Handles parsing of the library name. Returns the name's ID on success, which
  33. // may be invalid for `default`.
  34. static auto HandleLibraryName(Context& context, bool accept_default)
  35. -> std::optional<StringLiteralValueId> {
  36. if (auto library_name_token =
  37. context.ConsumeIf(Lex::TokenKind::StringLiteral)) {
  38. context.AddLeafNode(NodeKind::LibraryName, *library_name_token);
  39. return context.tokens().GetStringLiteralValue(*library_name_token);
  40. }
  41. if (accept_default) {
  42. if (auto default_token = context.ConsumeIf(Lex::TokenKind::Default)) {
  43. context.AddLeafNode(NodeKind::DefaultLibrary, *default_token);
  44. return StringLiteralValueId::Invalid;
  45. }
  46. }
  47. CARBON_DIAGNOSTIC(
  48. ExpectedLibraryNameOrDefault, Error,
  49. "Expected `default` or a string literal to specify the library name.");
  50. CARBON_DIAGNOSTIC(ExpectedLibraryName, Error,
  51. "Expected a string literal to specify the library name.");
  52. context.emitter().Emit(*context.position(), accept_default
  53. ? ExpectedLibraryNameOrDefault
  54. : ExpectedLibraryName);
  55. return std::nullopt;
  56. }
  57. // Handles everything after the declaration's introducer.
  58. static auto HandleDeclContent(Context& context, Context::StateStackEntry state,
  59. NodeKind declaration, bool is_export,
  60. bool is_impl,
  61. llvm::function_ref<void()> on_parse_error)
  62. -> void {
  63. Tree::PackagingNames names{
  64. .node_id = ImportDeclId(NodeId(state.subtree_start)),
  65. .is_export = is_export};
  66. if (declaration != NodeKind::LibraryDecl) {
  67. if (auto package_name_token =
  68. context.ConsumeIf(Lex::TokenKind::Identifier)) {
  69. if (names.is_export) {
  70. names.is_export = false;
  71. state.has_error = true;
  72. CARBON_DIAGNOSTIC(ExportImportPackage, Error,
  73. "`export` cannot be used when importing a package.");
  74. context.emitter().Emit(*package_name_token, ExportImportPackage);
  75. }
  76. names.package_id = context.tokens().GetIdentifier(*package_name_token);
  77. context.AddLeafNode(NodeKind::PackageName, *package_name_token);
  78. } else if (declaration == NodeKind::PackageDecl ||
  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. declaration == NodeKind::PackageDecl
  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 (declaration == NodeKind::LibraryDecl) {
  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. if (auto semi = context.ConsumeIf(Lex::TokenKind::Semi)) {
  128. if (declaration == NodeKind::ImportDecl) {
  129. context.AddImport(names);
  130. } else {
  131. context.set_packaging_decl(names, is_impl);
  132. }
  133. context.AddNode(declaration, *semi, state.subtree_start, state.has_error);
  134. } else {
  135. context.DiagnoseExpectedDeclSemi(context.tokens().GetKind(state.token));
  136. on_parse_error();
  137. }
  138. }
  139. // Returns true if currently in a valid state for imports, false otherwise. May
  140. // update the packaging state respectively.
  141. static auto VerifyInImports(Context& context, Lex::TokenIndex intro_token)
  142. -> bool {
  143. switch (context.packaging_state()) {
  144. case Context::PackagingState::FileStart:
  145. // `package` is no longer allowed, but `import` may repeat.
  146. context.set_packaging_state(Context::PackagingState::InImports);
  147. return true;
  148. case Context::PackagingState::InImports:
  149. return true;
  150. case Context::PackagingState::AfterNonPackagingDecl: {
  151. context.set_packaging_state(
  152. Context::PackagingState::InImportsAfterNonPackagingDecl);
  153. CARBON_DIAGNOSTIC(ImportTooLate, Error,
  154. "`import` declarations must come after the `package` "
  155. "declaration (if present) and before any other "
  156. "entities in the file.");
  157. CARBON_DIAGNOSTIC(FirstDecl, Note, "First declaration is here.");
  158. context.emitter()
  159. .Build(intro_token, ImportTooLate)
  160. .Note(context.first_non_packaging_token(), FirstDecl)
  161. .Emit();
  162. return false;
  163. }
  164. case Context::PackagingState::InImportsAfterNonPackagingDecl:
  165. // There is a sequential block of misplaced `import` statements, which can
  166. // occur if a declaration is added above `import`s. Avoid duplicate
  167. // warnings.
  168. return false;
  169. }
  170. }
  171. // Diagnoses if `export` is used in an `impl` file.
  172. static auto RestrictExportToApi(Context& context,
  173. Context::StateStackEntry& state) -> void {
  174. // Error for both Main//default and every implementation file.
  175. auto packaging = context.tree().packaging_decl();
  176. if (!packaging || packaging->is_impl) {
  177. CARBON_DIAGNOSTIC(ExportFromImpl, Error,
  178. "`export` is only allowed in API files.");
  179. context.emitter().Emit(state.token, ExportFromImpl);
  180. state.has_error = true;
  181. }
  182. }
  183. auto HandleImport(Context& context) -> void {
  184. auto state = context.PopState();
  185. auto declaration = NodeKind::ImportDecl;
  186. auto on_parse_error = [&] { OnParseError(context, state, declaration); };
  187. if (VerifyInImports(context, state.token)) {
  188. // Scan the modifiers to see if this import declaration is exported.
  189. bool is_export = HasModifier(context, state, Lex::TokenKind::Export);
  190. if (is_export) {
  191. RestrictExportToApi(context, state);
  192. }
  193. HandleDeclContent(context, state, declaration, is_export,
  194. /*is_impl=*/false, on_parse_error);
  195. } else {
  196. on_parse_error();
  197. }
  198. }
  199. auto HandleExportName(Context& context) -> void {
  200. auto state = context.PopState();
  201. RestrictExportToApi(context, state);
  202. context.PushState(state, State::ExportNameFinish);
  203. context.PushState(State::DeclNameAndParams, state.token);
  204. }
  205. auto HandleExportNameFinish(Context& context) -> void {
  206. auto state = context.PopState();
  207. context.AddNodeExpectingDeclSemi(state, NodeKind::ExportDecl,
  208. Lex::TokenKind::Export,
  209. /*is_def_allowed=*/false);
  210. }
  211. // Handles common logic for `package` and `library`.
  212. static auto HandlePackageAndLibraryDecls(Context& context,
  213. Lex::TokenKind intro_token_kind,
  214. NodeKind declaration) -> void {
  215. auto state = context.PopState();
  216. bool is_impl = HasModifier(context, state, Lex::TokenKind::Impl);
  217. auto on_parse_error = [&] { OnParseError(context, state, declaration); };
  218. if (state.token != Lex::TokenIndex::FirstNonCommentToken) {
  219. CARBON_DIAGNOSTIC(
  220. PackageTooLate, Error,
  221. "The `{0}` declaration must be the first non-comment line.",
  222. Lex::TokenKind);
  223. CARBON_DIAGNOSTIC(FirstNonCommentLine, Note,
  224. "First non-comment line is here.");
  225. context.emitter()
  226. .Build(state.token, PackageTooLate, intro_token_kind)
  227. .Note(Lex::TokenIndex::FirstNonCommentToken, FirstNonCommentLine)
  228. .Emit();
  229. on_parse_error();
  230. return;
  231. }
  232. // `package`/`library` is no longer allowed, but `import` may repeat.
  233. context.set_packaging_state(Context::PackagingState::InImports);
  234. HandleDeclContent(context, state, declaration, /*is_export=*/false, is_impl,
  235. on_parse_error);
  236. }
  237. auto HandlePackage(Context& context) -> void {
  238. HandlePackageAndLibraryDecls(context, Lex::TokenKind::Package,
  239. NodeKind::PackageDecl);
  240. }
  241. auto HandleLibrary(Context& context) -> void {
  242. HandlePackageAndLibraryDecls(context, Lex::TokenKind::Library,
  243. NodeKind::LibraryDecl);
  244. }
  245. } // namespace Carbon::Parse