Debian Codegraph @

src/blib2to3/pgen2/literals.py

raw
1 # Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved.
2 # Licensed to PSF under a Contributor Agreement.
3
4 """Safely evaluate Python string literals without using eval()."""
5
6 import re
7
8 simple_escapes: dict[str, str] = {
9 "a": "\a",
10 "b": "\b",
11 "f": "\f",
12 "n": "\n",
13 "r": "\r",
14 "t": "\t",
15 "v": "\v",
16 "'": "'",
17 '"': '"',
18 "\\": "\\",
19 }
20
21
22 def escape(m: re.Match[str]) -> str:
23 all, tail = m.group(0, 1)
24 assert all.startswith("\\")
25 esc = simple_escapes.get(tail)
26 if esc is not None:
27 return esc
28 if tail.startswith("x"):
29 hexes = tail[1:]
30 if len(hexes) < 2:
31 raise ValueError(f"invalid hex string escape ('\\{tail}')")
32 try:
33 i = int(hexes, 16)
34 except ValueError:
35 raise ValueError(f"invalid hex string escape ('\\{tail}')") from None
36 else:
37 try:
38 i = int(tail, 8)
39 except ValueError:
40 raise ValueError(f"invalid octal string escape ('\\{tail}')") from None
41 return chr(i)
42
43
44 def evalString(s: str) -> str:
45 assert s.startswith("'") or s.startswith('"'), repr(s[:1])
46 q = s[0]
47 if s[:3] == q * 3:
48 q = q * 3
49 assert s.endswith(q), repr(s[-len(q) :])
50 assert len(s) >= 2 * len(q)
51 s = s[len(q) : -len(q)]
52 return re.sub(r"\\(\'|\"|\\|[abfnrtv]|x.{0,2}|[0-7]{1,3})", escape, s)
53
54
55 def test() -> None:
56 for i in range(256):
57 c = chr(i)
58 s = repr(c)
59 e = evalString(s)
60 if e != c:
61 print(i, c, s, e)
62
63
64 if __name__ == "__main__":
65 test()