handle_namespace.cpp 2.4 KB

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