diagnostic.cpp 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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::Diagnostics {
  8. auto Loc::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 Loc::FormatSnippet(llvm::raw_ostream& out, int indent) const -> void {
  22. if (column_number == -1) {
  23. return;
  24. }
  25. // column_number is 1-based.
  26. int32_t column = column_number - 1;
  27. out.indent(indent);
  28. out << line << "\n";
  29. out.indent(indent + column);
  30. out << "^";
  31. // We want to ensure that we don't underline past the end of the line in
  32. // case of a multiline token.
  33. // TODO: Revisit this once we can reference multiple ranges on multiple
  34. // lines in a single diagnostic message.
  35. int underline_length =
  36. std::min(length, static_cast<int32_t>(line.size()) - column);
  37. for (int i = 1; i < underline_length; ++i) {
  38. out << '~';
  39. }
  40. out << '\n';
  41. }
  42. } // namespace Carbon::Diagnostics