diagnostic.cpp 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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/diagnostics/diagnostic.h"
  5. #include <algorithm>
  6. #include <cstdint>
  7. namespace Carbon {
  8. auto DiagnosticLoc::FormatLocation(llvm::raw_ostream& out) const -> void {
  9. if (filename.empty()) {
  10. return;
  11. }
  12. out << filename;
  13. if (line_number > 0) {
  14. out << ":" << line_number;
  15. if (column_number > 0) {
  16. out << ":" << column_number;
  17. }
  18. }
  19. out << ": ";
  20. }
  21. auto DiagnosticLoc::FormatSnippet(llvm::raw_ostream& out, int indent) const
  22. -> void {
  23. if (column_number == -1) {
  24. return;
  25. }
  26. // column_number is 1-based.
  27. int32_t column = column_number - 1;
  28. out.indent(indent);
  29. out << line << "\n";
  30. out.indent(indent + column);
  31. out << "^";
  32. // We want to ensure that we don't underline past the end of the line in
  33. // case of a multiline token.
  34. // TODO: Revisit this once we can reference multiple ranges on multiple
  35. // lines in a single diagnostic message.
  36. int underline_length =
  37. std::min(length, static_cast<int32_t>(line.size()) - column);
  38. for (int i = 1; i < underline_length; ++i) {
  39. out << '~';
  40. }
  41. out << '\n';
  42. }
  43. } // namespace Carbon