1+ #pragma once
2+
3+ #include < ATen/core/ivalue.h>
4+ #include < torch/csrc/jit/source_range.h>
5+
6+ namespace torch {
7+ namespace jit {
8+
9+ class SourceRangeSerializer {
10+ public:
11+ // Serialize SourceRange as Tuple[SourceType, int, int]
12+ // where SourceType = Tuple[str, Optional[str], int, List[int]],
13+ // the serialized form of Source
14+ c10::IValue serialize (const SourceRange& sr) {
15+ std::vector<c10::IValue> elements = {
16+ serialize_source (sr.source ()), (int64_t )sr.start (), (int64_t )sr.end ()};
17+ return c10::ivalue::Tuple::create (std::move (elements));
18+ }
19+
20+ private:
21+ // Serialize Source as Tuple[str, Optional[str], int, List[int]]
22+ // This caches serialized sources, since many SourceRanges can
23+ // refer to the same one.
24+ c10::IValue serialize_source (const std::shared_ptr<Source>& s) {
25+ if (serialized_sources.count (s)) {
26+ return serialized_sources.at (s);
27+ }
28+ std::vector<c10::IValue> elements{
29+ s->text (), s->filename (), (int64_t )s->starting_line_no ()};
30+ auto serialized = c10::ivalue::Tuple::create (std::move (elements));
31+ serialized_sources[s] = serialized;
32+ return serialized;
33+ }
34+
35+ std::unordered_map<std::shared_ptr<Source>, c10::IValue> serialized_sources;
36+ };
37+
38+ } // namespace jit
39+ } // namespace torch
0 commit comments