unused.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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/unused.h"
  5. #include "toolchain/base/kind_switch.h"
  6. #include "toolchain/check/context.h"
  7. #include "toolchain/check/diagnostic_helpers.h"
  8. namespace Carbon::Check {
  9. auto CheckUnusedBinding(Context& context, SemIR::NameId name_id,
  10. const LexicalLookup::Result& result) -> void {
  11. // Don't warn about the special name `_`. Other special names, such as `self`,
  12. // are warned if unused. `.Self` is also excluded as it is often implicit.
  13. if (name_id == SemIR::NameId::Underscore ||
  14. name_id == SemIR::NameId::PeriodSelf) {
  15. return;
  16. }
  17. // Don't warn about names that aren't in the current file.
  18. auto decl_loc = context.insts().GetCanonicalLocId(result.inst_id);
  19. if (decl_loc.kind() == SemIR::LocId::Kind::ImportIRInstId) {
  20. return;
  21. }
  22. auto binding = context.insts().TryGetAs<SemIR::AnyBinding>(result.inst_id);
  23. if (!binding) {
  24. return;
  25. }
  26. const auto& entity_name = context.entity_names().Get(binding->entity_name_id);
  27. if (entity_name.is_unused) {
  28. if (result.use_loc_id.has_value()) {
  29. CARBON_DIAGNOSTIC_ON_SCOPE(UnusedButUsed, Error,
  30. "variable `{0}` marked `unused` but used",
  31. SemIR::NameId);
  32. CARBON_DIAGNOSTIC(UnusedButUsedHere, Note, "usage here");
  33. context.emitter()
  34. .Build(decl_loc, UnusedButUsed, name_id)
  35. .Note(result.use_loc_id, UnusedButUsedHere)
  36. .Emit();
  37. }
  38. } else {
  39. if (!result.use_loc_id.has_value() && result.is_decl_reachable) {
  40. CARBON_DIAGNOSTIC_ON_SCOPE(UnusedBinding, Warning, "binding `{0}` unused",
  41. SemIR::NameId);
  42. context.emitter().Emit(decl_loc, UnusedBinding, name_id);
  43. }
  44. }
  45. }
  46. } // namespace Carbon::Check