Caffe2 - C++ API
A deep learning, cross platform ML framework
source_range.h
1 #pragma once
2 #include <c10/util/Exception.h>
3 #include <torch/csrc/jit/source_location.h>
4 
5 #include <algorithm>
6 #include <memory>
7 
8 namespace torch {
9 namespace jit {
10 
11 // a range of a shared string 'file_' with functions to help debug by highlight
12 // that
13 // range.
14 struct SourceRange : public SourceLocation {
15  SourceRange(std::shared_ptr<std::string> file_, size_t start_, size_t end_)
16  : file_(std::move(file_)), start_(start_), end_(end_) {}
17  const std::string text() const {
18  return file().substr(start(), end() - start());
19  }
20  size_t size() const {
21  return end() - start();
22  }
23 
24  static const size_t CONTEXT = 10;
25  void highlight(std::ostream& out) const override {
26  const std::string& str = file();
27  size_t begin_line = start(); // beginning of line to highlight
28  size_t end_line = start(); // end of line to highlight
29  while (begin_line > 0 && str[begin_line - 1] != '\n')
30  --begin_line;
31  while (end_line < str.size() && str[end_line] != '\n')
32  ++end_line;
33  AT_ASSERT(begin_line == 0 || str[begin_line - 1] == '\n');
34  AT_ASSERT(end_line == str.size() || str[end_line] == '\n');
35 
36  size_t begin_highlight = begin_line; // beginning of context, CONTEXT lines
37  // before the highlight line
38  for (size_t i = 0; begin_highlight > 0; --begin_highlight) {
39  if (str[begin_highlight - 1] == '\n')
40  ++i;
41  if (i >= CONTEXT)
42  break;
43  }
44  AT_ASSERT(begin_highlight == 0 || str[begin_highlight - 1] == '\n');
45 
46  size_t end_highlight =
47  end_line; // end of context, CONTEXT lines after the highlight line
48  for (size_t i = 0; end_highlight < str.size(); ++end_highlight) {
49  if (str[end_highlight] == '\n')
50  ++i;
51  if (i >= CONTEXT)
52  break;
53  }
54  AT_ASSERT(end_highlight == str.size() || str[end_highlight] == '\n');
55 
56  out << str.substr(begin_highlight, end_line - begin_highlight) << "\n";
57  out << std::string(start() - begin_line, ' ');
58  size_t len = std::min(size(), end_line - start());
59  out << std::string(len, '~')
60  << (len < size() ? "... <--- HERE" : " <--- HERE");
61  out << str.substr(end_line, end_highlight - end_line);
62  if (!str.empty() && str.back() != '\n')
63  out << "\n";
64  }
65  const std::string& file() const {
66  return *file_;
67  }
68  const std::shared_ptr<std::string>& file_ptr() const {
69  return file_;
70  }
71  size_t start() const {
72  return start_;
73  }
74  size_t end() const {
75  return end_;
76  }
77 
78  private:
79  std::shared_ptr<std::string> file_;
80  size_t start_;
81  size_t end_;
82 };
83 
84 } // namespace jit
85 } // namespace torch
Represents a location in source code (for debugging).
Definition: StringUtil.h:69
Definition: jit_type.h:17