diagnostic.cpp 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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 (!snippet.empty()) {
  23. llvm::StringRef snippet_ref = snippet;
  24. do {
  25. auto [snippet_line, rest] = snippet_ref.split('\n');
  26. out.indent(indent);
  27. out << snippet_line << "\n";
  28. snippet_ref = rest;
  29. } while (!snippet_ref.empty());
  30. return;
  31. }
  32. if (column_number == -1) {
  33. return;
  34. }
  35. // column_number is 1-based.
  36. int32_t column = column_number - 1;
  37. out.indent(indent);
  38. out << line << "\n";
  39. out.indent(indent + column);
  40. out << "^";
  41. // We want to ensure that we don't underline past the end of the line in
  42. // case of a multiline token.
  43. // TODO: Revisit this once we can reference multiple ranges on multiple
  44. // lines in a single diagnostic message.
  45. int underline_length =
  46. std::min(length, static_cast<int32_t>(line.size()) - column);
  47. for (int i = 1; i < underline_length; ++i) {
  48. out << '~';
  49. }
  50. out << '\n';
  51. }
  52. } // namespace Carbon::Diagnostics