diagnostic.cpp 1.2 KB

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