xref: /aosp_15_r20/external/pytorch/torch/csrc/jit/frontend/error_report.h (revision da0073e96a02ea20f0ac840b70461e3646d07c45)
1 #pragma once
2 
3 #include <torch/csrc/jit/frontend/tree.h>
4 
5 namespace torch::jit {
6 
7 struct Call {
8   std::string fn_name;
9   SourceRange caller_range;
10 };
11 
12 struct TORCH_API ErrorReport : public std::exception {
13   ErrorReport(const ErrorReport& e);
14 
15   explicit ErrorReport(const SourceRange& r);
ErrorReportErrorReport16   explicit ErrorReport(const TreeRef& tree) : ErrorReport(tree->range()) {}
ErrorReportErrorReport17   explicit ErrorReport(const Token& tok) : ErrorReport(tok.range) {}
18 
19   const char* what() const noexcept override;
20 
21   struct TORCH_API CallStack {
22     // These functions are used to report why a function was being compiled
23     // (i.e. what was the call stack of user functions at compilation time that
24     // led to this error)
25     CallStack(const std::string& name, const SourceRange& range);
26     ~CallStack();
27 
28     // Change the range that is relevant for the current function (i.e. after
29     // each successful expression compilation, change it to the next expression)
30     static void update_pending_range(const SourceRange& range);
31   };
32 
33   static std::string current_call_stack();
34 
35  private:
36   template <typename T>
37   friend const ErrorReport& operator<<(const ErrorReport& e, const T& t);
38 
39   mutable std::stringstream ss;
40   OwnedSourceRange context;
41   mutable std::string the_message;
42   std::vector<Call> error_stack;
43 };
44 
45 template <typename T>
46 const ErrorReport& operator<<(const ErrorReport& e, const T& t) {
47   e.ss << t;
48   return e;
49 }
50 
51 } // namespace torch::jit
52