Skip to content

Commit e05942c

Browse files
James Reedfacebook-github-bot
authored andcommitted
Serialization methods for SourceRange and Source (#22178)
Summary: Pull Request resolved: #22178 ghimport-source-id: 85ca4d4 Test Plan: Imported from OSS Differential Revision: D15981426 Pulled By: jamesr66a fbshipit-source-id: f81f5ee3b66fc4a0d4a708b8109712b5df9f241a
1 parent 671782d commit e05942c

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
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

Comments
 (0)