Caffe2 - C++ API
A deep learning, cross platform ML framework
parse_string_literal.h
1 #pragma once
2 #include <c10/util/Optional.h>
3 #include <torch/csrc/jit/script/error_report.h>
4 #include <torch/csrc/jit/script/lexer.h>
5 
6 namespace torch {
7 namespace jit {
8 namespace script {
9 
10 inline bool isCharCount(char c, const std::string& str, size_t start, int len) {
11  // count checks from [start, start + len)
12  return start + len <= str.size() &&
13  std::count(str.begin() + start, str.begin() + start + len, c) == len;
14 }
15 
16 inline static bool isOctal(char c) {
17  return c >= '0' && c < '8';
18 }
19 
20 inline c10::optional<char> parseOctal(const std::string& str, size_t pos) {
21  //\xxx where x are 0-7
22  if (pos + 3 >= str.size())
23  return c10::nullopt;
24  size_t c = 0;
25  for (size_t i = 1, b = 64; i < 4; ++i, b /= 8) {
26  int d = str[pos + i];
27  if (d < '0' || d > '7')
28  return c10::nullopt;
29  c += b * (d - '0');
30  }
31  if (c >= 256)
32  return c10::nullopt;
33  return c;
34 }
35 
36 inline std::string parseStringLiteral(
37  const SourceRange& range,
38  const std::string& str) {
39  int quote_len = isCharCount(str[0], str, 0, 3) ? 3 : 1;
40  auto ret_str = str.substr(quote_len, str.size() - quote_len * 2);
41  size_t pos = ret_str.find('\\');
42  while (pos != std::string::npos) {
43  // invariant: pos has to escape a character because it is a valid string
44  char c = ret_str[pos + 1];
45  size_t to_erase = 2;
46  switch (ret_str[pos + 1]) {
47  case '\\':
48  case '\'':
49  case '\"':
50  case '\n':
51  break;
52  case 'a':
53  c = '\a';
54  break;
55  case 'b':
56  c = '\b';
57  break;
58  case 'f':
59  c = '\f';
60  break;
61  case 'n':
62  c = '\n';
63  break;
64  case 'v':
65  c = '\v';
66  break;
67  case 't':
68  c = '\t';
69  break;
70  case 'h':
71  throw ErrorReport(range) << "unsupported hex specifier";
72  default:
73  // \0NN
74  if (auto v = parseOctal(str, pos + 1)) {
75  to_erase = 4;
76  c = *v;
77  } else {
78  throw ErrorReport(range) << " ill formed octal specifier";
79  }
80  }
81  ret_str.replace(pos, to_erase, /* num copies */ 1, c);
82  pos = ret_str.find('\\', pos + 1);
83  }
84  return ret_str;
85 }
86 
87 } // namespace script
88 } // namespace jit
89 } // namespace torch
Definition: jit_type.h:17