]> git.madduck.net Git - etc/vim.git/blob - blib2to3/pgen2/literals.py

madduck's git repository

Every one of the projects in this repository is available at the canonical URL git://git.madduck.net/madduck/pub/<projectpath> — see each project's metadata for the exact URL.

All patches and comments are welcome. Please squash your changes to logical commits before using git-format-patch and git-send-email to patches@git.madduck.net. If you'd read over the Git project's submission guidelines and adhered to them, I'd be especially grateful.

SSH access, as well as push access can be individually arranged.

If you use my repositories frequently, consider adding the following snippet to ~/.gitconfig and using the third clone URL listed for each project:

[url "git://git.madduck.net/madduck/"]
  insteadOf = madduck:

Test Windows, macOS and Linux on GitHub Actions (#1085)
[etc/vim.git] / blib2to3 / pgen2 / literals.py
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 regex as re
7
8 simple_escapes = {
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):
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("invalid hex string escape ('\\%s')" % tail)
32         try:
33             i = int(hexes, 16)
34         except ValueError:
35             raise ValueError("invalid hex string escape ('\\%s')" % tail) from None
36     else:
37         try:
38             i = int(tail, 8)
39         except ValueError:
40             raise ValueError("invalid octal string escape ('\\%s')" % tail) from None
41     return chr(i)
42
43
44 def evalString(s):
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():
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()