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