handle_namespace.cpp 2.4 KB

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