ยปCore Development>Code coverage>Lib/lib2to3/pgen2/literals.py

# Python code coverage for Lib/lib2to3/pgen2/literals.py

#countcontent
2n/a# Licensed to PSF under a Contributor Agreement.
3n/a
4n/a"""Safely evaluate Python string literals without using eval()."""
5n/a
6n/aimport re
7n/a
8n/asimple_escapes = {"a": "\a",
9n/a "b": "\b",
10n/a "f": "\f",
11n/a "n": "\n",
12n/a "r": "\r",
13n/a "t": "\t",
14n/a "v": "\v",
15n/a "'": "'",
16n/a '"': '"',
17n/a "\\": "\\"}
18n/a
20n/a all, tail = m.group(0, 1)
21n/a assert all.startswith("\\")
22n/a esc = simple_escapes.get(tail)
23n/a if esc is not None:
24n/a return esc
25n/a if tail.startswith("x"):
26n/a hexes = tail[1:]
27n/a if len(hexes) < 2:
28n/a raise ValueError("invalid hex string escape ('\\%s')" % tail)
29n/a try:
30n/a i = int(hexes, 16)
31n/a except ValueError:
32n/a raise ValueError("invalid hex string escape ('\\%s')" % tail)
33n/a else:
34n/a try:
35n/a i = int(tail, 8)
36n/a except ValueError:
37n/a raise ValueError("invalid octal string escape ('\\%s')" % tail)
38n/a return chr(i)
39n/a
41n/a assert s.startswith("'") or s.startswith('"'), repr(s[:1])
42n/a q = s[0]
43n/a if s[:3] == q*3:
44n/a q = q*3
45n/a assert s.endswith(q), repr(s[-len(q):])
46n/a assert len(s) >= 2*len(q)
47n/a s = s[len(q):-len(q)]
48n/a return re.sub(r"\\(\'|\"|\\|[abfnrtv]|x.{0,2}|[0-7]{1,3})", escape, s)
49n/a