dump.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. // This library contains functions to assist dumping objects to stderr during
  5. // interactive debugging. Functions named `Dump` are intended for direct use by
  6. // developers, and should use overload resolution to determine which will be
  7. // invoked. The debugger should do namespace resolution automatically. For
  8. // example:
  9. //
  10. // - lldb: `expr Dump(context, id)`
  11. // - gdb: `call Dump(context, id)`
  12. //
  13. // The `DumpNoNewline` functions are helpers that exclude a trailing newline.
  14. // They're intended to be composed by `Dump` function implementations.
  15. #ifndef NDEBUG
  16. #include "toolchain/lex/dump.h"
  17. #include "common/check.h"
  18. #include "common/ostream.h"
  19. #include "toolchain/check/context.h"
  20. #include "toolchain/lex/tokenized_buffer.h"
  21. #include "toolchain/parse/dump.h"
  22. #include "toolchain/parse/tree.h"
  23. #include "toolchain/sem_ir/file.h"
  24. namespace Carbon::Check {
  25. static auto DumpNoNewline(const Context& context, SemIR::LocId loc_id) -> void {
  26. if (!loc_id.is_valid()) {
  27. llvm::errs() << "LocId(invalid)";
  28. return;
  29. }
  30. if (loc_id.is_node_id()) {
  31. auto token = context.parse_tree().node_token(loc_id.node_id());
  32. auto line = context.tokens().GetLineNumber(token);
  33. auto col = context.tokens().GetColumnNumber(token);
  34. const char* implicit = loc_id.is_implicit() ? " implicit" : "";
  35. llvm::errs() << "LocId(";
  36. llvm::errs().write_escaped(context.sem_ir().filename());
  37. llvm::errs() << ":" << line << ":" << col << implicit << ")";
  38. } else {
  39. CARBON_CHECK(loc_id.is_import_ir_inst_id());
  40. auto import_ir_id = context.sem_ir()
  41. .import_ir_insts()
  42. .Get(loc_id.import_ir_inst_id())
  43. .ir_id;
  44. const auto* import_file =
  45. context.sem_ir().import_irs().Get(import_ir_id).sem_ir;
  46. llvm::errs() << "LocId(import from \"";
  47. llvm::errs().write_escaped(import_file->filename());
  48. llvm::errs() << "\")";
  49. }
  50. }
  51. LLVM_DUMP_METHOD auto Dump(const Context& context, Lex::TokenIndex token)
  52. -> void {
  53. Parse::Dump(context.parse_tree(), token);
  54. }
  55. LLVM_DUMP_METHOD auto Dump(const Context& context, Parse::NodeId node_id)
  56. -> void {
  57. Parse::Dump(context.parse_tree(), node_id);
  58. }
  59. LLVM_DUMP_METHOD auto Dump(const Context& context, SemIR::LocId loc_id)
  60. -> void {
  61. DumpNoNewline(context, loc_id);
  62. llvm::errs() << '\n';
  63. }
  64. } // namespace Carbon::Check
  65. #endif // NDEBUG