handle_namespace.cpp 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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, Parse::NamespaceStartId /*node_id*/)
  10. -> 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 node_id) -> 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({node_id, 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, namespace_inst);
  28. auto existing_inst_id =
  29. context.decl_name_stack().LookupOrAddName(name_context, namespace_id);
  30. if (existing_inst_id.is_valid()) {
  31. // If there's a name conflict with a namespace, "merge" by using the
  32. // previous declaration. Otherwise, diagnose the issue.
  33. if (auto existing =
  34. context.insts().TryGetAs<SemIR::Namespace>(existing_inst_id)) {
  35. // When the name conflict is an imported namespace, fill the location ID
  36. // so that future diagnostics point at this declaration.
  37. if (existing->import_id.is_valid() &&
  38. !context.insts().GetLocId(existing_inst_id).is_valid()) {
  39. context.SetNamespaceNodeId(existing_inst_id, node_id);
  40. }
  41. } else {
  42. context.DiagnoseDuplicateName(namespace_id, existing_inst_id);
  43. }
  44. }
  45. context.decl_name_stack().PopScope();
  46. context.decl_state_stack().Pop(DeclState::Namespace);
  47. return true;
  48. }
  49. } // namespace Carbon::Check