handle_namespace.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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/check/context.h"
  5. #include "toolchain/check/decl_state.h"
  6. #include "toolchain/check/modifiers.h"
  7. #include "toolchain/sem_ir/ids.h"
  8. namespace Carbon::Check {
  9. auto HandleNamespaceStart(Context& context,
  10. Parse::NamespaceStartId /*parse_node*/) -> bool {
  11. // Optional modifiers and the name follow.
  12. context.decl_state_stack().Push(DeclState::Namespace);
  13. context.decl_name_stack().PushScopeAndStartName();
  14. return true;
  15. }
  16. auto HandleNamespace(Context& context, Parse::NamespaceId parse_node) -> bool {
  17. auto name_context = context.decl_name_stack().FinishName();
  18. LimitModifiersOnDecl(context, KeywordModifierSet::None,
  19. Lex::TokenKind::Namespace);
  20. auto namespace_inst = SemIR::Namespace{
  21. context.GetBuiltinType(SemIR::BuiltinKind::NamespaceType),
  22. SemIR::NameScopeId::Invalid, SemIR::InstId::Invalid};
  23. auto namespace_id = context.AddPlaceholderInst({parse_node, namespace_inst});
  24. namespace_inst.name_scope_id = context.name_scopes().Add(
  25. namespace_id, name_context.name_id_for_new_inst(),
  26. name_context.enclosing_scope_id_for_new_inst());
  27. context.ReplaceInstBeforeConstantUse(namespace_id,
  28. {parse_node, namespace_inst});
  29. auto existing_inst_id =
  30. context.decl_name_stack().LookupOrAddName(name_context, namespace_id);
  31. if (existing_inst_id.is_valid()) {
  32. // If there's a name conflict with a namespace, "merge" by using the
  33. // previous declaration. Otherwise, diagnose the issue.
  34. if (auto existing =
  35. context.insts().TryGetAs<SemIR::Namespace>(existing_inst_id)) {
  36. // When the name conflict is an imported namespace, fill the parse node
  37. // so that future diagnostics point at this declaration.
  38. if (existing->import_id.is_valid() &&
  39. !context.insts().GetParseNode(existing_inst_id).is_valid()) {
  40. context.SetNamespaceParseNode(existing_inst_id, parse_node);
  41. }
  42. } else {
  43. context.DiagnoseDuplicateName(namespace_id, existing_inst_id);
  44. }
  45. }
  46. context.decl_name_stack().PopScope();
  47. context.decl_state_stack().Pop(DeclState::Namespace);
  48. return true;
  49. }
  50. } // namespace Carbon::Check