ZTWHHH commited on
Commit
f6b900c
·
verified ·
1 Parent(s): 409a400

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. parrot/lib/python3.10/asyncio/__pycache__/runners.cpython-310.pyc +0 -0
  2. parrot/lib/python3.10/html/__init__.py +132 -0
  3. parrot/lib/python3.10/html/__pycache__/parser.cpython-310.pyc +0 -0
  4. parrot/lib/python3.10/html/entities.py +2510 -0
  5. parrot/lib/python3.10/html/parser.py +462 -0
  6. parrot/lib/python3.10/pydoc_data/topics.py +0 -0
  7. parrot/lib/python3.10/unittest/__init__.py +95 -0
  8. parrot/lib/python3.10/unittest/__pycache__/__init__.cpython-310.pyc +0 -0
  9. parrot/lib/python3.10/unittest/__pycache__/_log.cpython-310.pyc +0 -0
  10. parrot/lib/python3.10/unittest/__pycache__/case.cpython-310.pyc +0 -0
  11. parrot/lib/python3.10/unittest/__pycache__/suite.cpython-310.pyc +0 -0
  12. parrot/lib/python3.10/unittest/__pycache__/util.cpython-310.pyc +0 -0
  13. parrot/lib/python3.10/unittest/_log.py +86 -0
  14. parrot/lib/python3.10/unittest/runner.py +230 -0
  15. parrot/lib/python3.10/xmlrpc/client.py +1532 -0
  16. vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/api/compilation_unit.h +351 -0
  17. vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/api/function_impl.h +180 -0
  18. vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/api/method.h +84 -0
  19. vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/api/module.h +685 -0
  20. vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/api/object.h +200 -0
  21. vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/builtin_functions.h +9 -0
  22. vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/convert_to_ssa.h +14 -0
  23. vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/ir_emitter.h +19 -0
  24. vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/lexer.h +562 -0
  25. vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/mini_environment.h +55 -0
  26. vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/parse_string_literal.h +87 -0
  27. vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/script_type_parser.h +53 -0
  28. vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/sugared_value.h +861 -0
  29. vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/tree.h +218 -0
  30. vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/tree_views.h +1276 -0
  31. vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/mobile/code.h +34 -0
  32. vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/mobile/debug_info.h +55 -0
  33. vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/mobile/file_format.h +194 -0
  34. vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/mobile/flatbuffer_loader.h +134 -0
  35. vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/mobile/frame.h +49 -0
  36. vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/mobile/function.h +84 -0
  37. vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/mobile/import.h +108 -0
  38. vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/mobile/import_export_common.h +15 -0
  39. vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/mobile/method.h +41 -0
  40. vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/mobile/module.h +193 -0
  41. vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/mobile/observer.h +110 -0
  42. vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/mobile/prim_ops_registery.h +28 -0
  43. vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/mobile/profiler_edge.h +115 -0
  44. vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/mobile/register_ops_common_utils.h +53 -0
  45. vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/mobile/type_parser.h +54 -0
  46. vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/mobile/upgrader_mobile.h +39 -0
  47. vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/init.h +9 -0
  48. vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/pybind.h +213 -0
  49. vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/python_arg_flatten.h +119 -0
  50. vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/python_custom_class.h +19 -0
parrot/lib/python3.10/asyncio/__pycache__/runners.cpython-310.pyc ADDED
Binary file (2.09 kB). View file
 
parrot/lib/python3.10/html/__init__.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ General functions for HTML manipulation.
3
+ """
4
+
5
+ import re as _re
6
+ from html.entities import html5 as _html5
7
+
8
+
9
+ __all__ = ['escape', 'unescape']
10
+
11
+
12
+ def escape(s, quote=True):
13
+ """
14
+ Replace special characters "&", "<" and ">" to HTML-safe sequences.
15
+ If the optional flag quote is true (the default), the quotation mark
16
+ characters, both double quote (") and single quote (') characters are also
17
+ translated.
18
+ """
19
+ s = s.replace("&", "&amp;") # Must be done first!
20
+ s = s.replace("<", "&lt;")
21
+ s = s.replace(">", "&gt;")
22
+ if quote:
23
+ s = s.replace('"', "&quot;")
24
+ s = s.replace('\'', "&#x27;")
25
+ return s
26
+
27
+
28
+ # see https://html.spec.whatwg.org/multipage/parsing.html#numeric-character-reference-end-state
29
+
30
+ _invalid_charrefs = {
31
+ 0x00: '\ufffd', # REPLACEMENT CHARACTER
32
+ 0x0d: '\r', # CARRIAGE RETURN
33
+ 0x80: '\u20ac', # EURO SIGN
34
+ 0x81: '\x81', # <control>
35
+ 0x82: '\u201a', # SINGLE LOW-9 QUOTATION MARK
36
+ 0x83: '\u0192', # LATIN SMALL LETTER F WITH HOOK
37
+ 0x84: '\u201e', # DOUBLE LOW-9 QUOTATION MARK
38
+ 0x85: '\u2026', # HORIZONTAL ELLIPSIS
39
+ 0x86: '\u2020', # DAGGER
40
+ 0x87: '\u2021', # DOUBLE DAGGER
41
+ 0x88: '\u02c6', # MODIFIER LETTER CIRCUMFLEX ACCENT
42
+ 0x89: '\u2030', # PER MILLE SIGN
43
+ 0x8a: '\u0160', # LATIN CAPITAL LETTER S WITH CARON
44
+ 0x8b: '\u2039', # SINGLE LEFT-POINTING ANGLE QUOTATION MARK
45
+ 0x8c: '\u0152', # LATIN CAPITAL LIGATURE OE
46
+ 0x8d: '\x8d', # <control>
47
+ 0x8e: '\u017d', # LATIN CAPITAL LETTER Z WITH CARON
48
+ 0x8f: '\x8f', # <control>
49
+ 0x90: '\x90', # <control>
50
+ 0x91: '\u2018', # LEFT SINGLE QUOTATION MARK
51
+ 0x92: '\u2019', # RIGHT SINGLE QUOTATION MARK
52
+ 0x93: '\u201c', # LEFT DOUBLE QUOTATION MARK
53
+ 0x94: '\u201d', # RIGHT DOUBLE QUOTATION MARK
54
+ 0x95: '\u2022', # BULLET
55
+ 0x96: '\u2013', # EN DASH
56
+ 0x97: '\u2014', # EM DASH
57
+ 0x98: '\u02dc', # SMALL TILDE
58
+ 0x99: '\u2122', # TRADE MARK SIGN
59
+ 0x9a: '\u0161', # LATIN SMALL LETTER S WITH CARON
60
+ 0x9b: '\u203a', # SINGLE RIGHT-POINTING ANGLE QUOTATION MARK
61
+ 0x9c: '\u0153', # LATIN SMALL LIGATURE OE
62
+ 0x9d: '\x9d', # <control>
63
+ 0x9e: '\u017e', # LATIN SMALL LETTER Z WITH CARON
64
+ 0x9f: '\u0178', # LATIN CAPITAL LETTER Y WITH DIAERESIS
65
+ }
66
+
67
+ _invalid_codepoints = {
68
+ # 0x0001 to 0x0008
69
+ 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8,
70
+ # 0x000E to 0x001F
71
+ 0xe, 0xf, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19,
72
+ 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
73
+ # 0x007F to 0x009F
74
+ 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a,
75
+ 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96,
76
+ 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
77
+ # 0xFDD0 to 0xFDEF
78
+ 0xfdd0, 0xfdd1, 0xfdd2, 0xfdd3, 0xfdd4, 0xfdd5, 0xfdd6, 0xfdd7, 0xfdd8,
79
+ 0xfdd9, 0xfdda, 0xfddb, 0xfddc, 0xfddd, 0xfdde, 0xfddf, 0xfde0, 0xfde1,
80
+ 0xfde2, 0xfde3, 0xfde4, 0xfde5, 0xfde6, 0xfde7, 0xfde8, 0xfde9, 0xfdea,
81
+ 0xfdeb, 0xfdec, 0xfded, 0xfdee, 0xfdef,
82
+ # others
83
+ 0xb, 0xfffe, 0xffff, 0x1fffe, 0x1ffff, 0x2fffe, 0x2ffff, 0x3fffe, 0x3ffff,
84
+ 0x4fffe, 0x4ffff, 0x5fffe, 0x5ffff, 0x6fffe, 0x6ffff, 0x7fffe, 0x7ffff,
85
+ 0x8fffe, 0x8ffff, 0x9fffe, 0x9ffff, 0xafffe, 0xaffff, 0xbfffe, 0xbffff,
86
+ 0xcfffe, 0xcffff, 0xdfffe, 0xdffff, 0xefffe, 0xeffff, 0xffffe, 0xfffff,
87
+ 0x10fffe, 0x10ffff
88
+ }
89
+
90
+
91
+ def _replace_charref(s):
92
+ s = s.group(1)
93
+ if s[0] == '#':
94
+ # numeric charref
95
+ if s[1] in 'xX':
96
+ num = int(s[2:].rstrip(';'), 16)
97
+ else:
98
+ num = int(s[1:].rstrip(';'))
99
+ if num in _invalid_charrefs:
100
+ return _invalid_charrefs[num]
101
+ if 0xD800 <= num <= 0xDFFF or num > 0x10FFFF:
102
+ return '\uFFFD'
103
+ if num in _invalid_codepoints:
104
+ return ''
105
+ return chr(num)
106
+ else:
107
+ # named charref
108
+ if s in _html5:
109
+ return _html5[s]
110
+ # find the longest matching name (as defined by the standard)
111
+ for x in range(len(s)-1, 1, -1):
112
+ if s[:x] in _html5:
113
+ return _html5[s[:x]] + s[x:]
114
+ else:
115
+ return '&' + s
116
+
117
+
118
+ _charref = _re.compile(r'&(#[0-9]+;?'
119
+ r'|#[xX][0-9a-fA-F]+;?'
120
+ r'|[^\t\n\f <&#;]{1,32};?)')
121
+
122
+ def unescape(s):
123
+ """
124
+ Convert all named and numeric character references (e.g. &gt;, &#62;,
125
+ &x3e;) in the string s to the corresponding unicode characters.
126
+ This function uses the rules defined by the HTML 5 standard
127
+ for both valid and invalid character references, and the list of
128
+ HTML 5 named character references defined in html.entities.html5.
129
+ """
130
+ if '&' not in s:
131
+ return s
132
+ return _charref.sub(_replace_charref, s)
parrot/lib/python3.10/html/__pycache__/parser.cpython-310.pyc ADDED
Binary file (11 kB). View file
 
parrot/lib/python3.10/html/entities.py ADDED
@@ -0,0 +1,2510 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """HTML character entity references."""
2
+
3
+ __all__ = ['html5', 'name2codepoint', 'codepoint2name', 'entitydefs']
4
+
5
+
6
+ # maps the HTML entity name to the Unicode code point
7
+ # from https://html.spec.whatwg.org/multipage/named-characters.html
8
+ name2codepoint = {
9
+ 'AElig': 0x00c6, # latin capital letter AE = latin capital ligature AE, U+00C6 ISOlat1
10
+ 'Aacute': 0x00c1, # latin capital letter A with acute, U+00C1 ISOlat1
11
+ 'Acirc': 0x00c2, # latin capital letter A with circumflex, U+00C2 ISOlat1
12
+ 'Agrave': 0x00c0, # latin capital letter A with grave = latin capital letter A grave, U+00C0 ISOlat1
13
+ 'Alpha': 0x0391, # greek capital letter alpha, U+0391
14
+ 'Aring': 0x00c5, # latin capital letter A with ring above = latin capital letter A ring, U+00C5 ISOlat1
15
+ 'Atilde': 0x00c3, # latin capital letter A with tilde, U+00C3 ISOlat1
16
+ 'Auml': 0x00c4, # latin capital letter A with diaeresis, U+00C4 ISOlat1
17
+ 'Beta': 0x0392, # greek capital letter beta, U+0392
18
+ 'Ccedil': 0x00c7, # latin capital letter C with cedilla, U+00C7 ISOlat1
19
+ 'Chi': 0x03a7, # greek capital letter chi, U+03A7
20
+ 'Dagger': 0x2021, # double dagger, U+2021 ISOpub
21
+ 'Delta': 0x0394, # greek capital letter delta, U+0394 ISOgrk3
22
+ 'ETH': 0x00d0, # latin capital letter ETH, U+00D0 ISOlat1
23
+ 'Eacute': 0x00c9, # latin capital letter E with acute, U+00C9 ISOlat1
24
+ 'Ecirc': 0x00ca, # latin capital letter E with circumflex, U+00CA ISOlat1
25
+ 'Egrave': 0x00c8, # latin capital letter E with grave, U+00C8 ISOlat1
26
+ 'Epsilon': 0x0395, # greek capital letter epsilon, U+0395
27
+ 'Eta': 0x0397, # greek capital letter eta, U+0397
28
+ 'Euml': 0x00cb, # latin capital letter E with diaeresis, U+00CB ISOlat1
29
+ 'Gamma': 0x0393, # greek capital letter gamma, U+0393 ISOgrk3
30
+ 'Iacute': 0x00cd, # latin capital letter I with acute, U+00CD ISOlat1
31
+ 'Icirc': 0x00ce, # latin capital letter I with circumflex, U+00CE ISOlat1
32
+ 'Igrave': 0x00cc, # latin capital letter I with grave, U+00CC ISOlat1
33
+ 'Iota': 0x0399, # greek capital letter iota, U+0399
34
+ 'Iuml': 0x00cf, # latin capital letter I with diaeresis, U+00CF ISOlat1
35
+ 'Kappa': 0x039a, # greek capital letter kappa, U+039A
36
+ 'Lambda': 0x039b, # greek capital letter lambda, U+039B ISOgrk3
37
+ 'Mu': 0x039c, # greek capital letter mu, U+039C
38
+ 'Ntilde': 0x00d1, # latin capital letter N with tilde, U+00D1 ISOlat1
39
+ 'Nu': 0x039d, # greek capital letter nu, U+039D
40
+ 'OElig': 0x0152, # latin capital ligature OE, U+0152 ISOlat2
41
+ 'Oacute': 0x00d3, # latin capital letter O with acute, U+00D3 ISOlat1
42
+ 'Ocirc': 0x00d4, # latin capital letter O with circumflex, U+00D4 ISOlat1
43
+ 'Ograve': 0x00d2, # latin capital letter O with grave, U+00D2 ISOlat1
44
+ 'Omega': 0x03a9, # greek capital letter omega, U+03A9 ISOgrk3
45
+ 'Omicron': 0x039f, # greek capital letter omicron, U+039F
46
+ 'Oslash': 0x00d8, # latin capital letter O with stroke = latin capital letter O slash, U+00D8 ISOlat1
47
+ 'Otilde': 0x00d5, # latin capital letter O with tilde, U+00D5 ISOlat1
48
+ 'Ouml': 0x00d6, # latin capital letter O with diaeresis, U+00D6 ISOlat1
49
+ 'Phi': 0x03a6, # greek capital letter phi, U+03A6 ISOgrk3
50
+ 'Pi': 0x03a0, # greek capital letter pi, U+03A0 ISOgrk3
51
+ 'Prime': 0x2033, # double prime = seconds = inches, U+2033 ISOtech
52
+ 'Psi': 0x03a8, # greek capital letter psi, U+03A8 ISOgrk3
53
+ 'Rho': 0x03a1, # greek capital letter rho, U+03A1
54
+ 'Scaron': 0x0160, # latin capital letter S with caron, U+0160 ISOlat2
55
+ 'Sigma': 0x03a3, # greek capital letter sigma, U+03A3 ISOgrk3
56
+ 'THORN': 0x00de, # latin capital letter THORN, U+00DE ISOlat1
57
+ 'Tau': 0x03a4, # greek capital letter tau, U+03A4
58
+ 'Theta': 0x0398, # greek capital letter theta, U+0398 ISOgrk3
59
+ 'Uacute': 0x00da, # latin capital letter U with acute, U+00DA ISOlat1
60
+ 'Ucirc': 0x00db, # latin capital letter U with circumflex, U+00DB ISOlat1
61
+ 'Ugrave': 0x00d9, # latin capital letter U with grave, U+00D9 ISOlat1
62
+ 'Upsilon': 0x03a5, # greek capital letter upsilon, U+03A5 ISOgrk3
63
+ 'Uuml': 0x00dc, # latin capital letter U with diaeresis, U+00DC ISOlat1
64
+ 'Xi': 0x039e, # greek capital letter xi, U+039E ISOgrk3
65
+ 'Yacute': 0x00dd, # latin capital letter Y with acute, U+00DD ISOlat1
66
+ 'Yuml': 0x0178, # latin capital letter Y with diaeresis, U+0178 ISOlat2
67
+ 'Zeta': 0x0396, # greek capital letter zeta, U+0396
68
+ 'aacute': 0x00e1, # latin small letter a with acute, U+00E1 ISOlat1
69
+ 'acirc': 0x00e2, # latin small letter a with circumflex, U+00E2 ISOlat1
70
+ 'acute': 0x00b4, # acute accent = spacing acute, U+00B4 ISOdia
71
+ 'aelig': 0x00e6, # latin small letter ae = latin small ligature ae, U+00E6 ISOlat1
72
+ 'agrave': 0x00e0, # latin small letter a with grave = latin small letter a grave, U+00E0 ISOlat1
73
+ 'alefsym': 0x2135, # alef symbol = first transfinite cardinal, U+2135 NEW
74
+ 'alpha': 0x03b1, # greek small letter alpha, U+03B1 ISOgrk3
75
+ 'amp': 0x0026, # ampersand, U+0026 ISOnum
76
+ 'and': 0x2227, # logical and = wedge, U+2227 ISOtech
77
+ 'ang': 0x2220, # angle, U+2220 ISOamso
78
+ 'aring': 0x00e5, # latin small letter a with ring above = latin small letter a ring, U+00E5 ISOlat1
79
+ 'asymp': 0x2248, # almost equal to = asymptotic to, U+2248 ISOamsr
80
+ 'atilde': 0x00e3, # latin small letter a with tilde, U+00E3 ISOlat1
81
+ 'auml': 0x00e4, # latin small letter a with diaeresis, U+00E4 ISOlat1
82
+ 'bdquo': 0x201e, # double low-9 quotation mark, U+201E NEW
83
+ 'beta': 0x03b2, # greek small letter beta, U+03B2 ISOgrk3
84
+ 'brvbar': 0x00a6, # broken bar = broken vertical bar, U+00A6 ISOnum
85
+ 'bull': 0x2022, # bullet = black small circle, U+2022 ISOpub
86
+ 'cap': 0x2229, # intersection = cap, U+2229 ISOtech
87
+ 'ccedil': 0x00e7, # latin small letter c with cedilla, U+00E7 ISOlat1
88
+ 'cedil': 0x00b8, # cedilla = spacing cedilla, U+00B8 ISOdia
89
+ 'cent': 0x00a2, # cent sign, U+00A2 ISOnum
90
+ 'chi': 0x03c7, # greek small letter chi, U+03C7 ISOgrk3
91
+ 'circ': 0x02c6, # modifier letter circumflex accent, U+02C6 ISOpub
92
+ 'clubs': 0x2663, # black club suit = shamrock, U+2663 ISOpub
93
+ 'cong': 0x2245, # approximately equal to, U+2245 ISOtech
94
+ 'copy': 0x00a9, # copyright sign, U+00A9 ISOnum
95
+ 'crarr': 0x21b5, # downwards arrow with corner leftwards = carriage return, U+21B5 NEW
96
+ 'cup': 0x222a, # union = cup, U+222A ISOtech
97
+ 'curren': 0x00a4, # currency sign, U+00A4 ISOnum
98
+ 'dArr': 0x21d3, # downwards double arrow, U+21D3 ISOamsa
99
+ 'dagger': 0x2020, # dagger, U+2020 ISOpub
100
+ 'darr': 0x2193, # downwards arrow, U+2193 ISOnum
101
+ 'deg': 0x00b0, # degree sign, U+00B0 ISOnum
102
+ 'delta': 0x03b4, # greek small letter delta, U+03B4 ISOgrk3
103
+ 'diams': 0x2666, # black diamond suit, U+2666 ISOpub
104
+ 'divide': 0x00f7, # division sign, U+00F7 ISOnum
105
+ 'eacute': 0x00e9, # latin small letter e with acute, U+00E9 ISOlat1
106
+ 'ecirc': 0x00ea, # latin small letter e with circumflex, U+00EA ISOlat1
107
+ 'egrave': 0x00e8, # latin small letter e with grave, U+00E8 ISOlat1
108
+ 'empty': 0x2205, # empty set = null set = diameter, U+2205 ISOamso
109
+ 'emsp': 0x2003, # em space, U+2003 ISOpub
110
+ 'ensp': 0x2002, # en space, U+2002 ISOpub
111
+ 'epsilon': 0x03b5, # greek small letter epsilon, U+03B5 ISOgrk3
112
+ 'equiv': 0x2261, # identical to, U+2261 ISOtech
113
+ 'eta': 0x03b7, # greek small letter eta, U+03B7 ISOgrk3
114
+ 'eth': 0x00f0, # latin small letter eth, U+00F0 ISOlat1
115
+ 'euml': 0x00eb, # latin small letter e with diaeresis, U+00EB ISOlat1
116
+ 'euro': 0x20ac, # euro sign, U+20AC NEW
117
+ 'exist': 0x2203, # there exists, U+2203 ISOtech
118
+ 'fnof': 0x0192, # latin small f with hook = function = florin, U+0192 ISOtech
119
+ 'forall': 0x2200, # for all, U+2200 ISOtech
120
+ 'frac12': 0x00bd, # vulgar fraction one half = fraction one half, U+00BD ISOnum
121
+ 'frac14': 0x00bc, # vulgar fraction one quarter = fraction one quarter, U+00BC ISOnum
122
+ 'frac34': 0x00be, # vulgar fraction three quarters = fraction three quarters, U+00BE ISOnum
123
+ 'frasl': 0x2044, # fraction slash, U+2044 NEW
124
+ 'gamma': 0x03b3, # greek small letter gamma, U+03B3 ISOgrk3
125
+ 'ge': 0x2265, # greater-than or equal to, U+2265 ISOtech
126
+ 'gt': 0x003e, # greater-than sign, U+003E ISOnum
127
+ 'hArr': 0x21d4, # left right double arrow, U+21D4 ISOamsa
128
+ 'harr': 0x2194, # left right arrow, U+2194 ISOamsa
129
+ 'hearts': 0x2665, # black heart suit = valentine, U+2665 ISOpub
130
+ 'hellip': 0x2026, # horizontal ellipsis = three dot leader, U+2026 ISOpub
131
+ 'iacute': 0x00ed, # latin small letter i with acute, U+00ED ISOlat1
132
+ 'icirc': 0x00ee, # latin small letter i with circumflex, U+00EE ISOlat1
133
+ 'iexcl': 0x00a1, # inverted exclamation mark, U+00A1 ISOnum
134
+ 'igrave': 0x00ec, # latin small letter i with grave, U+00EC ISOlat1
135
+ 'image': 0x2111, # blackletter capital I = imaginary part, U+2111 ISOamso
136
+ 'infin': 0x221e, # infinity, U+221E ISOtech
137
+ 'int': 0x222b, # integral, U+222B ISOtech
138
+ 'iota': 0x03b9, # greek small letter iota, U+03B9 ISOgrk3
139
+ 'iquest': 0x00bf, # inverted question mark = turned question mark, U+00BF ISOnum
140
+ 'isin': 0x2208, # element of, U+2208 ISOtech
141
+ 'iuml': 0x00ef, # latin small letter i with diaeresis, U+00EF ISOlat1
142
+ 'kappa': 0x03ba, # greek small letter kappa, U+03BA ISOgrk3
143
+ 'lArr': 0x21d0, # leftwards double arrow, U+21D0 ISOtech
144
+ 'lambda': 0x03bb, # greek small letter lambda, U+03BB ISOgrk3
145
+ 'lang': 0x2329, # left-pointing angle bracket = bra, U+2329 ISOtech
146
+ 'laquo': 0x00ab, # left-pointing double angle quotation mark = left pointing guillemet, U+00AB ISOnum
147
+ 'larr': 0x2190, # leftwards arrow, U+2190 ISOnum
148
+ 'lceil': 0x2308, # left ceiling = apl upstile, U+2308 ISOamsc
149
+ 'ldquo': 0x201c, # left double quotation mark, U+201C ISOnum
150
+ 'le': 0x2264, # less-than or equal to, U+2264 ISOtech
151
+ 'lfloor': 0x230a, # left floor = apl downstile, U+230A ISOamsc
152
+ 'lowast': 0x2217, # asterisk operator, U+2217 ISOtech
153
+ 'loz': 0x25ca, # lozenge, U+25CA ISOpub
154
+ 'lrm': 0x200e, # left-to-right mark, U+200E NEW RFC 2070
155
+ 'lsaquo': 0x2039, # single left-pointing angle quotation mark, U+2039 ISO proposed
156
+ 'lsquo': 0x2018, # left single quotation mark, U+2018 ISOnum
157
+ 'lt': 0x003c, # less-than sign, U+003C ISOnum
158
+ 'macr': 0x00af, # macron = spacing macron = overline = APL overbar, U+00AF ISOdia
159
+ 'mdash': 0x2014, # em dash, U+2014 ISOpub
160
+ 'micro': 0x00b5, # micro sign, U+00B5 ISOnum
161
+ 'middot': 0x00b7, # middle dot = Georgian comma = Greek middle dot, U+00B7 ISOnum
162
+ 'minus': 0x2212, # minus sign, U+2212 ISOtech
163
+ 'mu': 0x03bc, # greek small letter mu, U+03BC ISOgrk3
164
+ 'nabla': 0x2207, # nabla = backward difference, U+2207 ISOtech
165
+ 'nbsp': 0x00a0, # no-break space = non-breaking space, U+00A0 ISOnum
166
+ 'ndash': 0x2013, # en dash, U+2013 ISOpub
167
+ 'ne': 0x2260, # not equal to, U+2260 ISOtech
168
+ 'ni': 0x220b, # contains as member, U+220B ISOtech
169
+ 'not': 0x00ac, # not sign, U+00AC ISOnum
170
+ 'notin': 0x2209, # not an element of, U+2209 ISOtech
171
+ 'nsub': 0x2284, # not a subset of, U+2284 ISOamsn
172
+ 'ntilde': 0x00f1, # latin small letter n with tilde, U+00F1 ISOlat1
173
+ 'nu': 0x03bd, # greek small letter nu, U+03BD ISOgrk3
174
+ 'oacute': 0x00f3, # latin small letter o with acute, U+00F3 ISOlat1
175
+ 'ocirc': 0x00f4, # latin small letter o with circumflex, U+00F4 ISOlat1
176
+ 'oelig': 0x0153, # latin small ligature oe, U+0153 ISOlat2
177
+ 'ograve': 0x00f2, # latin small letter o with grave, U+00F2 ISOlat1
178
+ 'oline': 0x203e, # overline = spacing overscore, U+203E NEW
179
+ 'omega': 0x03c9, # greek small letter omega, U+03C9 ISOgrk3
180
+ 'omicron': 0x03bf, # greek small letter omicron, U+03BF NEW
181
+ 'oplus': 0x2295, # circled plus = direct sum, U+2295 ISOamsb
182
+ 'or': 0x2228, # logical or = vee, U+2228 ISOtech
183
+ 'ordf': 0x00aa, # feminine ordinal indicator, U+00AA ISOnum
184
+ 'ordm': 0x00ba, # masculine ordinal indicator, U+00BA ISOnum
185
+ 'oslash': 0x00f8, # latin small letter o with stroke, = latin small letter o slash, U+00F8 ISOlat1
186
+ 'otilde': 0x00f5, # latin small letter o with tilde, U+00F5 ISOlat1
187
+ 'otimes': 0x2297, # circled times = vector product, U+2297 ISOamsb
188
+ 'ouml': 0x00f6, # latin small letter o with diaeresis, U+00F6 ISOlat1
189
+ 'para': 0x00b6, # pilcrow sign = paragraph sign, U+00B6 ISOnum
190
+ 'part': 0x2202, # partial differential, U+2202 ISOtech
191
+ 'permil': 0x2030, # per mille sign, U+2030 ISOtech
192
+ 'perp': 0x22a5, # up tack = orthogonal to = perpendicular, U+22A5 ISOtech
193
+ 'phi': 0x03c6, # greek small letter phi, U+03C6 ISOgrk3
194
+ 'pi': 0x03c0, # greek small letter pi, U+03C0 ISOgrk3
195
+ 'piv': 0x03d6, # greek pi symbol, U+03D6 ISOgrk3
196
+ 'plusmn': 0x00b1, # plus-minus sign = plus-or-minus sign, U+00B1 ISOnum
197
+ 'pound': 0x00a3, # pound sign, U+00A3 ISOnum
198
+ 'prime': 0x2032, # prime = minutes = feet, U+2032 ISOtech
199
+ 'prod': 0x220f, # n-ary product = product sign, U+220F ISOamsb
200
+ 'prop': 0x221d, # proportional to, U+221D ISOtech
201
+ 'psi': 0x03c8, # greek small letter psi, U+03C8 ISOgrk3
202
+ 'quot': 0x0022, # quotation mark = APL quote, U+0022 ISOnum
203
+ 'rArr': 0x21d2, # rightwards double arrow, U+21D2 ISOtech
204
+ 'radic': 0x221a, # square root = radical sign, U+221A ISOtech
205
+ 'rang': 0x232a, # right-pointing angle bracket = ket, U+232A ISOtech
206
+ 'raquo': 0x00bb, # right-pointing double angle quotation mark = right pointing guillemet, U+00BB ISOnum
207
+ 'rarr': 0x2192, # rightwards arrow, U+2192 ISOnum
208
+ 'rceil': 0x2309, # right ceiling, U+2309 ISOamsc
209
+ 'rdquo': 0x201d, # right double quotation mark, U+201D ISOnum
210
+ 'real': 0x211c, # blackletter capital R = real part symbol, U+211C ISOamso
211
+ 'reg': 0x00ae, # registered sign = registered trade mark sign, U+00AE ISOnum
212
+ 'rfloor': 0x230b, # right floor, U+230B ISOamsc
213
+ 'rho': 0x03c1, # greek small letter rho, U+03C1 ISOgrk3
214
+ 'rlm': 0x200f, # right-to-left mark, U+200F NEW RFC 2070
215
+ 'rsaquo': 0x203a, # single right-pointing angle quotation mark, U+203A ISO proposed
216
+ 'rsquo': 0x2019, # right single quotation mark, U+2019 ISOnum
217
+ 'sbquo': 0x201a, # single low-9 quotation mark, U+201A NEW
218
+ 'scaron': 0x0161, # latin small letter s with caron, U+0161 ISOlat2
219
+ 'sdot': 0x22c5, # dot operator, U+22C5 ISOamsb
220
+ 'sect': 0x00a7, # section sign, U+00A7 ISOnum
221
+ 'shy': 0x00ad, # soft hyphen = discretionary hyphen, U+00AD ISOnum
222
+ 'sigma': 0x03c3, # greek small letter sigma, U+03C3 ISOgrk3
223
+ 'sigmaf': 0x03c2, # greek small letter final sigma, U+03C2 ISOgrk3
224
+ 'sim': 0x223c, # tilde operator = varies with = similar to, U+223C ISOtech
225
+ 'spades': 0x2660, # black spade suit, U+2660 ISOpub
226
+ 'sub': 0x2282, # subset of, U+2282 ISOtech
227
+ 'sube': 0x2286, # subset of or equal to, U+2286 ISOtech
228
+ 'sum': 0x2211, # n-ary summation, U+2211 ISOamsb
229
+ 'sup': 0x2283, # superset of, U+2283 ISOtech
230
+ 'sup1': 0x00b9, # superscript one = superscript digit one, U+00B9 ISOnum
231
+ 'sup2': 0x00b2, # superscript two = superscript digit two = squared, U+00B2 ISOnum
232
+ 'sup3': 0x00b3, # superscript three = superscript digit three = cubed, U+00B3 ISOnum
233
+ 'supe': 0x2287, # superset of or equal to, U+2287 ISOtech
234
+ 'szlig': 0x00df, # latin small letter sharp s = ess-zed, U+00DF ISOlat1
235
+ 'tau': 0x03c4, # greek small letter tau, U+03C4 ISOgrk3
236
+ 'there4': 0x2234, # therefore, U+2234 ISOtech
237
+ 'theta': 0x03b8, # greek small letter theta, U+03B8 ISOgrk3
238
+ 'thetasym': 0x03d1, # greek small letter theta symbol, U+03D1 NEW
239
+ 'thinsp': 0x2009, # thin space, U+2009 ISOpub
240
+ 'thorn': 0x00fe, # latin small letter thorn with, U+00FE ISOlat1
241
+ 'tilde': 0x02dc, # small tilde, U+02DC ISOdia
242
+ 'times': 0x00d7, # multiplication sign, U+00D7 ISOnum
243
+ 'trade': 0x2122, # trade mark sign, U+2122 ISOnum
244
+ 'uArr': 0x21d1, # upwards double arrow, U+21D1 ISOamsa
245
+ 'uacute': 0x00fa, # latin small letter u with acute, U+00FA ISOlat1
246
+ 'uarr': 0x2191, # upwards arrow, U+2191 ISOnum
247
+ 'ucirc': 0x00fb, # latin small letter u with circumflex, U+00FB ISOlat1
248
+ 'ugrave': 0x00f9, # latin small letter u with grave, U+00F9 ISOlat1
249
+ 'uml': 0x00a8, # diaeresis = spacing diaeresis, U+00A8 ISOdia
250
+ 'upsih': 0x03d2, # greek upsilon with hook symbol, U+03D2 NEW
251
+ 'upsilon': 0x03c5, # greek small letter upsilon, U+03C5 ISOgrk3
252
+ 'uuml': 0x00fc, # latin small letter u with diaeresis, U+00FC ISOlat1
253
+ 'weierp': 0x2118, # script capital P = power set = Weierstrass p, U+2118 ISOamso
254
+ 'xi': 0x03be, # greek small letter xi, U+03BE ISOgrk3
255
+ 'yacute': 0x00fd, # latin small letter y with acute, U+00FD ISOlat1
256
+ 'yen': 0x00a5, # yen sign = yuan sign, U+00A5 ISOnum
257
+ 'yuml': 0x00ff, # latin small letter y with diaeresis, U+00FF ISOlat1
258
+ 'zeta': 0x03b6, # greek small letter zeta, U+03B6 ISOgrk3
259
+ 'zwj': 0x200d, # zero width joiner, U+200D NEW RFC 2070
260
+ 'zwnj': 0x200c, # zero width non-joiner, U+200C NEW RFC 2070
261
+ }
262
+
263
+
264
+ # maps the HTML5 named character references to the equivalent Unicode character(s)
265
+ html5 = {
266
+ 'Aacute': '\xc1',
267
+ 'aacute': '\xe1',
268
+ 'Aacute;': '\xc1',
269
+ 'aacute;': '\xe1',
270
+ 'Abreve;': '\u0102',
271
+ 'abreve;': '\u0103',
272
+ 'ac;': '\u223e',
273
+ 'acd;': '\u223f',
274
+ 'acE;': '\u223e\u0333',
275
+ 'Acirc': '\xc2',
276
+ 'acirc': '\xe2',
277
+ 'Acirc;': '\xc2',
278
+ 'acirc;': '\xe2',
279
+ 'acute': '\xb4',
280
+ 'acute;': '\xb4',
281
+ 'Acy;': '\u0410',
282
+ 'acy;': '\u0430',
283
+ 'AElig': '\xc6',
284
+ 'aelig': '\xe6',
285
+ 'AElig;': '\xc6',
286
+ 'aelig;': '\xe6',
287
+ 'af;': '\u2061',
288
+ 'Afr;': '\U0001d504',
289
+ 'afr;': '\U0001d51e',
290
+ 'Agrave': '\xc0',
291
+ 'agrave': '\xe0',
292
+ 'Agrave;': '\xc0',
293
+ 'agrave;': '\xe0',
294
+ 'alefsym;': '\u2135',
295
+ 'aleph;': '\u2135',
296
+ 'Alpha;': '\u0391',
297
+ 'alpha;': '\u03b1',
298
+ 'Amacr;': '\u0100',
299
+ 'amacr;': '\u0101',
300
+ 'amalg;': '\u2a3f',
301
+ 'AMP': '&',
302
+ 'amp': '&',
303
+ 'AMP;': '&',
304
+ 'amp;': '&',
305
+ 'And;': '\u2a53',
306
+ 'and;': '\u2227',
307
+ 'andand;': '\u2a55',
308
+ 'andd;': '\u2a5c',
309
+ 'andslope;': '\u2a58',
310
+ 'andv;': '\u2a5a',
311
+ 'ang;': '\u2220',
312
+ 'ange;': '\u29a4',
313
+ 'angle;': '\u2220',
314
+ 'angmsd;': '\u2221',
315
+ 'angmsdaa;': '\u29a8',
316
+ 'angmsdab;': '\u29a9',
317
+ 'angmsdac;': '\u29aa',
318
+ 'angmsdad;': '\u29ab',
319
+ 'angmsdae;': '\u29ac',
320
+ 'angmsdaf;': '\u29ad',
321
+ 'angmsdag;': '\u29ae',
322
+ 'angmsdah;': '\u29af',
323
+ 'angrt;': '\u221f',
324
+ 'angrtvb;': '\u22be',
325
+ 'angrtvbd;': '\u299d',
326
+ 'angsph;': '\u2222',
327
+ 'angst;': '\xc5',
328
+ 'angzarr;': '\u237c',
329
+ 'Aogon;': '\u0104',
330
+ 'aogon;': '\u0105',
331
+ 'Aopf;': '\U0001d538',
332
+ 'aopf;': '\U0001d552',
333
+ 'ap;': '\u2248',
334
+ 'apacir;': '\u2a6f',
335
+ 'apE;': '\u2a70',
336
+ 'ape;': '\u224a',
337
+ 'apid;': '\u224b',
338
+ 'apos;': "'",
339
+ 'ApplyFunction;': '\u2061',
340
+ 'approx;': '\u2248',
341
+ 'approxeq;': '\u224a',
342
+ 'Aring': '\xc5',
343
+ 'aring': '\xe5',
344
+ 'Aring;': '\xc5',
345
+ 'aring;': '\xe5',
346
+ 'Ascr;': '\U0001d49c',
347
+ 'ascr;': '\U0001d4b6',
348
+ 'Assign;': '\u2254',
349
+ 'ast;': '*',
350
+ 'asymp;': '\u2248',
351
+ 'asympeq;': '\u224d',
352
+ 'Atilde': '\xc3',
353
+ 'atilde': '\xe3',
354
+ 'Atilde;': '\xc3',
355
+ 'atilde;': '\xe3',
356
+ 'Auml': '\xc4',
357
+ 'auml': '\xe4',
358
+ 'Auml;': '\xc4',
359
+ 'auml;': '\xe4',
360
+ 'awconint;': '\u2233',
361
+ 'awint;': '\u2a11',
362
+ 'backcong;': '\u224c',
363
+ 'backepsilon;': '\u03f6',
364
+ 'backprime;': '\u2035',
365
+ 'backsim;': '\u223d',
366
+ 'backsimeq;': '\u22cd',
367
+ 'Backslash;': '\u2216',
368
+ 'Barv;': '\u2ae7',
369
+ 'barvee;': '\u22bd',
370
+ 'Barwed;': '\u2306',
371
+ 'barwed;': '\u2305',
372
+ 'barwedge;': '\u2305',
373
+ 'bbrk;': '\u23b5',
374
+ 'bbrktbrk;': '\u23b6',
375
+ 'bcong;': '\u224c',
376
+ 'Bcy;': '\u0411',
377
+ 'bcy;': '\u0431',
378
+ 'bdquo;': '\u201e',
379
+ 'becaus;': '\u2235',
380
+ 'Because;': '\u2235',
381
+ 'because;': '\u2235',
382
+ 'bemptyv;': '\u29b0',
383
+ 'bepsi;': '\u03f6',
384
+ 'bernou;': '\u212c',
385
+ 'Bernoullis;': '\u212c',
386
+ 'Beta;': '\u0392',
387
+ 'beta;': '\u03b2',
388
+ 'beth;': '\u2136',
389
+ 'between;': '\u226c',
390
+ 'Bfr;': '\U0001d505',
391
+ 'bfr;': '\U0001d51f',
392
+ 'bigcap;': '\u22c2',
393
+ 'bigcirc;': '\u25ef',
394
+ 'bigcup;': '\u22c3',
395
+ 'bigodot;': '\u2a00',
396
+ 'bigoplus;': '\u2a01',
397
+ 'bigotimes;': '\u2a02',
398
+ 'bigsqcup;': '\u2a06',
399
+ 'bigstar;': '\u2605',
400
+ 'bigtriangledown;': '\u25bd',
401
+ 'bigtriangleup;': '\u25b3',
402
+ 'biguplus;': '\u2a04',
403
+ 'bigvee;': '\u22c1',
404
+ 'bigwedge;': '\u22c0',
405
+ 'bkarow;': '\u290d',
406
+ 'blacklozenge;': '\u29eb',
407
+ 'blacksquare;': '\u25aa',
408
+ 'blacktriangle;': '\u25b4',
409
+ 'blacktriangledown;': '\u25be',
410
+ 'blacktriangleleft;': '\u25c2',
411
+ 'blacktriangleright;': '\u25b8',
412
+ 'blank;': '\u2423',
413
+ 'blk12;': '\u2592',
414
+ 'blk14;': '\u2591',
415
+ 'blk34;': '\u2593',
416
+ 'block;': '\u2588',
417
+ 'bne;': '=\u20e5',
418
+ 'bnequiv;': '\u2261\u20e5',
419
+ 'bNot;': '\u2aed',
420
+ 'bnot;': '\u2310',
421
+ 'Bopf;': '\U0001d539',
422
+ 'bopf;': '\U0001d553',
423
+ 'bot;': '\u22a5',
424
+ 'bottom;': '\u22a5',
425
+ 'bowtie;': '\u22c8',
426
+ 'boxbox;': '\u29c9',
427
+ 'boxDL;': '\u2557',
428
+ 'boxDl;': '\u2556',
429
+ 'boxdL;': '\u2555',
430
+ 'boxdl;': '\u2510',
431
+ 'boxDR;': '\u2554',
432
+ 'boxDr;': '\u2553',
433
+ 'boxdR;': '\u2552',
434
+ 'boxdr;': '\u250c',
435
+ 'boxH;': '\u2550',
436
+ 'boxh;': '\u2500',
437
+ 'boxHD;': '\u2566',
438
+ 'boxHd;': '\u2564',
439
+ 'boxhD;': '\u2565',
440
+ 'boxhd;': '\u252c',
441
+ 'boxHU;': '\u2569',
442
+ 'boxHu;': '\u2567',
443
+ 'boxhU;': '\u2568',
444
+ 'boxhu;': '\u2534',
445
+ 'boxminus;': '\u229f',
446
+ 'boxplus;': '\u229e',
447
+ 'boxtimes;': '\u22a0',
448
+ 'boxUL;': '\u255d',
449
+ 'boxUl;': '\u255c',
450
+ 'boxuL;': '\u255b',
451
+ 'boxul;': '\u2518',
452
+ 'boxUR;': '\u255a',
453
+ 'boxUr;': '\u2559',
454
+ 'boxuR;': '\u2558',
455
+ 'boxur;': '\u2514',
456
+ 'boxV;': '\u2551',
457
+ 'boxv;': '\u2502',
458
+ 'boxVH;': '\u256c',
459
+ 'boxVh;': '\u256b',
460
+ 'boxvH;': '\u256a',
461
+ 'boxvh;': '\u253c',
462
+ 'boxVL;': '\u2563',
463
+ 'boxVl;': '\u2562',
464
+ 'boxvL;': '\u2561',
465
+ 'boxvl;': '\u2524',
466
+ 'boxVR;': '\u2560',
467
+ 'boxVr;': '\u255f',
468
+ 'boxvR;': '\u255e',
469
+ 'boxvr;': '\u251c',
470
+ 'bprime;': '\u2035',
471
+ 'Breve;': '\u02d8',
472
+ 'breve;': '\u02d8',
473
+ 'brvbar': '\xa6',
474
+ 'brvbar;': '\xa6',
475
+ 'Bscr;': '\u212c',
476
+ 'bscr;': '\U0001d4b7',
477
+ 'bsemi;': '\u204f',
478
+ 'bsim;': '\u223d',
479
+ 'bsime;': '\u22cd',
480
+ 'bsol;': '\\',
481
+ 'bsolb;': '\u29c5',
482
+ 'bsolhsub;': '\u27c8',
483
+ 'bull;': '\u2022',
484
+ 'bullet;': '\u2022',
485
+ 'bump;': '\u224e',
486
+ 'bumpE;': '\u2aae',
487
+ 'bumpe;': '\u224f',
488
+ 'Bumpeq;': '\u224e',
489
+ 'bumpeq;': '\u224f',
490
+ 'Cacute;': '\u0106',
491
+ 'cacute;': '\u0107',
492
+ 'Cap;': '\u22d2',
493
+ 'cap;': '\u2229',
494
+ 'capand;': '\u2a44',
495
+ 'capbrcup;': '\u2a49',
496
+ 'capcap;': '\u2a4b',
497
+ 'capcup;': '\u2a47',
498
+ 'capdot;': '\u2a40',
499
+ 'CapitalDifferentialD;': '\u2145',
500
+ 'caps;': '\u2229\ufe00',
501
+ 'caret;': '\u2041',
502
+ 'caron;': '\u02c7',
503
+ 'Cayleys;': '\u212d',
504
+ 'ccaps;': '\u2a4d',
505
+ 'Ccaron;': '\u010c',
506
+ 'ccaron;': '\u010d',
507
+ 'Ccedil': '\xc7',
508
+ 'ccedil': '\xe7',
509
+ 'Ccedil;': '\xc7',
510
+ 'ccedil;': '\xe7',
511
+ 'Ccirc;': '\u0108',
512
+ 'ccirc;': '\u0109',
513
+ 'Cconint;': '\u2230',
514
+ 'ccups;': '\u2a4c',
515
+ 'ccupssm;': '\u2a50',
516
+ 'Cdot;': '\u010a',
517
+ 'cdot;': '\u010b',
518
+ 'cedil': '\xb8',
519
+ 'cedil;': '\xb8',
520
+ 'Cedilla;': '\xb8',
521
+ 'cemptyv;': '\u29b2',
522
+ 'cent': '\xa2',
523
+ 'cent;': '\xa2',
524
+ 'CenterDot;': '\xb7',
525
+ 'centerdot;': '\xb7',
526
+ 'Cfr;': '\u212d',
527
+ 'cfr;': '\U0001d520',
528
+ 'CHcy;': '\u0427',
529
+ 'chcy;': '\u0447',
530
+ 'check;': '\u2713',
531
+ 'checkmark;': '\u2713',
532
+ 'Chi;': '\u03a7',
533
+ 'chi;': '\u03c7',
534
+ 'cir;': '\u25cb',
535
+ 'circ;': '\u02c6',
536
+ 'circeq;': '\u2257',
537
+ 'circlearrowleft;': '\u21ba',
538
+ 'circlearrowright;': '\u21bb',
539
+ 'circledast;': '\u229b',
540
+ 'circledcirc;': '\u229a',
541
+ 'circleddash;': '\u229d',
542
+ 'CircleDot;': '\u2299',
543
+ 'circledR;': '\xae',
544
+ 'circledS;': '\u24c8',
545
+ 'CircleMinus;': '\u2296',
546
+ 'CirclePlus;': '\u2295',
547
+ 'CircleTimes;': '\u2297',
548
+ 'cirE;': '\u29c3',
549
+ 'cire;': '\u2257',
550
+ 'cirfnint;': '\u2a10',
551
+ 'cirmid;': '\u2aef',
552
+ 'cirscir;': '\u29c2',
553
+ 'ClockwiseContourIntegral;': '\u2232',
554
+ 'CloseCurlyDoubleQuote;': '\u201d',
555
+ 'CloseCurlyQuote;': '\u2019',
556
+ 'clubs;': '\u2663',
557
+ 'clubsuit;': '\u2663',
558
+ 'Colon;': '\u2237',
559
+ 'colon;': ':',
560
+ 'Colone;': '\u2a74',
561
+ 'colone;': '\u2254',
562
+ 'coloneq;': '\u2254',
563
+ 'comma;': ',',
564
+ 'commat;': '@',
565
+ 'comp;': '\u2201',
566
+ 'compfn;': '\u2218',
567
+ 'complement;': '\u2201',
568
+ 'complexes;': '\u2102',
569
+ 'cong;': '\u2245',
570
+ 'congdot;': '\u2a6d',
571
+ 'Congruent;': '\u2261',
572
+ 'Conint;': '\u222f',
573
+ 'conint;': '\u222e',
574
+ 'ContourIntegral;': '\u222e',
575
+ 'Copf;': '\u2102',
576
+ 'copf;': '\U0001d554',
577
+ 'coprod;': '\u2210',
578
+ 'Coproduct;': '\u2210',
579
+ 'COPY': '\xa9',
580
+ 'copy': '\xa9',
581
+ 'COPY;': '\xa9',
582
+ 'copy;': '\xa9',
583
+ 'copysr;': '\u2117',
584
+ 'CounterClockwiseContourIntegral;': '\u2233',
585
+ 'crarr;': '\u21b5',
586
+ 'Cross;': '\u2a2f',
587
+ 'cross;': '\u2717',
588
+ 'Cscr;': '\U0001d49e',
589
+ 'cscr;': '\U0001d4b8',
590
+ 'csub;': '\u2acf',
591
+ 'csube;': '\u2ad1',
592
+ 'csup;': '\u2ad0',
593
+ 'csupe;': '\u2ad2',
594
+ 'ctdot;': '\u22ef',
595
+ 'cudarrl;': '\u2938',
596
+ 'cudarrr;': '\u2935',
597
+ 'cuepr;': '\u22de',
598
+ 'cuesc;': '\u22df',
599
+ 'cularr;': '\u21b6',
600
+ 'cularrp;': '\u293d',
601
+ 'Cup;': '\u22d3',
602
+ 'cup;': '\u222a',
603
+ 'cupbrcap;': '\u2a48',
604
+ 'CupCap;': '\u224d',
605
+ 'cupcap;': '\u2a46',
606
+ 'cupcup;': '\u2a4a',
607
+ 'cupdot;': '\u228d',
608
+ 'cupor;': '\u2a45',
609
+ 'cups;': '\u222a\ufe00',
610
+ 'curarr;': '\u21b7',
611
+ 'curarrm;': '\u293c',
612
+ 'curlyeqprec;': '\u22de',
613
+ 'curlyeqsucc;': '\u22df',
614
+ 'curlyvee;': '\u22ce',
615
+ 'curlywedge;': '\u22cf',
616
+ 'curren': '\xa4',
617
+ 'curren;': '\xa4',
618
+ 'curvearrowleft;': '\u21b6',
619
+ 'curvearrowright;': '\u21b7',
620
+ 'cuvee;': '\u22ce',
621
+ 'cuwed;': '\u22cf',
622
+ 'cwconint;': '\u2232',
623
+ 'cwint;': '\u2231',
624
+ 'cylcty;': '\u232d',
625
+ 'Dagger;': '\u2021',
626
+ 'dagger;': '\u2020',
627
+ 'daleth;': '\u2138',
628
+ 'Darr;': '\u21a1',
629
+ 'dArr;': '\u21d3',
630
+ 'darr;': '\u2193',
631
+ 'dash;': '\u2010',
632
+ 'Dashv;': '\u2ae4',
633
+ 'dashv;': '\u22a3',
634
+ 'dbkarow;': '\u290f',
635
+ 'dblac;': '\u02dd',
636
+ 'Dcaron;': '\u010e',
637
+ 'dcaron;': '\u010f',
638
+ 'Dcy;': '\u0414',
639
+ 'dcy;': '\u0434',
640
+ 'DD;': '\u2145',
641
+ 'dd;': '\u2146',
642
+ 'ddagger;': '\u2021',
643
+ 'ddarr;': '\u21ca',
644
+ 'DDotrahd;': '\u2911',
645
+ 'ddotseq;': '\u2a77',
646
+ 'deg': '\xb0',
647
+ 'deg;': '\xb0',
648
+ 'Del;': '\u2207',
649
+ 'Delta;': '\u0394',
650
+ 'delta;': '\u03b4',
651
+ 'demptyv;': '\u29b1',
652
+ 'dfisht;': '\u297f',
653
+ 'Dfr;': '\U0001d507',
654
+ 'dfr;': '\U0001d521',
655
+ 'dHar;': '\u2965',
656
+ 'dharl;': '\u21c3',
657
+ 'dharr;': '\u21c2',
658
+ 'DiacriticalAcute;': '\xb4',
659
+ 'DiacriticalDot;': '\u02d9',
660
+ 'DiacriticalDoubleAcute;': '\u02dd',
661
+ 'DiacriticalGrave;': '`',
662
+ 'DiacriticalTilde;': '\u02dc',
663
+ 'diam;': '\u22c4',
664
+ 'Diamond;': '\u22c4',
665
+ 'diamond;': '\u22c4',
666
+ 'diamondsuit;': '\u2666',
667
+ 'diams;': '\u2666',
668
+ 'die;': '\xa8',
669
+ 'DifferentialD;': '\u2146',
670
+ 'digamma;': '\u03dd',
671
+ 'disin;': '\u22f2',
672
+ 'div;': '\xf7',
673
+ 'divide': '\xf7',
674
+ 'divide;': '\xf7',
675
+ 'divideontimes;': '\u22c7',
676
+ 'divonx;': '\u22c7',
677
+ 'DJcy;': '\u0402',
678
+ 'djcy;': '\u0452',
679
+ 'dlcorn;': '\u231e',
680
+ 'dlcrop;': '\u230d',
681
+ 'dollar;': '$',
682
+ 'Dopf;': '\U0001d53b',
683
+ 'dopf;': '\U0001d555',
684
+ 'Dot;': '\xa8',
685
+ 'dot;': '\u02d9',
686
+ 'DotDot;': '\u20dc',
687
+ 'doteq;': '\u2250',
688
+ 'doteqdot;': '\u2251',
689
+ 'DotEqual;': '\u2250',
690
+ 'dotminus;': '\u2238',
691
+ 'dotplus;': '\u2214',
692
+ 'dotsquare;': '\u22a1',
693
+ 'doublebarwedge;': '\u2306',
694
+ 'DoubleContourIntegral;': '\u222f',
695
+ 'DoubleDot;': '\xa8',
696
+ 'DoubleDownArrow;': '\u21d3',
697
+ 'DoubleLeftArrow;': '\u21d0',
698
+ 'DoubleLeftRightArrow;': '\u21d4',
699
+ 'DoubleLeftTee;': '\u2ae4',
700
+ 'DoubleLongLeftArrow;': '\u27f8',
701
+ 'DoubleLongLeftRightArrow;': '\u27fa',
702
+ 'DoubleLongRightArrow;': '\u27f9',
703
+ 'DoubleRightArrow;': '\u21d2',
704
+ 'DoubleRightTee;': '\u22a8',
705
+ 'DoubleUpArrow;': '\u21d1',
706
+ 'DoubleUpDownArrow;': '\u21d5',
707
+ 'DoubleVerticalBar;': '\u2225',
708
+ 'DownArrow;': '\u2193',
709
+ 'Downarrow;': '\u21d3',
710
+ 'downarrow;': '\u2193',
711
+ 'DownArrowBar;': '\u2913',
712
+ 'DownArrowUpArrow;': '\u21f5',
713
+ 'DownBreve;': '\u0311',
714
+ 'downdownarrows;': '\u21ca',
715
+ 'downharpoonleft;': '\u21c3',
716
+ 'downharpoonright;': '\u21c2',
717
+ 'DownLeftRightVector;': '\u2950',
718
+ 'DownLeftTeeVector;': '\u295e',
719
+ 'DownLeftVector;': '\u21bd',
720
+ 'DownLeftVectorBar;': '\u2956',
721
+ 'DownRightTeeVector;': '\u295f',
722
+ 'DownRightVector;': '\u21c1',
723
+ 'DownRightVectorBar;': '\u2957',
724
+ 'DownTee;': '\u22a4',
725
+ 'DownTeeArrow;': '\u21a7',
726
+ 'drbkarow;': '\u2910',
727
+ 'drcorn;': '\u231f',
728
+ 'drcrop;': '\u230c',
729
+ 'Dscr;': '\U0001d49f',
730
+ 'dscr;': '\U0001d4b9',
731
+ 'DScy;': '\u0405',
732
+ 'dscy;': '\u0455',
733
+ 'dsol;': '\u29f6',
734
+ 'Dstrok;': '\u0110',
735
+ 'dstrok;': '\u0111',
736
+ 'dtdot;': '\u22f1',
737
+ 'dtri;': '\u25bf',
738
+ 'dtrif;': '\u25be',
739
+ 'duarr;': '\u21f5',
740
+ 'duhar;': '\u296f',
741
+ 'dwangle;': '\u29a6',
742
+ 'DZcy;': '\u040f',
743
+ 'dzcy;': '\u045f',
744
+ 'dzigrarr;': '\u27ff',
745
+ 'Eacute': '\xc9',
746
+ 'eacute': '\xe9',
747
+ 'Eacute;': '\xc9',
748
+ 'eacute;': '\xe9',
749
+ 'easter;': '\u2a6e',
750
+ 'Ecaron;': '\u011a',
751
+ 'ecaron;': '\u011b',
752
+ 'ecir;': '\u2256',
753
+ 'Ecirc': '\xca',
754
+ 'ecirc': '\xea',
755
+ 'Ecirc;': '\xca',
756
+ 'ecirc;': '\xea',
757
+ 'ecolon;': '\u2255',
758
+ 'Ecy;': '\u042d',
759
+ 'ecy;': '\u044d',
760
+ 'eDDot;': '\u2a77',
761
+ 'Edot;': '\u0116',
762
+ 'eDot;': '\u2251',
763
+ 'edot;': '\u0117',
764
+ 'ee;': '\u2147',
765
+ 'efDot;': '\u2252',
766
+ 'Efr;': '\U0001d508',
767
+ 'efr;': '\U0001d522',
768
+ 'eg;': '\u2a9a',
769
+ 'Egrave': '\xc8',
770
+ 'egrave': '\xe8',
771
+ 'Egrave;': '\xc8',
772
+ 'egrave;': '\xe8',
773
+ 'egs;': '\u2a96',
774
+ 'egsdot;': '\u2a98',
775
+ 'el;': '\u2a99',
776
+ 'Element;': '\u2208',
777
+ 'elinters;': '\u23e7',
778
+ 'ell;': '\u2113',
779
+ 'els;': '\u2a95',
780
+ 'elsdot;': '\u2a97',
781
+ 'Emacr;': '\u0112',
782
+ 'emacr;': '\u0113',
783
+ 'empty;': '\u2205',
784
+ 'emptyset;': '\u2205',
785
+ 'EmptySmallSquare;': '\u25fb',
786
+ 'emptyv;': '\u2205',
787
+ 'EmptyVerySmallSquare;': '\u25ab',
788
+ 'emsp13;': '\u2004',
789
+ 'emsp14;': '\u2005',
790
+ 'emsp;': '\u2003',
791
+ 'ENG;': '\u014a',
792
+ 'eng;': '\u014b',
793
+ 'ensp;': '\u2002',
794
+ 'Eogon;': '\u0118',
795
+ 'eogon;': '\u0119',
796
+ 'Eopf;': '\U0001d53c',
797
+ 'eopf;': '\U0001d556',
798
+ 'epar;': '\u22d5',
799
+ 'eparsl;': '\u29e3',
800
+ 'eplus;': '\u2a71',
801
+ 'epsi;': '\u03b5',
802
+ 'Epsilon;': '\u0395',
803
+ 'epsilon;': '\u03b5',
804
+ 'epsiv;': '\u03f5',
805
+ 'eqcirc;': '\u2256',
806
+ 'eqcolon;': '\u2255',
807
+ 'eqsim;': '\u2242',
808
+ 'eqslantgtr;': '\u2a96',
809
+ 'eqslantless;': '\u2a95',
810
+ 'Equal;': '\u2a75',
811
+ 'equals;': '=',
812
+ 'EqualTilde;': '\u2242',
813
+ 'equest;': '\u225f',
814
+ 'Equilibrium;': '\u21cc',
815
+ 'equiv;': '\u2261',
816
+ 'equivDD;': '\u2a78',
817
+ 'eqvparsl;': '\u29e5',
818
+ 'erarr;': '\u2971',
819
+ 'erDot;': '\u2253',
820
+ 'Escr;': '\u2130',
821
+ 'escr;': '\u212f',
822
+ 'esdot;': '\u2250',
823
+ 'Esim;': '\u2a73',
824
+ 'esim;': '\u2242',
825
+ 'Eta;': '\u0397',
826
+ 'eta;': '\u03b7',
827
+ 'ETH': '\xd0',
828
+ 'eth': '\xf0',
829
+ 'ETH;': '\xd0',
830
+ 'eth;': '\xf0',
831
+ 'Euml': '\xcb',
832
+ 'euml': '\xeb',
833
+ 'Euml;': '\xcb',
834
+ 'euml;': '\xeb',
835
+ 'euro;': '\u20ac',
836
+ 'excl;': '!',
837
+ 'exist;': '\u2203',
838
+ 'Exists;': '\u2203',
839
+ 'expectation;': '\u2130',
840
+ 'ExponentialE;': '\u2147',
841
+ 'exponentiale;': '\u2147',
842
+ 'fallingdotseq;': '\u2252',
843
+ 'Fcy;': '\u0424',
844
+ 'fcy;': '\u0444',
845
+ 'female;': '\u2640',
846
+ 'ffilig;': '\ufb03',
847
+ 'fflig;': '\ufb00',
848
+ 'ffllig;': '\ufb04',
849
+ 'Ffr;': '\U0001d509',
850
+ 'ffr;': '\U0001d523',
851
+ 'filig;': '\ufb01',
852
+ 'FilledSmallSquare;': '\u25fc',
853
+ 'FilledVerySmallSquare;': '\u25aa',
854
+ 'fjlig;': 'fj',
855
+ 'flat;': '\u266d',
856
+ 'fllig;': '\ufb02',
857
+ 'fltns;': '\u25b1',
858
+ 'fnof;': '\u0192',
859
+ 'Fopf;': '\U0001d53d',
860
+ 'fopf;': '\U0001d557',
861
+ 'ForAll;': '\u2200',
862
+ 'forall;': '\u2200',
863
+ 'fork;': '\u22d4',
864
+ 'forkv;': '\u2ad9',
865
+ 'Fouriertrf;': '\u2131',
866
+ 'fpartint;': '\u2a0d',
867
+ 'frac12': '\xbd',
868
+ 'frac12;': '\xbd',
869
+ 'frac13;': '\u2153',
870
+ 'frac14': '\xbc',
871
+ 'frac14;': '\xbc',
872
+ 'frac15;': '\u2155',
873
+ 'frac16;': '\u2159',
874
+ 'frac18;': '\u215b',
875
+ 'frac23;': '\u2154',
876
+ 'frac25;': '\u2156',
877
+ 'frac34': '\xbe',
878
+ 'frac34;': '\xbe',
879
+ 'frac35;': '\u2157',
880
+ 'frac38;': '\u215c',
881
+ 'frac45;': '\u2158',
882
+ 'frac56;': '\u215a',
883
+ 'frac58;': '\u215d',
884
+ 'frac78;': '\u215e',
885
+ 'frasl;': '\u2044',
886
+ 'frown;': '\u2322',
887
+ 'Fscr;': '\u2131',
888
+ 'fscr;': '\U0001d4bb',
889
+ 'gacute;': '\u01f5',
890
+ 'Gamma;': '\u0393',
891
+ 'gamma;': '\u03b3',
892
+ 'Gammad;': '\u03dc',
893
+ 'gammad;': '\u03dd',
894
+ 'gap;': '\u2a86',
895
+ 'Gbreve;': '\u011e',
896
+ 'gbreve;': '\u011f',
897
+ 'Gcedil;': '\u0122',
898
+ 'Gcirc;': '\u011c',
899
+ 'gcirc;': '\u011d',
900
+ 'Gcy;': '\u0413',
901
+ 'gcy;': '\u0433',
902
+ 'Gdot;': '\u0120',
903
+ 'gdot;': '\u0121',
904
+ 'gE;': '\u2267',
905
+ 'ge;': '\u2265',
906
+ 'gEl;': '\u2a8c',
907
+ 'gel;': '\u22db',
908
+ 'geq;': '\u2265',
909
+ 'geqq;': '\u2267',
910
+ 'geqslant;': '\u2a7e',
911
+ 'ges;': '\u2a7e',
912
+ 'gescc;': '\u2aa9',
913
+ 'gesdot;': '\u2a80',
914
+ 'gesdoto;': '\u2a82',
915
+ 'gesdotol;': '\u2a84',
916
+ 'gesl;': '\u22db\ufe00',
917
+ 'gesles;': '\u2a94',
918
+ 'Gfr;': '\U0001d50a',
919
+ 'gfr;': '\U0001d524',
920
+ 'Gg;': '\u22d9',
921
+ 'gg;': '\u226b',
922
+ 'ggg;': '\u22d9',
923
+ 'gimel;': '\u2137',
924
+ 'GJcy;': '\u0403',
925
+ 'gjcy;': '\u0453',
926
+ 'gl;': '\u2277',
927
+ 'gla;': '\u2aa5',
928
+ 'glE;': '\u2a92',
929
+ 'glj;': '\u2aa4',
930
+ 'gnap;': '\u2a8a',
931
+ 'gnapprox;': '\u2a8a',
932
+ 'gnE;': '\u2269',
933
+ 'gne;': '\u2a88',
934
+ 'gneq;': '\u2a88',
935
+ 'gneqq;': '\u2269',
936
+ 'gnsim;': '\u22e7',
937
+ 'Gopf;': '\U0001d53e',
938
+ 'gopf;': '\U0001d558',
939
+ 'grave;': '`',
940
+ 'GreaterEqual;': '\u2265',
941
+ 'GreaterEqualLess;': '\u22db',
942
+ 'GreaterFullEqual;': '\u2267',
943
+ 'GreaterGreater;': '\u2aa2',
944
+ 'GreaterLess;': '\u2277',
945
+ 'GreaterSlantEqual;': '\u2a7e',
946
+ 'GreaterTilde;': '\u2273',
947
+ 'Gscr;': '\U0001d4a2',
948
+ 'gscr;': '\u210a',
949
+ 'gsim;': '\u2273',
950
+ 'gsime;': '\u2a8e',
951
+ 'gsiml;': '\u2a90',
952
+ 'GT': '>',
953
+ 'gt': '>',
954
+ 'GT;': '>',
955
+ 'Gt;': '\u226b',
956
+ 'gt;': '>',
957
+ 'gtcc;': '\u2aa7',
958
+ 'gtcir;': '\u2a7a',
959
+ 'gtdot;': '\u22d7',
960
+ 'gtlPar;': '\u2995',
961
+ 'gtquest;': '\u2a7c',
962
+ 'gtrapprox;': '\u2a86',
963
+ 'gtrarr;': '\u2978',
964
+ 'gtrdot;': '\u22d7',
965
+ 'gtreqless;': '\u22db',
966
+ 'gtreqqless;': '\u2a8c',
967
+ 'gtrless;': '\u2277',
968
+ 'gtrsim;': '\u2273',
969
+ 'gvertneqq;': '\u2269\ufe00',
970
+ 'gvnE;': '\u2269\ufe00',
971
+ 'Hacek;': '\u02c7',
972
+ 'hairsp;': '\u200a',
973
+ 'half;': '\xbd',
974
+ 'hamilt;': '\u210b',
975
+ 'HARDcy;': '\u042a',
976
+ 'hardcy;': '\u044a',
977
+ 'hArr;': '\u21d4',
978
+ 'harr;': '\u2194',
979
+ 'harrcir;': '\u2948',
980
+ 'harrw;': '\u21ad',
981
+ 'Hat;': '^',
982
+ 'hbar;': '\u210f',
983
+ 'Hcirc;': '\u0124',
984
+ 'hcirc;': '\u0125',
985
+ 'hearts;': '\u2665',
986
+ 'heartsuit;': '\u2665',
987
+ 'hellip;': '\u2026',
988
+ 'hercon;': '\u22b9',
989
+ 'Hfr;': '\u210c',
990
+ 'hfr;': '\U0001d525',
991
+ 'HilbertSpace;': '\u210b',
992
+ 'hksearow;': '\u2925',
993
+ 'hkswarow;': '\u2926',
994
+ 'hoarr;': '\u21ff',
995
+ 'homtht;': '\u223b',
996
+ 'hookleftarrow;': '\u21a9',
997
+ 'hookrightarrow;': '\u21aa',
998
+ 'Hopf;': '\u210d',
999
+ 'hopf;': '\U0001d559',
1000
+ 'horbar;': '\u2015',
1001
+ 'HorizontalLine;': '\u2500',
1002
+ 'Hscr;': '\u210b',
1003
+ 'hscr;': '\U0001d4bd',
1004
+ 'hslash;': '\u210f',
1005
+ 'Hstrok;': '\u0126',
1006
+ 'hstrok;': '\u0127',
1007
+ 'HumpDownHump;': '\u224e',
1008
+ 'HumpEqual;': '\u224f',
1009
+ 'hybull;': '\u2043',
1010
+ 'hyphen;': '\u2010',
1011
+ 'Iacute': '\xcd',
1012
+ 'iacute': '\xed',
1013
+ 'Iacute;': '\xcd',
1014
+ 'iacute;': '\xed',
1015
+ 'ic;': '\u2063',
1016
+ 'Icirc': '\xce',
1017
+ 'icirc': '\xee',
1018
+ 'Icirc;': '\xce',
1019
+ 'icirc;': '\xee',
1020
+ 'Icy;': '\u0418',
1021
+ 'icy;': '\u0438',
1022
+ 'Idot;': '\u0130',
1023
+ 'IEcy;': '\u0415',
1024
+ 'iecy;': '\u0435',
1025
+ 'iexcl': '\xa1',
1026
+ 'iexcl;': '\xa1',
1027
+ 'iff;': '\u21d4',
1028
+ 'Ifr;': '\u2111',
1029
+ 'ifr;': '\U0001d526',
1030
+ 'Igrave': '\xcc',
1031
+ 'igrave': '\xec',
1032
+ 'Igrave;': '\xcc',
1033
+ 'igrave;': '\xec',
1034
+ 'ii;': '\u2148',
1035
+ 'iiiint;': '\u2a0c',
1036
+ 'iiint;': '\u222d',
1037
+ 'iinfin;': '\u29dc',
1038
+ 'iiota;': '\u2129',
1039
+ 'IJlig;': '\u0132',
1040
+ 'ijlig;': '\u0133',
1041
+ 'Im;': '\u2111',
1042
+ 'Imacr;': '\u012a',
1043
+ 'imacr;': '\u012b',
1044
+ 'image;': '\u2111',
1045
+ 'ImaginaryI;': '\u2148',
1046
+ 'imagline;': '\u2110',
1047
+ 'imagpart;': '\u2111',
1048
+ 'imath;': '\u0131',
1049
+ 'imof;': '\u22b7',
1050
+ 'imped;': '\u01b5',
1051
+ 'Implies;': '\u21d2',
1052
+ 'in;': '\u2208',
1053
+ 'incare;': '\u2105',
1054
+ 'infin;': '\u221e',
1055
+ 'infintie;': '\u29dd',
1056
+ 'inodot;': '\u0131',
1057
+ 'Int;': '\u222c',
1058
+ 'int;': '\u222b',
1059
+ 'intcal;': '\u22ba',
1060
+ 'integers;': '\u2124',
1061
+ 'Integral;': '\u222b',
1062
+ 'intercal;': '\u22ba',
1063
+ 'Intersection;': '\u22c2',
1064
+ 'intlarhk;': '\u2a17',
1065
+ 'intprod;': '\u2a3c',
1066
+ 'InvisibleComma;': '\u2063',
1067
+ 'InvisibleTimes;': '\u2062',
1068
+ 'IOcy;': '\u0401',
1069
+ 'iocy;': '\u0451',
1070
+ 'Iogon;': '\u012e',
1071
+ 'iogon;': '\u012f',
1072
+ 'Iopf;': '\U0001d540',
1073
+ 'iopf;': '\U0001d55a',
1074
+ 'Iota;': '\u0399',
1075
+ 'iota;': '\u03b9',
1076
+ 'iprod;': '\u2a3c',
1077
+ 'iquest': '\xbf',
1078
+ 'iquest;': '\xbf',
1079
+ 'Iscr;': '\u2110',
1080
+ 'iscr;': '\U0001d4be',
1081
+ 'isin;': '\u2208',
1082
+ 'isindot;': '\u22f5',
1083
+ 'isinE;': '\u22f9',
1084
+ 'isins;': '\u22f4',
1085
+ 'isinsv;': '\u22f3',
1086
+ 'isinv;': '\u2208',
1087
+ 'it;': '\u2062',
1088
+ 'Itilde;': '\u0128',
1089
+ 'itilde;': '\u0129',
1090
+ 'Iukcy;': '\u0406',
1091
+ 'iukcy;': '\u0456',
1092
+ 'Iuml': '\xcf',
1093
+ 'iuml': '\xef',
1094
+ 'Iuml;': '\xcf',
1095
+ 'iuml;': '\xef',
1096
+ 'Jcirc;': '\u0134',
1097
+ 'jcirc;': '\u0135',
1098
+ 'Jcy;': '\u0419',
1099
+ 'jcy;': '\u0439',
1100
+ 'Jfr;': '\U0001d50d',
1101
+ 'jfr;': '\U0001d527',
1102
+ 'jmath;': '\u0237',
1103
+ 'Jopf;': '\U0001d541',
1104
+ 'jopf;': '\U0001d55b',
1105
+ 'Jscr;': '\U0001d4a5',
1106
+ 'jscr;': '\U0001d4bf',
1107
+ 'Jsercy;': '\u0408',
1108
+ 'jsercy;': '\u0458',
1109
+ 'Jukcy;': '\u0404',
1110
+ 'jukcy;': '\u0454',
1111
+ 'Kappa;': '\u039a',
1112
+ 'kappa;': '\u03ba',
1113
+ 'kappav;': '\u03f0',
1114
+ 'Kcedil;': '\u0136',
1115
+ 'kcedil;': '\u0137',
1116
+ 'Kcy;': '\u041a',
1117
+ 'kcy;': '\u043a',
1118
+ 'Kfr;': '\U0001d50e',
1119
+ 'kfr;': '\U0001d528',
1120
+ 'kgreen;': '\u0138',
1121
+ 'KHcy;': '\u0425',
1122
+ 'khcy;': '\u0445',
1123
+ 'KJcy;': '\u040c',
1124
+ 'kjcy;': '\u045c',
1125
+ 'Kopf;': '\U0001d542',
1126
+ 'kopf;': '\U0001d55c',
1127
+ 'Kscr;': '\U0001d4a6',
1128
+ 'kscr;': '\U0001d4c0',
1129
+ 'lAarr;': '\u21da',
1130
+ 'Lacute;': '\u0139',
1131
+ 'lacute;': '\u013a',
1132
+ 'laemptyv;': '\u29b4',
1133
+ 'lagran;': '\u2112',
1134
+ 'Lambda;': '\u039b',
1135
+ 'lambda;': '\u03bb',
1136
+ 'Lang;': '\u27ea',
1137
+ 'lang;': '\u27e8',
1138
+ 'langd;': '\u2991',
1139
+ 'langle;': '\u27e8',
1140
+ 'lap;': '\u2a85',
1141
+ 'Laplacetrf;': '\u2112',
1142
+ 'laquo': '\xab',
1143
+ 'laquo;': '\xab',
1144
+ 'Larr;': '\u219e',
1145
+ 'lArr;': '\u21d0',
1146
+ 'larr;': '\u2190',
1147
+ 'larrb;': '\u21e4',
1148
+ 'larrbfs;': '\u291f',
1149
+ 'larrfs;': '\u291d',
1150
+ 'larrhk;': '\u21a9',
1151
+ 'larrlp;': '\u21ab',
1152
+ 'larrpl;': '\u2939',
1153
+ 'larrsim;': '\u2973',
1154
+ 'larrtl;': '\u21a2',
1155
+ 'lat;': '\u2aab',
1156
+ 'lAtail;': '\u291b',
1157
+ 'latail;': '\u2919',
1158
+ 'late;': '\u2aad',
1159
+ 'lates;': '\u2aad\ufe00',
1160
+ 'lBarr;': '\u290e',
1161
+ 'lbarr;': '\u290c',
1162
+ 'lbbrk;': '\u2772',
1163
+ 'lbrace;': '{',
1164
+ 'lbrack;': '[',
1165
+ 'lbrke;': '\u298b',
1166
+ 'lbrksld;': '\u298f',
1167
+ 'lbrkslu;': '\u298d',
1168
+ 'Lcaron;': '\u013d',
1169
+ 'lcaron;': '\u013e',
1170
+ 'Lcedil;': '\u013b',
1171
+ 'lcedil;': '\u013c',
1172
+ 'lceil;': '\u2308',
1173
+ 'lcub;': '{',
1174
+ 'Lcy;': '\u041b',
1175
+ 'lcy;': '\u043b',
1176
+ 'ldca;': '\u2936',
1177
+ 'ldquo;': '\u201c',
1178
+ 'ldquor;': '\u201e',
1179
+ 'ldrdhar;': '\u2967',
1180
+ 'ldrushar;': '\u294b',
1181
+ 'ldsh;': '\u21b2',
1182
+ 'lE;': '\u2266',
1183
+ 'le;': '\u2264',
1184
+ 'LeftAngleBracket;': '\u27e8',
1185
+ 'LeftArrow;': '\u2190',
1186
+ 'Leftarrow;': '\u21d0',
1187
+ 'leftarrow;': '\u2190',
1188
+ 'LeftArrowBar;': '\u21e4',
1189
+ 'LeftArrowRightArrow;': '\u21c6',
1190
+ 'leftarrowtail;': '\u21a2',
1191
+ 'LeftCeiling;': '\u2308',
1192
+ 'LeftDoubleBracket;': '\u27e6',
1193
+ 'LeftDownTeeVector;': '\u2961',
1194
+ 'LeftDownVector;': '\u21c3',
1195
+ 'LeftDownVectorBar;': '\u2959',
1196
+ 'LeftFloor;': '\u230a',
1197
+ 'leftharpoondown;': '\u21bd',
1198
+ 'leftharpoonup;': '\u21bc',
1199
+ 'leftleftarrows;': '\u21c7',
1200
+ 'LeftRightArrow;': '\u2194',
1201
+ 'Leftrightarrow;': '\u21d4',
1202
+ 'leftrightarrow;': '\u2194',
1203
+ 'leftrightarrows;': '\u21c6',
1204
+ 'leftrightharpoons;': '\u21cb',
1205
+ 'leftrightsquigarrow;': '\u21ad',
1206
+ 'LeftRightVector;': '\u294e',
1207
+ 'LeftTee;': '\u22a3',
1208
+ 'LeftTeeArrow;': '\u21a4',
1209
+ 'LeftTeeVector;': '\u295a',
1210
+ 'leftthreetimes;': '\u22cb',
1211
+ 'LeftTriangle;': '\u22b2',
1212
+ 'LeftTriangleBar;': '\u29cf',
1213
+ 'LeftTriangleEqual;': '\u22b4',
1214
+ 'LeftUpDownVector;': '\u2951',
1215
+ 'LeftUpTeeVector;': '\u2960',
1216
+ 'LeftUpVector;': '\u21bf',
1217
+ 'LeftUpVectorBar;': '\u2958',
1218
+ 'LeftVector;': '\u21bc',
1219
+ 'LeftVectorBar;': '\u2952',
1220
+ 'lEg;': '\u2a8b',
1221
+ 'leg;': '\u22da',
1222
+ 'leq;': '\u2264',
1223
+ 'leqq;': '\u2266',
1224
+ 'leqslant;': '\u2a7d',
1225
+ 'les;': '\u2a7d',
1226
+ 'lescc;': '\u2aa8',
1227
+ 'lesdot;': '\u2a7f',
1228
+ 'lesdoto;': '\u2a81',
1229
+ 'lesdotor;': '\u2a83',
1230
+ 'lesg;': '\u22da\ufe00',
1231
+ 'lesges;': '\u2a93',
1232
+ 'lessapprox;': '\u2a85',
1233
+ 'lessdot;': '\u22d6',
1234
+ 'lesseqgtr;': '\u22da',
1235
+ 'lesseqqgtr;': '\u2a8b',
1236
+ 'LessEqualGreater;': '\u22da',
1237
+ 'LessFullEqual;': '\u2266',
1238
+ 'LessGreater;': '\u2276',
1239
+ 'lessgtr;': '\u2276',
1240
+ 'LessLess;': '\u2aa1',
1241
+ 'lesssim;': '\u2272',
1242
+ 'LessSlantEqual;': '\u2a7d',
1243
+ 'LessTilde;': '\u2272',
1244
+ 'lfisht;': '\u297c',
1245
+ 'lfloor;': '\u230a',
1246
+ 'Lfr;': '\U0001d50f',
1247
+ 'lfr;': '\U0001d529',
1248
+ 'lg;': '\u2276',
1249
+ 'lgE;': '\u2a91',
1250
+ 'lHar;': '\u2962',
1251
+ 'lhard;': '\u21bd',
1252
+ 'lharu;': '\u21bc',
1253
+ 'lharul;': '\u296a',
1254
+ 'lhblk;': '\u2584',
1255
+ 'LJcy;': '\u0409',
1256
+ 'ljcy;': '\u0459',
1257
+ 'Ll;': '\u22d8',
1258
+ 'll;': '\u226a',
1259
+ 'llarr;': '\u21c7',
1260
+ 'llcorner;': '\u231e',
1261
+ 'Lleftarrow;': '\u21da',
1262
+ 'llhard;': '\u296b',
1263
+ 'lltri;': '\u25fa',
1264
+ 'Lmidot;': '\u013f',
1265
+ 'lmidot;': '\u0140',
1266
+ 'lmoust;': '\u23b0',
1267
+ 'lmoustache;': '\u23b0',
1268
+ 'lnap;': '\u2a89',
1269
+ 'lnapprox;': '\u2a89',
1270
+ 'lnE;': '\u2268',
1271
+ 'lne;': '\u2a87',
1272
+ 'lneq;': '\u2a87',
1273
+ 'lneqq;': '\u2268',
1274
+ 'lnsim;': '\u22e6',
1275
+ 'loang;': '\u27ec',
1276
+ 'loarr;': '\u21fd',
1277
+ 'lobrk;': '\u27e6',
1278
+ 'LongLeftArrow;': '\u27f5',
1279
+ 'Longleftarrow;': '\u27f8',
1280
+ 'longleftarrow;': '\u27f5',
1281
+ 'LongLeftRightArrow;': '\u27f7',
1282
+ 'Longleftrightarrow;': '\u27fa',
1283
+ 'longleftrightarrow;': '\u27f7',
1284
+ 'longmapsto;': '\u27fc',
1285
+ 'LongRightArrow;': '\u27f6',
1286
+ 'Longrightarrow;': '\u27f9',
1287
+ 'longrightarrow;': '\u27f6',
1288
+ 'looparrowleft;': '\u21ab',
1289
+ 'looparrowright;': '\u21ac',
1290
+ 'lopar;': '\u2985',
1291
+ 'Lopf;': '\U0001d543',
1292
+ 'lopf;': '\U0001d55d',
1293
+ 'loplus;': '\u2a2d',
1294
+ 'lotimes;': '\u2a34',
1295
+ 'lowast;': '\u2217',
1296
+ 'lowbar;': '_',
1297
+ 'LowerLeftArrow;': '\u2199',
1298
+ 'LowerRightArrow;': '\u2198',
1299
+ 'loz;': '\u25ca',
1300
+ 'lozenge;': '\u25ca',
1301
+ 'lozf;': '\u29eb',
1302
+ 'lpar;': '(',
1303
+ 'lparlt;': '\u2993',
1304
+ 'lrarr;': '\u21c6',
1305
+ 'lrcorner;': '\u231f',
1306
+ 'lrhar;': '\u21cb',
1307
+ 'lrhard;': '\u296d',
1308
+ 'lrm;': '\u200e',
1309
+ 'lrtri;': '\u22bf',
1310
+ 'lsaquo;': '\u2039',
1311
+ 'Lscr;': '\u2112',
1312
+ 'lscr;': '\U0001d4c1',
1313
+ 'Lsh;': '\u21b0',
1314
+ 'lsh;': '\u21b0',
1315
+ 'lsim;': '\u2272',
1316
+ 'lsime;': '\u2a8d',
1317
+ 'lsimg;': '\u2a8f',
1318
+ 'lsqb;': '[',
1319
+ 'lsquo;': '\u2018',
1320
+ 'lsquor;': '\u201a',
1321
+ 'Lstrok;': '\u0141',
1322
+ 'lstrok;': '\u0142',
1323
+ 'LT': '<',
1324
+ 'lt': '<',
1325
+ 'LT;': '<',
1326
+ 'Lt;': '\u226a',
1327
+ 'lt;': '<',
1328
+ 'ltcc;': '\u2aa6',
1329
+ 'ltcir;': '\u2a79',
1330
+ 'ltdot;': '\u22d6',
1331
+ 'lthree;': '\u22cb',
1332
+ 'ltimes;': '\u22c9',
1333
+ 'ltlarr;': '\u2976',
1334
+ 'ltquest;': '\u2a7b',
1335
+ 'ltri;': '\u25c3',
1336
+ 'ltrie;': '\u22b4',
1337
+ 'ltrif;': '\u25c2',
1338
+ 'ltrPar;': '\u2996',
1339
+ 'lurdshar;': '\u294a',
1340
+ 'luruhar;': '\u2966',
1341
+ 'lvertneqq;': '\u2268\ufe00',
1342
+ 'lvnE;': '\u2268\ufe00',
1343
+ 'macr': '\xaf',
1344
+ 'macr;': '\xaf',
1345
+ 'male;': '\u2642',
1346
+ 'malt;': '\u2720',
1347
+ 'maltese;': '\u2720',
1348
+ 'Map;': '\u2905',
1349
+ 'map;': '\u21a6',
1350
+ 'mapsto;': '\u21a6',
1351
+ 'mapstodown;': '\u21a7',
1352
+ 'mapstoleft;': '\u21a4',
1353
+ 'mapstoup;': '\u21a5',
1354
+ 'marker;': '\u25ae',
1355
+ 'mcomma;': '\u2a29',
1356
+ 'Mcy;': '\u041c',
1357
+ 'mcy;': '\u043c',
1358
+ 'mdash;': '\u2014',
1359
+ 'mDDot;': '\u223a',
1360
+ 'measuredangle;': '\u2221',
1361
+ 'MediumSpace;': '\u205f',
1362
+ 'Mellintrf;': '\u2133',
1363
+ 'Mfr;': '\U0001d510',
1364
+ 'mfr;': '\U0001d52a',
1365
+ 'mho;': '\u2127',
1366
+ 'micro': '\xb5',
1367
+ 'micro;': '\xb5',
1368
+ 'mid;': '\u2223',
1369
+ 'midast;': '*',
1370
+ 'midcir;': '\u2af0',
1371
+ 'middot': '\xb7',
1372
+ 'middot;': '\xb7',
1373
+ 'minus;': '\u2212',
1374
+ 'minusb;': '\u229f',
1375
+ 'minusd;': '\u2238',
1376
+ 'minusdu;': '\u2a2a',
1377
+ 'MinusPlus;': '\u2213',
1378
+ 'mlcp;': '\u2adb',
1379
+ 'mldr;': '\u2026',
1380
+ 'mnplus;': '\u2213',
1381
+ 'models;': '\u22a7',
1382
+ 'Mopf;': '\U0001d544',
1383
+ 'mopf;': '\U0001d55e',
1384
+ 'mp;': '\u2213',
1385
+ 'Mscr;': '\u2133',
1386
+ 'mscr;': '\U0001d4c2',
1387
+ 'mstpos;': '\u223e',
1388
+ 'Mu;': '\u039c',
1389
+ 'mu;': '\u03bc',
1390
+ 'multimap;': '\u22b8',
1391
+ 'mumap;': '\u22b8',
1392
+ 'nabla;': '\u2207',
1393
+ 'Nacute;': '\u0143',
1394
+ 'nacute;': '\u0144',
1395
+ 'nang;': '\u2220\u20d2',
1396
+ 'nap;': '\u2249',
1397
+ 'napE;': '\u2a70\u0338',
1398
+ 'napid;': '\u224b\u0338',
1399
+ 'napos;': '\u0149',
1400
+ 'napprox;': '\u2249',
1401
+ 'natur;': '\u266e',
1402
+ 'natural;': '\u266e',
1403
+ 'naturals;': '\u2115',
1404
+ 'nbsp': '\xa0',
1405
+ 'nbsp;': '\xa0',
1406
+ 'nbump;': '\u224e\u0338',
1407
+ 'nbumpe;': '\u224f\u0338',
1408
+ 'ncap;': '\u2a43',
1409
+ 'Ncaron;': '\u0147',
1410
+ 'ncaron;': '\u0148',
1411
+ 'Ncedil;': '\u0145',
1412
+ 'ncedil;': '\u0146',
1413
+ 'ncong;': '\u2247',
1414
+ 'ncongdot;': '\u2a6d\u0338',
1415
+ 'ncup;': '\u2a42',
1416
+ 'Ncy;': '\u041d',
1417
+ 'ncy;': '\u043d',
1418
+ 'ndash;': '\u2013',
1419
+ 'ne;': '\u2260',
1420
+ 'nearhk;': '\u2924',
1421
+ 'neArr;': '\u21d7',
1422
+ 'nearr;': '\u2197',
1423
+ 'nearrow;': '\u2197',
1424
+ 'nedot;': '\u2250\u0338',
1425
+ 'NegativeMediumSpace;': '\u200b',
1426
+ 'NegativeThickSpace;': '\u200b',
1427
+ 'NegativeThinSpace;': '\u200b',
1428
+ 'NegativeVeryThinSpace;': '\u200b',
1429
+ 'nequiv;': '\u2262',
1430
+ 'nesear;': '\u2928',
1431
+ 'nesim;': '\u2242\u0338',
1432
+ 'NestedGreaterGreater;': '\u226b',
1433
+ 'NestedLessLess;': '\u226a',
1434
+ 'NewLine;': '\n',
1435
+ 'nexist;': '\u2204',
1436
+ 'nexists;': '\u2204',
1437
+ 'Nfr;': '\U0001d511',
1438
+ 'nfr;': '\U0001d52b',
1439
+ 'ngE;': '\u2267\u0338',
1440
+ 'nge;': '\u2271',
1441
+ 'ngeq;': '\u2271',
1442
+ 'ngeqq;': '\u2267\u0338',
1443
+ 'ngeqslant;': '\u2a7e\u0338',
1444
+ 'nges;': '\u2a7e\u0338',
1445
+ 'nGg;': '\u22d9\u0338',
1446
+ 'ngsim;': '\u2275',
1447
+ 'nGt;': '\u226b\u20d2',
1448
+ 'ngt;': '\u226f',
1449
+ 'ngtr;': '\u226f',
1450
+ 'nGtv;': '\u226b\u0338',
1451
+ 'nhArr;': '\u21ce',
1452
+ 'nharr;': '\u21ae',
1453
+ 'nhpar;': '\u2af2',
1454
+ 'ni;': '\u220b',
1455
+ 'nis;': '\u22fc',
1456
+ 'nisd;': '\u22fa',
1457
+ 'niv;': '\u220b',
1458
+ 'NJcy;': '\u040a',
1459
+ 'njcy;': '\u045a',
1460
+ 'nlArr;': '\u21cd',
1461
+ 'nlarr;': '\u219a',
1462
+ 'nldr;': '\u2025',
1463
+ 'nlE;': '\u2266\u0338',
1464
+ 'nle;': '\u2270',
1465
+ 'nLeftarrow;': '\u21cd',
1466
+ 'nleftarrow;': '\u219a',
1467
+ 'nLeftrightarrow;': '\u21ce',
1468
+ 'nleftrightarrow;': '\u21ae',
1469
+ 'nleq;': '\u2270',
1470
+ 'nleqq;': '\u2266\u0338',
1471
+ 'nleqslant;': '\u2a7d\u0338',
1472
+ 'nles;': '\u2a7d\u0338',
1473
+ 'nless;': '\u226e',
1474
+ 'nLl;': '\u22d8\u0338',
1475
+ 'nlsim;': '\u2274',
1476
+ 'nLt;': '\u226a\u20d2',
1477
+ 'nlt;': '\u226e',
1478
+ 'nltri;': '\u22ea',
1479
+ 'nltrie;': '\u22ec',
1480
+ 'nLtv;': '\u226a\u0338',
1481
+ 'nmid;': '\u2224',
1482
+ 'NoBreak;': '\u2060',
1483
+ 'NonBreakingSpace;': '\xa0',
1484
+ 'Nopf;': '\u2115',
1485
+ 'nopf;': '\U0001d55f',
1486
+ 'not': '\xac',
1487
+ 'Not;': '\u2aec',
1488
+ 'not;': '\xac',
1489
+ 'NotCongruent;': '\u2262',
1490
+ 'NotCupCap;': '\u226d',
1491
+ 'NotDoubleVerticalBar;': '\u2226',
1492
+ 'NotElement;': '\u2209',
1493
+ 'NotEqual;': '\u2260',
1494
+ 'NotEqualTilde;': '\u2242\u0338',
1495
+ 'NotExists;': '\u2204',
1496
+ 'NotGreater;': '\u226f',
1497
+ 'NotGreaterEqual;': '\u2271',
1498
+ 'NotGreaterFullEqual;': '\u2267\u0338',
1499
+ 'NotGreaterGreater;': '\u226b\u0338',
1500
+ 'NotGreaterLess;': '\u2279',
1501
+ 'NotGreaterSlantEqual;': '\u2a7e\u0338',
1502
+ 'NotGreaterTilde;': '\u2275',
1503
+ 'NotHumpDownHump;': '\u224e\u0338',
1504
+ 'NotHumpEqual;': '\u224f\u0338',
1505
+ 'notin;': '\u2209',
1506
+ 'notindot;': '\u22f5\u0338',
1507
+ 'notinE;': '\u22f9\u0338',
1508
+ 'notinva;': '\u2209',
1509
+ 'notinvb;': '\u22f7',
1510
+ 'notinvc;': '\u22f6',
1511
+ 'NotLeftTriangle;': '\u22ea',
1512
+ 'NotLeftTriangleBar;': '\u29cf\u0338',
1513
+ 'NotLeftTriangleEqual;': '\u22ec',
1514
+ 'NotLess;': '\u226e',
1515
+ 'NotLessEqual;': '\u2270',
1516
+ 'NotLessGreater;': '\u2278',
1517
+ 'NotLessLess;': '\u226a\u0338',
1518
+ 'NotLessSlantEqual;': '\u2a7d\u0338',
1519
+ 'NotLessTilde;': '\u2274',
1520
+ 'NotNestedGreaterGreater;': '\u2aa2\u0338',
1521
+ 'NotNestedLessLess;': '\u2aa1\u0338',
1522
+ 'notni;': '\u220c',
1523
+ 'notniva;': '\u220c',
1524
+ 'notnivb;': '\u22fe',
1525
+ 'notnivc;': '\u22fd',
1526
+ 'NotPrecedes;': '\u2280',
1527
+ 'NotPrecedesEqual;': '\u2aaf\u0338',
1528
+ 'NotPrecedesSlantEqual;': '\u22e0',
1529
+ 'NotReverseElement;': '\u220c',
1530
+ 'NotRightTriangle;': '\u22eb',
1531
+ 'NotRightTriangleBar;': '\u29d0\u0338',
1532
+ 'NotRightTriangleEqual;': '\u22ed',
1533
+ 'NotSquareSubset;': '\u228f\u0338',
1534
+ 'NotSquareSubsetEqual;': '\u22e2',
1535
+ 'NotSquareSuperset;': '\u2290\u0338',
1536
+ 'NotSquareSupersetEqual;': '\u22e3',
1537
+ 'NotSubset;': '\u2282\u20d2',
1538
+ 'NotSubsetEqual;': '\u2288',
1539
+ 'NotSucceeds;': '\u2281',
1540
+ 'NotSucceedsEqual;': '\u2ab0\u0338',
1541
+ 'NotSucceedsSlantEqual;': '\u22e1',
1542
+ 'NotSucceedsTilde;': '\u227f\u0338',
1543
+ 'NotSuperset;': '\u2283\u20d2',
1544
+ 'NotSupersetEqual;': '\u2289',
1545
+ 'NotTilde;': '\u2241',
1546
+ 'NotTildeEqual;': '\u2244',
1547
+ 'NotTildeFullEqual;': '\u2247',
1548
+ 'NotTildeTilde;': '\u2249',
1549
+ 'NotVerticalBar;': '\u2224',
1550
+ 'npar;': '\u2226',
1551
+ 'nparallel;': '\u2226',
1552
+ 'nparsl;': '\u2afd\u20e5',
1553
+ 'npart;': '\u2202\u0338',
1554
+ 'npolint;': '\u2a14',
1555
+ 'npr;': '\u2280',
1556
+ 'nprcue;': '\u22e0',
1557
+ 'npre;': '\u2aaf\u0338',
1558
+ 'nprec;': '\u2280',
1559
+ 'npreceq;': '\u2aaf\u0338',
1560
+ 'nrArr;': '\u21cf',
1561
+ 'nrarr;': '\u219b',
1562
+ 'nrarrc;': '\u2933\u0338',
1563
+ 'nrarrw;': '\u219d\u0338',
1564
+ 'nRightarrow;': '\u21cf',
1565
+ 'nrightarrow;': '\u219b',
1566
+ 'nrtri;': '\u22eb',
1567
+ 'nrtrie;': '\u22ed',
1568
+ 'nsc;': '\u2281',
1569
+ 'nsccue;': '\u22e1',
1570
+ 'nsce;': '\u2ab0\u0338',
1571
+ 'Nscr;': '\U0001d4a9',
1572
+ 'nscr;': '\U0001d4c3',
1573
+ 'nshortmid;': '\u2224',
1574
+ 'nshortparallel;': '\u2226',
1575
+ 'nsim;': '\u2241',
1576
+ 'nsime;': '\u2244',
1577
+ 'nsimeq;': '\u2244',
1578
+ 'nsmid;': '\u2224',
1579
+ 'nspar;': '\u2226',
1580
+ 'nsqsube;': '\u22e2',
1581
+ 'nsqsupe;': '\u22e3',
1582
+ 'nsub;': '\u2284',
1583
+ 'nsubE;': '\u2ac5\u0338',
1584
+ 'nsube;': '\u2288',
1585
+ 'nsubset;': '\u2282\u20d2',
1586
+ 'nsubseteq;': '\u2288',
1587
+ 'nsubseteqq;': '\u2ac5\u0338',
1588
+ 'nsucc;': '\u2281',
1589
+ 'nsucceq;': '\u2ab0\u0338',
1590
+ 'nsup;': '\u2285',
1591
+ 'nsupE;': '\u2ac6\u0338',
1592
+ 'nsupe;': '\u2289',
1593
+ 'nsupset;': '\u2283\u20d2',
1594
+ 'nsupseteq;': '\u2289',
1595
+ 'nsupseteqq;': '\u2ac6\u0338',
1596
+ 'ntgl;': '\u2279',
1597
+ 'Ntilde': '\xd1',
1598
+ 'ntilde': '\xf1',
1599
+ 'Ntilde;': '\xd1',
1600
+ 'ntilde;': '\xf1',
1601
+ 'ntlg;': '\u2278',
1602
+ 'ntriangleleft;': '\u22ea',
1603
+ 'ntrianglelefteq;': '\u22ec',
1604
+ 'ntriangleright;': '\u22eb',
1605
+ 'ntrianglerighteq;': '\u22ed',
1606
+ 'Nu;': '\u039d',
1607
+ 'nu;': '\u03bd',
1608
+ 'num;': '#',
1609
+ 'numero;': '\u2116',
1610
+ 'numsp;': '\u2007',
1611
+ 'nvap;': '\u224d\u20d2',
1612
+ 'nVDash;': '\u22af',
1613
+ 'nVdash;': '\u22ae',
1614
+ 'nvDash;': '\u22ad',
1615
+ 'nvdash;': '\u22ac',
1616
+ 'nvge;': '\u2265\u20d2',
1617
+ 'nvgt;': '>\u20d2',
1618
+ 'nvHarr;': '\u2904',
1619
+ 'nvinfin;': '\u29de',
1620
+ 'nvlArr;': '\u2902',
1621
+ 'nvle;': '\u2264\u20d2',
1622
+ 'nvlt;': '<\u20d2',
1623
+ 'nvltrie;': '\u22b4\u20d2',
1624
+ 'nvrArr;': '\u2903',
1625
+ 'nvrtrie;': '\u22b5\u20d2',
1626
+ 'nvsim;': '\u223c\u20d2',
1627
+ 'nwarhk;': '\u2923',
1628
+ 'nwArr;': '\u21d6',
1629
+ 'nwarr;': '\u2196',
1630
+ 'nwarrow;': '\u2196',
1631
+ 'nwnear;': '\u2927',
1632
+ 'Oacute': '\xd3',
1633
+ 'oacute': '\xf3',
1634
+ 'Oacute;': '\xd3',
1635
+ 'oacute;': '\xf3',
1636
+ 'oast;': '\u229b',
1637
+ 'ocir;': '\u229a',
1638
+ 'Ocirc': '\xd4',
1639
+ 'ocirc': '\xf4',
1640
+ 'Ocirc;': '\xd4',
1641
+ 'ocirc;': '\xf4',
1642
+ 'Ocy;': '\u041e',
1643
+ 'ocy;': '\u043e',
1644
+ 'odash;': '\u229d',
1645
+ 'Odblac;': '\u0150',
1646
+ 'odblac;': '\u0151',
1647
+ 'odiv;': '\u2a38',
1648
+ 'odot;': '\u2299',
1649
+ 'odsold;': '\u29bc',
1650
+ 'OElig;': '\u0152',
1651
+ 'oelig;': '\u0153',
1652
+ 'ofcir;': '\u29bf',
1653
+ 'Ofr;': '\U0001d512',
1654
+ 'ofr;': '\U0001d52c',
1655
+ 'ogon;': '\u02db',
1656
+ 'Ograve': '\xd2',
1657
+ 'ograve': '\xf2',
1658
+ 'Ograve;': '\xd2',
1659
+ 'ograve;': '\xf2',
1660
+ 'ogt;': '\u29c1',
1661
+ 'ohbar;': '\u29b5',
1662
+ 'ohm;': '\u03a9',
1663
+ 'oint;': '\u222e',
1664
+ 'olarr;': '\u21ba',
1665
+ 'olcir;': '\u29be',
1666
+ 'olcross;': '\u29bb',
1667
+ 'oline;': '\u203e',
1668
+ 'olt;': '\u29c0',
1669
+ 'Omacr;': '\u014c',
1670
+ 'omacr;': '\u014d',
1671
+ 'Omega;': '\u03a9',
1672
+ 'omega;': '\u03c9',
1673
+ 'Omicron;': '\u039f',
1674
+ 'omicron;': '\u03bf',
1675
+ 'omid;': '\u29b6',
1676
+ 'ominus;': '\u2296',
1677
+ 'Oopf;': '\U0001d546',
1678
+ 'oopf;': '\U0001d560',
1679
+ 'opar;': '\u29b7',
1680
+ 'OpenCurlyDoubleQuote;': '\u201c',
1681
+ 'OpenCurlyQuote;': '\u2018',
1682
+ 'operp;': '\u29b9',
1683
+ 'oplus;': '\u2295',
1684
+ 'Or;': '\u2a54',
1685
+ 'or;': '\u2228',
1686
+ 'orarr;': '\u21bb',
1687
+ 'ord;': '\u2a5d',
1688
+ 'order;': '\u2134',
1689
+ 'orderof;': '\u2134',
1690
+ 'ordf': '\xaa',
1691
+ 'ordf;': '\xaa',
1692
+ 'ordm': '\xba',
1693
+ 'ordm;': '\xba',
1694
+ 'origof;': '\u22b6',
1695
+ 'oror;': '\u2a56',
1696
+ 'orslope;': '\u2a57',
1697
+ 'orv;': '\u2a5b',
1698
+ 'oS;': '\u24c8',
1699
+ 'Oscr;': '\U0001d4aa',
1700
+ 'oscr;': '\u2134',
1701
+ 'Oslash': '\xd8',
1702
+ 'oslash': '\xf8',
1703
+ 'Oslash;': '\xd8',
1704
+ 'oslash;': '\xf8',
1705
+ 'osol;': '\u2298',
1706
+ 'Otilde': '\xd5',
1707
+ 'otilde': '\xf5',
1708
+ 'Otilde;': '\xd5',
1709
+ 'otilde;': '\xf5',
1710
+ 'Otimes;': '\u2a37',
1711
+ 'otimes;': '\u2297',
1712
+ 'otimesas;': '\u2a36',
1713
+ 'Ouml': '\xd6',
1714
+ 'ouml': '\xf6',
1715
+ 'Ouml;': '\xd6',
1716
+ 'ouml;': '\xf6',
1717
+ 'ovbar;': '\u233d',
1718
+ 'OverBar;': '\u203e',
1719
+ 'OverBrace;': '\u23de',
1720
+ 'OverBracket;': '\u23b4',
1721
+ 'OverParenthesis;': '\u23dc',
1722
+ 'par;': '\u2225',
1723
+ 'para': '\xb6',
1724
+ 'para;': '\xb6',
1725
+ 'parallel;': '\u2225',
1726
+ 'parsim;': '\u2af3',
1727
+ 'parsl;': '\u2afd',
1728
+ 'part;': '\u2202',
1729
+ 'PartialD;': '\u2202',
1730
+ 'Pcy;': '\u041f',
1731
+ 'pcy;': '\u043f',
1732
+ 'percnt;': '%',
1733
+ 'period;': '.',
1734
+ 'permil;': '\u2030',
1735
+ 'perp;': '\u22a5',
1736
+ 'pertenk;': '\u2031',
1737
+ 'Pfr;': '\U0001d513',
1738
+ 'pfr;': '\U0001d52d',
1739
+ 'Phi;': '\u03a6',
1740
+ 'phi;': '\u03c6',
1741
+ 'phiv;': '\u03d5',
1742
+ 'phmmat;': '\u2133',
1743
+ 'phone;': '\u260e',
1744
+ 'Pi;': '\u03a0',
1745
+ 'pi;': '\u03c0',
1746
+ 'pitchfork;': '\u22d4',
1747
+ 'piv;': '\u03d6',
1748
+ 'planck;': '\u210f',
1749
+ 'planckh;': '\u210e',
1750
+ 'plankv;': '\u210f',
1751
+ 'plus;': '+',
1752
+ 'plusacir;': '\u2a23',
1753
+ 'plusb;': '\u229e',
1754
+ 'pluscir;': '\u2a22',
1755
+ 'plusdo;': '\u2214',
1756
+ 'plusdu;': '\u2a25',
1757
+ 'pluse;': '\u2a72',
1758
+ 'PlusMinus;': '\xb1',
1759
+ 'plusmn': '\xb1',
1760
+ 'plusmn;': '\xb1',
1761
+ 'plussim;': '\u2a26',
1762
+ 'plustwo;': '\u2a27',
1763
+ 'pm;': '\xb1',
1764
+ 'Poincareplane;': '\u210c',
1765
+ 'pointint;': '\u2a15',
1766
+ 'Popf;': '\u2119',
1767
+ 'popf;': '\U0001d561',
1768
+ 'pound': '\xa3',
1769
+ 'pound;': '\xa3',
1770
+ 'Pr;': '\u2abb',
1771
+ 'pr;': '\u227a',
1772
+ 'prap;': '\u2ab7',
1773
+ 'prcue;': '\u227c',
1774
+ 'prE;': '\u2ab3',
1775
+ 'pre;': '\u2aaf',
1776
+ 'prec;': '\u227a',
1777
+ 'precapprox;': '\u2ab7',
1778
+ 'preccurlyeq;': '\u227c',
1779
+ 'Precedes;': '\u227a',
1780
+ 'PrecedesEqual;': '\u2aaf',
1781
+ 'PrecedesSlantEqual;': '\u227c',
1782
+ 'PrecedesTilde;': '\u227e',
1783
+ 'preceq;': '\u2aaf',
1784
+ 'precnapprox;': '\u2ab9',
1785
+ 'precneqq;': '\u2ab5',
1786
+ 'precnsim;': '\u22e8',
1787
+ 'precsim;': '\u227e',
1788
+ 'Prime;': '\u2033',
1789
+ 'prime;': '\u2032',
1790
+ 'primes;': '\u2119',
1791
+ 'prnap;': '\u2ab9',
1792
+ 'prnE;': '\u2ab5',
1793
+ 'prnsim;': '\u22e8',
1794
+ 'prod;': '\u220f',
1795
+ 'Product;': '\u220f',
1796
+ 'profalar;': '\u232e',
1797
+ 'profline;': '\u2312',
1798
+ 'profsurf;': '\u2313',
1799
+ 'prop;': '\u221d',
1800
+ 'Proportion;': '\u2237',
1801
+ 'Proportional;': '\u221d',
1802
+ 'propto;': '\u221d',
1803
+ 'prsim;': '\u227e',
1804
+ 'prurel;': '\u22b0',
1805
+ 'Pscr;': '\U0001d4ab',
1806
+ 'pscr;': '\U0001d4c5',
1807
+ 'Psi;': '\u03a8',
1808
+ 'psi;': '\u03c8',
1809
+ 'puncsp;': '\u2008',
1810
+ 'Qfr;': '\U0001d514',
1811
+ 'qfr;': '\U0001d52e',
1812
+ 'qint;': '\u2a0c',
1813
+ 'Qopf;': '\u211a',
1814
+ 'qopf;': '\U0001d562',
1815
+ 'qprime;': '\u2057',
1816
+ 'Qscr;': '\U0001d4ac',
1817
+ 'qscr;': '\U0001d4c6',
1818
+ 'quaternions;': '\u210d',
1819
+ 'quatint;': '\u2a16',
1820
+ 'quest;': '?',
1821
+ 'questeq;': '\u225f',
1822
+ 'QUOT': '"',
1823
+ 'quot': '"',
1824
+ 'QUOT;': '"',
1825
+ 'quot;': '"',
1826
+ 'rAarr;': '\u21db',
1827
+ 'race;': '\u223d\u0331',
1828
+ 'Racute;': '\u0154',
1829
+ 'racute;': '\u0155',
1830
+ 'radic;': '\u221a',
1831
+ 'raemptyv;': '\u29b3',
1832
+ 'Rang;': '\u27eb',
1833
+ 'rang;': '\u27e9',
1834
+ 'rangd;': '\u2992',
1835
+ 'range;': '\u29a5',
1836
+ 'rangle;': '\u27e9',
1837
+ 'raquo': '\xbb',
1838
+ 'raquo;': '\xbb',
1839
+ 'Rarr;': '\u21a0',
1840
+ 'rArr;': '\u21d2',
1841
+ 'rarr;': '\u2192',
1842
+ 'rarrap;': '\u2975',
1843
+ 'rarrb;': '\u21e5',
1844
+ 'rarrbfs;': '\u2920',
1845
+ 'rarrc;': '\u2933',
1846
+ 'rarrfs;': '\u291e',
1847
+ 'rarrhk;': '\u21aa',
1848
+ 'rarrlp;': '\u21ac',
1849
+ 'rarrpl;': '\u2945',
1850
+ 'rarrsim;': '\u2974',
1851
+ 'Rarrtl;': '\u2916',
1852
+ 'rarrtl;': '\u21a3',
1853
+ 'rarrw;': '\u219d',
1854
+ 'rAtail;': '\u291c',
1855
+ 'ratail;': '\u291a',
1856
+ 'ratio;': '\u2236',
1857
+ 'rationals;': '\u211a',
1858
+ 'RBarr;': '\u2910',
1859
+ 'rBarr;': '\u290f',
1860
+ 'rbarr;': '\u290d',
1861
+ 'rbbrk;': '\u2773',
1862
+ 'rbrace;': '}',
1863
+ 'rbrack;': ']',
1864
+ 'rbrke;': '\u298c',
1865
+ 'rbrksld;': '\u298e',
1866
+ 'rbrkslu;': '\u2990',
1867
+ 'Rcaron;': '\u0158',
1868
+ 'rcaron;': '\u0159',
1869
+ 'Rcedil;': '\u0156',
1870
+ 'rcedil;': '\u0157',
1871
+ 'rceil;': '\u2309',
1872
+ 'rcub;': '}',
1873
+ 'Rcy;': '\u0420',
1874
+ 'rcy;': '\u0440',
1875
+ 'rdca;': '\u2937',
1876
+ 'rdldhar;': '\u2969',
1877
+ 'rdquo;': '\u201d',
1878
+ 'rdquor;': '\u201d',
1879
+ 'rdsh;': '\u21b3',
1880
+ 'Re;': '\u211c',
1881
+ 'real;': '\u211c',
1882
+ 'realine;': '\u211b',
1883
+ 'realpart;': '\u211c',
1884
+ 'reals;': '\u211d',
1885
+ 'rect;': '\u25ad',
1886
+ 'REG': '\xae',
1887
+ 'reg': '\xae',
1888
+ 'REG;': '\xae',
1889
+ 'reg;': '\xae',
1890
+ 'ReverseElement;': '\u220b',
1891
+ 'ReverseEquilibrium;': '\u21cb',
1892
+ 'ReverseUpEquilibrium;': '\u296f',
1893
+ 'rfisht;': '\u297d',
1894
+ 'rfloor;': '\u230b',
1895
+ 'Rfr;': '\u211c',
1896
+ 'rfr;': '\U0001d52f',
1897
+ 'rHar;': '\u2964',
1898
+ 'rhard;': '\u21c1',
1899
+ 'rharu;': '\u21c0',
1900
+ 'rharul;': '\u296c',
1901
+ 'Rho;': '\u03a1',
1902
+ 'rho;': '\u03c1',
1903
+ 'rhov;': '\u03f1',
1904
+ 'RightAngleBracket;': '\u27e9',
1905
+ 'RightArrow;': '\u2192',
1906
+ 'Rightarrow;': '\u21d2',
1907
+ 'rightarrow;': '\u2192',
1908
+ 'RightArrowBar;': '\u21e5',
1909
+ 'RightArrowLeftArrow;': '\u21c4',
1910
+ 'rightarrowtail;': '\u21a3',
1911
+ 'RightCeiling;': '\u2309',
1912
+ 'RightDoubleBracket;': '\u27e7',
1913
+ 'RightDownTeeVector;': '\u295d',
1914
+ 'RightDownVector;': '\u21c2',
1915
+ 'RightDownVectorBar;': '\u2955',
1916
+ 'RightFloor;': '\u230b',
1917
+ 'rightharpoondown;': '\u21c1',
1918
+ 'rightharpoonup;': '\u21c0',
1919
+ 'rightleftarrows;': '\u21c4',
1920
+ 'rightleftharpoons;': '\u21cc',
1921
+ 'rightrightarrows;': '\u21c9',
1922
+ 'rightsquigarrow;': '\u219d',
1923
+ 'RightTee;': '\u22a2',
1924
+ 'RightTeeArrow;': '\u21a6',
1925
+ 'RightTeeVector;': '\u295b',
1926
+ 'rightthreetimes;': '\u22cc',
1927
+ 'RightTriangle;': '\u22b3',
1928
+ 'RightTriangleBar;': '\u29d0',
1929
+ 'RightTriangleEqual;': '\u22b5',
1930
+ 'RightUpDownVector;': '\u294f',
1931
+ 'RightUpTeeVector;': '\u295c',
1932
+ 'RightUpVector;': '\u21be',
1933
+ 'RightUpVectorBar;': '\u2954',
1934
+ 'RightVector;': '\u21c0',
1935
+ 'RightVectorBar;': '\u2953',
1936
+ 'ring;': '\u02da',
1937
+ 'risingdotseq;': '\u2253',
1938
+ 'rlarr;': '\u21c4',
1939
+ 'rlhar;': '\u21cc',
1940
+ 'rlm;': '\u200f',
1941
+ 'rmoust;': '\u23b1',
1942
+ 'rmoustache;': '\u23b1',
1943
+ 'rnmid;': '\u2aee',
1944
+ 'roang;': '\u27ed',
1945
+ 'roarr;': '\u21fe',
1946
+ 'robrk;': '\u27e7',
1947
+ 'ropar;': '\u2986',
1948
+ 'Ropf;': '\u211d',
1949
+ 'ropf;': '\U0001d563',
1950
+ 'roplus;': '\u2a2e',
1951
+ 'rotimes;': '\u2a35',
1952
+ 'RoundImplies;': '\u2970',
1953
+ 'rpar;': ')',
1954
+ 'rpargt;': '\u2994',
1955
+ 'rppolint;': '\u2a12',
1956
+ 'rrarr;': '\u21c9',
1957
+ 'Rrightarrow;': '\u21db',
1958
+ 'rsaquo;': '\u203a',
1959
+ 'Rscr;': '\u211b',
1960
+ 'rscr;': '\U0001d4c7',
1961
+ 'Rsh;': '\u21b1',
1962
+ 'rsh;': '\u21b1',
1963
+ 'rsqb;': ']',
1964
+ 'rsquo;': '\u2019',
1965
+ 'rsquor;': '\u2019',
1966
+ 'rthree;': '\u22cc',
1967
+ 'rtimes;': '\u22ca',
1968
+ 'rtri;': '\u25b9',
1969
+ 'rtrie;': '\u22b5',
1970
+ 'rtrif;': '\u25b8',
1971
+ 'rtriltri;': '\u29ce',
1972
+ 'RuleDelayed;': '\u29f4',
1973
+ 'ruluhar;': '\u2968',
1974
+ 'rx;': '\u211e',
1975
+ 'Sacute;': '\u015a',
1976
+ 'sacute;': '\u015b',
1977
+ 'sbquo;': '\u201a',
1978
+ 'Sc;': '\u2abc',
1979
+ 'sc;': '\u227b',
1980
+ 'scap;': '\u2ab8',
1981
+ 'Scaron;': '\u0160',
1982
+ 'scaron;': '\u0161',
1983
+ 'sccue;': '\u227d',
1984
+ 'scE;': '\u2ab4',
1985
+ 'sce;': '\u2ab0',
1986
+ 'Scedil;': '\u015e',
1987
+ 'scedil;': '\u015f',
1988
+ 'Scirc;': '\u015c',
1989
+ 'scirc;': '\u015d',
1990
+ 'scnap;': '\u2aba',
1991
+ 'scnE;': '\u2ab6',
1992
+ 'scnsim;': '\u22e9',
1993
+ 'scpolint;': '\u2a13',
1994
+ 'scsim;': '\u227f',
1995
+ 'Scy;': '\u0421',
1996
+ 'scy;': '\u0441',
1997
+ 'sdot;': '\u22c5',
1998
+ 'sdotb;': '\u22a1',
1999
+ 'sdote;': '\u2a66',
2000
+ 'searhk;': '\u2925',
2001
+ 'seArr;': '\u21d8',
2002
+ 'searr;': '\u2198',
2003
+ 'searrow;': '\u2198',
2004
+ 'sect': '\xa7',
2005
+ 'sect;': '\xa7',
2006
+ 'semi;': ';',
2007
+ 'seswar;': '\u2929',
2008
+ 'setminus;': '\u2216',
2009
+ 'setmn;': '\u2216',
2010
+ 'sext;': '\u2736',
2011
+ 'Sfr;': '\U0001d516',
2012
+ 'sfr;': '\U0001d530',
2013
+ 'sfrown;': '\u2322',
2014
+ 'sharp;': '\u266f',
2015
+ 'SHCHcy;': '\u0429',
2016
+ 'shchcy;': '\u0449',
2017
+ 'SHcy;': '\u0428',
2018
+ 'shcy;': '\u0448',
2019
+ 'ShortDownArrow;': '\u2193',
2020
+ 'ShortLeftArrow;': '\u2190',
2021
+ 'shortmid;': '\u2223',
2022
+ 'shortparallel;': '\u2225',
2023
+ 'ShortRightArrow;': '\u2192',
2024
+ 'ShortUpArrow;': '\u2191',
2025
+ 'shy': '\xad',
2026
+ 'shy;': '\xad',
2027
+ 'Sigma;': '\u03a3',
2028
+ 'sigma;': '\u03c3',
2029
+ 'sigmaf;': '\u03c2',
2030
+ 'sigmav;': '\u03c2',
2031
+ 'sim;': '\u223c',
2032
+ 'simdot;': '\u2a6a',
2033
+ 'sime;': '\u2243',
2034
+ 'simeq;': '\u2243',
2035
+ 'simg;': '\u2a9e',
2036
+ 'simgE;': '\u2aa0',
2037
+ 'siml;': '\u2a9d',
2038
+ 'simlE;': '\u2a9f',
2039
+ 'simne;': '\u2246',
2040
+ 'simplus;': '\u2a24',
2041
+ 'simrarr;': '\u2972',
2042
+ 'slarr;': '\u2190',
2043
+ 'SmallCircle;': '\u2218',
2044
+ 'smallsetminus;': '\u2216',
2045
+ 'smashp;': '\u2a33',
2046
+ 'smeparsl;': '\u29e4',
2047
+ 'smid;': '\u2223',
2048
+ 'smile;': '\u2323',
2049
+ 'smt;': '\u2aaa',
2050
+ 'smte;': '\u2aac',
2051
+ 'smtes;': '\u2aac\ufe00',
2052
+ 'SOFTcy;': '\u042c',
2053
+ 'softcy;': '\u044c',
2054
+ 'sol;': '/',
2055
+ 'solb;': '\u29c4',
2056
+ 'solbar;': '\u233f',
2057
+ 'Sopf;': '\U0001d54a',
2058
+ 'sopf;': '\U0001d564',
2059
+ 'spades;': '\u2660',
2060
+ 'spadesuit;': '\u2660',
2061
+ 'spar;': '\u2225',
2062
+ 'sqcap;': '\u2293',
2063
+ 'sqcaps;': '\u2293\ufe00',
2064
+ 'sqcup;': '\u2294',
2065
+ 'sqcups;': '\u2294\ufe00',
2066
+ 'Sqrt;': '\u221a',
2067
+ 'sqsub;': '\u228f',
2068
+ 'sqsube;': '\u2291',
2069
+ 'sqsubset;': '\u228f',
2070
+ 'sqsubseteq;': '\u2291',
2071
+ 'sqsup;': '\u2290',
2072
+ 'sqsupe;': '\u2292',
2073
+ 'sqsupset;': '\u2290',
2074
+ 'sqsupseteq;': '\u2292',
2075
+ 'squ;': '\u25a1',
2076
+ 'Square;': '\u25a1',
2077
+ 'square;': '\u25a1',
2078
+ 'SquareIntersection;': '\u2293',
2079
+ 'SquareSubset;': '\u228f',
2080
+ 'SquareSubsetEqual;': '\u2291',
2081
+ 'SquareSuperset;': '\u2290',
2082
+ 'SquareSupersetEqual;': '\u2292',
2083
+ 'SquareUnion;': '\u2294',
2084
+ 'squarf;': '\u25aa',
2085
+ 'squf;': '\u25aa',
2086
+ 'srarr;': '\u2192',
2087
+ 'Sscr;': '\U0001d4ae',
2088
+ 'sscr;': '\U0001d4c8',
2089
+ 'ssetmn;': '\u2216',
2090
+ 'ssmile;': '\u2323',
2091
+ 'sstarf;': '\u22c6',
2092
+ 'Star;': '\u22c6',
2093
+ 'star;': '\u2606',
2094
+ 'starf;': '\u2605',
2095
+ 'straightepsilon;': '\u03f5',
2096
+ 'straightphi;': '\u03d5',
2097
+ 'strns;': '\xaf',
2098
+ 'Sub;': '\u22d0',
2099
+ 'sub;': '\u2282',
2100
+ 'subdot;': '\u2abd',
2101
+ 'subE;': '\u2ac5',
2102
+ 'sube;': '\u2286',
2103
+ 'subedot;': '\u2ac3',
2104
+ 'submult;': '\u2ac1',
2105
+ 'subnE;': '\u2acb',
2106
+ 'subne;': '\u228a',
2107
+ 'subplus;': '\u2abf',
2108
+ 'subrarr;': '\u2979',
2109
+ 'Subset;': '\u22d0',
2110
+ 'subset;': '\u2282',
2111
+ 'subseteq;': '\u2286',
2112
+ 'subseteqq;': '\u2ac5',
2113
+ 'SubsetEqual;': '\u2286',
2114
+ 'subsetneq;': '\u228a',
2115
+ 'subsetneqq;': '\u2acb',
2116
+ 'subsim;': '\u2ac7',
2117
+ 'subsub;': '\u2ad5',
2118
+ 'subsup;': '\u2ad3',
2119
+ 'succ;': '\u227b',
2120
+ 'succapprox;': '\u2ab8',
2121
+ 'succcurlyeq;': '\u227d',
2122
+ 'Succeeds;': '\u227b',
2123
+ 'SucceedsEqual;': '\u2ab0',
2124
+ 'SucceedsSlantEqual;': '\u227d',
2125
+ 'SucceedsTilde;': '\u227f',
2126
+ 'succeq;': '\u2ab0',
2127
+ 'succnapprox;': '\u2aba',
2128
+ 'succneqq;': '\u2ab6',
2129
+ 'succnsim;': '\u22e9',
2130
+ 'succsim;': '\u227f',
2131
+ 'SuchThat;': '\u220b',
2132
+ 'Sum;': '\u2211',
2133
+ 'sum;': '\u2211',
2134
+ 'sung;': '\u266a',
2135
+ 'sup1': '\xb9',
2136
+ 'sup1;': '\xb9',
2137
+ 'sup2': '\xb2',
2138
+ 'sup2;': '\xb2',
2139
+ 'sup3': '\xb3',
2140
+ 'sup3;': '\xb3',
2141
+ 'Sup;': '\u22d1',
2142
+ 'sup;': '\u2283',
2143
+ 'supdot;': '\u2abe',
2144
+ 'supdsub;': '\u2ad8',
2145
+ 'supE;': '\u2ac6',
2146
+ 'supe;': '\u2287',
2147
+ 'supedot;': '\u2ac4',
2148
+ 'Superset;': '\u2283',
2149
+ 'SupersetEqual;': '\u2287',
2150
+ 'suphsol;': '\u27c9',
2151
+ 'suphsub;': '\u2ad7',
2152
+ 'suplarr;': '\u297b',
2153
+ 'supmult;': '\u2ac2',
2154
+ 'supnE;': '\u2acc',
2155
+ 'supne;': '\u228b',
2156
+ 'supplus;': '\u2ac0',
2157
+ 'Supset;': '\u22d1',
2158
+ 'supset;': '\u2283',
2159
+ 'supseteq;': '\u2287',
2160
+ 'supseteqq;': '\u2ac6',
2161
+ 'supsetneq;': '\u228b',
2162
+ 'supsetneqq;': '\u2acc',
2163
+ 'supsim;': '\u2ac8',
2164
+ 'supsub;': '\u2ad4',
2165
+ 'supsup;': '\u2ad6',
2166
+ 'swarhk;': '\u2926',
2167
+ 'swArr;': '\u21d9',
2168
+ 'swarr;': '\u2199',
2169
+ 'swarrow;': '\u2199',
2170
+ 'swnwar;': '\u292a',
2171
+ 'szlig': '\xdf',
2172
+ 'szlig;': '\xdf',
2173
+ 'Tab;': '\t',
2174
+ 'target;': '\u2316',
2175
+ 'Tau;': '\u03a4',
2176
+ 'tau;': '\u03c4',
2177
+ 'tbrk;': '\u23b4',
2178
+ 'Tcaron;': '\u0164',
2179
+ 'tcaron;': '\u0165',
2180
+ 'Tcedil;': '\u0162',
2181
+ 'tcedil;': '\u0163',
2182
+ 'Tcy;': '\u0422',
2183
+ 'tcy;': '\u0442',
2184
+ 'tdot;': '\u20db',
2185
+ 'telrec;': '\u2315',
2186
+ 'Tfr;': '\U0001d517',
2187
+ 'tfr;': '\U0001d531',
2188
+ 'there4;': '\u2234',
2189
+ 'Therefore;': '\u2234',
2190
+ 'therefore;': '\u2234',
2191
+ 'Theta;': '\u0398',
2192
+ 'theta;': '\u03b8',
2193
+ 'thetasym;': '\u03d1',
2194
+ 'thetav;': '\u03d1',
2195
+ 'thickapprox;': '\u2248',
2196
+ 'thicksim;': '\u223c',
2197
+ 'ThickSpace;': '\u205f\u200a',
2198
+ 'thinsp;': '\u2009',
2199
+ 'ThinSpace;': '\u2009',
2200
+ 'thkap;': '\u2248',
2201
+ 'thksim;': '\u223c',
2202
+ 'THORN': '\xde',
2203
+ 'thorn': '\xfe',
2204
+ 'THORN;': '\xde',
2205
+ 'thorn;': '\xfe',
2206
+ 'Tilde;': '\u223c',
2207
+ 'tilde;': '\u02dc',
2208
+ 'TildeEqual;': '\u2243',
2209
+ 'TildeFullEqual;': '\u2245',
2210
+ 'TildeTilde;': '\u2248',
2211
+ 'times': '\xd7',
2212
+ 'times;': '\xd7',
2213
+ 'timesb;': '\u22a0',
2214
+ 'timesbar;': '\u2a31',
2215
+ 'timesd;': '\u2a30',
2216
+ 'tint;': '\u222d',
2217
+ 'toea;': '\u2928',
2218
+ 'top;': '\u22a4',
2219
+ 'topbot;': '\u2336',
2220
+ 'topcir;': '\u2af1',
2221
+ 'Topf;': '\U0001d54b',
2222
+ 'topf;': '\U0001d565',
2223
+ 'topfork;': '\u2ada',
2224
+ 'tosa;': '\u2929',
2225
+ 'tprime;': '\u2034',
2226
+ 'TRADE;': '\u2122',
2227
+ 'trade;': '\u2122',
2228
+ 'triangle;': '\u25b5',
2229
+ 'triangledown;': '\u25bf',
2230
+ 'triangleleft;': '\u25c3',
2231
+ 'trianglelefteq;': '\u22b4',
2232
+ 'triangleq;': '\u225c',
2233
+ 'triangleright;': '\u25b9',
2234
+ 'trianglerighteq;': '\u22b5',
2235
+ 'tridot;': '\u25ec',
2236
+ 'trie;': '\u225c',
2237
+ 'triminus;': '\u2a3a',
2238
+ 'TripleDot;': '\u20db',
2239
+ 'triplus;': '\u2a39',
2240
+ 'trisb;': '\u29cd',
2241
+ 'tritime;': '\u2a3b',
2242
+ 'trpezium;': '\u23e2',
2243
+ 'Tscr;': '\U0001d4af',
2244
+ 'tscr;': '\U0001d4c9',
2245
+ 'TScy;': '\u0426',
2246
+ 'tscy;': '\u0446',
2247
+ 'TSHcy;': '\u040b',
2248
+ 'tshcy;': '\u045b',
2249
+ 'Tstrok;': '\u0166',
2250
+ 'tstrok;': '\u0167',
2251
+ 'twixt;': '\u226c',
2252
+ 'twoheadleftarrow;': '\u219e',
2253
+ 'twoheadrightarrow;': '\u21a0',
2254
+ 'Uacute': '\xda',
2255
+ 'uacute': '\xfa',
2256
+ 'Uacute;': '\xda',
2257
+ 'uacute;': '\xfa',
2258
+ 'Uarr;': '\u219f',
2259
+ 'uArr;': '\u21d1',
2260
+ 'uarr;': '\u2191',
2261
+ 'Uarrocir;': '\u2949',
2262
+ 'Ubrcy;': '\u040e',
2263
+ 'ubrcy;': '\u045e',
2264
+ 'Ubreve;': '\u016c',
2265
+ 'ubreve;': '\u016d',
2266
+ 'Ucirc': '\xdb',
2267
+ 'ucirc': '\xfb',
2268
+ 'Ucirc;': '\xdb',
2269
+ 'ucirc;': '\xfb',
2270
+ 'Ucy;': '\u0423',
2271
+ 'ucy;': '\u0443',
2272
+ 'udarr;': '\u21c5',
2273
+ 'Udblac;': '\u0170',
2274
+ 'udblac;': '\u0171',
2275
+ 'udhar;': '\u296e',
2276
+ 'ufisht;': '\u297e',
2277
+ 'Ufr;': '\U0001d518',
2278
+ 'ufr;': '\U0001d532',
2279
+ 'Ugrave': '\xd9',
2280
+ 'ugrave': '\xf9',
2281
+ 'Ugrave;': '\xd9',
2282
+ 'ugrave;': '\xf9',
2283
+ 'uHar;': '\u2963',
2284
+ 'uharl;': '\u21bf',
2285
+ 'uharr;': '\u21be',
2286
+ 'uhblk;': '\u2580',
2287
+ 'ulcorn;': '\u231c',
2288
+ 'ulcorner;': '\u231c',
2289
+ 'ulcrop;': '\u230f',
2290
+ 'ultri;': '\u25f8',
2291
+ 'Umacr;': '\u016a',
2292
+ 'umacr;': '\u016b',
2293
+ 'uml': '\xa8',
2294
+ 'uml;': '\xa8',
2295
+ 'UnderBar;': '_',
2296
+ 'UnderBrace;': '\u23df',
2297
+ 'UnderBracket;': '\u23b5',
2298
+ 'UnderParenthesis;': '\u23dd',
2299
+ 'Union;': '\u22c3',
2300
+ 'UnionPlus;': '\u228e',
2301
+ 'Uogon;': '\u0172',
2302
+ 'uogon;': '\u0173',
2303
+ 'Uopf;': '\U0001d54c',
2304
+ 'uopf;': '\U0001d566',
2305
+ 'UpArrow;': '\u2191',
2306
+ 'Uparrow;': '\u21d1',
2307
+ 'uparrow;': '\u2191',
2308
+ 'UpArrowBar;': '\u2912',
2309
+ 'UpArrowDownArrow;': '\u21c5',
2310
+ 'UpDownArrow;': '\u2195',
2311
+ 'Updownarrow;': '\u21d5',
2312
+ 'updownarrow;': '\u2195',
2313
+ 'UpEquilibrium;': '\u296e',
2314
+ 'upharpoonleft;': '\u21bf',
2315
+ 'upharpoonright;': '\u21be',
2316
+ 'uplus;': '\u228e',
2317
+ 'UpperLeftArrow;': '\u2196',
2318
+ 'UpperRightArrow;': '\u2197',
2319
+ 'Upsi;': '\u03d2',
2320
+ 'upsi;': '\u03c5',
2321
+ 'upsih;': '\u03d2',
2322
+ 'Upsilon;': '\u03a5',
2323
+ 'upsilon;': '\u03c5',
2324
+ 'UpTee;': '\u22a5',
2325
+ 'UpTeeArrow;': '\u21a5',
2326
+ 'upuparrows;': '\u21c8',
2327
+ 'urcorn;': '\u231d',
2328
+ 'urcorner;': '\u231d',
2329
+ 'urcrop;': '\u230e',
2330
+ 'Uring;': '\u016e',
2331
+ 'uring;': '\u016f',
2332
+ 'urtri;': '\u25f9',
2333
+ 'Uscr;': '\U0001d4b0',
2334
+ 'uscr;': '\U0001d4ca',
2335
+ 'utdot;': '\u22f0',
2336
+ 'Utilde;': '\u0168',
2337
+ 'utilde;': '\u0169',
2338
+ 'utri;': '\u25b5',
2339
+ 'utrif;': '\u25b4',
2340
+ 'uuarr;': '\u21c8',
2341
+ 'Uuml': '\xdc',
2342
+ 'uuml': '\xfc',
2343
+ 'Uuml;': '\xdc',
2344
+ 'uuml;': '\xfc',
2345
+ 'uwangle;': '\u29a7',
2346
+ 'vangrt;': '\u299c',
2347
+ 'varepsilon;': '\u03f5',
2348
+ 'varkappa;': '\u03f0',
2349
+ 'varnothing;': '\u2205',
2350
+ 'varphi;': '\u03d5',
2351
+ 'varpi;': '\u03d6',
2352
+ 'varpropto;': '\u221d',
2353
+ 'vArr;': '\u21d5',
2354
+ 'varr;': '\u2195',
2355
+ 'varrho;': '\u03f1',
2356
+ 'varsigma;': '\u03c2',
2357
+ 'varsubsetneq;': '\u228a\ufe00',
2358
+ 'varsubsetneqq;': '\u2acb\ufe00',
2359
+ 'varsupsetneq;': '\u228b\ufe00',
2360
+ 'varsupsetneqq;': '\u2acc\ufe00',
2361
+ 'vartheta;': '\u03d1',
2362
+ 'vartriangleleft;': '\u22b2',
2363
+ 'vartriangleright;': '\u22b3',
2364
+ 'Vbar;': '\u2aeb',
2365
+ 'vBar;': '\u2ae8',
2366
+ 'vBarv;': '\u2ae9',
2367
+ 'Vcy;': '\u0412',
2368
+ 'vcy;': '\u0432',
2369
+ 'VDash;': '\u22ab',
2370
+ 'Vdash;': '\u22a9',
2371
+ 'vDash;': '\u22a8',
2372
+ 'vdash;': '\u22a2',
2373
+ 'Vdashl;': '\u2ae6',
2374
+ 'Vee;': '\u22c1',
2375
+ 'vee;': '\u2228',
2376
+ 'veebar;': '\u22bb',
2377
+ 'veeeq;': '\u225a',
2378
+ 'vellip;': '\u22ee',
2379
+ 'Verbar;': '\u2016',
2380
+ 'verbar;': '|',
2381
+ 'Vert;': '\u2016',
2382
+ 'vert;': '|',
2383
+ 'VerticalBar;': '\u2223',
2384
+ 'VerticalLine;': '|',
2385
+ 'VerticalSeparator;': '\u2758',
2386
+ 'VerticalTilde;': '\u2240',
2387
+ 'VeryThinSpace;': '\u200a',
2388
+ 'Vfr;': '\U0001d519',
2389
+ 'vfr;': '\U0001d533',
2390
+ 'vltri;': '\u22b2',
2391
+ 'vnsub;': '\u2282\u20d2',
2392
+ 'vnsup;': '\u2283\u20d2',
2393
+ 'Vopf;': '\U0001d54d',
2394
+ 'vopf;': '\U0001d567',
2395
+ 'vprop;': '\u221d',
2396
+ 'vrtri;': '\u22b3',
2397
+ 'Vscr;': '\U0001d4b1',
2398
+ 'vscr;': '\U0001d4cb',
2399
+ 'vsubnE;': '\u2acb\ufe00',
2400
+ 'vsubne;': '\u228a\ufe00',
2401
+ 'vsupnE;': '\u2acc\ufe00',
2402
+ 'vsupne;': '\u228b\ufe00',
2403
+ 'Vvdash;': '\u22aa',
2404
+ 'vzigzag;': '\u299a',
2405
+ 'Wcirc;': '\u0174',
2406
+ 'wcirc;': '\u0175',
2407
+ 'wedbar;': '\u2a5f',
2408
+ 'Wedge;': '\u22c0',
2409
+ 'wedge;': '\u2227',
2410
+ 'wedgeq;': '\u2259',
2411
+ 'weierp;': '\u2118',
2412
+ 'Wfr;': '\U0001d51a',
2413
+ 'wfr;': '\U0001d534',
2414
+ 'Wopf;': '\U0001d54e',
2415
+ 'wopf;': '\U0001d568',
2416
+ 'wp;': '\u2118',
2417
+ 'wr;': '\u2240',
2418
+ 'wreath;': '\u2240',
2419
+ 'Wscr;': '\U0001d4b2',
2420
+ 'wscr;': '\U0001d4cc',
2421
+ 'xcap;': '\u22c2',
2422
+ 'xcirc;': '\u25ef',
2423
+ 'xcup;': '\u22c3',
2424
+ 'xdtri;': '\u25bd',
2425
+ 'Xfr;': '\U0001d51b',
2426
+ 'xfr;': '\U0001d535',
2427
+ 'xhArr;': '\u27fa',
2428
+ 'xharr;': '\u27f7',
2429
+ 'Xi;': '\u039e',
2430
+ 'xi;': '\u03be',
2431
+ 'xlArr;': '\u27f8',
2432
+ 'xlarr;': '\u27f5',
2433
+ 'xmap;': '\u27fc',
2434
+ 'xnis;': '\u22fb',
2435
+ 'xodot;': '\u2a00',
2436
+ 'Xopf;': '\U0001d54f',
2437
+ 'xopf;': '\U0001d569',
2438
+ 'xoplus;': '\u2a01',
2439
+ 'xotime;': '\u2a02',
2440
+ 'xrArr;': '\u27f9',
2441
+ 'xrarr;': '\u27f6',
2442
+ 'Xscr;': '\U0001d4b3',
2443
+ 'xscr;': '\U0001d4cd',
2444
+ 'xsqcup;': '\u2a06',
2445
+ 'xuplus;': '\u2a04',
2446
+ 'xutri;': '\u25b3',
2447
+ 'xvee;': '\u22c1',
2448
+ 'xwedge;': '\u22c0',
2449
+ 'Yacute': '\xdd',
2450
+ 'yacute': '\xfd',
2451
+ 'Yacute;': '\xdd',
2452
+ 'yacute;': '\xfd',
2453
+ 'YAcy;': '\u042f',
2454
+ 'yacy;': '\u044f',
2455
+ 'Ycirc;': '\u0176',
2456
+ 'ycirc;': '\u0177',
2457
+ 'Ycy;': '\u042b',
2458
+ 'ycy;': '\u044b',
2459
+ 'yen': '\xa5',
2460
+ 'yen;': '\xa5',
2461
+ 'Yfr;': '\U0001d51c',
2462
+ 'yfr;': '\U0001d536',
2463
+ 'YIcy;': '\u0407',
2464
+ 'yicy;': '\u0457',
2465
+ 'Yopf;': '\U0001d550',
2466
+ 'yopf;': '\U0001d56a',
2467
+ 'Yscr;': '\U0001d4b4',
2468
+ 'yscr;': '\U0001d4ce',
2469
+ 'YUcy;': '\u042e',
2470
+ 'yucy;': '\u044e',
2471
+ 'yuml': '\xff',
2472
+ 'Yuml;': '\u0178',
2473
+ 'yuml;': '\xff',
2474
+ 'Zacute;': '\u0179',
2475
+ 'zacute;': '\u017a',
2476
+ 'Zcaron;': '\u017d',
2477
+ 'zcaron;': '\u017e',
2478
+ 'Zcy;': '\u0417',
2479
+ 'zcy;': '\u0437',
2480
+ 'Zdot;': '\u017b',
2481
+ 'zdot;': '\u017c',
2482
+ 'zeetrf;': '\u2128',
2483
+ 'ZeroWidthSpace;': '\u200b',
2484
+ 'Zeta;': '\u0396',
2485
+ 'zeta;': '\u03b6',
2486
+ 'Zfr;': '\u2128',
2487
+ 'zfr;': '\U0001d537',
2488
+ 'ZHcy;': '\u0416',
2489
+ 'zhcy;': '\u0436',
2490
+ 'zigrarr;': '\u21dd',
2491
+ 'Zopf;': '\u2124',
2492
+ 'zopf;': '\U0001d56b',
2493
+ 'Zscr;': '\U0001d4b5',
2494
+ 'zscr;': '\U0001d4cf',
2495
+ 'zwj;': '\u200d',
2496
+ 'zwnj;': '\u200c',
2497
+ }
2498
+
2499
+ # maps the Unicode code point to the HTML entity name
2500
+ codepoint2name = {}
2501
+
2502
+ # maps the HTML entity name to the character
2503
+ # (or a character reference if the character is outside the Latin-1 range)
2504
+ entitydefs = {}
2505
+
2506
+ for (name, codepoint) in name2codepoint.items():
2507
+ codepoint2name[codepoint] = name
2508
+ entitydefs[name] = chr(codepoint)
2509
+
2510
+ del name, codepoint
parrot/lib/python3.10/html/parser.py ADDED
@@ -0,0 +1,462 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A parser for HTML and XHTML."""
2
+
3
+ # This file is based on sgmllib.py, but the API is slightly different.
4
+
5
+ # XXX There should be a way to distinguish between PCDATA (parsed
6
+ # character data -- the normal case), RCDATA (replaceable character
7
+ # data -- only char and entity references and end tags are special)
8
+ # and CDATA (character data -- only end tags are special).
9
+
10
+
11
+ import re
12
+ import _markupbase
13
+
14
+ from html import unescape
15
+
16
+
17
+ __all__ = ['HTMLParser']
18
+
19
+ # Regular expressions used for parsing
20
+
21
+ interesting_normal = re.compile('[&<]')
22
+ incomplete = re.compile('&[a-zA-Z#]')
23
+
24
+ entityref = re.compile('&([a-zA-Z][-.a-zA-Z0-9]*)[^a-zA-Z0-9]')
25
+ charref = re.compile('&#(?:[0-9]+|[xX][0-9a-fA-F]+)[^0-9a-fA-F]')
26
+
27
+ starttagopen = re.compile('<[a-zA-Z]')
28
+ piclose = re.compile('>')
29
+ commentclose = re.compile(r'--\s*>')
30
+ # Note:
31
+ # 1) if you change tagfind/attrfind remember to update locatestarttagend too;
32
+ # 2) if you change tagfind/attrfind and/or locatestarttagend the parser will
33
+ # explode, so don't do it.
34
+ # see http://www.w3.org/TR/html5/tokenization.html#tag-open-state
35
+ # and http://www.w3.org/TR/html5/tokenization.html#tag-name-state
36
+ tagfind_tolerant = re.compile(r'([a-zA-Z][^\t\n\r\f />\x00]*)(?:\s|/(?!>))*')
37
+ attrfind_tolerant = re.compile(
38
+ r'((?<=[\'"\s/])[^\s/>][^\s/=>]*)(\s*=+\s*'
39
+ r'(\'[^\']*\'|"[^"]*"|(?![\'"])[^>\s]*))?(?:\s|/(?!>))*')
40
+ locatestarttagend_tolerant = re.compile(r"""
41
+ <[a-zA-Z][^\t\n\r\f />\x00]* # tag name
42
+ (?:[\s/]* # optional whitespace before attribute name
43
+ (?:(?<=['"\s/])[^\s/>][^\s/=>]* # attribute name
44
+ (?:\s*=+\s* # value indicator
45
+ (?:'[^']*' # LITA-enclosed value
46
+ |"[^"]*" # LIT-enclosed value
47
+ |(?!['"])[^>\s]* # bare value
48
+ )
49
+ \s* # possibly followed by a space
50
+ )?(?:\s|/(?!>))*
51
+ )*
52
+ )?
53
+ \s* # trailing whitespace
54
+ """, re.VERBOSE)
55
+ endendtag = re.compile('>')
56
+ # the HTML 5 spec, section 8.1.2.2, doesn't allow spaces between
57
+ # </ and the tag name, so maybe this should be fixed
58
+ endtagfind = re.compile(r'</\s*([a-zA-Z][-.a-zA-Z0-9:_]*)\s*>')
59
+
60
+
61
+
62
+ class HTMLParser(_markupbase.ParserBase):
63
+ """Find tags and other markup and call handler functions.
64
+
65
+ Usage:
66
+ p = HTMLParser()
67
+ p.feed(data)
68
+ ...
69
+ p.close()
70
+
71
+ Start tags are handled by calling self.handle_starttag() or
72
+ self.handle_startendtag(); end tags by self.handle_endtag(). The
73
+ data between tags is passed from the parser to the derived class
74
+ by calling self.handle_data() with the data as argument (the data
75
+ may be split up in arbitrary chunks). If convert_charrefs is
76
+ True the character references are converted automatically to the
77
+ corresponding Unicode character (and self.handle_data() is no
78
+ longer split in chunks), otherwise they are passed by calling
79
+ self.handle_entityref() or self.handle_charref() with the string
80
+ containing respectively the named or numeric reference as the
81
+ argument.
82
+ """
83
+
84
+ CDATA_CONTENT_ELEMENTS = ("script", "style")
85
+
86
+ def __init__(self, *, convert_charrefs=True):
87
+ """Initialize and reset this instance.
88
+
89
+ If convert_charrefs is True (the default), all character references
90
+ are automatically converted to the corresponding Unicode characters.
91
+ """
92
+ self.convert_charrefs = convert_charrefs
93
+ self.reset()
94
+
95
+ def reset(self):
96
+ """Reset this instance. Loses all unprocessed data."""
97
+ self.rawdata = ''
98
+ self.lasttag = '???'
99
+ self.interesting = interesting_normal
100
+ self.cdata_elem = None
101
+ _markupbase.ParserBase.reset(self)
102
+
103
+ def feed(self, data):
104
+ r"""Feed data to the parser.
105
+
106
+ Call this as often as you want, with as little or as much text
107
+ as you want (may include '\n').
108
+ """
109
+ self.rawdata = self.rawdata + data
110
+ self.goahead(0)
111
+
112
+ def close(self):
113
+ """Handle any buffered data."""
114
+ self.goahead(1)
115
+
116
+ __starttag_text = None
117
+
118
+ def get_starttag_text(self):
119
+ """Return full source of start tag: '<...>'."""
120
+ return self.__starttag_text
121
+
122
+ def set_cdata_mode(self, elem):
123
+ self.cdata_elem = elem.lower()
124
+ self.interesting = re.compile(r'</\s*%s\s*>' % self.cdata_elem, re.I)
125
+
126
+ def clear_cdata_mode(self):
127
+ self.interesting = interesting_normal
128
+ self.cdata_elem = None
129
+
130
+ # Internal -- handle data as far as reasonable. May leave state
131
+ # and data to be processed by a subsequent call. If 'end' is
132
+ # true, force handling all data as if followed by EOF marker.
133
+ def goahead(self, end):
134
+ rawdata = self.rawdata
135
+ i = 0
136
+ n = len(rawdata)
137
+ while i < n:
138
+ if self.convert_charrefs and not self.cdata_elem:
139
+ j = rawdata.find('<', i)
140
+ if j < 0:
141
+ # if we can't find the next <, either we are at the end
142
+ # or there's more text incoming. If the latter is True,
143
+ # we can't pass the text to handle_data in case we have
144
+ # a charref cut in half at end. Try to determine if
145
+ # this is the case before proceeding by looking for an
146
+ # & near the end and see if it's followed by a space or ;.
147
+ amppos = rawdata.rfind('&', max(i, n-34))
148
+ if (amppos >= 0 and
149
+ not re.compile(r'[\s;]').search(rawdata, amppos)):
150
+ break # wait till we get all the text
151
+ j = n
152
+ else:
153
+ match = self.interesting.search(rawdata, i) # < or &
154
+ if match:
155
+ j = match.start()
156
+ else:
157
+ if self.cdata_elem:
158
+ break
159
+ j = n
160
+ if i < j:
161
+ if self.convert_charrefs and not self.cdata_elem:
162
+ self.handle_data(unescape(rawdata[i:j]))
163
+ else:
164
+ self.handle_data(rawdata[i:j])
165
+ i = self.updatepos(i, j)
166
+ if i == n: break
167
+ startswith = rawdata.startswith
168
+ if startswith('<', i):
169
+ if starttagopen.match(rawdata, i): # < + letter
170
+ k = self.parse_starttag(i)
171
+ elif startswith("</", i):
172
+ k = self.parse_endtag(i)
173
+ elif startswith("<!--", i):
174
+ k = self.parse_comment(i)
175
+ elif startswith("<?", i):
176
+ k = self.parse_pi(i)
177
+ elif startswith("<!", i):
178
+ k = self.parse_html_declaration(i)
179
+ elif (i + 1) < n:
180
+ self.handle_data("<")
181
+ k = i + 1
182
+ else:
183
+ break
184
+ if k < 0:
185
+ if not end:
186
+ break
187
+ k = rawdata.find('>', i + 1)
188
+ if k < 0:
189
+ k = rawdata.find('<', i + 1)
190
+ if k < 0:
191
+ k = i + 1
192
+ else:
193
+ k += 1
194
+ if self.convert_charrefs and not self.cdata_elem:
195
+ self.handle_data(unescape(rawdata[i:k]))
196
+ else:
197
+ self.handle_data(rawdata[i:k])
198
+ i = self.updatepos(i, k)
199
+ elif startswith("&#", i):
200
+ match = charref.match(rawdata, i)
201
+ if match:
202
+ name = match.group()[2:-1]
203
+ self.handle_charref(name)
204
+ k = match.end()
205
+ if not startswith(';', k-1):
206
+ k = k - 1
207
+ i = self.updatepos(i, k)
208
+ continue
209
+ else:
210
+ if ";" in rawdata[i:]: # bail by consuming &#
211
+ self.handle_data(rawdata[i:i+2])
212
+ i = self.updatepos(i, i+2)
213
+ break
214
+ elif startswith('&', i):
215
+ match = entityref.match(rawdata, i)
216
+ if match:
217
+ name = match.group(1)
218
+ self.handle_entityref(name)
219
+ k = match.end()
220
+ if not startswith(';', k-1):
221
+ k = k - 1
222
+ i = self.updatepos(i, k)
223
+ continue
224
+ match = incomplete.match(rawdata, i)
225
+ if match:
226
+ # match.group() will contain at least 2 chars
227
+ if end and match.group() == rawdata[i:]:
228
+ k = match.end()
229
+ if k <= i:
230
+ k = n
231
+ i = self.updatepos(i, i + 1)
232
+ # incomplete
233
+ break
234
+ elif (i + 1) < n:
235
+ # not the end of the buffer, and can't be confused
236
+ # with some other construct
237
+ self.handle_data("&")
238
+ i = self.updatepos(i, i + 1)
239
+ else:
240
+ break
241
+ else:
242
+ assert 0, "interesting.search() lied"
243
+ # end while
244
+ if end and i < n and not self.cdata_elem:
245
+ if self.convert_charrefs and not self.cdata_elem:
246
+ self.handle_data(unescape(rawdata[i:n]))
247
+ else:
248
+ self.handle_data(rawdata[i:n])
249
+ i = self.updatepos(i, n)
250
+ self.rawdata = rawdata[i:]
251
+
252
+ # Internal -- parse html declarations, return length or -1 if not terminated
253
+ # See w3.org/TR/html5/tokenization.html#markup-declaration-open-state
254
+ # See also parse_declaration in _markupbase
255
+ def parse_html_declaration(self, i):
256
+ rawdata = self.rawdata
257
+ assert rawdata[i:i+2] == '<!', ('unexpected call to '
258
+ 'parse_html_declaration()')
259
+ if rawdata[i:i+4] == '<!--':
260
+ # this case is actually already handled in goahead()
261
+ return self.parse_comment(i)
262
+ elif rawdata[i:i+3] == '<![':
263
+ return self.parse_marked_section(i)
264
+ elif rawdata[i:i+9].lower() == '<!doctype':
265
+ # find the closing >
266
+ gtpos = rawdata.find('>', i+9)
267
+ if gtpos == -1:
268
+ return -1
269
+ self.handle_decl(rawdata[i+2:gtpos])
270
+ return gtpos+1
271
+ else:
272
+ return self.parse_bogus_comment(i)
273
+
274
+ # Internal -- parse bogus comment, return length or -1 if not terminated
275
+ # see http://www.w3.org/TR/html5/tokenization.html#bogus-comment-state
276
+ def parse_bogus_comment(self, i, report=1):
277
+ rawdata = self.rawdata
278
+ assert rawdata[i:i+2] in ('<!', '</'), ('unexpected call to '
279
+ 'parse_comment()')
280
+ pos = rawdata.find('>', i+2)
281
+ if pos == -1:
282
+ return -1
283
+ if report:
284
+ self.handle_comment(rawdata[i+2:pos])
285
+ return pos + 1
286
+
287
+ # Internal -- parse processing instr, return end or -1 if not terminated
288
+ def parse_pi(self, i):
289
+ rawdata = self.rawdata
290
+ assert rawdata[i:i+2] == '<?', 'unexpected call to parse_pi()'
291
+ match = piclose.search(rawdata, i+2) # >
292
+ if not match:
293
+ return -1
294
+ j = match.start()
295
+ self.handle_pi(rawdata[i+2: j])
296
+ j = match.end()
297
+ return j
298
+
299
+ # Internal -- handle starttag, return end or -1 if not terminated
300
+ def parse_starttag(self, i):
301
+ self.__starttag_text = None
302
+ endpos = self.check_for_whole_start_tag(i)
303
+ if endpos < 0:
304
+ return endpos
305
+ rawdata = self.rawdata
306
+ self.__starttag_text = rawdata[i:endpos]
307
+
308
+ # Now parse the data between i+1 and j into a tag and attrs
309
+ attrs = []
310
+ match = tagfind_tolerant.match(rawdata, i+1)
311
+ assert match, 'unexpected call to parse_starttag()'
312
+ k = match.end()
313
+ self.lasttag = tag = match.group(1).lower()
314
+ while k < endpos:
315
+ m = attrfind_tolerant.match(rawdata, k)
316
+ if not m:
317
+ break
318
+ attrname, rest, attrvalue = m.group(1, 2, 3)
319
+ if not rest:
320
+ attrvalue = None
321
+ elif attrvalue[:1] == '\'' == attrvalue[-1:] or \
322
+ attrvalue[:1] == '"' == attrvalue[-1:]:
323
+ attrvalue = attrvalue[1:-1]
324
+ if attrvalue:
325
+ attrvalue = unescape(attrvalue)
326
+ attrs.append((attrname.lower(), attrvalue))
327
+ k = m.end()
328
+
329
+ end = rawdata[k:endpos].strip()
330
+ if end not in (">", "/>"):
331
+ lineno, offset = self.getpos()
332
+ if "\n" in self.__starttag_text:
333
+ lineno = lineno + self.__starttag_text.count("\n")
334
+ offset = len(self.__starttag_text) \
335
+ - self.__starttag_text.rfind("\n")
336
+ else:
337
+ offset = offset + len(self.__starttag_text)
338
+ self.handle_data(rawdata[i:endpos])
339
+ return endpos
340
+ if end.endswith('/>'):
341
+ # XHTML-style empty tag: <span attr="value" />
342
+ self.handle_startendtag(tag, attrs)
343
+ else:
344
+ self.handle_starttag(tag, attrs)
345
+ if tag in self.CDATA_CONTENT_ELEMENTS:
346
+ self.set_cdata_mode(tag)
347
+ return endpos
348
+
349
+ # Internal -- check to see if we have a complete starttag; return end
350
+ # or -1 if incomplete.
351
+ def check_for_whole_start_tag(self, i):
352
+ rawdata = self.rawdata
353
+ m = locatestarttagend_tolerant.match(rawdata, i)
354
+ if m:
355
+ j = m.end()
356
+ next = rawdata[j:j+1]
357
+ if next == ">":
358
+ return j + 1
359
+ if next == "/":
360
+ if rawdata.startswith("/>", j):
361
+ return j + 2
362
+ if rawdata.startswith("/", j):
363
+ # buffer boundary
364
+ return -1
365
+ # else bogus input
366
+ if j > i:
367
+ return j
368
+ else:
369
+ return i + 1
370
+ if next == "":
371
+ # end of input
372
+ return -1
373
+ if next in ("abcdefghijklmnopqrstuvwxyz=/"
374
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZ"):
375
+ # end of input in or before attribute value, or we have the
376
+ # '/' from a '/>' ending
377
+ return -1
378
+ if j > i:
379
+ return j
380
+ else:
381
+ return i + 1
382
+ raise AssertionError("we should not get here!")
383
+
384
+ # Internal -- parse endtag, return end or -1 if incomplete
385
+ def parse_endtag(self, i):
386
+ rawdata = self.rawdata
387
+ assert rawdata[i:i+2] == "</", "unexpected call to parse_endtag"
388
+ match = endendtag.search(rawdata, i+1) # >
389
+ if not match:
390
+ return -1
391
+ gtpos = match.end()
392
+ match = endtagfind.match(rawdata, i) # </ + tag + >
393
+ if not match:
394
+ if self.cdata_elem is not None:
395
+ self.handle_data(rawdata[i:gtpos])
396
+ return gtpos
397
+ # find the name: w3.org/TR/html5/tokenization.html#tag-name-state
398
+ namematch = tagfind_tolerant.match(rawdata, i+2)
399
+ if not namematch:
400
+ # w3.org/TR/html5/tokenization.html#end-tag-open-state
401
+ if rawdata[i:i+3] == '</>':
402
+ return i+3
403
+ else:
404
+ return self.parse_bogus_comment(i)
405
+ tagname = namematch.group(1).lower()
406
+ # consume and ignore other stuff between the name and the >
407
+ # Note: this is not 100% correct, since we might have things like
408
+ # </tag attr=">">, but looking for > after the name should cover
409
+ # most of the cases and is much simpler
410
+ gtpos = rawdata.find('>', namematch.end())
411
+ self.handle_endtag(tagname)
412
+ return gtpos+1
413
+
414
+ elem = match.group(1).lower() # script or style
415
+ if self.cdata_elem is not None:
416
+ if elem != self.cdata_elem:
417
+ self.handle_data(rawdata[i:gtpos])
418
+ return gtpos
419
+
420
+ self.handle_endtag(elem)
421
+ self.clear_cdata_mode()
422
+ return gtpos
423
+
424
+ # Overridable -- finish processing of start+end tag: <tag.../>
425
+ def handle_startendtag(self, tag, attrs):
426
+ self.handle_starttag(tag, attrs)
427
+ self.handle_endtag(tag)
428
+
429
+ # Overridable -- handle start tag
430
+ def handle_starttag(self, tag, attrs):
431
+ pass
432
+
433
+ # Overridable -- handle end tag
434
+ def handle_endtag(self, tag):
435
+ pass
436
+
437
+ # Overridable -- handle character reference
438
+ def handle_charref(self, name):
439
+ pass
440
+
441
+ # Overridable -- handle entity reference
442
+ def handle_entityref(self, name):
443
+ pass
444
+
445
+ # Overridable -- handle data
446
+ def handle_data(self, data):
447
+ pass
448
+
449
+ # Overridable -- handle comment
450
+ def handle_comment(self, data):
451
+ pass
452
+
453
+ # Overridable -- handle declaration
454
+ def handle_decl(self, decl):
455
+ pass
456
+
457
+ # Overridable -- handle processing instruction
458
+ def handle_pi(self, data):
459
+ pass
460
+
461
+ def unknown_decl(self, data):
462
+ pass
parrot/lib/python3.10/pydoc_data/topics.py ADDED
The diff for this file is too large to render. See raw diff
 
parrot/lib/python3.10/unittest/__init__.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Python unit testing framework, based on Erich Gamma's JUnit and Kent Beck's
3
+ Smalltalk testing framework (used with permission).
4
+
5
+ This module contains the core framework classes that form the basis of
6
+ specific test cases and suites (TestCase, TestSuite etc.), and also a
7
+ text-based utility class for running the tests and reporting the results
8
+ (TextTestRunner).
9
+
10
+ Simple usage:
11
+
12
+ import unittest
13
+
14
+ class IntegerArithmeticTestCase(unittest.TestCase):
15
+ def testAdd(self): # test method names begin with 'test'
16
+ self.assertEqual((1 + 2), 3)
17
+ self.assertEqual(0 + 1, 1)
18
+ def testMultiply(self):
19
+ self.assertEqual((0 * 10), 0)
20
+ self.assertEqual((5 * 8), 40)
21
+
22
+ if __name__ == '__main__':
23
+ unittest.main()
24
+
25
+ Further information is available in the bundled documentation, and from
26
+
27
+ http://docs.python.org/library/unittest.html
28
+
29
+ Copyright (c) 1999-2003 Steve Purcell
30
+ Copyright (c) 2003-2010 Python Software Foundation
31
+ This module is free software, and you may redistribute it and/or modify
32
+ it under the same terms as Python itself, so long as this copyright message
33
+ and disclaimer are retained in their original form.
34
+
35
+ IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
36
+ SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF
37
+ THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
38
+ DAMAGE.
39
+
40
+ THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
41
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
42
+ PARTICULAR PURPOSE. THE CODE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS,
43
+ AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE,
44
+ SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
45
+ """
46
+
47
+ __all__ = ['TestResult', 'TestCase', 'IsolatedAsyncioTestCase', 'TestSuite',
48
+ 'TextTestRunner', 'TestLoader', 'FunctionTestCase', 'main',
49
+ 'defaultTestLoader', 'SkipTest', 'skip', 'skipIf', 'skipUnless',
50
+ 'expectedFailure', 'TextTestResult', 'installHandler',
51
+ 'registerResult', 'removeResult', 'removeHandler',
52
+ 'addModuleCleanup']
53
+
54
+ # Expose obsolete functions for backwards compatibility
55
+ __all__.extend(['getTestCaseNames', 'makeSuite', 'findTestCases'])
56
+
57
+ __unittest = True
58
+
59
+ from .result import TestResult
60
+ from .case import (addModuleCleanup, TestCase, FunctionTestCase, SkipTest, skip,
61
+ skipIf, skipUnless, expectedFailure)
62
+ from .suite import BaseTestSuite, TestSuite
63
+ from .loader import (TestLoader, defaultTestLoader, makeSuite, getTestCaseNames,
64
+ findTestCases)
65
+ from .main import TestProgram, main
66
+ from .runner import TextTestRunner, TextTestResult
67
+ from .signals import installHandler, registerResult, removeResult, removeHandler
68
+ # IsolatedAsyncioTestCase will be imported lazily.
69
+
70
+ # deprecated
71
+ _TextTestResult = TextTestResult
72
+
73
+ # There are no tests here, so don't try to run anything discovered from
74
+ # introspecting the symbols (e.g. FunctionTestCase). Instead, all our
75
+ # tests come from within unittest.test.
76
+ def load_tests(loader, tests, pattern):
77
+ import os.path
78
+ # top level directory cached on loader instance
79
+ this_dir = os.path.dirname(__file__)
80
+ return loader.discover(start_dir=this_dir, pattern=pattern)
81
+
82
+
83
+ # Lazy import of IsolatedAsyncioTestCase from .async_case
84
+ # It imports asyncio, which is relatively heavy, but most tests
85
+ # do not need it.
86
+
87
+ def __dir__():
88
+ return globals().keys() | {'IsolatedAsyncioTestCase'}
89
+
90
+ def __getattr__(name):
91
+ if name == 'IsolatedAsyncioTestCase':
92
+ global IsolatedAsyncioTestCase
93
+ from .async_case import IsolatedAsyncioTestCase
94
+ return IsolatedAsyncioTestCase
95
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
parrot/lib/python3.10/unittest/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (3.65 kB). View file
 
parrot/lib/python3.10/unittest/__pycache__/_log.cpython-310.pyc ADDED
Binary file (2.94 kB). View file
 
parrot/lib/python3.10/unittest/__pycache__/case.cpython-310.pyc ADDED
Binary file (48.7 kB). View file
 
parrot/lib/python3.10/unittest/__pycache__/suite.cpython-310.pyc ADDED
Binary file (10.3 kB). View file
 
parrot/lib/python3.10/unittest/__pycache__/util.cpython-310.pyc ADDED
Binary file (4.54 kB). View file
 
parrot/lib/python3.10/unittest/_log.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import collections
3
+
4
+ from .case import _BaseTestCaseContext
5
+
6
+
7
+ _LoggingWatcher = collections.namedtuple("_LoggingWatcher",
8
+ ["records", "output"])
9
+
10
+ class _CapturingHandler(logging.Handler):
11
+ """
12
+ A logging handler capturing all (raw and formatted) logging output.
13
+ """
14
+
15
+ def __init__(self):
16
+ logging.Handler.__init__(self)
17
+ self.watcher = _LoggingWatcher([], [])
18
+
19
+ def flush(self):
20
+ pass
21
+
22
+ def emit(self, record):
23
+ self.watcher.records.append(record)
24
+ msg = self.format(record)
25
+ self.watcher.output.append(msg)
26
+
27
+
28
+ class _AssertLogsContext(_BaseTestCaseContext):
29
+ """A context manager for assertLogs() and assertNoLogs() """
30
+
31
+ LOGGING_FORMAT = "%(levelname)s:%(name)s:%(message)s"
32
+
33
+ def __init__(self, test_case, logger_name, level, no_logs):
34
+ _BaseTestCaseContext.__init__(self, test_case)
35
+ self.logger_name = logger_name
36
+ if level:
37
+ self.level = logging._nameToLevel.get(level, level)
38
+ else:
39
+ self.level = logging.INFO
40
+ self.msg = None
41
+ self.no_logs = no_logs
42
+
43
+ def __enter__(self):
44
+ if isinstance(self.logger_name, logging.Logger):
45
+ logger = self.logger = self.logger_name
46
+ else:
47
+ logger = self.logger = logging.getLogger(self.logger_name)
48
+ formatter = logging.Formatter(self.LOGGING_FORMAT)
49
+ handler = _CapturingHandler()
50
+ handler.setLevel(self.level)
51
+ handler.setFormatter(formatter)
52
+ self.watcher = handler.watcher
53
+ self.old_handlers = logger.handlers[:]
54
+ self.old_level = logger.level
55
+ self.old_propagate = logger.propagate
56
+ logger.handlers = [handler]
57
+ logger.setLevel(self.level)
58
+ logger.propagate = False
59
+ if self.no_logs:
60
+ return
61
+ return handler.watcher
62
+
63
+ def __exit__(self, exc_type, exc_value, tb):
64
+ self.logger.handlers = self.old_handlers
65
+ self.logger.propagate = self.old_propagate
66
+ self.logger.setLevel(self.old_level)
67
+
68
+ if exc_type is not None:
69
+ # let unexpected exceptions pass through
70
+ return False
71
+
72
+ if self.no_logs:
73
+ # assertNoLogs
74
+ if len(self.watcher.records) > 0:
75
+ self._raiseFailure(
76
+ "Unexpected logs found: {!r}".format(
77
+ self.watcher.output
78
+ )
79
+ )
80
+
81
+ else:
82
+ # assertLogs
83
+ if len(self.watcher.records) == 0:
84
+ self._raiseFailure(
85
+ "no logs of level {} or higher triggered on {}"
86
+ .format(logging.getLevelName(self.level), self.logger.name))
parrot/lib/python3.10/unittest/runner.py ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Running tests"""
2
+
3
+ import sys
4
+ import time
5
+ import warnings
6
+
7
+ from . import result
8
+ from .signals import registerResult
9
+
10
+ __unittest = True
11
+
12
+
13
+ class _WritelnDecorator(object):
14
+ """Used to decorate file-like objects with a handy 'writeln' method"""
15
+ def __init__(self,stream):
16
+ self.stream = stream
17
+
18
+ def __getattr__(self, attr):
19
+ if attr in ('stream', '__getstate__'):
20
+ raise AttributeError(attr)
21
+ return getattr(self.stream,attr)
22
+
23
+ def writeln(self, arg=None):
24
+ if arg:
25
+ self.write(arg)
26
+ self.write('\n') # text-mode streams translate to \r\n if needed
27
+
28
+
29
+ class TextTestResult(result.TestResult):
30
+ """A test result class that can print formatted text results to a stream.
31
+
32
+ Used by TextTestRunner.
33
+ """
34
+ separator1 = '=' * 70
35
+ separator2 = '-' * 70
36
+
37
+ def __init__(self, stream, descriptions, verbosity):
38
+ super(TextTestResult, self).__init__(stream, descriptions, verbosity)
39
+ self.stream = stream
40
+ self.showAll = verbosity > 1
41
+ self.dots = verbosity == 1
42
+ self.descriptions = descriptions
43
+
44
+ def getDescription(self, test):
45
+ doc_first_line = test.shortDescription()
46
+ if self.descriptions and doc_first_line:
47
+ return '\n'.join((str(test), doc_first_line))
48
+ else:
49
+ return str(test)
50
+
51
+ def startTest(self, test):
52
+ super(TextTestResult, self).startTest(test)
53
+ if self.showAll:
54
+ self.stream.write(self.getDescription(test))
55
+ self.stream.write(" ... ")
56
+ self.stream.flush()
57
+
58
+ def addSuccess(self, test):
59
+ super(TextTestResult, self).addSuccess(test)
60
+ if self.showAll:
61
+ self.stream.writeln("ok")
62
+ self.stream.flush()
63
+ elif self.dots:
64
+ self.stream.write('.')
65
+ self.stream.flush()
66
+
67
+ def addError(self, test, err):
68
+ super(TextTestResult, self).addError(test, err)
69
+ if self.showAll:
70
+ self.stream.writeln("ERROR")
71
+ self.stream.flush()
72
+ elif self.dots:
73
+ self.stream.write('E')
74
+ self.stream.flush()
75
+
76
+ def addFailure(self, test, err):
77
+ super(TextTestResult, self).addFailure(test, err)
78
+ if self.showAll:
79
+ self.stream.writeln("FAIL")
80
+ self.stream.flush()
81
+ elif self.dots:
82
+ self.stream.write('F')
83
+ self.stream.flush()
84
+
85
+ def addSkip(self, test, reason):
86
+ super(TextTestResult, self).addSkip(test, reason)
87
+ if self.showAll:
88
+ self.stream.writeln("skipped {0!r}".format(reason))
89
+ self.stream.flush()
90
+ elif self.dots:
91
+ self.stream.write("s")
92
+ self.stream.flush()
93
+
94
+ def addExpectedFailure(self, test, err):
95
+ super(TextTestResult, self).addExpectedFailure(test, err)
96
+ if self.showAll:
97
+ self.stream.writeln("expected failure")
98
+ self.stream.flush()
99
+ elif self.dots:
100
+ self.stream.write("x")
101
+ self.stream.flush()
102
+
103
+ def addUnexpectedSuccess(self, test):
104
+ super(TextTestResult, self).addUnexpectedSuccess(test)
105
+ if self.showAll:
106
+ self.stream.writeln("unexpected success")
107
+ self.stream.flush()
108
+ elif self.dots:
109
+ self.stream.write("u")
110
+ self.stream.flush()
111
+
112
+ def printErrors(self):
113
+ if self.dots or self.showAll:
114
+ self.stream.writeln()
115
+ self.stream.flush()
116
+ self.printErrorList('ERROR', self.errors)
117
+ self.printErrorList('FAIL', self.failures)
118
+
119
+ def printErrorList(self, flavour, errors):
120
+ for test, err in errors:
121
+ self.stream.writeln(self.separator1)
122
+ self.stream.writeln("%s: %s" % (flavour,self.getDescription(test)))
123
+ self.stream.writeln(self.separator2)
124
+ self.stream.writeln("%s" % err)
125
+ self.stream.flush()
126
+
127
+
128
+ class TextTestRunner(object):
129
+ """A test runner class that displays results in textual form.
130
+
131
+ It prints out the names of tests as they are run, errors as they
132
+ occur, and a summary of the results at the end of the test run.
133
+ """
134
+ resultclass = TextTestResult
135
+
136
+ def __init__(self, stream=None, descriptions=True, verbosity=1,
137
+ failfast=False, buffer=False, resultclass=None, warnings=None,
138
+ *, tb_locals=False):
139
+ """Construct a TextTestRunner.
140
+
141
+ Subclasses should accept **kwargs to ensure compatibility as the
142
+ interface changes.
143
+ """
144
+ if stream is None:
145
+ stream = sys.stderr
146
+ self.stream = _WritelnDecorator(stream)
147
+ self.descriptions = descriptions
148
+ self.verbosity = verbosity
149
+ self.failfast = failfast
150
+ self.buffer = buffer
151
+ self.tb_locals = tb_locals
152
+ self.warnings = warnings
153
+ if resultclass is not None:
154
+ self.resultclass = resultclass
155
+
156
+ def _makeResult(self):
157
+ return self.resultclass(self.stream, self.descriptions, self.verbosity)
158
+
159
+ def run(self, test):
160
+ "Run the given test case or test suite."
161
+ result = self._makeResult()
162
+ registerResult(result)
163
+ result.failfast = self.failfast
164
+ result.buffer = self.buffer
165
+ result.tb_locals = self.tb_locals
166
+ with warnings.catch_warnings():
167
+ if self.warnings:
168
+ # if self.warnings is set, use it to filter all the warnings
169
+ warnings.simplefilter(self.warnings)
170
+ # if the filter is 'default' or 'always', special-case the
171
+ # warnings from the deprecated unittest methods to show them
172
+ # no more than once per module, because they can be fairly
173
+ # noisy. The -Wd and -Wa flags can be used to bypass this
174
+ # only when self.warnings is None.
175
+ if self.warnings in ['default', 'always']:
176
+ warnings.filterwarnings('module',
177
+ category=DeprecationWarning,
178
+ message=r'Please use assert\w+ instead.')
179
+ startTime = time.perf_counter()
180
+ startTestRun = getattr(result, 'startTestRun', None)
181
+ if startTestRun is not None:
182
+ startTestRun()
183
+ try:
184
+ test(result)
185
+ finally:
186
+ stopTestRun = getattr(result, 'stopTestRun', None)
187
+ if stopTestRun is not None:
188
+ stopTestRun()
189
+ stopTime = time.perf_counter()
190
+ timeTaken = stopTime - startTime
191
+ result.printErrors()
192
+ if hasattr(result, 'separator2'):
193
+ self.stream.writeln(result.separator2)
194
+ run = result.testsRun
195
+ self.stream.writeln("Ran %d test%s in %.3fs" %
196
+ (run, run != 1 and "s" or "", timeTaken))
197
+ self.stream.writeln()
198
+
199
+ expectedFails = unexpectedSuccesses = skipped = 0
200
+ try:
201
+ results = map(len, (result.expectedFailures,
202
+ result.unexpectedSuccesses,
203
+ result.skipped))
204
+ except AttributeError:
205
+ pass
206
+ else:
207
+ expectedFails, unexpectedSuccesses, skipped = results
208
+
209
+ infos = []
210
+ if not result.wasSuccessful():
211
+ self.stream.write("FAILED")
212
+ failed, errored = len(result.failures), len(result.errors)
213
+ if failed:
214
+ infos.append("failures=%d" % failed)
215
+ if errored:
216
+ infos.append("errors=%d" % errored)
217
+ else:
218
+ self.stream.write("OK")
219
+ if skipped:
220
+ infos.append("skipped=%d" % skipped)
221
+ if expectedFails:
222
+ infos.append("expected failures=%d" % expectedFails)
223
+ if unexpectedSuccesses:
224
+ infos.append("unexpected successes=%d" % unexpectedSuccesses)
225
+ if infos:
226
+ self.stream.writeln(" (%s)" % (", ".join(infos),))
227
+ else:
228
+ self.stream.write("\n")
229
+ self.stream.flush()
230
+ return result
parrot/lib/python3.10/xmlrpc/client.py ADDED
@@ -0,0 +1,1532 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # XML-RPC CLIENT LIBRARY
3
+ # $Id$
4
+ #
5
+ # an XML-RPC client interface for Python.
6
+ #
7
+ # the marshalling and response parser code can also be used to
8
+ # implement XML-RPC servers.
9
+ #
10
+ # Notes:
11
+ # this version is designed to work with Python 2.1 or newer.
12
+ #
13
+ # History:
14
+ # 1999-01-14 fl Created
15
+ # 1999-01-15 fl Changed dateTime to use localtime
16
+ # 1999-01-16 fl Added Binary/base64 element, default to RPC2 service
17
+ # 1999-01-19 fl Fixed array data element (from Skip Montanaro)
18
+ # 1999-01-21 fl Fixed dateTime constructor, etc.
19
+ # 1999-02-02 fl Added fault handling, handle empty sequences, etc.
20
+ # 1999-02-10 fl Fixed problem with empty responses (from Skip Montanaro)
21
+ # 1999-06-20 fl Speed improvements, pluggable parsers/transports (0.9.8)
22
+ # 2000-11-28 fl Changed boolean to check the truth value of its argument
23
+ # 2001-02-24 fl Added encoding/Unicode/SafeTransport patches
24
+ # 2001-02-26 fl Added compare support to wrappers (0.9.9/1.0b1)
25
+ # 2001-03-28 fl Make sure response tuple is a singleton
26
+ # 2001-03-29 fl Don't require empty params element (from Nicholas Riley)
27
+ # 2001-06-10 fl Folded in _xmlrpclib accelerator support (1.0b2)
28
+ # 2001-08-20 fl Base xmlrpclib.Error on built-in Exception (from Paul Prescod)
29
+ # 2001-09-03 fl Allow Transport subclass to override getparser
30
+ # 2001-09-10 fl Lazy import of urllib, cgi, xmllib (20x import speedup)
31
+ # 2001-10-01 fl Remove containers from memo cache when done with them
32
+ # 2001-10-01 fl Use faster escape method (80% dumps speedup)
33
+ # 2001-10-02 fl More dumps microtuning
34
+ # 2001-10-04 fl Make sure import expat gets a parser (from Guido van Rossum)
35
+ # 2001-10-10 sm Allow long ints to be passed as ints if they don't overflow
36
+ # 2001-10-17 sm Test for int and long overflow (allows use on 64-bit systems)
37
+ # 2001-11-12 fl Use repr() to marshal doubles (from Paul Felix)
38
+ # 2002-03-17 fl Avoid buffered read when possible (from James Rucker)
39
+ # 2002-04-07 fl Added pythondoc comments
40
+ # 2002-04-16 fl Added __str__ methods to datetime/binary wrappers
41
+ # 2002-05-15 fl Added error constants (from Andrew Kuchling)
42
+ # 2002-06-27 fl Merged with Python CVS version
43
+ # 2002-10-22 fl Added basic authentication (based on code from Phillip Eby)
44
+ # 2003-01-22 sm Add support for the bool type
45
+ # 2003-02-27 gvr Remove apply calls
46
+ # 2003-04-24 sm Use cStringIO if available
47
+ # 2003-04-25 ak Add support for nil
48
+ # 2003-06-15 gn Add support for time.struct_time
49
+ # 2003-07-12 gp Correct marshalling of Faults
50
+ # 2003-10-31 mvl Add multicall support
51
+ # 2004-08-20 mvl Bump minimum supported Python version to 2.1
52
+ # 2014-12-02 ch/doko Add workaround for gzip bomb vulnerability
53
+ #
54
+ # Copyright (c) 1999-2002 by Secret Labs AB.
55
+ # Copyright (c) 1999-2002 by Fredrik Lundh.
56
+ #
57
+ # info@pythonware.com
58
+ # http://www.pythonware.com
59
+ #
60
+ # --------------------------------------------------------------------
61
+ # The XML-RPC client interface is
62
+ #
63
+ # Copyright (c) 1999-2002 by Secret Labs AB
64
+ # Copyright (c) 1999-2002 by Fredrik Lundh
65
+ #
66
+ # By obtaining, using, and/or copying this software and/or its
67
+ # associated documentation, you agree that you have read, understood,
68
+ # and will comply with the following terms and conditions:
69
+ #
70
+ # Permission to use, copy, modify, and distribute this software and
71
+ # its associated documentation for any purpose and without fee is
72
+ # hereby granted, provided that the above copyright notice appears in
73
+ # all copies, and that both that copyright notice and this permission
74
+ # notice appear in supporting documentation, and that the name of
75
+ # Secret Labs AB or the author not be used in advertising or publicity
76
+ # pertaining to distribution of the software without specific, written
77
+ # prior permission.
78
+ #
79
+ # SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
80
+ # TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
81
+ # ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
82
+ # BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
83
+ # DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
84
+ # WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
85
+ # ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
86
+ # OF THIS SOFTWARE.
87
+ # --------------------------------------------------------------------
88
+
89
+ """
90
+ An XML-RPC client interface for Python.
91
+
92
+ The marshalling and response parser code can also be used to
93
+ implement XML-RPC servers.
94
+
95
+ Exported exceptions:
96
+
97
+ Error Base class for client errors
98
+ ProtocolError Indicates an HTTP protocol error
99
+ ResponseError Indicates a broken response package
100
+ Fault Indicates an XML-RPC fault package
101
+
102
+ Exported classes:
103
+
104
+ ServerProxy Represents a logical connection to an XML-RPC server
105
+
106
+ MultiCall Executor of boxcared xmlrpc requests
107
+ DateTime dateTime wrapper for an ISO 8601 string or time tuple or
108
+ localtime integer value to generate a "dateTime.iso8601"
109
+ XML-RPC value
110
+ Binary binary data wrapper
111
+
112
+ Marshaller Generate an XML-RPC params chunk from a Python data structure
113
+ Unmarshaller Unmarshal an XML-RPC response from incoming XML event message
114
+ Transport Handles an HTTP transaction to an XML-RPC server
115
+ SafeTransport Handles an HTTPS transaction to an XML-RPC server
116
+
117
+ Exported constants:
118
+
119
+ (none)
120
+
121
+ Exported functions:
122
+
123
+ getparser Create instance of the fastest available parser & attach
124
+ to an unmarshalling object
125
+ dumps Convert an argument tuple or a Fault instance to an XML-RPC
126
+ request (or response, if the methodresponse option is used).
127
+ loads Convert an XML-RPC packet to unmarshalled data plus a method
128
+ name (None if not present).
129
+ """
130
+
131
+ import base64
132
+ import sys
133
+ import time
134
+ from datetime import datetime
135
+ from decimal import Decimal
136
+ import http.client
137
+ import urllib.parse
138
+ from xml.parsers import expat
139
+ import errno
140
+ from io import BytesIO
141
+ try:
142
+ import gzip
143
+ except ImportError:
144
+ gzip = None #python can be built without zlib/gzip support
145
+
146
+ # --------------------------------------------------------------------
147
+ # Internal stuff
148
+
149
+ def escape(s):
150
+ s = s.replace("&", "&amp;")
151
+ s = s.replace("<", "&lt;")
152
+ return s.replace(">", "&gt;",)
153
+
154
+ # used in User-Agent header sent
155
+ __version__ = '%d.%d' % sys.version_info[:2]
156
+
157
+ # xmlrpc integer limits
158
+ MAXINT = 2**31-1
159
+ MININT = -2**31
160
+
161
+ # --------------------------------------------------------------------
162
+ # Error constants (from Dan Libby's specification at
163
+ # http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php)
164
+
165
+ # Ranges of errors
166
+ PARSE_ERROR = -32700
167
+ SERVER_ERROR = -32600
168
+ APPLICATION_ERROR = -32500
169
+ SYSTEM_ERROR = -32400
170
+ TRANSPORT_ERROR = -32300
171
+
172
+ # Specific errors
173
+ NOT_WELLFORMED_ERROR = -32700
174
+ UNSUPPORTED_ENCODING = -32701
175
+ INVALID_ENCODING_CHAR = -32702
176
+ INVALID_XMLRPC = -32600
177
+ METHOD_NOT_FOUND = -32601
178
+ INVALID_METHOD_PARAMS = -32602
179
+ INTERNAL_ERROR = -32603
180
+
181
+ # --------------------------------------------------------------------
182
+ # Exceptions
183
+
184
+ ##
185
+ # Base class for all kinds of client-side errors.
186
+
187
+ class Error(Exception):
188
+ """Base class for client errors."""
189
+ __str__ = object.__str__
190
+
191
+ ##
192
+ # Indicates an HTTP-level protocol error. This is raised by the HTTP
193
+ # transport layer, if the server returns an error code other than 200
194
+ # (OK).
195
+ #
196
+ # @param url The target URL.
197
+ # @param errcode The HTTP error code.
198
+ # @param errmsg The HTTP error message.
199
+ # @param headers The HTTP header dictionary.
200
+
201
+ class ProtocolError(Error):
202
+ """Indicates an HTTP protocol error."""
203
+ def __init__(self, url, errcode, errmsg, headers):
204
+ Error.__init__(self)
205
+ self.url = url
206
+ self.errcode = errcode
207
+ self.errmsg = errmsg
208
+ self.headers = headers
209
+ def __repr__(self):
210
+ return (
211
+ "<%s for %s: %s %s>" %
212
+ (self.__class__.__name__, self.url, self.errcode, self.errmsg)
213
+ )
214
+
215
+ ##
216
+ # Indicates a broken XML-RPC response package. This exception is
217
+ # raised by the unmarshalling layer, if the XML-RPC response is
218
+ # malformed.
219
+
220
+ class ResponseError(Error):
221
+ """Indicates a broken response package."""
222
+ pass
223
+
224
+ ##
225
+ # Indicates an XML-RPC fault response package. This exception is
226
+ # raised by the unmarshalling layer, if the XML-RPC response contains
227
+ # a fault string. This exception can also be used as a class, to
228
+ # generate a fault XML-RPC message.
229
+ #
230
+ # @param faultCode The XML-RPC fault code.
231
+ # @param faultString The XML-RPC fault string.
232
+
233
+ class Fault(Error):
234
+ """Indicates an XML-RPC fault package."""
235
+ def __init__(self, faultCode, faultString, **extra):
236
+ Error.__init__(self)
237
+ self.faultCode = faultCode
238
+ self.faultString = faultString
239
+ def __repr__(self):
240
+ return "<%s %s: %r>" % (self.__class__.__name__,
241
+ self.faultCode, self.faultString)
242
+
243
+ # --------------------------------------------------------------------
244
+ # Special values
245
+
246
+ ##
247
+ # Backwards compatibility
248
+
249
+ boolean = Boolean = bool
250
+
251
+ ##
252
+ # Wrapper for XML-RPC DateTime values. This converts a time value to
253
+ # the format used by XML-RPC.
254
+ # <p>
255
+ # The value can be given as a datetime object, as a string in the
256
+ # format "yyyymmddThh:mm:ss", as a 9-item time tuple (as returned by
257
+ # time.localtime()), or an integer value (as returned by time.time()).
258
+ # The wrapper uses time.localtime() to convert an integer to a time
259
+ # tuple.
260
+ #
261
+ # @param value The time, given as a datetime object, an ISO 8601 string,
262
+ # a time tuple, or an integer time value.
263
+
264
+
265
+ # Issue #13305: different format codes across platforms
266
+ _day0 = datetime(1, 1, 1)
267
+ def _try(fmt):
268
+ try:
269
+ return _day0.strftime(fmt) == '0001'
270
+ except ValueError:
271
+ return False
272
+ if _try('%Y'): # Mac OS X
273
+ def _iso8601_format(value):
274
+ return value.strftime("%Y%m%dT%H:%M:%S")
275
+ elif _try('%4Y'): # Linux
276
+ def _iso8601_format(value):
277
+ return value.strftime("%4Y%m%dT%H:%M:%S")
278
+ else:
279
+ def _iso8601_format(value):
280
+ return value.strftime("%Y%m%dT%H:%M:%S").zfill(17)
281
+ del _day0
282
+ del _try
283
+
284
+
285
+ def _strftime(value):
286
+ if isinstance(value, datetime):
287
+ return _iso8601_format(value)
288
+
289
+ if not isinstance(value, (tuple, time.struct_time)):
290
+ if value == 0:
291
+ value = time.time()
292
+ value = time.localtime(value)
293
+
294
+ return "%04d%02d%02dT%02d:%02d:%02d" % value[:6]
295
+
296
+ class DateTime:
297
+ """DateTime wrapper for an ISO 8601 string or time tuple or
298
+ localtime integer value to generate 'dateTime.iso8601' XML-RPC
299
+ value.
300
+ """
301
+
302
+ def __init__(self, value=0):
303
+ if isinstance(value, str):
304
+ self.value = value
305
+ else:
306
+ self.value = _strftime(value)
307
+
308
+ def make_comparable(self, other):
309
+ if isinstance(other, DateTime):
310
+ s = self.value
311
+ o = other.value
312
+ elif isinstance(other, datetime):
313
+ s = self.value
314
+ o = _iso8601_format(other)
315
+ elif isinstance(other, str):
316
+ s = self.value
317
+ o = other
318
+ elif hasattr(other, "timetuple"):
319
+ s = self.timetuple()
320
+ o = other.timetuple()
321
+ else:
322
+ s = self
323
+ o = NotImplemented
324
+ return s, o
325
+
326
+ def __lt__(self, other):
327
+ s, o = self.make_comparable(other)
328
+ if o is NotImplemented:
329
+ return NotImplemented
330
+ return s < o
331
+
332
+ def __le__(self, other):
333
+ s, o = self.make_comparable(other)
334
+ if o is NotImplemented:
335
+ return NotImplemented
336
+ return s <= o
337
+
338
+ def __gt__(self, other):
339
+ s, o = self.make_comparable(other)
340
+ if o is NotImplemented:
341
+ return NotImplemented
342
+ return s > o
343
+
344
+ def __ge__(self, other):
345
+ s, o = self.make_comparable(other)
346
+ if o is NotImplemented:
347
+ return NotImplemented
348
+ return s >= o
349
+
350
+ def __eq__(self, other):
351
+ s, o = self.make_comparable(other)
352
+ if o is NotImplemented:
353
+ return NotImplemented
354
+ return s == o
355
+
356
+ def timetuple(self):
357
+ return time.strptime(self.value, "%Y%m%dT%H:%M:%S")
358
+
359
+ ##
360
+ # Get date/time value.
361
+ #
362
+ # @return Date/time value, as an ISO 8601 string.
363
+
364
+ def __str__(self):
365
+ return self.value
366
+
367
+ def __repr__(self):
368
+ return "<%s %r at %#x>" % (self.__class__.__name__, self.value, id(self))
369
+
370
+ def decode(self, data):
371
+ self.value = str(data).strip()
372
+
373
+ def encode(self, out):
374
+ out.write("<value><dateTime.iso8601>")
375
+ out.write(self.value)
376
+ out.write("</dateTime.iso8601></value>\n")
377
+
378
+ def _datetime(data):
379
+ # decode xml element contents into a DateTime structure.
380
+ value = DateTime()
381
+ value.decode(data)
382
+ return value
383
+
384
+ def _datetime_type(data):
385
+ return datetime.strptime(data, "%Y%m%dT%H:%M:%S")
386
+
387
+ ##
388
+ # Wrapper for binary data. This can be used to transport any kind
389
+ # of binary data over XML-RPC, using BASE64 encoding.
390
+ #
391
+ # @param data An 8-bit string containing arbitrary data.
392
+
393
+ class Binary:
394
+ """Wrapper for binary data."""
395
+
396
+ def __init__(self, data=None):
397
+ if data is None:
398
+ data = b""
399
+ else:
400
+ if not isinstance(data, (bytes, bytearray)):
401
+ raise TypeError("expected bytes or bytearray, not %s" %
402
+ data.__class__.__name__)
403
+ data = bytes(data) # Make a copy of the bytes!
404
+ self.data = data
405
+
406
+ ##
407
+ # Get buffer contents.
408
+ #
409
+ # @return Buffer contents, as an 8-bit string.
410
+
411
+ def __str__(self):
412
+ return str(self.data, "latin-1") # XXX encoding?!
413
+
414
+ def __eq__(self, other):
415
+ if isinstance(other, Binary):
416
+ other = other.data
417
+ return self.data == other
418
+
419
+ def decode(self, data):
420
+ self.data = base64.decodebytes(data)
421
+
422
+ def encode(self, out):
423
+ out.write("<value><base64>\n")
424
+ encoded = base64.encodebytes(self.data)
425
+ out.write(encoded.decode('ascii'))
426
+ out.write("</base64></value>\n")
427
+
428
+ def _binary(data):
429
+ # decode xml element contents into a Binary structure
430
+ value = Binary()
431
+ value.decode(data)
432
+ return value
433
+
434
+ WRAPPERS = (DateTime, Binary)
435
+
436
+ # --------------------------------------------------------------------
437
+ # XML parsers
438
+
439
+ class ExpatParser:
440
+ # fast expat parser for Python 2.0 and later.
441
+ def __init__(self, target):
442
+ self._parser = parser = expat.ParserCreate(None, None)
443
+ self._target = target
444
+ parser.StartElementHandler = target.start
445
+ parser.EndElementHandler = target.end
446
+ parser.CharacterDataHandler = target.data
447
+ encoding = None
448
+ target.xml(encoding, None)
449
+
450
+ def feed(self, data):
451
+ self._parser.Parse(data, False)
452
+
453
+ def close(self):
454
+ try:
455
+ parser = self._parser
456
+ except AttributeError:
457
+ pass
458
+ else:
459
+ del self._target, self._parser # get rid of circular references
460
+ parser.Parse(b"", True) # end of data
461
+
462
+ # --------------------------------------------------------------------
463
+ # XML-RPC marshalling and unmarshalling code
464
+
465
+ ##
466
+ # XML-RPC marshaller.
467
+ #
468
+ # @param encoding Default encoding for 8-bit strings. The default
469
+ # value is None (interpreted as UTF-8).
470
+ # @see dumps
471
+
472
+ class Marshaller:
473
+ """Generate an XML-RPC params chunk from a Python data structure.
474
+
475
+ Create a Marshaller instance for each set of parameters, and use
476
+ the "dumps" method to convert your data (represented as a tuple)
477
+ to an XML-RPC params chunk. To write a fault response, pass a
478
+ Fault instance instead. You may prefer to use the "dumps" module
479
+ function for this purpose.
480
+ """
481
+
482
+ # by the way, if you don't understand what's going on in here,
483
+ # that's perfectly ok.
484
+
485
+ def __init__(self, encoding=None, allow_none=False):
486
+ self.memo = {}
487
+ self.data = None
488
+ self.encoding = encoding
489
+ self.allow_none = allow_none
490
+
491
+ dispatch = {}
492
+
493
+ def dumps(self, values):
494
+ out = []
495
+ write = out.append
496
+ dump = self.__dump
497
+ if isinstance(values, Fault):
498
+ # fault instance
499
+ write("<fault>\n")
500
+ dump({'faultCode': values.faultCode,
501
+ 'faultString': values.faultString},
502
+ write)
503
+ write("</fault>\n")
504
+ else:
505
+ # parameter block
506
+ # FIXME: the xml-rpc specification allows us to leave out
507
+ # the entire <params> block if there are no parameters.
508
+ # however, changing this may break older code (including
509
+ # old versions of xmlrpclib.py), so this is better left as
510
+ # is for now. See @XMLRPC3 for more information. /F
511
+ write("<params>\n")
512
+ for v in values:
513
+ write("<param>\n")
514
+ dump(v, write)
515
+ write("</param>\n")
516
+ write("</params>\n")
517
+ result = "".join(out)
518
+ return result
519
+
520
+ def __dump(self, value, write):
521
+ try:
522
+ f = self.dispatch[type(value)]
523
+ except KeyError:
524
+ # check if this object can be marshalled as a structure
525
+ if not hasattr(value, '__dict__'):
526
+ raise TypeError("cannot marshal %s objects" % type(value))
527
+ # check if this class is a sub-class of a basic type,
528
+ # because we don't know how to marshal these types
529
+ # (e.g. a string sub-class)
530
+ for type_ in type(value).__mro__:
531
+ if type_ in self.dispatch.keys():
532
+ raise TypeError("cannot marshal %s objects" % type(value))
533
+ # XXX(twouters): using "_arbitrary_instance" as key as a quick-fix
534
+ # for the p3yk merge, this should probably be fixed more neatly.
535
+ f = self.dispatch["_arbitrary_instance"]
536
+ f(self, value, write)
537
+
538
+ def dump_nil (self, value, write):
539
+ if not self.allow_none:
540
+ raise TypeError("cannot marshal None unless allow_none is enabled")
541
+ write("<value><nil/></value>")
542
+ dispatch[type(None)] = dump_nil
543
+
544
+ def dump_bool(self, value, write):
545
+ write("<value><boolean>")
546
+ write(value and "1" or "0")
547
+ write("</boolean></value>\n")
548
+ dispatch[bool] = dump_bool
549
+
550
+ def dump_long(self, value, write):
551
+ if value > MAXINT or value < MININT:
552
+ raise OverflowError("int exceeds XML-RPC limits")
553
+ write("<value><int>")
554
+ write(str(int(value)))
555
+ write("</int></value>\n")
556
+ dispatch[int] = dump_long
557
+
558
+ # backward compatible
559
+ dump_int = dump_long
560
+
561
+ def dump_double(self, value, write):
562
+ write("<value><double>")
563
+ write(repr(value))
564
+ write("</double></value>\n")
565
+ dispatch[float] = dump_double
566
+
567
+ def dump_unicode(self, value, write, escape=escape):
568
+ write("<value><string>")
569
+ write(escape(value))
570
+ write("</string></value>\n")
571
+ dispatch[str] = dump_unicode
572
+
573
+ def dump_bytes(self, value, write):
574
+ write("<value><base64>\n")
575
+ encoded = base64.encodebytes(value)
576
+ write(encoded.decode('ascii'))
577
+ write("</base64></value>\n")
578
+ dispatch[bytes] = dump_bytes
579
+ dispatch[bytearray] = dump_bytes
580
+
581
+ def dump_array(self, value, write):
582
+ i = id(value)
583
+ if i in self.memo:
584
+ raise TypeError("cannot marshal recursive sequences")
585
+ self.memo[i] = None
586
+ dump = self.__dump
587
+ write("<value><array><data>\n")
588
+ for v in value:
589
+ dump(v, write)
590
+ write("</data></array></value>\n")
591
+ del self.memo[i]
592
+ dispatch[tuple] = dump_array
593
+ dispatch[list] = dump_array
594
+
595
+ def dump_struct(self, value, write, escape=escape):
596
+ i = id(value)
597
+ if i in self.memo:
598
+ raise TypeError("cannot marshal recursive dictionaries")
599
+ self.memo[i] = None
600
+ dump = self.__dump
601
+ write("<value><struct>\n")
602
+ for k, v in value.items():
603
+ write("<member>\n")
604
+ if not isinstance(k, str):
605
+ raise TypeError("dictionary key must be string")
606
+ write("<name>%s</name>\n" % escape(k))
607
+ dump(v, write)
608
+ write("</member>\n")
609
+ write("</struct></value>\n")
610
+ del self.memo[i]
611
+ dispatch[dict] = dump_struct
612
+
613
+ def dump_datetime(self, value, write):
614
+ write("<value><dateTime.iso8601>")
615
+ write(_strftime(value))
616
+ write("</dateTime.iso8601></value>\n")
617
+ dispatch[datetime] = dump_datetime
618
+
619
+ def dump_instance(self, value, write):
620
+ # check for special wrappers
621
+ if value.__class__ in WRAPPERS:
622
+ self.write = write
623
+ value.encode(self)
624
+ del self.write
625
+ else:
626
+ # store instance attributes as a struct (really?)
627
+ self.dump_struct(value.__dict__, write)
628
+ dispatch[DateTime] = dump_instance
629
+ dispatch[Binary] = dump_instance
630
+ # XXX(twouters): using "_arbitrary_instance" as key as a quick-fix
631
+ # for the p3yk merge, this should probably be fixed more neatly.
632
+ dispatch["_arbitrary_instance"] = dump_instance
633
+
634
+ ##
635
+ # XML-RPC unmarshaller.
636
+ #
637
+ # @see loads
638
+
639
+ class Unmarshaller:
640
+ """Unmarshal an XML-RPC response, based on incoming XML event
641
+ messages (start, data, end). Call close() to get the resulting
642
+ data structure.
643
+
644
+ Note that this reader is fairly tolerant, and gladly accepts bogus
645
+ XML-RPC data without complaining (but not bogus XML).
646
+ """
647
+
648
+ # and again, if you don't understand what's going on in here,
649
+ # that's perfectly ok.
650
+
651
+ def __init__(self, use_datetime=False, use_builtin_types=False):
652
+ self._type = None
653
+ self._stack = []
654
+ self._marks = []
655
+ self._data = []
656
+ self._value = False
657
+ self._methodname = None
658
+ self._encoding = "utf-8"
659
+ self.append = self._stack.append
660
+ self._use_datetime = use_builtin_types or use_datetime
661
+ self._use_bytes = use_builtin_types
662
+
663
+ def close(self):
664
+ # return response tuple and target method
665
+ if self._type is None or self._marks:
666
+ raise ResponseError()
667
+ if self._type == "fault":
668
+ raise Fault(**self._stack[0])
669
+ return tuple(self._stack)
670
+
671
+ def getmethodname(self):
672
+ return self._methodname
673
+
674
+ #
675
+ # event handlers
676
+
677
+ def xml(self, encoding, standalone):
678
+ self._encoding = encoding
679
+ # FIXME: assert standalone == 1 ???
680
+
681
+ def start(self, tag, attrs):
682
+ # prepare to handle this element
683
+ if ':' in tag:
684
+ tag = tag.split(':')[-1]
685
+ if tag == "array" or tag == "struct":
686
+ self._marks.append(len(self._stack))
687
+ self._data = []
688
+ if self._value and tag not in self.dispatch:
689
+ raise ResponseError("unknown tag %r" % tag)
690
+ self._value = (tag == "value")
691
+
692
+ def data(self, text):
693
+ self._data.append(text)
694
+
695
+ def end(self, tag):
696
+ # call the appropriate end tag handler
697
+ try:
698
+ f = self.dispatch[tag]
699
+ except KeyError:
700
+ if ':' not in tag:
701
+ return # unknown tag ?
702
+ try:
703
+ f = self.dispatch[tag.split(':')[-1]]
704
+ except KeyError:
705
+ return # unknown tag ?
706
+ return f(self, "".join(self._data))
707
+
708
+ #
709
+ # accelerator support
710
+
711
+ def end_dispatch(self, tag, data):
712
+ # dispatch data
713
+ try:
714
+ f = self.dispatch[tag]
715
+ except KeyError:
716
+ if ':' not in tag:
717
+ return # unknown tag ?
718
+ try:
719
+ f = self.dispatch[tag.split(':')[-1]]
720
+ except KeyError:
721
+ return # unknown tag ?
722
+ return f(self, data)
723
+
724
+ #
725
+ # element decoders
726
+
727
+ dispatch = {}
728
+
729
+ def end_nil (self, data):
730
+ self.append(None)
731
+ self._value = 0
732
+ dispatch["nil"] = end_nil
733
+
734
+ def end_boolean(self, data):
735
+ if data == "0":
736
+ self.append(False)
737
+ elif data == "1":
738
+ self.append(True)
739
+ else:
740
+ raise TypeError("bad boolean value")
741
+ self._value = 0
742
+ dispatch["boolean"] = end_boolean
743
+
744
+ def end_int(self, data):
745
+ self.append(int(data))
746
+ self._value = 0
747
+ dispatch["i1"] = end_int
748
+ dispatch["i2"] = end_int
749
+ dispatch["i4"] = end_int
750
+ dispatch["i8"] = end_int
751
+ dispatch["int"] = end_int
752
+ dispatch["biginteger"] = end_int
753
+
754
+ def end_double(self, data):
755
+ self.append(float(data))
756
+ self._value = 0
757
+ dispatch["double"] = end_double
758
+ dispatch["float"] = end_double
759
+
760
+ def end_bigdecimal(self, data):
761
+ self.append(Decimal(data))
762
+ self._value = 0
763
+ dispatch["bigdecimal"] = end_bigdecimal
764
+
765
+ def end_string(self, data):
766
+ if self._encoding:
767
+ data = data.decode(self._encoding)
768
+ self.append(data)
769
+ self._value = 0
770
+ dispatch["string"] = end_string
771
+ dispatch["name"] = end_string # struct keys are always strings
772
+
773
+ def end_array(self, data):
774
+ mark = self._marks.pop()
775
+ # map arrays to Python lists
776
+ self._stack[mark:] = [self._stack[mark:]]
777
+ self._value = 0
778
+ dispatch["array"] = end_array
779
+
780
+ def end_struct(self, data):
781
+ mark = self._marks.pop()
782
+ # map structs to Python dictionaries
783
+ dict = {}
784
+ items = self._stack[mark:]
785
+ for i in range(0, len(items), 2):
786
+ dict[items[i]] = items[i+1]
787
+ self._stack[mark:] = [dict]
788
+ self._value = 0
789
+ dispatch["struct"] = end_struct
790
+
791
+ def end_base64(self, data):
792
+ value = Binary()
793
+ value.decode(data.encode("ascii"))
794
+ if self._use_bytes:
795
+ value = value.data
796
+ self.append(value)
797
+ self._value = 0
798
+ dispatch["base64"] = end_base64
799
+
800
+ def end_dateTime(self, data):
801
+ value = DateTime()
802
+ value.decode(data)
803
+ if self._use_datetime:
804
+ value = _datetime_type(data)
805
+ self.append(value)
806
+ dispatch["dateTime.iso8601"] = end_dateTime
807
+
808
+ def end_value(self, data):
809
+ # if we stumble upon a value element with no internal
810
+ # elements, treat it as a string element
811
+ if self._value:
812
+ self.end_string(data)
813
+ dispatch["value"] = end_value
814
+
815
+ def end_params(self, data):
816
+ self._type = "params"
817
+ dispatch["params"] = end_params
818
+
819
+ def end_fault(self, data):
820
+ self._type = "fault"
821
+ dispatch["fault"] = end_fault
822
+
823
+ def end_methodName(self, data):
824
+ if self._encoding:
825
+ data = data.decode(self._encoding)
826
+ self._methodname = data
827
+ self._type = "methodName" # no params
828
+ dispatch["methodName"] = end_methodName
829
+
830
+ ## Multicall support
831
+ #
832
+
833
+ class _MultiCallMethod:
834
+ # some lesser magic to store calls made to a MultiCall object
835
+ # for batch execution
836
+ def __init__(self, call_list, name):
837
+ self.__call_list = call_list
838
+ self.__name = name
839
+ def __getattr__(self, name):
840
+ return _MultiCallMethod(self.__call_list, "%s.%s" % (self.__name, name))
841
+ def __call__(self, *args):
842
+ self.__call_list.append((self.__name, args))
843
+
844
+ class MultiCallIterator:
845
+ """Iterates over the results of a multicall. Exceptions are
846
+ raised in response to xmlrpc faults."""
847
+
848
+ def __init__(self, results):
849
+ self.results = results
850
+
851
+ def __getitem__(self, i):
852
+ item = self.results[i]
853
+ if type(item) == type({}):
854
+ raise Fault(item['faultCode'], item['faultString'])
855
+ elif type(item) == type([]):
856
+ return item[0]
857
+ else:
858
+ raise ValueError("unexpected type in multicall result")
859
+
860
+ class MultiCall:
861
+ """server -> an object used to boxcar method calls
862
+
863
+ server should be a ServerProxy object.
864
+
865
+ Methods can be added to the MultiCall using normal
866
+ method call syntax e.g.:
867
+
868
+ multicall = MultiCall(server_proxy)
869
+ multicall.add(2,3)
870
+ multicall.get_address("Guido")
871
+
872
+ To execute the multicall, call the MultiCall object e.g.:
873
+
874
+ add_result, address = multicall()
875
+ """
876
+
877
+ def __init__(self, server):
878
+ self.__server = server
879
+ self.__call_list = []
880
+
881
+ def __repr__(self):
882
+ return "<%s at %#x>" % (self.__class__.__name__, id(self))
883
+
884
+ def __getattr__(self, name):
885
+ return _MultiCallMethod(self.__call_list, name)
886
+
887
+ def __call__(self):
888
+ marshalled_list = []
889
+ for name, args in self.__call_list:
890
+ marshalled_list.append({'methodName' : name, 'params' : args})
891
+
892
+ return MultiCallIterator(self.__server.system.multicall(marshalled_list))
893
+
894
+ # --------------------------------------------------------------------
895
+ # convenience functions
896
+
897
+ FastMarshaller = FastParser = FastUnmarshaller = None
898
+
899
+ ##
900
+ # Create a parser object, and connect it to an unmarshalling instance.
901
+ # This function picks the fastest available XML parser.
902
+ #
903
+ # return A (parser, unmarshaller) tuple.
904
+
905
+ def getparser(use_datetime=False, use_builtin_types=False):
906
+ """getparser() -> parser, unmarshaller
907
+
908
+ Create an instance of the fastest available parser, and attach it
909
+ to an unmarshalling object. Return both objects.
910
+ """
911
+ if FastParser and FastUnmarshaller:
912
+ if use_builtin_types:
913
+ mkdatetime = _datetime_type
914
+ mkbytes = base64.decodebytes
915
+ elif use_datetime:
916
+ mkdatetime = _datetime_type
917
+ mkbytes = _binary
918
+ else:
919
+ mkdatetime = _datetime
920
+ mkbytes = _binary
921
+ target = FastUnmarshaller(True, False, mkbytes, mkdatetime, Fault)
922
+ parser = FastParser(target)
923
+ else:
924
+ target = Unmarshaller(use_datetime=use_datetime, use_builtin_types=use_builtin_types)
925
+ if FastParser:
926
+ parser = FastParser(target)
927
+ else:
928
+ parser = ExpatParser(target)
929
+ return parser, target
930
+
931
+ ##
932
+ # Convert a Python tuple or a Fault instance to an XML-RPC packet.
933
+ #
934
+ # @def dumps(params, **options)
935
+ # @param params A tuple or Fault instance.
936
+ # @keyparam methodname If given, create a methodCall request for
937
+ # this method name.
938
+ # @keyparam methodresponse If given, create a methodResponse packet.
939
+ # If used with a tuple, the tuple must be a singleton (that is,
940
+ # it must contain exactly one element).
941
+ # @keyparam encoding The packet encoding.
942
+ # @return A string containing marshalled data.
943
+
944
+ def dumps(params, methodname=None, methodresponse=None, encoding=None,
945
+ allow_none=False):
946
+ """data [,options] -> marshalled data
947
+
948
+ Convert an argument tuple or a Fault instance to an XML-RPC
949
+ request (or response, if the methodresponse option is used).
950
+
951
+ In addition to the data object, the following options can be given
952
+ as keyword arguments:
953
+
954
+ methodname: the method name for a methodCall packet
955
+
956
+ methodresponse: true to create a methodResponse packet.
957
+ If this option is used with a tuple, the tuple must be
958
+ a singleton (i.e. it can contain only one element).
959
+
960
+ encoding: the packet encoding (default is UTF-8)
961
+
962
+ All byte strings in the data structure are assumed to use the
963
+ packet encoding. Unicode strings are automatically converted,
964
+ where necessary.
965
+ """
966
+
967
+ assert isinstance(params, (tuple, Fault)), "argument must be tuple or Fault instance"
968
+ if isinstance(params, Fault):
969
+ methodresponse = 1
970
+ elif methodresponse and isinstance(params, tuple):
971
+ assert len(params) == 1, "response tuple must be a singleton"
972
+
973
+ if not encoding:
974
+ encoding = "utf-8"
975
+
976
+ if FastMarshaller:
977
+ m = FastMarshaller(encoding)
978
+ else:
979
+ m = Marshaller(encoding, allow_none)
980
+
981
+ data = m.dumps(params)
982
+
983
+ if encoding != "utf-8":
984
+ xmlheader = "<?xml version='1.0' encoding='%s'?>\n" % str(encoding)
985
+ else:
986
+ xmlheader = "<?xml version='1.0'?>\n" # utf-8 is default
987
+
988
+ # standard XML-RPC wrappings
989
+ if methodname:
990
+ # a method call
991
+ data = (
992
+ xmlheader,
993
+ "<methodCall>\n"
994
+ "<methodName>", methodname, "</methodName>\n",
995
+ data,
996
+ "</methodCall>\n"
997
+ )
998
+ elif methodresponse:
999
+ # a method response, or a fault structure
1000
+ data = (
1001
+ xmlheader,
1002
+ "<methodResponse>\n",
1003
+ data,
1004
+ "</methodResponse>\n"
1005
+ )
1006
+ else:
1007
+ return data # return as is
1008
+ return "".join(data)
1009
+
1010
+ ##
1011
+ # Convert an XML-RPC packet to a Python object. If the XML-RPC packet
1012
+ # represents a fault condition, this function raises a Fault exception.
1013
+ #
1014
+ # @param data An XML-RPC packet, given as an 8-bit string.
1015
+ # @return A tuple containing the unpacked data, and the method name
1016
+ # (None if not present).
1017
+ # @see Fault
1018
+
1019
+ def loads(data, use_datetime=False, use_builtin_types=False):
1020
+ """data -> unmarshalled data, method name
1021
+
1022
+ Convert an XML-RPC packet to unmarshalled data plus a method
1023
+ name (None if not present).
1024
+
1025
+ If the XML-RPC packet represents a fault condition, this function
1026
+ raises a Fault exception.
1027
+ """
1028
+ p, u = getparser(use_datetime=use_datetime, use_builtin_types=use_builtin_types)
1029
+ p.feed(data)
1030
+ p.close()
1031
+ return u.close(), u.getmethodname()
1032
+
1033
+ ##
1034
+ # Encode a string using the gzip content encoding such as specified by the
1035
+ # Content-Encoding: gzip
1036
+ # in the HTTP header, as described in RFC 1952
1037
+ #
1038
+ # @param data the unencoded data
1039
+ # @return the encoded data
1040
+
1041
+ def gzip_encode(data):
1042
+ """data -> gzip encoded data
1043
+
1044
+ Encode data using the gzip content encoding as described in RFC 1952
1045
+ """
1046
+ if not gzip:
1047
+ raise NotImplementedError
1048
+ f = BytesIO()
1049
+ with gzip.GzipFile(mode="wb", fileobj=f, compresslevel=1) as gzf:
1050
+ gzf.write(data)
1051
+ return f.getvalue()
1052
+
1053
+ ##
1054
+ # Decode a string using the gzip content encoding such as specified by the
1055
+ # Content-Encoding: gzip
1056
+ # in the HTTP header, as described in RFC 1952
1057
+ #
1058
+ # @param data The encoded data
1059
+ # @keyparam max_decode Maximum bytes to decode (20 MiB default), use negative
1060
+ # values for unlimited decoding
1061
+ # @return the unencoded data
1062
+ # @raises ValueError if data is not correctly coded.
1063
+ # @raises ValueError if max gzipped payload length exceeded
1064
+
1065
+ def gzip_decode(data, max_decode=20971520):
1066
+ """gzip encoded data -> unencoded data
1067
+
1068
+ Decode data using the gzip content encoding as described in RFC 1952
1069
+ """
1070
+ if not gzip:
1071
+ raise NotImplementedError
1072
+ with gzip.GzipFile(mode="rb", fileobj=BytesIO(data)) as gzf:
1073
+ try:
1074
+ if max_decode < 0: # no limit
1075
+ decoded = gzf.read()
1076
+ else:
1077
+ decoded = gzf.read(max_decode + 1)
1078
+ except OSError:
1079
+ raise ValueError("invalid data")
1080
+ if max_decode >= 0 and len(decoded) > max_decode:
1081
+ raise ValueError("max gzipped payload length exceeded")
1082
+ return decoded
1083
+
1084
+ ##
1085
+ # Return a decoded file-like object for the gzip encoding
1086
+ # as described in RFC 1952.
1087
+ #
1088
+ # @param response A stream supporting a read() method
1089
+ # @return a file-like object that the decoded data can be read() from
1090
+
1091
+ class GzipDecodedResponse(gzip.GzipFile if gzip else object):
1092
+ """a file-like object to decode a response encoded with the gzip
1093
+ method, as described in RFC 1952.
1094
+ """
1095
+ def __init__(self, response):
1096
+ #response doesn't support tell() and read(), required by
1097
+ #GzipFile
1098
+ if not gzip:
1099
+ raise NotImplementedError
1100
+ self.io = BytesIO(response.read())
1101
+ gzip.GzipFile.__init__(self, mode="rb", fileobj=self.io)
1102
+
1103
+ def close(self):
1104
+ try:
1105
+ gzip.GzipFile.close(self)
1106
+ finally:
1107
+ self.io.close()
1108
+
1109
+
1110
+ # --------------------------------------------------------------------
1111
+ # request dispatcher
1112
+
1113
+ class _Method:
1114
+ # some magic to bind an XML-RPC method to an RPC server.
1115
+ # supports "nested" methods (e.g. examples.getStateName)
1116
+ def __init__(self, send, name):
1117
+ self.__send = send
1118
+ self.__name = name
1119
+ def __getattr__(self, name):
1120
+ return _Method(self.__send, "%s.%s" % (self.__name, name))
1121
+ def __call__(self, *args):
1122
+ return self.__send(self.__name, args)
1123
+
1124
+ ##
1125
+ # Standard transport class for XML-RPC over HTTP.
1126
+ # <p>
1127
+ # You can create custom transports by subclassing this method, and
1128
+ # overriding selected methods.
1129
+
1130
+ class Transport:
1131
+ """Handles an HTTP transaction to an XML-RPC server."""
1132
+
1133
+ # client identifier (may be overridden)
1134
+ user_agent = "Python-xmlrpc/%s" % __version__
1135
+
1136
+ #if true, we'll request gzip encoding
1137
+ accept_gzip_encoding = True
1138
+
1139
+ # if positive, encode request using gzip if it exceeds this threshold
1140
+ # note that many servers will get confused, so only use it if you know
1141
+ # that they can decode such a request
1142
+ encode_threshold = None #None = don't encode
1143
+
1144
+ def __init__(self, use_datetime=False, use_builtin_types=False,
1145
+ *, headers=()):
1146
+ self._use_datetime = use_datetime
1147
+ self._use_builtin_types = use_builtin_types
1148
+ self._connection = (None, None)
1149
+ self._headers = list(headers)
1150
+ self._extra_headers = []
1151
+
1152
+ ##
1153
+ # Send a complete request, and parse the response.
1154
+ # Retry request if a cached connection has disconnected.
1155
+ #
1156
+ # @param host Target host.
1157
+ # @param handler Target PRC handler.
1158
+ # @param request_body XML-RPC request body.
1159
+ # @param verbose Debugging flag.
1160
+ # @return Parsed response.
1161
+
1162
+ def request(self, host, handler, request_body, verbose=False):
1163
+ #retry request once if cached connection has gone cold
1164
+ for i in (0, 1):
1165
+ try:
1166
+ return self.single_request(host, handler, request_body, verbose)
1167
+ except http.client.RemoteDisconnected:
1168
+ if i:
1169
+ raise
1170
+ except OSError as e:
1171
+ if i or e.errno not in (errno.ECONNRESET, errno.ECONNABORTED,
1172
+ errno.EPIPE):
1173
+ raise
1174
+
1175
+ def single_request(self, host, handler, request_body, verbose=False):
1176
+ # issue XML-RPC request
1177
+ try:
1178
+ http_conn = self.send_request(host, handler, request_body, verbose)
1179
+ resp = http_conn.getresponse()
1180
+ if resp.status == 200:
1181
+ self.verbose = verbose
1182
+ return self.parse_response(resp)
1183
+
1184
+ except Fault:
1185
+ raise
1186
+ except Exception:
1187
+ #All unexpected errors leave connection in
1188
+ # a strange state, so we clear it.
1189
+ self.close()
1190
+ raise
1191
+
1192
+ #We got an error response.
1193
+ #Discard any response data and raise exception
1194
+ if resp.getheader("content-length", ""):
1195
+ resp.read()
1196
+ raise ProtocolError(
1197
+ host + handler,
1198
+ resp.status, resp.reason,
1199
+ dict(resp.getheaders())
1200
+ )
1201
+
1202
+
1203
+ ##
1204
+ # Create parser.
1205
+ #
1206
+ # @return A 2-tuple containing a parser and an unmarshaller.
1207
+
1208
+ def getparser(self):
1209
+ # get parser and unmarshaller
1210
+ return getparser(use_datetime=self._use_datetime,
1211
+ use_builtin_types=self._use_builtin_types)
1212
+
1213
+ ##
1214
+ # Get authorization info from host parameter
1215
+ # Host may be a string, or a (host, x509-dict) tuple; if a string,
1216
+ # it is checked for a "user:pw@host" format, and a "Basic
1217
+ # Authentication" header is added if appropriate.
1218
+ #
1219
+ # @param host Host descriptor (URL or (URL, x509 info) tuple).
1220
+ # @return A 3-tuple containing (actual host, extra headers,
1221
+ # x509 info). The header and x509 fields may be None.
1222
+
1223
+ def get_host_info(self, host):
1224
+
1225
+ x509 = {}
1226
+ if isinstance(host, tuple):
1227
+ host, x509 = host
1228
+
1229
+ auth, host = urllib.parse._splituser(host)
1230
+
1231
+ if auth:
1232
+ auth = urllib.parse.unquote_to_bytes(auth)
1233
+ auth = base64.encodebytes(auth).decode("utf-8")
1234
+ auth = "".join(auth.split()) # get rid of whitespace
1235
+ extra_headers = [
1236
+ ("Authorization", "Basic " + auth)
1237
+ ]
1238
+ else:
1239
+ extra_headers = []
1240
+
1241
+ return host, extra_headers, x509
1242
+
1243
+ ##
1244
+ # Connect to server.
1245
+ #
1246
+ # @param host Target host.
1247
+ # @return An HTTPConnection object
1248
+
1249
+ def make_connection(self, host):
1250
+ #return an existing connection if possible. This allows
1251
+ #HTTP/1.1 keep-alive.
1252
+ if self._connection and host == self._connection[0]:
1253
+ return self._connection[1]
1254
+ # create a HTTP connection object from a host descriptor
1255
+ chost, self._extra_headers, x509 = self.get_host_info(host)
1256
+ self._connection = host, http.client.HTTPConnection(chost)
1257
+ return self._connection[1]
1258
+
1259
+ ##
1260
+ # Clear any cached connection object.
1261
+ # Used in the event of socket errors.
1262
+ #
1263
+ def close(self):
1264
+ host, connection = self._connection
1265
+ if connection:
1266
+ self._connection = (None, None)
1267
+ connection.close()
1268
+
1269
+ ##
1270
+ # Send HTTP request.
1271
+ #
1272
+ # @param host Host descriptor (URL or (URL, x509 info) tuple).
1273
+ # @param handler Target RPC handler (a path relative to host)
1274
+ # @param request_body The XML-RPC request body
1275
+ # @param debug Enable debugging if debug is true.
1276
+ # @return An HTTPConnection.
1277
+
1278
+ def send_request(self, host, handler, request_body, debug):
1279
+ connection = self.make_connection(host)
1280
+ headers = self._headers + self._extra_headers
1281
+ if debug:
1282
+ connection.set_debuglevel(1)
1283
+ if self.accept_gzip_encoding and gzip:
1284
+ connection.putrequest("POST", handler, skip_accept_encoding=True)
1285
+ headers.append(("Accept-Encoding", "gzip"))
1286
+ else:
1287
+ connection.putrequest("POST", handler)
1288
+ headers.append(("Content-Type", "text/xml"))
1289
+ headers.append(("User-Agent", self.user_agent))
1290
+ self.send_headers(connection, headers)
1291
+ self.send_content(connection, request_body)
1292
+ return connection
1293
+
1294
+ ##
1295
+ # Send request headers.
1296
+ # This function provides a useful hook for subclassing
1297
+ #
1298
+ # @param connection httpConnection.
1299
+ # @param headers list of key,value pairs for HTTP headers
1300
+
1301
+ def send_headers(self, connection, headers):
1302
+ for key, val in headers:
1303
+ connection.putheader(key, val)
1304
+
1305
+ ##
1306
+ # Send request body.
1307
+ # This function provides a useful hook for subclassing
1308
+ #
1309
+ # @param connection httpConnection.
1310
+ # @param request_body XML-RPC request body.
1311
+
1312
+ def send_content(self, connection, request_body):
1313
+ #optionally encode the request
1314
+ if (self.encode_threshold is not None and
1315
+ self.encode_threshold < len(request_body) and
1316
+ gzip):
1317
+ connection.putheader("Content-Encoding", "gzip")
1318
+ request_body = gzip_encode(request_body)
1319
+
1320
+ connection.putheader("Content-Length", str(len(request_body)))
1321
+ connection.endheaders(request_body)
1322
+
1323
+ ##
1324
+ # Parse response.
1325
+ #
1326
+ # @param file Stream.
1327
+ # @return Response tuple and target method.
1328
+
1329
+ def parse_response(self, response):
1330
+ # read response data from httpresponse, and parse it
1331
+ # Check for new http response object, otherwise it is a file object.
1332
+ if hasattr(response, 'getheader'):
1333
+ if response.getheader("Content-Encoding", "") == "gzip":
1334
+ stream = GzipDecodedResponse(response)
1335
+ else:
1336
+ stream = response
1337
+ else:
1338
+ stream = response
1339
+
1340
+ p, u = self.getparser()
1341
+
1342
+ while 1:
1343
+ data = stream.read(1024)
1344
+ if not data:
1345
+ break
1346
+ if self.verbose:
1347
+ print("body:", repr(data))
1348
+ p.feed(data)
1349
+
1350
+ if stream is not response:
1351
+ stream.close()
1352
+ p.close()
1353
+
1354
+ return u.close()
1355
+
1356
+ ##
1357
+ # Standard transport class for XML-RPC over HTTPS.
1358
+
1359
+ class SafeTransport(Transport):
1360
+ """Handles an HTTPS transaction to an XML-RPC server."""
1361
+
1362
+ def __init__(self, use_datetime=False, use_builtin_types=False,
1363
+ *, headers=(), context=None):
1364
+ super().__init__(use_datetime=use_datetime,
1365
+ use_builtin_types=use_builtin_types,
1366
+ headers=headers)
1367
+ self.context = context
1368
+
1369
+ # FIXME: mostly untested
1370
+
1371
+ def make_connection(self, host):
1372
+ if self._connection and host == self._connection[0]:
1373
+ return self._connection[1]
1374
+
1375
+ if not hasattr(http.client, "HTTPSConnection"):
1376
+ raise NotImplementedError(
1377
+ "your version of http.client doesn't support HTTPS")
1378
+ # create a HTTPS connection object from a host descriptor
1379
+ # host may be a string, or a (host, x509-dict) tuple
1380
+ chost, self._extra_headers, x509 = self.get_host_info(host)
1381
+ self._connection = host, http.client.HTTPSConnection(chost,
1382
+ None, context=self.context, **(x509 or {}))
1383
+ return self._connection[1]
1384
+
1385
+ ##
1386
+ # Standard server proxy. This class establishes a virtual connection
1387
+ # to an XML-RPC server.
1388
+ # <p>
1389
+ # This class is available as ServerProxy and Server. New code should
1390
+ # use ServerProxy, to avoid confusion.
1391
+ #
1392
+ # @def ServerProxy(uri, **options)
1393
+ # @param uri The connection point on the server.
1394
+ # @keyparam transport A transport factory, compatible with the
1395
+ # standard transport class.
1396
+ # @keyparam encoding The default encoding used for 8-bit strings
1397
+ # (default is UTF-8).
1398
+ # @keyparam verbose Use a true value to enable debugging output.
1399
+ # (printed to standard output).
1400
+ # @see Transport
1401
+
1402
+ class ServerProxy:
1403
+ """uri [,options] -> a logical connection to an XML-RPC server
1404
+
1405
+ uri is the connection point on the server, given as
1406
+ scheme://host/target.
1407
+
1408
+ The standard implementation always supports the "http" scheme. If
1409
+ SSL socket support is available (Python 2.0), it also supports
1410
+ "https".
1411
+
1412
+ If the target part and the slash preceding it are both omitted,
1413
+ "/RPC2" is assumed.
1414
+
1415
+ The following options can be given as keyword arguments:
1416
+
1417
+ transport: a transport factory
1418
+ encoding: the request encoding (default is UTF-8)
1419
+
1420
+ All 8-bit strings passed to the server proxy are assumed to use
1421
+ the given encoding.
1422
+ """
1423
+
1424
+ def __init__(self, uri, transport=None, encoding=None, verbose=False,
1425
+ allow_none=False, use_datetime=False, use_builtin_types=False,
1426
+ *, headers=(), context=None):
1427
+ # establish a "logical" server connection
1428
+
1429
+ # get the url
1430
+ p = urllib.parse.urlsplit(uri)
1431
+ if p.scheme not in ("http", "https"):
1432
+ raise OSError("unsupported XML-RPC protocol")
1433
+ self.__host = p.netloc
1434
+ self.__handler = urllib.parse.urlunsplit(["", "", *p[2:]])
1435
+ if not self.__handler:
1436
+ self.__handler = "/RPC2"
1437
+
1438
+ if transport is None:
1439
+ if p.scheme == "https":
1440
+ handler = SafeTransport
1441
+ extra_kwargs = {"context": context}
1442
+ else:
1443
+ handler = Transport
1444
+ extra_kwargs = {}
1445
+ transport = handler(use_datetime=use_datetime,
1446
+ use_builtin_types=use_builtin_types,
1447
+ headers=headers,
1448
+ **extra_kwargs)
1449
+ self.__transport = transport
1450
+
1451
+ self.__encoding = encoding or 'utf-8'
1452
+ self.__verbose = verbose
1453
+ self.__allow_none = allow_none
1454
+
1455
+ def __close(self):
1456
+ self.__transport.close()
1457
+
1458
+ def __request(self, methodname, params):
1459
+ # call a method on the remote server
1460
+
1461
+ request = dumps(params, methodname, encoding=self.__encoding,
1462
+ allow_none=self.__allow_none).encode(self.__encoding, 'xmlcharrefreplace')
1463
+
1464
+ response = self.__transport.request(
1465
+ self.__host,
1466
+ self.__handler,
1467
+ request,
1468
+ verbose=self.__verbose
1469
+ )
1470
+
1471
+ if len(response) == 1:
1472
+ response = response[0]
1473
+
1474
+ return response
1475
+
1476
+ def __repr__(self):
1477
+ return (
1478
+ "<%s for %s%s>" %
1479
+ (self.__class__.__name__, self.__host, self.__handler)
1480
+ )
1481
+
1482
+ def __getattr__(self, name):
1483
+ # magic method dispatcher
1484
+ return _Method(self.__request, name)
1485
+
1486
+ # note: to call a remote object with a non-standard name, use
1487
+ # result getattr(server, "strange-python-name")(args)
1488
+
1489
+ def __call__(self, attr):
1490
+ """A workaround to get special attributes on the ServerProxy
1491
+ without interfering with the magic __getattr__
1492
+ """
1493
+ if attr == "close":
1494
+ return self.__close
1495
+ elif attr == "transport":
1496
+ return self.__transport
1497
+ raise AttributeError("Attribute %r not found" % (attr,))
1498
+
1499
+ def __enter__(self):
1500
+ return self
1501
+
1502
+ def __exit__(self, *args):
1503
+ self.__close()
1504
+
1505
+ # compatibility
1506
+
1507
+ Server = ServerProxy
1508
+
1509
+ # --------------------------------------------------------------------
1510
+ # test code
1511
+
1512
+ if __name__ == "__main__":
1513
+
1514
+ # simple test program (from the XML-RPC specification)
1515
+
1516
+ # local server, available from Lib/xmlrpc/server.py
1517
+ server = ServerProxy("http://localhost:8000")
1518
+
1519
+ try:
1520
+ print(server.currentTime.getCurrentTime())
1521
+ except Error as v:
1522
+ print("ERROR", v)
1523
+
1524
+ multi = MultiCall(server)
1525
+ multi.getData()
1526
+ multi.pow(2,9)
1527
+ multi.add(1,2)
1528
+ try:
1529
+ for response in multi():
1530
+ print(response)
1531
+ except Error as v:
1532
+ print("ERROR", v)
vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/api/compilation_unit.h ADDED
@@ -0,0 +1,351 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <ATen/core/function.h>
3
+ #include <c10/util/Exception.h>
4
+ #include <torch/csrc/jit/api/function_impl.h>
5
+ #include <torch/csrc/jit/frontend/name_mangler.h>
6
+ #include <torch/csrc/jit/frontend/source_range.h>
7
+ #include <torch/csrc/jit/ir/ir.h>
8
+ #include <torch/csrc/jit/runtime/graph_executor.h>
9
+
10
+ #include <torch/csrc/Export.h>
11
+
12
+ #include <ATen/core/function_schema.h>
13
+ #include <ATen/core/qualified_name.h>
14
+ #include <c10/util/ArrayRef.h>
15
+ #include <optional>
16
+
17
+ #include <functional>
18
+ #include <memory>
19
+ #include <mutex>
20
+ #include <ostream>
21
+ #include <string>
22
+ #include <unordered_map>
23
+ #include <vector>
24
+
25
+ namespace torch::jit {
26
+
27
+ struct Def;
28
+ struct Property;
29
+ struct ClassDef;
30
+ struct SugaredValue;
31
+ struct Resolver;
32
+
33
+ using ResolverPtr = std::shared_ptr<Resolver>;
34
+ struct Self {
35
+ virtual ~Self() = default;
36
+ virtual std::shared_ptr<SugaredValue> makeSugared(Value* v) const = 0;
37
+ virtual ClassTypePtr getClassType() const = 0;
38
+ };
39
+
40
+ // A CompilationUnit is a list of named Functions
41
+ // with helper methods to iterate the list or invoke the function.
42
+ // Classes have a CompilationUnit holding the class methods,
43
+ // and Modules have a CompilationUnit holding the Functions that
44
+ // are used to implement their Methods
45
+
46
+ struct TORCH_API CompilationUnit {
47
+ enum class FunctionType { Method, Hook, PreHook };
48
+ // constructor that takes a set of functions to compile using the native
49
+ // resolver
50
+ explicit CompilationUnit(const std::string& source);
51
+ CompilationUnit() = default;
52
+
53
+ CompilationUnit& operator=(CompilationUnit&&) = default;
54
+ CompilationUnit(CompilationUnit&&) = default;
55
+ CompilationUnit& operator=(const CompilationUnit&) = delete;
56
+ CompilationUnit(const CompilationUnit&) = delete;
57
+
58
+ Function* find_function(const c10::QualifiedName& name) const {
59
+ auto it = dict_.find(name);
60
+ if (it == dict_.end()) {
61
+ return nullptr;
62
+ }
63
+ return functions_[it->second].get();
64
+ }
65
+
66
+ Function& get_function(const c10::QualifiedName& name) const {
67
+ if (auto r = find_function(name)) {
68
+ return *r;
69
+ }
70
+ TORCH_CHECK(false, "attempted to get undefined function ", name.name());
71
+ }
72
+
73
+ void set_optimized(bool o) {
74
+ TORCH_WARN(
75
+ "CompilationUnit::set_optimized() is deprecated and has no effect. "
76
+ "Please use setGraphExecutorOptimize()");
77
+ }
78
+
79
+ bool is_optimized() const {
80
+ TORCH_WARN(
81
+ "CompilationUnit::is_optimized() is deprecated and always returns true. "
82
+ "Please use getGraphExecutorOptimize()");
83
+ return true;
84
+ }
85
+
86
+ // for historic reasons, these are defined in ir_emitter.cpp
87
+ // Returns the list of Functions just defined.
88
+ std::vector<Function*> define(
89
+ const std::optional<c10::QualifiedName>& prefix,
90
+ const std::vector<Property>& properties,
91
+ const std::vector<ResolverPtr>& propResolvers,
92
+ const std::vector<Def>& definitions,
93
+ const std::vector<ResolverPtr>&
94
+ defResolvers, /* determines how we handle free
95
+ variables in each definition*/
96
+ // if non-null, the first argument to each def, is bound to this value
97
+ const Self* self,
98
+ // see [name mangling]
99
+ bool shouldMangle = false,
100
+ std::optional<size_t> operator_set_version = std::nullopt);
101
+
102
+ void define_hooks(
103
+ const std::optional<c10::QualifiedName>& prefix,
104
+ const std::vector<Def>& hookDefs,
105
+ const std::vector<ResolverPtr>& hookResolvers,
106
+ const std::vector<Def>& preHookDefs,
107
+ const std::vector<ResolverPtr>& preHookResolvers,
108
+ const Self* self,
109
+ bool shouldMangle = false);
110
+
111
+ // same as above but parse the definitions from source
112
+ // Returns the list of Functions just defined.
113
+ std::vector<Function*> define(
114
+ // prefix namespace to put all the defined functions into
115
+ const std::optional<c10::QualifiedName>& prefix,
116
+ const std::string& source,
117
+ const ResolverPtr& resolver,
118
+ const Self* self);
119
+
120
+ void define_interface(
121
+ const c10::QualifiedName& qualifiedName,
122
+ const ClassDef& classDef,
123
+ ResolverPtr rcb,
124
+ bool is_module = false);
125
+
126
+ Function* create_function(
127
+ c10::QualifiedName name,
128
+ std::shared_ptr<Graph> graph,
129
+ bool shouldMangle = false) {
130
+ if (shouldMangle) {
131
+ name = mangle(name);
132
+ }
133
+ auto fn = std::make_unique<GraphFunction>(
134
+ std::move(name), std::move(graph), nullptr);
135
+ auto ret = fn.get();
136
+ register_function(std::move(fn));
137
+ return ret;
138
+ }
139
+
140
+ std::vector<Function*> get_functions() const {
141
+ return fmap(functions_, [](const std::unique_ptr<Function>& fn) {
142
+ return fn.get();
143
+ });
144
+ }
145
+
146
+ /// Run a method from this compilation.
147
+ ///
148
+ /// For example:
149
+ /// @code
150
+ /// IValue output = module->run("relu_script", a, b);
151
+ /// @endcode
152
+ ///
153
+ /// To get a compile a module from a source string, see torch::jit::compile
154
+ ///
155
+ /// @param method_name The name of the method to run
156
+ /// @param args Arguments to be passed to the method
157
+ /// @return An IValue containing the return value (or values if it is a tuple)
158
+ /// from the method
159
+ template <typename... Types>
160
+ IValue run_method(const c10::QualifiedName& method_name, Types&&... args) {
161
+ return get_function(method_name)({IValue(std::forward<Types>(args))...});
162
+ }
163
+
164
+ void drop_all_functions() {
165
+ dict_.clear();
166
+ functions_.clear();
167
+ }
168
+
169
+ /**
170
+ * Register a class as being owned by this compilation unit.
171
+ */
172
+ void register_type(c10::NamedTypePtr namedType) {
173
+ // TODO: class types cannot be redefined because we have no way right now
174
+ // of invalidating their methods. NamedTuples are fine though, since they
175
+ // don't have methods.
176
+ TORCH_CHECK(
177
+ 0 == classDict_.count(*namedType->name()),
178
+ "class '",
179
+ namedType->name()->qualifiedName(),
180
+ "' already defined.");
181
+ classes_.push_back(std::move(namedType));
182
+ classDict_[*classes_.back()->name()] = classes_.size() - 1;
183
+ };
184
+
185
+ c10::ClassTypePtr get_class(const c10::QualifiedName& name) const {
186
+ auto type = get_type(name);
187
+ if (!type) {
188
+ return nullptr;
189
+ }
190
+ return type->cast<c10::ClassType>();
191
+ }
192
+
193
+ c10::InterfaceTypePtr get_interface(const c10::QualifiedName& name) const {
194
+ auto type = get_type(name);
195
+ if (!type) {
196
+ return nullptr;
197
+ }
198
+ return type->cast<c10::InterfaceType>();
199
+ }
200
+
201
+ c10::TupleTypePtr get_named_tuple(const c10::QualifiedName& name) const {
202
+ for (const auto& cls : classes_) {
203
+ if (cls->name()->qualifiedName() == name.qualifiedName()) {
204
+ return cls->expect<TupleType>();
205
+ }
206
+ }
207
+ return nullptr;
208
+ }
209
+
210
+ c10::NamedTypePtr get_type(const c10::QualifiedName& name) const {
211
+ auto it = classDict_.find(name);
212
+ if (it == classDict_.end()) {
213
+ return nullptr;
214
+ }
215
+ return classes_[it->second];
216
+ }
217
+
218
+ // For testing: clear all Python-defined classes to ensure that unit tests
219
+ // have isolation.
220
+ void _clear_python_cu() {
221
+ // Delete all the associated class methods
222
+ for (const auto& type : classes_) {
223
+ if (auto cls = type->cast<ClassType>()) {
224
+ for (auto method : cls->methods()) {
225
+ // Tombstone the method in the compilation unit.
226
+ // Don't erase because the dict_
227
+ auto it = dict_.find(method->qualname());
228
+ if (it != dict_.end()) {
229
+ functions_[it->second] = nullptr;
230
+ // Erase in our big lookup table
231
+ dict_.erase(it);
232
+ }
233
+ }
234
+ // Classes can have multiple pointers to the same hook,
235
+ // need to make sure to not delete it twice
236
+ std::unordered_set<Function*> hooks_to_delete;
237
+ for (const auto& hook : cls->getForwardHooks()) {
238
+ hooks_to_delete.insert(hook);
239
+ }
240
+ for (const auto& pre_hook : cls->getForwardPreHooks()) {
241
+ hooks_to_delete.insert(pre_hook);
242
+ }
243
+ for (const auto& hook : hooks_to_delete) {
244
+ // Tombstone the hook in the compilation unit.
245
+ auto it = dict_.find(hook->qualname());
246
+ if (it != dict_.end()) {
247
+ functions_[it->second] = nullptr;
248
+ // Erase in our big lookup table
249
+ dict_.erase(it);
250
+ }
251
+ }
252
+ }
253
+ }
254
+ classes_.clear();
255
+ classDict_.clear();
256
+ }
257
+
258
+ // [Internal Only] Remove method.
259
+ // Note Used for freezing.
260
+ void unsafeRemoveMethod(const c10::QualifiedName& method_name) {
261
+ auto it = dict_.find(method_name);
262
+ TORCH_CHECK(
263
+ it != dict_.end(),
264
+ "method '",
265
+ method_name.qualifiedName(),
266
+ "' does not exist.");
267
+ functions_[it->second] = nullptr;
268
+ dict_.erase(it);
269
+ }
270
+
271
+ // [name mangling] All code objects must have a unique qualified name in a
272
+ // CompilationUnit. In Python, sometimes functions won't have unique qualified
273
+ // name (for example, nested functions). So we mangle Python functions to
274
+ // ensure that they are uniquely named.
275
+ //
276
+ // We also use mangling to distinguish different Module instances. Since each
277
+ // Module is a singleton class instance, different instances of the same
278
+ // Python Module will have different types but the same qualified name.
279
+ c10::QualifiedName mangle(const c10::QualifiedName& name) const {
280
+ auto mangled = name;
281
+ while (get_type(mangled) || find_function(mangled)) {
282
+ mangled = mangler_.mangle(mangled);
283
+ }
284
+ return mangled;
285
+ }
286
+
287
+ private:
288
+ std::unique_ptr<Function> define(
289
+ const std::optional<c10::QualifiedName>& prefix,
290
+ const Def& def,
291
+ const ResolverPtr& resolver,
292
+ const Self* self,
293
+ const std::unordered_map<std::string, Function*>& function_table,
294
+ bool shouldMangle = false,
295
+ FunctionType type = FunctionType::Method,
296
+ std::optional<size_t> version = std::nullopt) const;
297
+
298
+ // Define a property on \p self.
299
+ struct PropertyPair;
300
+ PropertyPair define_property(
301
+ const std::optional<c10::QualifiedName>& prefix,
302
+ const Property& prop,
303
+ const ResolverPtr& resolver,
304
+ const Self* self,
305
+ const std::unordered_map<std::string, Function*>& function_table,
306
+ bool shouldMangle = false) const;
307
+
308
+ Function& register_function(std::unique_ptr<Function> fn) {
309
+ TORCH_CHECK(
310
+ 0 == dict_.count(fn->qualname().qualifiedName()),
311
+ "method '",
312
+ fn->qualname().qualifiedName(),
313
+ "' already defined.");
314
+ functions_.emplace_back(std::move(fn));
315
+ dict_[functions_.back()->qualname()] = functions_.size() - 1;
316
+ return *functions_.back();
317
+ }
318
+ std::vector<std::unique_ptr<Function>> functions_;
319
+ // for fast lookup
320
+ std::unordered_map<c10::QualifiedName, size_t> dict_;
321
+ std::unordered_map<c10::QualifiedName, size_t> classDict_;
322
+
323
+ // [class ownership] Right now there are two relationships between classes
324
+ // and compilation units:
325
+ // 1. Classes have compilation units internally that hold their methods.
326
+ // 2. On load, the TypePtrs of any imported classes are owned by the main
327
+ // module's compilation unit.
328
+ std::vector<c10::NamedTypePtr> classes_;
329
+
330
+ mutable NameMangler mangler_;
331
+ };
332
+
333
+ // An owning pointer to a Function. Just a pair of a raw Function ptr and it's
334
+ // owning CU. We need this because pybind requires a ref-counted way to refer to
335
+ // Functions.
336
+ struct StrongFunctionPtr {
337
+ StrongFunctionPtr(std::shared_ptr<CompilationUnit> cu, Function* function)
338
+ : cu_(std::move(cu)), function_(function) {
339
+ TORCH_INTERNAL_ASSERT(cu_);
340
+ TORCH_INTERNAL_ASSERT(function_);
341
+ }
342
+ std::shared_ptr<CompilationUnit> cu_;
343
+ Function* function_;
344
+ };
345
+
346
+ namespace script {
347
+ // We once had a `script::` namespace that was deleted. This is for backcompat
348
+ // of the public API; new code should not use this type alias.
349
+ using CompilationUnit = ::torch::jit::CompilationUnit;
350
+ } // namespace script
351
+ } // namespace torch::jit
vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/api/function_impl.h ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/function.h>
4
+ #include <torch/csrc/jit/ir/ir.h>
5
+ #include <torch/csrc/jit/runtime/graph_executor.h>
6
+
7
+ namespace torch::jit {
8
+
9
+ struct TORCH_API GraphFunction : public Function {
10
+ GraphFunction(
11
+ c10::QualifiedName name,
12
+ std::shared_ptr<Graph> graph,
13
+ std::function<void(GraphFunction&)> function_creator,
14
+ std::optional<ExecutorExecutionMode> executor_execution_mode =
15
+ std::nullopt)
16
+ : name_(std::move(name)),
17
+ graph_(std::move(graph)),
18
+ executor_execution_mode_(executor_execution_mode),
19
+ function_creator_(std::move(function_creator)) {}
20
+
21
+ bool isGraphFunction() const override {
22
+ return true;
23
+ }
24
+
25
+ void run(Stack& stack) override;
26
+
27
+ std::function<void(GraphFunction&)> function_creator() const {
28
+ return function_creator_;
29
+ }
30
+
31
+ c10::intrusive_ptr<c10::ivalue::Future> runAsync(
32
+ Stack& stack,
33
+ TaskLauncher taskLauncher = at::launch) override;
34
+
35
+ std::shared_ptr<Graph> graph() const {
36
+ return graph_;
37
+ }
38
+
39
+ std::shared_ptr<Graph> optimized_graph() const;
40
+
41
+ const c10::QualifiedName& qualname() const override {
42
+ return name_;
43
+ }
44
+
45
+ // private/unstable api. sets the initial execution mode
46
+ // will not affect executor if there is an existing executor
47
+ // created for this function
48
+ void _set_initial_executor_execution_mode(ExecutorExecutionMode mode) {
49
+ executor_execution_mode_ = mode;
50
+ }
51
+ // private/unstable api. sets flag of whether or not to ignore amp.
52
+ // will not affect executor if there is an existing executor
53
+ // created for this function
54
+ void _set_ignore_amp(bool ignore_amp) {
55
+ force_no_amp_ = ignore_amp;
56
+ }
57
+
58
+ // if this isn't yet defined, run its method_creator function
59
+ void ensure_defined() override;
60
+
61
+ size_t num_inputs() const override {
62
+ return graph()->inputs().size();
63
+ }
64
+
65
+ Function& setSchema(FunctionSchema schema) override {
66
+ schema_ = std::make_unique<FunctionSchema>(std::move(schema));
67
+ return *this;
68
+ }
69
+
70
+ const FunctionSchema& getSchema() const override;
71
+
72
+ GraphExecutorState getDebugState() {
73
+ return get_executor().getDebugState();
74
+ }
75
+
76
+ bool is_optimized() const {
77
+ TORCH_WARN(
78
+ "GraphFunction::is_optimized() is deprecated and always returns true. "
79
+ "Please use getGraphExecutorOptimize()");
80
+ return true;
81
+ }
82
+
83
+ void check_single_output() {
84
+ TORCH_CHECK(
85
+ graph()->outputs().size() == 1,
86
+ "Method (but not graphs in general) require a single output. Use None/Tuple for 0 or 2+ outputs");
87
+ }
88
+
89
+ GraphExecutor& get_executor() {
90
+ ensure_defined();
91
+ std::lock_guard<std::recursive_mutex> lock(compile_mutex);
92
+ auto& executor = executors_[currentSpecialization()];
93
+ if (executor) {
94
+ return *executor;
95
+ }
96
+ check_single_output();
97
+ const std::string& name = name_.name();
98
+ std::shared_ptr<Graph> opt_graph = optimized_graph();
99
+ if (!executor_execution_mode_) {
100
+ executor = GraphExecutor(opt_graph, name);
101
+ } else {
102
+ executor = GraphExecutor(opt_graph, name, *executor_execution_mode_);
103
+ }
104
+ return *executor;
105
+ }
106
+
107
+ using Function::call;
108
+ bool call(
109
+ Stack& stack,
110
+ std::optional<size_t> bailOut,
111
+ c10::function_ref<void(const Code&)> f) override {
112
+ f(get_executor().getPlanFor(stack, bailOut).code);
113
+ return true;
114
+ }
115
+
116
+ void clear_optimized_graphs() {
117
+ optimized_graphs_.fill(nullptr);
118
+ }
119
+
120
+ private:
121
+ enum SpecializationKey {
122
+ AutocastOff,
123
+ CpuAutocastOn,
124
+ GpuAutocastOn,
125
+ CpuGpuAutocastOn,
126
+
127
+ // This provides the number of specializations
128
+ // (Must be last entry)
129
+ TotalCount
130
+ };
131
+
132
+ SpecializationKey currentSpecialization() const;
133
+
134
+ private:
135
+ c10::QualifiedName name_;
136
+ // The original, non-optimized graph
137
+ std::shared_ptr<Graph> graph_; // for debugging and for inlining
138
+
139
+ // allows users to specify Simple/Profiling Executor for function
140
+ // TODO: add more executors
141
+ mutable std::optional<ExecutorExecutionMode> executor_execution_mode_;
142
+
143
+ // if invoked on a graph that has already traced through amp
144
+ // don't invoke amp pass
145
+ mutable bool force_no_amp_ = false;
146
+ // Optimized graph, computed lazily. Used for inlining.
147
+ mutable std::array<std::shared_ptr<Graph>, SpecializationKey::TotalCount>
148
+ optimized_graphs_;
149
+
150
+ // GraphFunctions are invokable from multiple threads, so this lock needs to
151
+ // be held when we're initializing graph executor for the first time or
152
+ // computing the optimized graph. We're using reentrant mutex so that we don't
153
+ // need to worry about causing a deadlock by calling one method from another
154
+ // (e.g. optimized_graph() from get_executor()).
155
+ mutable std::recursive_mutex compile_mutex;
156
+
157
+ // executor_[0] - autocast off
158
+ // executor_[1] - autocast cpu on
159
+ // executor_[2] - autocast gpu on
160
+ // executor_[3] - autocast cpu & gpu on
161
+ std::array<std::optional<GraphExecutor>, SpecializationKey::TotalCount>
162
+ executors_;
163
+
164
+ // an optional function that actually creates the method when
165
+ // ensure_defined() is called. This is used by the compiler so
166
+ // that it can construct methods out of order
167
+ std::function<void(GraphFunction&)> function_creator_;
168
+
169
+ // if absent, then we generate a default schema based on the graph
170
+ // mutable because getSchema caches the default schema if one is requested
171
+ // before a call to setSchema
172
+ mutable std::unique_ptr<FunctionSchema> schema_;
173
+ };
174
+
175
+ // Short hands for dynamic_cast<GraphFunction*>.
176
+ TORCH_API GraphFunction* tryToGraphFunction(Function&) noexcept;
177
+ TORCH_API GraphFunction& toGraphFunction(Function&);
178
+ TORCH_API const GraphFunction& toGraphFunction(const Function&);
179
+
180
+ } // namespace torch::jit
vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/api/method.h ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/function.h>
4
+ #include <ATen/core/ivalue.h>
5
+ #include <ATen/core/stack.h>
6
+ #include <torch/csrc/api/include/torch/imethod.h>
7
+ #include <torch/csrc/jit/api/function_impl.h>
8
+
9
+ namespace torch::jit {
10
+
11
+ using ObjectPtr = c10::intrusive_ptr<c10::ivalue::Object>;
12
+
13
+ // A method in a module, e.g. f in:
14
+ //
15
+ // class M(ScriptModule):
16
+ // @script_method
17
+ // def f(self, x):
18
+ // ...
19
+ // Note: because Method/Module are exposed to python these
20
+ // classes use python method naming conventions
21
+ struct TORCH_API Method : public torch::IMethod {
22
+ Method(ObjectPtr owner, Function* function);
23
+
24
+ // the module that contains this method.
25
+ Module owner() const;
26
+ // the raw objectptr that owns this method, for when the method is owned by a
27
+ // torchbind object.
28
+ ObjectPtr raw_owner() const;
29
+ void run(Stack& stack);
30
+ void run(Stack&& stack) {
31
+ run(stack);
32
+ }
33
+
34
+ c10::IValue operator()(
35
+ std::vector<c10::IValue> stack,
36
+ const Kwargs& kwargs = Kwargs()) const override;
37
+
38
+ // Run method async. Invocation on this function would invokes a JIT
39
+ // interpreter that executes ops inline, one by one, on caller's thread. A
40
+ // model can utilize async op, i.e. `fork`, to launch an asynchronous task
41
+ // which will be launched on provided `taskLauncher`.
42
+ c10::intrusive_ptr<c10::ivalue::Future> run_async(
43
+ std::vector<c10::IValue> stack,
44
+ const Kwargs& kwargs = Kwargs(),
45
+ TaskLauncher taskLauncher = at::launch);
46
+
47
+ std::shared_ptr<Graph> graph() const {
48
+ return toGraphFunction(*function_).graph();
49
+ }
50
+
51
+ const std::string& name() const override {
52
+ return function_->name();
53
+ }
54
+
55
+ size_t num_inputs() const {
56
+ return function_->num_inputs();
57
+ }
58
+
59
+ GraphExecutor& get_executor() {
60
+ return toGraphFunction(*function_).get_executor();
61
+ }
62
+
63
+ Function& function() const {
64
+ return *function_;
65
+ }
66
+
67
+ private:
68
+ void setArgumentNames(std::vector<std::string>&) const override;
69
+
70
+ // Methods are uniqued onwed by a single module. This raw pointer allows
71
+ // looking up the module.
72
+ ObjectPtr owner_;
73
+
74
+ // Underlying unbound function
75
+ Function* function_;
76
+ };
77
+
78
+ namespace script {
79
+ // We once had a `script::` namespace that was deleted. This is for backcompat
80
+ // of the public API; new code should not use this type alias.
81
+ using Method = ::torch::jit::Method;
82
+ } // namespace script
83
+
84
+ } // namespace torch::jit
vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/api/module.h ADDED
@@ -0,0 +1,685 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <c10/util/Exception.h>
3
+ #include <torch/csrc/autograd/variable.h>
4
+ #include <torch/csrc/jit/api/object.h>
5
+ #include <torch/csrc/jit/frontend/source_range.h>
6
+ #include <torch/csrc/jit/ir/ir.h>
7
+ #include <torch/csrc/jit/ir/named_value.h>
8
+ #include <torch/csrc/jit/runtime/argument_spec.h>
9
+ #include <torch/csrc/jit/runtime/graph_executor.h>
10
+
11
+ #include <torch/csrc/Export.h>
12
+ #include <torch/csrc/api/include/torch/ordered_dict.h>
13
+ #include <torch/csrc/jit/api/compilation_unit.h>
14
+
15
+ #include <ATen/core/function_schema.h>
16
+ #include <ATen/core/qualified_name.h>
17
+ #include <c10/util/ArrayRef.h>
18
+ #include <c10/util/irange.h>
19
+ #include <optional>
20
+
21
+ #include <functional>
22
+ #include <memory>
23
+ #include <mutex>
24
+ #include <ostream>
25
+ #include <string>
26
+ #include <unordered_map>
27
+ #include <unordered_set>
28
+ #include <utility>
29
+ #include <vector>
30
+
31
+ // This file contains classes which assist in desugaring Python style
32
+ // modules and their methods into flattened graphs which don't have any
33
+ // function calls.
34
+
35
+ namespace torch::jit {
36
+
37
+ using ::c10::Argument;
38
+ using ::c10::FunctionSchema;
39
+ using ::c10::QualifiedName;
40
+ // Map which stores filename to content.
41
+ using ExtraFilesMap = std::unordered_map<std::string, std::string>;
42
+
43
+ using ModulePtr = c10::intrusive_ptr<c10::ivalue::Object>;
44
+
45
+ struct Module;
46
+
47
+ template <typename T>
48
+ struct slot_list_impl;
49
+
50
+ template <typename T>
51
+ struct Named {
52
+ std::string name;
53
+ T value;
54
+ };
55
+
56
+ using NameModule = Named<Module>;
57
+ using NameValue = Named<IValue>;
58
+ using NameTensor = Named<at::Tensor>;
59
+
60
+ namespace detail {
61
+ struct TORCH_API ModulePolicy;
62
+ struct TORCH_API ParameterPolicy;
63
+ struct TORCH_API AttributePolicy;
64
+ struct TORCH_API BufferPolicy;
65
+ template <typename P>
66
+ struct NamedPolicy;
67
+ } // namespace detail
68
+
69
+ using module_list = slot_list_impl<detail::ModulePolicy>;
70
+ using named_module_list =
71
+ slot_list_impl<detail::NamedPolicy<detail::ModulePolicy>>;
72
+
73
+ using parameter_list = slot_list_impl<detail::ParameterPolicy>;
74
+ using named_parameter_list =
75
+ slot_list_impl<detail::NamedPolicy<detail::ParameterPolicy>>;
76
+
77
+ using attribute_list = slot_list_impl<detail::AttributePolicy>;
78
+ using named_attribute_list =
79
+ slot_list_impl<detail::NamedPolicy<detail::AttributePolicy>>;
80
+
81
+ using buffer_list = slot_list_impl<detail::BufferPolicy>;
82
+ using named_buffer_list =
83
+ slot_list_impl<detail::NamedPolicy<detail::BufferPolicy>>;
84
+
85
+ using ModuleLookup = std::function<Module(const std::vector<std::string>&)>;
86
+
87
+ struct TORCH_API Module : public Object {
88
+ explicit Module(c10::QualifiedName class_name);
89
+ Module(std::shared_ptr<CompilationUnit> cu, const c10::ClassTypePtr& type);
90
+ Module() = default;
91
+ Module(const Module&) = default;
92
+ Module& operator=(const Module&) = default;
93
+ Module(Module&&) noexcept = default;
94
+ Module& operator=(Module&&) noexcept = default;
95
+ Module(
96
+ c10::QualifiedName,
97
+ std::shared_ptr<CompilationUnit> cu,
98
+ bool shouldMangle = false);
99
+ Module(ModulePtr module_value) : Object(std::move(module_value)) {}
100
+ ~Module() = default;
101
+
102
+ void set_optimized(bool o) {
103
+ TORCH_WARN(
104
+ "Module::set_optimized() is deprecated and has no effect. "
105
+ "Please use setGraphExecutorOptimize()");
106
+ }
107
+
108
+ bool is_optimized() const {
109
+ TORCH_WARN(
110
+ "Module::is_optimized() is deprecated and always returns true. "
111
+ "Please use getGraphExecutorOptimize()");
112
+ return true;
113
+ }
114
+
115
+ IValue forward(std::vector<IValue> inputs, const Kwargs& kwargs = Kwargs()) {
116
+ return get_method("forward")(std::move(inputs), kwargs);
117
+ }
118
+
119
+ // In script modules, buffers are Tensors attribute that are _not_ registered
120
+ // as parameters. This is different than in nn.Module where there is a special
121
+ // register_buffer method. With this simplification, we only need to track
122
+ // whether a slot is a parameter to be able to classify it.
123
+ void register_buffer(const std::string& name, at::Tensor v) {
124
+ bool is_param = false;
125
+ bool is_buffer = true;
126
+ std::lock_guard<std::mutex> lock(*register_mutex_);
127
+ type()->addOrCheckAttribute(name, TensorType::get(), is_param, is_buffer);
128
+ _ivalue()->setAttr(name, std::move(v));
129
+ }
130
+
131
+ void register_parameter(
132
+ const std::string& name,
133
+ at::Tensor v,
134
+ bool is_buffer) {
135
+ std::lock_guard<std::mutex> lock(*register_mutex_);
136
+ type()->addOrCheckAttribute(name, TensorType::get(), !is_buffer, is_buffer);
137
+ _ivalue()->setAttr(name, std::move(v));
138
+ }
139
+
140
+ void register_attribute(
141
+ const std::string& name,
142
+ const TypePtr& t,
143
+ IValue v,
144
+ bool is_param = false,
145
+ bool is_buffer = false) {
146
+ type()->addOrCheckAttribute(name, t, is_param, is_buffer);
147
+ _ivalue()->setAttr(name, std::move(v));
148
+ }
149
+
150
+ void register_module(const std::string& name, const Module& module) {
151
+ type()->addOrCheckAttribute(name, module.type());
152
+ _ivalue()->setAttr(name, module._ivalue());
153
+ }
154
+
155
+ void apply(const std::function<void(Module&)>& fn);
156
+
157
+ buffer_list buffers(bool recurse = true) const;
158
+ named_buffer_list named_buffers(bool recurse = true) const;
159
+
160
+ module_list children() const; // direct modules
161
+ named_module_list named_children() const;
162
+ module_list modules() const; // all modules, including this one, recursively
163
+ named_module_list named_modules() const;
164
+
165
+ // all tensors involved in gradient optimization
166
+ parameter_list parameters(bool recurse = true) const;
167
+ named_parameter_list named_parameters(bool recurse = true) const;
168
+
169
+ // all members of the object, similar to iterating over dir(obj) in python
170
+ attribute_list attributes(bool recurse = true) const;
171
+ named_attribute_list named_attributes(bool recurse = true) const;
172
+
173
+ void dump(
174
+ bool print_method_bodies,
175
+ bool print_attr_values,
176
+ bool print_param_values) const;
177
+
178
+ std::string dump_to_str(
179
+ bool print_method_bodies,
180
+ bool print_attr_values,
181
+ bool print_param_values) const;
182
+
183
+ /// Enables "training" mode.
184
+ void train(bool on = true);
185
+ /// Calls train(false) to enable "eval" mode.
186
+ /// Do not override this method, override `train()` instead.
187
+ void eval() {
188
+ train(/*on=*/false);
189
+ }
190
+ /// True if the module is in training mode.
191
+ bool is_training() const {
192
+ return attr("training", true).toBool();
193
+ }
194
+
195
+ /// Recursively casts all parameters to the given `dtype` and `device`.
196
+ ///
197
+ /// If `non_blocking` is true and the source is in pinned memory and
198
+ /// destination is on the GPU or vice versa, the copy is performed
199
+ /// asynchronously with respect to the host. Otherwise, the argument has no
200
+ /// effect.
201
+ void to(at::Device device, at::ScalarType dtype, bool non_blocking = false);
202
+
203
+ /// Recursively casts all parameters to the given dtype.
204
+ ///
205
+ /// If `non_blocking` is true and the source is in pinned memory and
206
+ /// destination is on the GPU or vice versa, the copy is performed
207
+ /// asynchronously with respect to the host. Otherwise, the argument has no
208
+ /// effect.
209
+ void to(at::ScalarType dtype, bool non_blocking = false);
210
+
211
+ /// Recursively moves all parameters to the given device.
212
+ ///
213
+ /// If `non_blocking` is true and the source is in pinned memory and
214
+ /// destination is on the GPU or vice versa, the copy is performed
215
+ /// asynchronously with respect to the host. Otherwise, the argument has no
216
+ /// effect.
217
+ void to(at::Device device, bool non_blocking = false);
218
+
219
+ void save(
220
+ std::ostream& out,
221
+ const ExtraFilesMap& extra_files = ExtraFilesMap()) const;
222
+
223
+ void save(
224
+ const std::string& filename,
225
+ const ExtraFilesMap& extra_files = ExtraFilesMap()) const;
226
+
227
+ void _save_for_mobile(
228
+ std::ostream& out,
229
+ const ExtraFilesMap& extra_files = ExtraFilesMap(),
230
+ bool save_mobile_debug_info = false,
231
+ bool use_flatbuffer = false) const;
232
+
233
+ void _save_for_mobile(
234
+ const std::string& filename,
235
+ const ExtraFilesMap& extra_files = ExtraFilesMap(),
236
+ bool save_mobile_debug_info = false,
237
+ bool use_flatbuffer = false) const;
238
+
239
+ Module copy() const;
240
+
241
+ Module deepcopy(std::optional<at::Device> device = std::nullopt) const;
242
+
243
+ // Clones both the underlying `ClassType` and the module instance(data), this
244
+ // function creates a new `ClassType` and returns a new instance that has the
245
+ // same data as the current instance but with the new type, shared ClassType
246
+ // will be preserved as well
247
+ Module clone(bool inplace = false) const;
248
+
249
+ // Clones both the underlying `ClassType` and the module instance(data), this
250
+ // function creates a new `ClassType` and returns a new instance that has the
251
+ // same data as the current instance but with the new type, shared ClassType
252
+ // will be preserved as well. Also allows the caller to specify a set of
253
+ // method and attribute names to not clone.
254
+ Module clone(
255
+ bool inplace,
256
+ const std::unordered_set<std::string>& ignored_method,
257
+ const std::unordered_set<std::string>& ignored_attributes) const;
258
+
259
+ void clone_method(const Module& orig, const std::string& name);
260
+
261
+ IValue operator()(std::vector<IValue> inputs);
262
+
263
+ template <typename... Types>
264
+ IValue create_class(const c10::QualifiedName& name, Types&&... args) const {
265
+ return create_class(name, {IValue(std::forward<Types>(args))...});
266
+ }
267
+
268
+ IValue create_class(const c10::QualifiedName& name, Stack stack) const;
269
+
270
+ inline bool operator==(const Module& y) const noexcept {
271
+ return _ivalue() == y._ivalue();
272
+ }
273
+
274
+ void set_delete_memory(std::shared_ptr<char> delete_mem) {
275
+ mem_to_delete_ = std::move(delete_mem);
276
+ }
277
+
278
+ // A set of functions to maintain input shapes through torch.jit.save and
279
+ // torch.jit.load. It only works on tensors and lists/dicts of tensors
280
+ // because tracing is only supported by these types.
281
+ void store_traced_inputs(
282
+ const std::string& func_name,
283
+ std::vector<IValue> inputs) {
284
+ if (inputs.empty()) {
285
+ return;
286
+ }
287
+ auto c10_inputs = c10::impl::GenericList(AnyType::get());
288
+ for (IValue& value : inputs) {
289
+ // Not checking whether this is traceable type as that is already checked
290
+ // higher up in the stack and changing that would require a larger
291
+ // restructuring.
292
+ c10_inputs.emplace_back(std::move(value));
293
+ }
294
+ traced_inputs_.insert_or_assign(func_name, c10_inputs);
295
+ }
296
+
297
+ c10::Dict<std::string, c10::impl::GenericList> retrieve_traced_inputs()
298
+ const {
299
+ return traced_inputs_;
300
+ }
301
+
302
+ private:
303
+ Module clone_impl(
304
+ std::unordered_map<TypePtr, TypePtr>& type_remap,
305
+ bool inplace,
306
+ IValue::HashIdentityIValueMap memo,
307
+ const std::unordered_set<std::string>& ignored_methods,
308
+ const std::unordered_set<std::string>& ignored_attributes) const;
309
+
310
+ void clone_method(
311
+ const Module& orig,
312
+ const Function& method,
313
+ const std::unordered_map<TypePtr, TypePtr>& type_remap);
314
+
315
+ c10::QualifiedName getNameForMethod(std::string basename) const {
316
+ return QualifiedName(*type()->name(), std::move(basename));
317
+ }
318
+
319
+ void to_impl(
320
+ const std::optional<at::Device>& device,
321
+ const std::optional<at::ScalarType>& dtype,
322
+ bool non_blocking);
323
+
324
+ // Extra handle for the module to delete when itself is deleted
325
+ std::shared_ptr<char> mem_to_delete_;
326
+
327
+ // Map of function names to the traced inputs that they have been traced with
328
+ c10::Dict<std::string, c10::impl::GenericList> traced_inputs_;
329
+
330
+ // Mutex to keep registring buffer or parameter thread safe.
331
+ std::shared_ptr<std::mutex> register_mutex_ = std::make_shared<std::mutex>();
332
+ };
333
+
334
+ // C++ equivalent api of `torch.jit.freeze`. See documentation there for
335
+ // details.
336
+ TORCH_API Module freeze(
337
+ const Module& module,
338
+ const std::optional<std::vector<std::string>>& preserved_attrs =
339
+ std::nullopt,
340
+ bool optimize_numerics = true);
341
+
342
+ // C++ equivalent api of `torch.jit.optimize_for_inference`. See documentation
343
+ // there for details.
344
+ TORCH_API Module optimize_for_inference(
345
+ Module& module,
346
+ const std::vector<std::string>& other_methods = {});
347
+
348
+ enum class FusionBehavior { STATIC, DYNAMIC };
349
+
350
+ using FusionStrategy = std::vector<std::pair<FusionBehavior, size_t>>;
351
+ // clang-format off
352
+ /*
353
+ Sets the type and number of specializations that can occur during fusion.
354
+
355
+ Usage: provide a list of pairs (type, depth) where type is one of STATIC or DYNAMIC
356
+ and depth is an integer.
357
+
358
+ Behavior - static vs dynamic:
359
+ In STATIC fusion, fused ops are compiled to have fixed input shapes. The shape is determined
360
+ based on some initial profiling runs.
361
+ In DYNAMIC fusion, fused ops are compiled to have variable input shapes, so that multiple
362
+ shapes are possible.
363
+
364
+ In both cases, we also recompile on new striding behavior, device, or dtype.
365
+
366
+ Behavior - fallback functions & depth:
367
+ When an input doesn't match the format required by the specialized compiled op, it will run
368
+ a fallback function. Fallback functions are recursively be compiled and specialized based
369
+ on the observed tensor shapes. Since compilation can be slow, the "depth" parameter is provided to
370
+ limit the number of specializations that can be compiled, before giving up on recompiling and
371
+ falling back to a completely un-fused, un-specialized implementation.
372
+
373
+ The list of (type, depth) pairs controls the type of specializations and the number of
374
+ specializations. For example: [(STATIC, 2), (DYNAMIC, 2)] indicates that the first
375
+ two specializations will use static fusions, the following two specializations will use
376
+ dynamic fusion, and any inputs that satisfy none of the 4 options will run an
377
+ unfused implementation.
378
+
379
+ NB: in the future, if more as more fusion backends are added there may be more granular
380
+ apis for specific fusers.
381
+ */
382
+ // clang-format on
383
+ TORCH_API FusionStrategy getFusionStrategy();
384
+ // returns previous strategy
385
+ TORCH_API FusionStrategy setFusionStrategy(FusionStrategy& fusion_strategy);
386
+
387
+ namespace detail {
388
+
389
+ struct TORCH_API SlotCursor {
390
+ Module module_;
391
+ int64_t i_; // slot offset, -1 indicates the module itself
392
+ };
393
+
394
+ } // namespace detail
395
+
396
+ // This iterator allows the (optionally recursive) enumeration of
397
+ // the members of a Module. It performs a depth-first pre-order
398
+ // traversal of the module. The Policy template parameter determines
399
+ // which slots of the object should be included. For instance,
400
+ // when iterating parameters, we return the parameter tensors,
401
+ // but skip modules, buffers, and other attributes.
402
+ // See ModulePolicy for comments about Policy object's API.
403
+ template <typename Policy>
404
+ struct slot_iterator_impl {
405
+ using SlotCursor = detail::SlotCursor;
406
+ using value_type = typename Policy::value_type;
407
+ slot_iterator_impl(
408
+ Module root,
409
+ bool recurse, // if true, do a depth-first search, otherwise, just look at
410
+ // slots of root
411
+ bool return_module) // if true include root itself as the first thing
412
+ // visited (used in modules())
413
+ : cursors_({SlotCursor{std::move(root), return_module ? -1 : 0}}),
414
+ recurse_(recurse) {
415
+ // advance iterator to first valid element (or the end, if empty)
416
+ while_not_valid_next();
417
+ }
418
+ // empty cursors_, represents end of iteration
419
+ slot_iterator_impl() : recurse_(false) {}
420
+ value_type operator*() const {
421
+ return Policy::create(cursors_, cur());
422
+ }
423
+ value_type operator->() const {
424
+ return **this;
425
+ }
426
+ slot_iterator_impl& operator++() {
427
+ next_valid();
428
+ return *this;
429
+ }
430
+ slot_iterator_impl operator++(int) {
431
+ // this is really expensive, should we delete it so people don't use it
432
+ // instead of prefix?
433
+ slot_iterator_impl old = *this;
434
+ ++(*this);
435
+ return old;
436
+ }
437
+
438
+ private:
439
+ // return_module() is a corner case where instead of returning a submodule
440
+ // of root, we are returning root itself, because we are iterating modules(),
441
+ // which contains the root module itself.
442
+ // It is represented with a single SlotCursor whose index is -1.
443
+ bool return_module() const {
444
+ return top().i_ == -1;
445
+ }
446
+ const SlotCursor& top() const {
447
+ return cursors_.back();
448
+ }
449
+ SlotCursor& top() {
450
+ return cursors_.back();
451
+ }
452
+ IValue cur() const {
453
+ return return_module() ? top().module_._ivalue()
454
+ : top().module_._ivalue()->getSlot(top().i_);
455
+ }
456
+
457
+ // advance to the next slot in a depth first pre-order traversal of the
458
+ // modules slots. This function does not guarantee the next slot is a
459
+ // valid element of the iteration. That is done by valid().
460
+ // invariant: !cursors_.empty()
461
+ void next() {
462
+ // we just returned the module itself, advance i_ to 0 so we are now
463
+ // at the first slot of the module.
464
+ if (return_module()) {
465
+ ++top().i_;
466
+ return;
467
+ }
468
+ // the last traversal action advanced beyond the number of slots in the
469
+ // module so continue the iteration in the parent.
470
+ if (top().i_ >= int64_t(top().module_._ivalue()->type()->numAttributes())) {
471
+ cursors_.pop_back();
472
+ if (!cursors_.empty()) {
473
+ ++top().i_;
474
+ }
475
+ return;
476
+ }
477
+ // if the current thing is a module, we have to scan it for recursive
478
+ // traversals. We do this by adding a new SlotCursor to track the traversal.
479
+ if (recurse_ &&
480
+ top().module_._ivalue()->type()->getAttribute(top().i_)->is_module()) {
481
+ cursors_.emplace_back(SlotCursor{cur().toModule(), 0});
482
+ return;
483
+ }
484
+ // common case: advance to the next slot.
485
+ ++top().i_;
486
+ }
487
+ // is the current position of the iterator a valid one?
488
+ // otherwise, we have to continue advancing.
489
+ bool valid() const {
490
+ return top().i_ <
491
+ int64_t(top().module_._ivalue()->type()->numAttributes()) &&
492
+ Policy::valid(
493
+ top().module_._ivalue()->type(),
494
+ top().i_,
495
+ top().module_._ivalue()->getSlot(top().i_));
496
+ }
497
+ void while_not_valid_next() {
498
+ // advance iteration until we are either at the end (cursors_.empty())
499
+ // or in a valid state. return_module() is a special case,
500
+ // and is always considered valid, regardless of Policy, because it is
501
+ // it is only true when we are iterating modules.
502
+ while (!cursors_.empty() && !return_module() && !valid()) {
503
+ next();
504
+ }
505
+ }
506
+ void next_valid() {
507
+ // avoid crashing if this is empty
508
+ if (cursors_.empty()) {
509
+ return;
510
+ }
511
+ // advance to next element, which is maybe not valid
512
+ next();
513
+ while_not_valid_next();
514
+ }
515
+
516
+ std::vector<SlotCursor> cursors_;
517
+ bool recurse_;
518
+
519
+ friend inline bool operator!=(
520
+ const slot_iterator_impl<Policy>& a,
521
+ const slot_iterator_impl<Policy>& b) {
522
+ // we are finished iteration when we have no more iteration SlotCursors.
523
+ // end is always an empty iterator with no cursors.
524
+ return (a.cursors_.empty() != b.cursors_.empty());
525
+ }
526
+ };
527
+
528
+ // This type represents lists of parameters, attributes, and
529
+ // submodules contained in the module. It is abstract because
530
+ // they are not stored directly in std::vectors but inside the
531
+ // module's IValue object itself.
532
+ template <typename Policy>
533
+ struct slot_list_impl {
534
+ using iterator = slot_iterator_impl<Policy>;
535
+ using const_iterator = slot_iterator_impl<Policy>;
536
+ using value_type = typename iterator::value_type;
537
+ slot_iterator_impl<Policy> begin() const {
538
+ return slot_iterator_impl<Policy>(module_, recurse_, return_module_);
539
+ }
540
+ slot_iterator_impl<Policy> end() const {
541
+ return slot_iterator_impl<Policy>();
542
+ }
543
+ size_t size() const {
544
+ if (!size_) {
545
+ size_ = size_t(0);
546
+ for ([[maybe_unused]] const value_type& _ : *(this)) {
547
+ ++*size_;
548
+ }
549
+ }
550
+ return *size_;
551
+ }
552
+
553
+ slot_list_impl(Module module, bool recurse, bool return_module)
554
+ : module_(std::move(module)),
555
+ recurse_(recurse),
556
+ return_module_(return_module),
557
+ size_(std::nullopt) {
558
+ if (!recurse && !return_module && Policy::all_slots) {
559
+ size_ = module_.num_slots();
560
+ }
561
+ }
562
+
563
+ private:
564
+ Module module_;
565
+ bool recurse_;
566
+ bool return_module_;
567
+ // size of this list, cached on first request
568
+ // when we need to filter the slot list
569
+ mutable std::optional<size_t> size_;
570
+ friend struct Module;
571
+ };
572
+
573
+ namespace detail {
574
+
575
+ // slot_iterator_impl always iterate over all the slots in a module,
576
+ // the Policy template argument determines slots should be returned and their
577
+ // types
578
+ struct TORCH_API ModulePolicy {
579
+ // the type of the value being returned
580
+ using value_type = Module;
581
+
582
+ // the logic for creating the type being returned, given the raw IValue
583
+ // of that object.
584
+ static value_type create(
585
+ const std::vector<detail::SlotCursor>& cursors,
586
+ IValue v) {
587
+ return Module(std::move(v).toObject());
588
+ }
589
+ // is slot i in typ something that this iterator should return, otherwise,
590
+ // we skip it.
591
+ static bool valid(const ClassTypePtr& typ, size_t i, const IValue& v) {
592
+ return typ->getAttribute(i)->is_module();
593
+ }
594
+ // are we going to return everything? If so, we can optimize the calculate
595
+ // of the size of the list.
596
+ static CONSTEXPR_EXCEPT_WIN_CUDA bool all_slots = false;
597
+ };
598
+
599
+ struct TORCH_API ParameterPolicy {
600
+ using value_type = at::Tensor;
601
+ static value_type create(
602
+ const std::vector<detail::SlotCursor>& cursors,
603
+ IValue v) {
604
+ return std::move(v).toTensor();
605
+ }
606
+ static bool valid(const ClassTypePtr& typ, size_t i, const IValue& v) {
607
+ return typ->is_parameter(i) && v.isTensor();
608
+ }
609
+ static CONSTEXPR_EXCEPT_WIN_CUDA bool all_slots = false;
610
+ };
611
+
612
+ struct TORCH_API BufferPolicy {
613
+ using value_type = at::Tensor;
614
+ static value_type create(
615
+ const std::vector<detail::SlotCursor>& cursors,
616
+ IValue v) {
617
+ return std::move(v).toTensor();
618
+ }
619
+ static bool valid(const ClassTypePtr& typ, size_t i, const IValue& v) {
620
+ return typ->getAttribute(i)->isSubtypeOf(*TensorType::get()) &&
621
+ typ->is_buffer(i);
622
+ }
623
+ static CONSTEXPR_EXCEPT_WIN_CUDA bool all_slots = false;
624
+ };
625
+
626
+ struct TORCH_API AttributePolicy {
627
+ using value_type = IValue;
628
+ static value_type create(
629
+ const std::vector<detail::SlotCursor>& cursors,
630
+ IValue v) {
631
+ return v;
632
+ }
633
+ static bool valid(const ClassTypePtr& typ, size_t i, const IValue& v) {
634
+ return true;
635
+ }
636
+ static CONSTEXPR_EXCEPT_WIN_CUDA bool all_slots = true;
637
+ };
638
+
639
+ // take a Policy object, and make a version of it that returns the slot.
640
+ // along with the fully qualified name of that slot. This is used for the named_
641
+ // variants like named_parameters().
642
+ template <typename Policy>
643
+ struct NamedPolicy {
644
+ using value_type = Named<typename Policy::value_type>;
645
+ static value_type create(
646
+ const std::vector<detail::SlotCursor>& cursors,
647
+ IValue v) {
648
+ std::string name;
649
+ if (cursors.size() == 1) {
650
+ name = (cursors.back().i_ == -1) ? "" : nameFragment(cursors.back());
651
+ } else {
652
+ std::ostringstream ss;
653
+ for (const auto i : c10::irange(cursors.size())) {
654
+ if (i > 0) {
655
+ ss << ".";
656
+ }
657
+ ss << nameFragment(cursors[i]);
658
+ }
659
+ name = ss.str();
660
+ }
661
+ return value_type{std::move(name), Policy::create(cursors, std::move(v))};
662
+ }
663
+ static bool valid(const ClassTypePtr& t, size_t i, const IValue& v) {
664
+ return Policy::valid(t, i, v);
665
+ }
666
+ static constexpr bool all_slots = Policy::all_slots;
667
+
668
+ private:
669
+ static std::string nameFragment(const detail::SlotCursor& f) {
670
+ return f.module_.type()->getAttributeName(f.i_);
671
+ }
672
+ };
673
+
674
+ } // namespace detail
675
+
676
+ TORCH_API bool& getInlineEverythingMode();
677
+
678
+ namespace script {
679
+ // We once had a `script::` namespace that was deleted. This is for backcompat
680
+ // of the public API; new code should not use this type alias.
681
+ using Module = ::torch::jit::Module;
682
+ using ExtraFilesMap = ::torch::jit::ExtraFilesMap;
683
+ } // namespace script
684
+
685
+ } // namespace torch::jit
vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/api/object.h ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/functional.h>
4
+ #include <ATen/core/ivalue.h>
5
+ #include <torch/csrc/jit/api/method.h>
6
+ #include <optional>
7
+
8
+ #include <utility>
9
+
10
+ namespace torch::jit {
11
+
12
+ struct Resolver;
13
+ using ResolverPtr = std::shared_ptr<Resolver>;
14
+
15
+ using ObjectPtr = c10::intrusive_ptr<c10::ivalue::Object>;
16
+
17
+ // Throw this in C++ land if `attr` fails. This will be converted to a Python
18
+ // AttributeError by the Python binding code
19
+ class ObjectAttributeError : public std::runtime_error {
20
+ public:
21
+ ObjectAttributeError(const std::string& what) : std::runtime_error(what) {}
22
+ };
23
+
24
+ struct TORCH_API Object {
25
+ Object() = default;
26
+ Object(const Object&) = default;
27
+ Object& operator=(const Object&) = default;
28
+ Object(Object&&) noexcept = default;
29
+ Object& operator=(Object&&) noexcept = default;
30
+ Object(ObjectPtr _ivalue) : _ivalue_(std::move(_ivalue)) {}
31
+ Object(std::shared_ptr<CompilationUnit> cu, const c10::ClassTypePtr& type);
32
+ Object(
33
+ c10::QualifiedName,
34
+ std::shared_ptr<CompilationUnit> cu,
35
+ bool shouldMangle = false);
36
+
37
+ ObjectPtr _ivalue() const {
38
+ TORCH_INTERNAL_ASSERT(_ivalue_);
39
+ return _ivalue_;
40
+ }
41
+
42
+ c10::ClassTypePtr type() const {
43
+ return _ivalue()->type();
44
+ }
45
+
46
+ struct Property {
47
+ std::string name;
48
+ Method getter_func;
49
+ std::optional<Method> setter_func;
50
+ };
51
+
52
+ void setattr(const std::string& name, c10::IValue v) {
53
+ if (_ivalue()->type()->hasConstant(name)) {
54
+ TORCH_CHECK(
55
+ false,
56
+ "Can't set constant '",
57
+ name,
58
+ "' which has value:",
59
+ _ivalue()->type()->getConstant(name));
60
+ } else if (auto slot = _ivalue()->type()->findAttributeSlot(name)) {
61
+ const c10::TypePtr& expected = _ivalue()->type()->getAttribute(*slot);
62
+ TORCH_CHECK(
63
+ v.type()->isSubtypeOf(*expected),
64
+ "Expected a value of type '",
65
+ expected->repr_str(),
66
+ "' for field '",
67
+ name,
68
+ "', but found '",
69
+ v.type()->repr_str(),
70
+ "'");
71
+ _ivalue()->setSlot(*slot, std::move(v));
72
+ } else {
73
+ TORCH_CHECK(false, "Module has no attribute '", name, "'");
74
+ }
75
+ }
76
+
77
+ c10::IValue attr(const std::string& name) const {
78
+ if (auto r = _ivalue()->type()->findAttributeSlot(name)) {
79
+ return _ivalue()->getSlot(*r);
80
+ }
81
+ if (auto r = _ivalue()->type()->findConstantSlot(name)) {
82
+ return _ivalue()->type()->getConstant(*r);
83
+ }
84
+ std::stringstream err;
85
+ err << _ivalue()->type()->repr_str() << " does not have a field with name '"
86
+ << name.c_str() << "'";
87
+ throw ObjectAttributeError(err.str());
88
+ }
89
+
90
+ c10::IValue attr(const std::string& name, c10::IValue or_else) const {
91
+ if (auto r = _ivalue()->type()->findAttributeSlot(name)) {
92
+ return _ivalue()->getSlot(*r);
93
+ }
94
+ if (auto r = _ivalue()->type()->findConstantSlot(name)) {
95
+ return _ivalue()->type()->getConstant(*r);
96
+ }
97
+ return or_else;
98
+ }
99
+
100
+ bool hasattr(const std::string& name) const {
101
+ return _ivalue()->type()->hasAttribute(name) ||
102
+ _ivalue()->type()->hasConstant(name);
103
+ }
104
+
105
+ // each object owns its methods. The reference returned here
106
+ // is guaranteed to stay valid until this module has been destroyed
107
+ Method get_method(const std::string& name) const {
108
+ if (auto method = find_method(name)) {
109
+ return *method;
110
+ }
111
+ AT_ERROR("Method '", name, "' is not defined.");
112
+ }
113
+
114
+ const std::vector<Method> get_methods() const {
115
+ return c10::fmap(type()->methods(), [&](Function* func) {
116
+ return Method(_ivalue(), func);
117
+ });
118
+ }
119
+
120
+ bool has_property(const std::string& name) const {
121
+ for (const auto& prop : type()->properties()) {
122
+ if (prop.name == name) {
123
+ return true;
124
+ }
125
+ }
126
+ return false;
127
+ }
128
+
129
+ const Property get_property(const std::string& name) const {
130
+ for (const auto& prop : type()->properties()) {
131
+ if (prop.name == name) {
132
+ std::optional<Method> setter = std::nullopt;
133
+ if (prop.setter) {
134
+ setter = Method(_ivalue(), prop.setter);
135
+ }
136
+ return Property{
137
+ prop.name, Method(_ivalue(), prop.getter), std::move(setter)};
138
+ }
139
+ }
140
+ AT_ERROR("Property '", name, "' is not defined.");
141
+ }
142
+
143
+ const std::vector<Property> get_properties() const {
144
+ return c10::fmap(type()->properties(), [&](ClassType::Property prop) {
145
+ std::optional<Method> setter = std::nullopt;
146
+ if (prop.setter) {
147
+ setter = Method(_ivalue(), prop.setter);
148
+ }
149
+ return Property{
150
+ std::move(prop.name),
151
+ Method(_ivalue(), prop.getter),
152
+ std::move(setter)};
153
+ });
154
+ }
155
+
156
+ std::optional<Method> find_method(const std::string& basename) const;
157
+
158
+ /// Run a method from this module.
159
+ ///
160
+ /// For example:
161
+ /// @code
162
+ /// IValue output = module->run("relu_script", a, b);
163
+ /// @endcode
164
+ ///
165
+ /// To get a compile a module from a source string, see torch::jit::compile
166
+ ///
167
+ /// @param method_name The name of the method to run
168
+ /// @param args Arguments to be passed to the method
169
+ /// @return An IValue containing the return value (or values if it is a tuple)
170
+ /// from the method
171
+ template <typename... Types>
172
+ IValue run_method(const std::string& method_name, Types&&... args) {
173
+ return get_method(method_name)({IValue(std::forward<Types>(args))...});
174
+ }
175
+
176
+ // so that C++ users can easily add methods
177
+ void define(const std::string& src, const ResolverPtr& resolver = nullptr);
178
+
179
+ size_t num_slots() const {
180
+ return _ivalue()->slots().size();
181
+ }
182
+
183
+ // shallow copy the object
184
+ Object copy() const;
185
+
186
+ // Copies all the attributes of the object recursively without creating new
187
+ // `ClassType`, including deepcopy of Tensors
188
+ Object deepcopy() const;
189
+
190
+ private:
191
+ // mutable be we lazily initialize in module_object.
192
+ mutable ObjectPtr _ivalue_;
193
+ };
194
+
195
+ namespace script {
196
+ // We once had a `script::` namespace that was deleted. This is for backcompat
197
+ // of the public API; new code should not use this type alias.
198
+ using Object = ::torch::jit::Object;
199
+ } // namespace script
200
+ } // namespace torch::jit
vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/builtin_functions.h ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <torch/csrc/Export.h>
4
+ #include <torch/csrc/jit/api/module.h>
5
+
6
+ namespace torch::jit {
7
+
8
+ TORCH_API const std::vector<Function*>& getAllBuiltinFunctionsFor(Symbol name);
9
+ } // namespace torch::jit
vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/convert_to_ssa.h ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <functional>
3
+ #include <memory>
4
+ #include <string>
5
+
6
+ #include <torch/csrc/Export.h>
7
+ #include <torch/csrc/jit/ir/ir.h>
8
+
9
+ namespace torch::jit {
10
+
11
+ // Convert a graph with Loads & Stores into SSA form
12
+ TORCH_API void ConvertToSSA(std::shared_ptr<Graph>& graph);
13
+
14
+ } // namespace torch::jit
vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/ir_emitter.h ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <functional>
3
+ #include <memory>
4
+ #include <string>
5
+
6
+ #include <torch/csrc/jit/api/module.h>
7
+ #include <torch/csrc/jit/frontend/error_report.h>
8
+ #include <torch/csrc/jit/frontend/resolver.h>
9
+ #include <torch/csrc/jit/frontend/sugared_value.h>
10
+ #include <torch/csrc/jit/frontend/tree_views.h>
11
+ #include <torch/csrc/jit/ir/ir.h>
12
+
13
+ namespace torch::jit {
14
+
15
+ TORCH_API void runCleanupPasses(std::shared_ptr<Graph>& to_clean);
16
+
17
+ TORCH_API bool meaningfulName(const std::string& name);
18
+
19
+ } // namespace torch::jit
vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/lexer.h ADDED
@@ -0,0 +1,562 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <c10/macros/Macros.h>
3
+ #include <c10/util/Exception.h>
4
+ #include <torch/csrc/Export.h>
5
+ #include <torch/csrc/jit/frontend/parser_constants.h>
6
+ #include <torch/csrc/jit/frontend/source_range.h>
7
+ #include <torch/csrc/jit/frontend/strtod.h>
8
+ #include <algorithm>
9
+ #include <clocale>
10
+ #include <cstdlib>
11
+ #include <memory>
12
+ #include <sstream>
13
+ #include <string>
14
+ #include <vector>
15
+
16
+ namespace torch::jit {
17
+
18
+ // single character tokens are just the character itself '+'
19
+ // multi-character tokens need an entry here
20
+ // if the third entry is not the empty string, it is used
21
+ // in the lexer to match this token.
22
+
23
+ // These kinds are also used in Tree.h as the kind of the AST node.
24
+ // Some kinds TK_APPLY, TK_LIST are only used in the AST and are not seen in the
25
+ // lexer.
26
+
27
+ #define TC_FORALL_TOKEN_KINDS(_) \
28
+ _(TK_EOF, "eof", "") \
29
+ _(TK_WHITESPACE, "whitespace", "") \
30
+ _(TK_WHITESPACE_EOF, "whitespace_eof", "") \
31
+ _(TK_NUMBER, "number", "") \
32
+ _(TK_NEWLINE, "newline", "") \
33
+ _(TK_INDENT, "indent", "") \
34
+ _(TK_DEDENT, "dedent", "") \
35
+ _(TK_DEF, "def", "def") \
36
+ _(TK_EQUIVALENT, "equivalent", "<=>") \
37
+ _(TK_IDENT, "ident", "") \
38
+ _(TK_STRING, "string", "") \
39
+ _(TK_STRINGLITERAL, "string_literal", "") \
40
+ _(TK_CONST, "const", "") \
41
+ _(TK_LIST, "list", "") \
42
+ _(TK_DICT, "dict", "") \
43
+ _(TK_OPTION, "option", "") \
44
+ _(TK_APPLY, "apply", "") \
45
+ _(TK_COMPREHENSION, "comprehension", "") \
46
+ _(TK_RANGE_CONSTRAINT, "range_constraint", "") \
47
+ _(TK_PARAM, "param", "") \
48
+ _(TK_INFERRED, "inferred", "") \
49
+ _(TK_ACCESS, "access", "") \
50
+ _(TK_ASSIGN, "assign", "") \
51
+ _(TK_AUG_ASSIGN, "aug_assign", "") \
52
+ _(TK_ATTRIBUTE, "attribute", "") \
53
+ _(TK_IF, "if", "if") \
54
+ _(TK_ELSE, "else", "else") \
55
+ _(TK_ELIF, "elif", "elif") \
56
+ _(TK_WHILE, "while", "while") \
57
+ _(TK_EXPR_STMT, "expression statement", "") \
58
+ _(TK_RETURN, "return", "return") \
59
+ _(TK_IS, "is", "is") \
60
+ _(TK_ISNOT, "is not", "is not") \
61
+ _(TK_NE, "ne", "!=") \
62
+ _(TK_EQ, "eq", "==") \
63
+ _(TK_LE, "le", "<=") \
64
+ _(TK_GE, "ge", ">=") \
65
+ _(TK_FLOOR_DIV, "floordiv", "//") \
66
+ _(TK_IF_EXPR, "if", "") \
67
+ _(TK_TRUE, "True", "True") \
68
+ _(TK_FALSE, "False", "False") \
69
+ _(TK_NONE, "None", "None") \
70
+ _(TK_AND, "and", "and") \
71
+ _(TK_OR, "or", "or") \
72
+ _(TK_NOT, "not", "not") \
73
+ _(TK_LSHIFT, "<<", "<<") \
74
+ _(TK_RSHIFT, ">>", ">>") \
75
+ _(TK_CAST, "cast", "") \
76
+ _(TK_PLUS_EQ, "+=", "+=") \
77
+ _(TK_MINUS_EQ, "-=", "-=") \
78
+ _(TK_TIMES_EQ, "*=", "*=") \
79
+ _(TK_DIV_EQ, "/=", "/=") \
80
+ _(TK_MOD_EQ, "%=", "%=") \
81
+ _(TK_BIT_OR_EQ, "|=", "|=") \
82
+ _(TK_BIT_AND_EQ, "&=", "&=") \
83
+ _(TK_BIT_XOR_EQ, "^=", "^=") \
84
+ _(TK_LSHIFT_EQ, "<<=", "<<=") \
85
+ _(TK_RSHIFT_EQ, ">>=", ">>=") \
86
+ _(TK_POW_EQ, "**=", "**=") \
87
+ _(TK_GLOBAL, "global", "global") \
88
+ _(TK_BUILT_IN, "built-in", "") \
89
+ _(TK_SUBSCRIPT, "subscript", "") \
90
+ _(TK_VAR, "variable", "") \
91
+ _(TK_NOTHING, "nothing", "") \
92
+ _(TK_DICT_LITERAL, "dict-literal", "") \
93
+ _(TK_LIST_LITERAL, "list-literal", "") \
94
+ _(TK_TUPLE_LITERAL, "tuple-literal", "") \
95
+ _(TK_FOR, "for", "for") \
96
+ _(TK_IN, "in", "in") \
97
+ _(TK_NOTIN, "not in", "not in") \
98
+ _(TK_STARRED, "starred", "") \
99
+ _(TK_UNARY_MINUS, "unary minus", "") \
100
+ _(TK_POW, "pow operator", "**") \
101
+ _(TK_ARROW, "arrow", "->") \
102
+ _(TK_DECL, "decl", "") \
103
+ _(TK_SLICE_EXPR, "slice expr", "") \
104
+ _(TK_TYPE_COMMENT, "type comment", "# type:") \
105
+ _(TK_RAISE, "raise", "raise") \
106
+ _(TK_ASSERT, "assert", "assert") \
107
+ _(TK_DOTS, "dots", "...") \
108
+ _(TK_LIST_COMP, "list comprehension", "") \
109
+ _(TK_DICT_COMP, "dict comprehension", "") \
110
+ _(TK_BREAK, "break", "break") \
111
+ _(TK_CONTINUE, "continue", "continue") \
112
+ _(TK_DELETE, "del", "del") \
113
+ _(TK_PASS, "pass", "pass") \
114
+ _(TK_CLASS_DEF, "class", "class") \
115
+ _(TK_IMPORT, "import", "import") \
116
+ _(TK_WITH, "with", "with") \
117
+ _(TK_WITH_ITEM, "withitem", "") \
118
+ _(TK_AS, "as", "as") \
119
+ _(TK_PROP, "property", "") \
120
+ _(TK_ELLIPSIS, "Ellipsis", "Ellipsis") \
121
+ _(TK_NONE_TYPE, "NoneType", "NoneType")
122
+
123
+ enum TokenKind {
124
+ // we use characters to represent themselves so skip all valid characters
125
+ // before
126
+ // assigning enum values to multi-char tokens.
127
+ TK_DUMMY_START = 256,
128
+ #define DEFINE_TOKEN(tok, _, _2) tok,
129
+ TC_FORALL_TOKEN_KINDS(DEFINE_TOKEN)
130
+ #undef DEFINE_TOKEN
131
+ };
132
+
133
+ TORCH_API std::string kindToString(int kind);
134
+ TORCH_API int stringToKind(const std::string& str);
135
+
136
+ // nested hash tables that indicate char-by-char what is a valid token.
137
+ struct TokenTrie;
138
+ using TokenTrieRef = std::unique_ptr<TokenTrie>;
139
+ struct TokenTrie {
140
+ TokenTrie() = default;
141
+ void insert(const char* str, int tok) {
142
+ if (*str == '\0') {
143
+ AT_ASSERT(kind == 0);
144
+ kind = tok;
145
+ return;
146
+ }
147
+
148
+ for (size_t i = 0, e = child_chars.size(); i < e; ++i) {
149
+ if (child_chars[i] == *str) {
150
+ child_tries[i]->insert(str + 1, tok);
151
+ return;
152
+ }
153
+ }
154
+
155
+ child_chars.emplace_back(*str);
156
+ child_tries.emplace_back(std::make_unique<TokenTrie>());
157
+ child_tries.back()->insert(str + 1, tok);
158
+ }
159
+ int kind{0}; // 0 == invalid token
160
+
161
+ std::vector<char> child_chars;
162
+ std::vector<TokenTrieRef> child_tries;
163
+ };
164
+
165
+ // stuff that is shared against all TC lexers/parsers and is initialized only
166
+ // once.
167
+ struct TORCH_API SharedParserData {
168
+ SharedParserData() : head(new TokenTrie()) {
169
+ for (const char* c = valid_single_char_tokens; *c; c++) {
170
+ std::string str(1, *c);
171
+ head->insert(str.c_str(), *c);
172
+ }
173
+
174
+ #define ADD_CASE(tok, _, tokstring) \
175
+ if (*(tokstring) != '\0') { \
176
+ head->insert((tokstring), (tok)); \
177
+ }
178
+ TC_FORALL_TOKEN_KINDS(ADD_CASE)
179
+ #undef ADD_CASE
180
+ }
181
+
182
+ bool match(
183
+ StringCordView::Iterator pos,
184
+ bool continuation, // are we inside a scope where newlines don't count
185
+ // (e.g. inside parens)
186
+ bool whitespace_token, // should we treat whitespace as a token
187
+ int* kind,
188
+ StringCordView::Iterator* start,
189
+ StringCordView::Iterator* end) {
190
+ *start = pos;
191
+ // skip whitespace
192
+ while (pos.has_next() && isblank(*pos)) {
193
+ ++pos;
194
+ }
195
+
196
+ // special handling
197
+ if (pos.has_next()) {
198
+ if (*pos == '#' && !isTypeComment(pos)) {
199
+ // skip comments
200
+ while (pos.has_next() && *pos != '\n')
201
+ ++pos;
202
+ // tail call, handle whitespace and more comments
203
+ return match(pos, continuation, whitespace_token, kind, start, end);
204
+ }
205
+ if (*pos == '\\') {
206
+ auto newiter = pos;
207
+ ++newiter;
208
+ if (newiter.has_next() && *newiter == '\n' && !whitespace_token) {
209
+ ++newiter;
210
+ return match(newiter, continuation, false, kind, start, end);
211
+ }
212
+ }
213
+ if (*pos == '\n') {
214
+ return match(++pos, continuation, !continuation, kind, start, end);
215
+ }
216
+ }
217
+ // we handle white space before EOF because in the case we have something
218
+ // like the following where we need to generate the dedent token if foo:
219
+ // ...
220
+ // else:
221
+ // pass
222
+ if (whitespace_token) {
223
+ *kind = !pos.has_next() ? TK_WHITESPACE_EOF : TK_WHITESPACE;
224
+ *end = pos;
225
+ return true;
226
+ }
227
+ if (!pos.has_next()) {
228
+ *kind = TK_EOF;
229
+ *start = pos;
230
+ *end = *start;
231
+ return true;
232
+ }
233
+ // invariant: the next token is not whitespace or newline
234
+ *start = pos;
235
+ // check for a valid number
236
+ size_t len = 0;
237
+ if (isNumber(pos.rest_line(), 0, &len)) {
238
+ *end = *start;
239
+ *end += len;
240
+ *kind = TK_NUMBER;
241
+ return true;
242
+ }
243
+ // check for string
244
+ if (isString(pos.rest_line(), 0, &len)) {
245
+ *kind = TK_STRINGLITERAL;
246
+ *end = *start;
247
+ *end += len;
248
+ return true;
249
+ }
250
+
251
+ // check for either an ident or a token
252
+ // ident tracks whether what we have scanned so far could be an identifier
253
+ // matched indicates if we have found any match.
254
+ bool matched = false;
255
+ bool ident = true;
256
+ TokenTrie* cur = head.get();
257
+ // for (size_t i = 0; pos + i < str.size() && (ident || cur != nullptr);
258
+ // i++)
259
+ for (size_t i = 0; pos.has_next() && (ident || cur != nullptr);
260
+ ++pos, ++i) {
261
+ ident = ident && validIdent(i, *pos);
262
+ if (ident) {
263
+ matched = true;
264
+ *end = pos.next_iter();
265
+ *kind = TK_IDENT;
266
+ }
267
+ // check for token second, so that e.g. 'max' matches the token TK_MAX
268
+ // rather the
269
+ // identifier 'max'
270
+ if (cur) {
271
+ const auto begin_it = cur->child_chars.begin();
272
+ const auto end_it = cur->child_chars.end();
273
+ const auto ch_it = std::find(begin_it, end_it, *pos);
274
+
275
+ cur = (ch_it == end_it) ? nullptr
276
+ : cur->child_tries[ch_it - begin_it].get();
277
+
278
+ if (cur && cur->kind != 0) {
279
+ matched = true;
280
+ *end = pos.next_iter();
281
+ *kind = cur->kind;
282
+ }
283
+ }
284
+ }
285
+ return matched;
286
+ }
287
+
288
+ bool isUnary(int kind, int* prec);
289
+ bool isBinary(int kind, int* prec);
290
+ bool isRightAssociative(int kind) {
291
+ switch (kind) {
292
+ case '?':
293
+ case TK_POW:
294
+ case TK_IF:
295
+ return true;
296
+ default:
297
+ return false;
298
+ }
299
+ }
300
+
301
+ private:
302
+ bool validIdent(size_t i, char n) {
303
+ return isalpha(n) || n == '_' || (i > 0 && isdigit(n));
304
+ }
305
+
306
+ // 1. skip whitespace
307
+ // 2. handle comment or newline
308
+ //
309
+ bool isNumber(c10::string_view str, size_t start, size_t* len) {
310
+ char first = str[start];
311
+ // strtod allows numbers to start with + or - or nan or inf
312
+ // http://en.cppreference.com/w/cpp/string/byte/strtof
313
+ // but we want only the number part, otherwise 1+3 will turn into two
314
+ // adjacent numbers in the lexer
315
+ if (first == '-' || first == '+' || isalpha(first))
316
+ return false;
317
+ const char* startptr = str.data() + start;
318
+ char* endptr = nullptr;
319
+ torch::jit::strtod_c(startptr, &endptr);
320
+ *len = endptr - startptr;
321
+ // check if the number is complex valued
322
+ // access is safe because string is assumed to be null terminated
323
+ if (endptr != nullptr && *endptr == 'j') {
324
+ *len += 1;
325
+ }
326
+ return *len > 0;
327
+ }
328
+
329
+ bool isCharCount(char c, c10::string_view str, size_t start, int len) {
330
+ // count checks from [start, start + len)
331
+ return start + len <= str.size() &&
332
+ std::count(str.begin() + start, str.begin() + start + len, c) == len;
333
+ }
334
+
335
+ // python concatenates all adjacent strings "a" "b" == "ab"
336
+ // strings can be enclosed with 1 or 3 single or double quotes
337
+ // if enclosed with 3 quotes newlines are valid
338
+ // as elsewhere, backslash and new line should be ignored
339
+ bool isString(c10::string_view str, size_t start, size_t* len) {
340
+ char quote = str[start];
341
+ if (quote != '\"' && quote != '\'')
342
+ return false;
343
+ int quote_len = isCharCount(quote, str, start, 3) ? 3 : 1;
344
+
345
+ // end is now set past the opening quotation marks
346
+ size_t end = start + quote_len;
347
+ while (end < str.size() && !isCharCount(quote, str, end, quote_len)) {
348
+ if (str[end] == '\n' && quote_len != 3) {
349
+ return false;
350
+ }
351
+ // handle escaped characters. advances past escaped quotation marks,
352
+ // escaped newlines and escaped backslashes
353
+ // multi-char escapes like \x1A are handled fine here because the
354
+ // remainder of the escape are valid string characters anyway
355
+ if (str[end] == '\\') {
356
+ end++;
357
+ }
358
+ end++;
359
+ }
360
+ // set length equal to the complete string including quotations
361
+ *len = end - start + quote_len;
362
+ // if end finished without going past the last character of the string than
363
+ // there is a match
364
+ return end < str.size();
365
+ }
366
+
367
+ bool isblank(int n) {
368
+ return isspace(n) && n != '\n';
369
+ }
370
+
371
+ bool isTypeComment(StringCordView::Iterator str_iter) {
372
+ c10::string_view rest_line = str_iter.rest_line();
373
+ const std::string type_string = "# type:";
374
+ if (rest_line.size() < type_string.length()) {
375
+ return false;
376
+ }
377
+ auto match_string = rest_line.substr(0, type_string.size());
378
+ return match_string == type_string;
379
+ }
380
+
381
+ // Make an exception ignoring comments for type annotation comments
382
+ bool isTypeComment(const StringCordView& str, size_t pos) {
383
+ const std::string type_string = "# type:";
384
+ if (str.size() < pos + type_string.length()) {
385
+ return false;
386
+ }
387
+ auto match_string = str.substr(pos, type_string.size());
388
+ return match_string == type_string;
389
+ }
390
+
391
+ TokenTrieRef head;
392
+ };
393
+
394
+ TORCH_API SharedParserData& sharedParserData();
395
+
396
+ struct Token {
397
+ int kind;
398
+ SourceRange range;
399
+ Token(int kind, SourceRange range) : kind(kind), range(std::move(range)) {}
400
+ std::string text() {
401
+ return std::string(range.token_text());
402
+ }
403
+ std::string kindString() const {
404
+ return kindToString(kind);
405
+ }
406
+ };
407
+
408
+ struct Lexer {
409
+ explicit Lexer(std::shared_ptr<Source> source)
410
+ : source(std::move(source)),
411
+
412
+ indent_stack(),
413
+ next_tokens(),
414
+ shared(sharedParserData()) {
415
+ auto first_indent = lexRaw(true);
416
+ indent_stack.push_back(first_indent.range.size());
417
+ lex();
418
+ }
419
+ // Return the current token, and then move to the next one
420
+ Token next() {
421
+ if (next_tokens.empty())
422
+ reportError("Lexer invariant violated: empty token queue");
423
+ Token r = std::move(next_tokens.front());
424
+ next_tokens.erase(next_tokens.begin());
425
+ if (next_tokens.empty()) {
426
+ lex();
427
+ }
428
+ return r;
429
+ }
430
+ // Skip the current token if it matches the given kind
431
+ bool nextIf(int kind) {
432
+ if (cur().kind != kind)
433
+ return false;
434
+ next();
435
+ return true;
436
+ }
437
+
438
+ [[noreturn]] void reportError(const std::string& what) {
439
+ reportError(what, cur());
440
+ }
441
+ [[noreturn]] void reportError(const std::string& what, const Token& t) {
442
+ std::stringstream ss;
443
+ ss << what << ":\n";
444
+ t.range.highlight(ss);
445
+ throw std::runtime_error(ss.str());
446
+ }
447
+ [[noreturn]] void expected(const std::string& what, const Token& t) {
448
+ std::stringstream ss;
449
+ ss << "expected " << what << " but found '" << t.kindString()
450
+ << "' here:\n";
451
+ t.range.highlight(ss);
452
+ throw std::runtime_error(ss.str());
453
+ }
454
+ [[noreturn]] void expected(const std::string& what) {
455
+ expected(what, cur());
456
+ }
457
+ // Check that the current token has a given kind, return the current token,
458
+ // and advance to the next one.
459
+ Token expect(int kind) {
460
+ if (cur().kind != kind) {
461
+ expected(kindToString(kind));
462
+ }
463
+ return next();
464
+ }
465
+ Token& lookahead() {
466
+ if (next_tokens.size() < 2) {
467
+ lex();
468
+ }
469
+ return next_tokens[1];
470
+ }
471
+ Token& cur() {
472
+ return next_tokens.front();
473
+ }
474
+
475
+ private:
476
+ void lex() {
477
+ auto r = lexRaw();
478
+ switch (r.kind) {
479
+ case '(':
480
+ case '[':
481
+ case '{':
482
+ nesting++;
483
+ break;
484
+ case ')':
485
+ case ']':
486
+ case '}':
487
+ nesting--;
488
+ break;
489
+ case TK_WHITESPACE:
490
+ case TK_WHITESPACE_EOF: {
491
+ const auto depth =
492
+ r.kind == TK_WHITESPACE_EOF ? indent_stack.front() : r.range.size();
493
+ // note: TK_WHITESPACE_EOF is whitespace right before the EOF token
494
+ // just like we allow the code to be indented to a particular initial
495
+ // indent level, we allow the final indent to be anything and set
496
+ // it back to the initial indent level. This allows the code to be
497
+ // put into string literals inside code without worrying about final
498
+ // whitespace
499
+ if (depth > indent_stack.back()) {
500
+ indent_stack.push_back(depth);
501
+ r.kind = TK_INDENT;
502
+ } else if (depth == indent_stack.back()) {
503
+ r.kind = TK_NEWLINE;
504
+ } else {
505
+ next_tokens.emplace_back(TK_NEWLINE, r.range);
506
+ while (indent_stack.back() != depth) {
507
+ indent_stack.pop_back();
508
+ next_tokens.emplace_back(TK_DEDENT, r.range);
509
+ if (indent_stack.empty()) {
510
+ reportError("invalid indent level " + std::to_string(depth), r);
511
+ }
512
+ }
513
+ return; // We've already queued the tokens
514
+ }
515
+ } break;
516
+ default:
517
+ break;
518
+ }
519
+ next_tokens.push_back(std::move(r));
520
+ }
521
+ Token lexRaw(bool whitespace_token = false) {
522
+ AT_ASSERT(source);
523
+ if (current == nullptr) {
524
+ AT_ASSERT(pos == 0);
525
+ current = std::make_unique<StringCordView::Iterator>(
526
+ source->text_str().begin());
527
+ }
528
+
529
+ StringCordView::Iterator start_iter = *current;
530
+ StringCordView::Iterator end_iter = *current;
531
+ int kind = 0;
532
+ if (!shared.match(
533
+ *current,
534
+ nesting > 0,
535
+ whitespace_token,
536
+ &kind,
537
+ &start_iter,
538
+ &end_iter)) {
539
+ expected(
540
+ "a valid token",
541
+ Token(
542
+ **current,
543
+ SourceRange(source, start_iter, start_iter.pos() + 1)));
544
+ }
545
+
546
+ auto t = Token(kind, SourceRange(source, start_iter, end_iter.pos()));
547
+ pos = end_iter.pos();
548
+ *current = end_iter;
549
+ return t;
550
+ }
551
+
552
+ std::shared_ptr<Source> source;
553
+ std::unique_ptr<StringCordView::Iterator> current;
554
+ size_t pos{0};
555
+ size_t nesting{0}; // depth of ( [ { nesting...
556
+ std::vector<size_t> indent_stack; // stack of indentation level of blocks
557
+ // Invariant: this should always contain at least a single element
558
+ std::vector<Token> next_tokens;
559
+ // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members)
560
+ SharedParserData& shared;
561
+ };
562
+ } // namespace torch::jit
vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/mini_environment.h ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/jit_type.h>
4
+ #include <torch/csrc/jit/ir/ir.h>
5
+
6
+ namespace torch::jit {
7
+
8
+ // Simple data structure for containing a type T in nested control blocks
9
+ // Should only be used after initial compilation where type checking and
10
+ // loads and stores are emitted
11
+
12
+ template <typename T>
13
+ struct MiniEnvironment {
14
+ MiniEnvironment(Block* b, std::shared_ptr<MiniEnvironment> next = nullptr)
15
+ : next(std::move(next)) {}
16
+
17
+ // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
18
+ std::shared_ptr<MiniEnvironment<T>> next;
19
+
20
+ T findInThisFrame(const std::string& name) {
21
+ auto it = table.find(name);
22
+ if (it != table.end()) {
23
+ return it->second;
24
+ }
25
+ return nullptr;
26
+ }
27
+
28
+ T findInAnyFrame(const std::string& name) {
29
+ for (auto runner = this; runner; runner = runner->next.get()) {
30
+ if (auto r = runner->findInThisFrame(name)) {
31
+ return r;
32
+ }
33
+ }
34
+ return nullptr;
35
+ }
36
+
37
+ void setVar(const std::string& name, T value) {
38
+ table[name] = value;
39
+ }
40
+
41
+ std::vector<std::string> definedVariables() {
42
+ std::vector<std::string> result;
43
+ result.reserve(table.size());
44
+ for (auto& kv : table) {
45
+ result.push_back(kv.first);
46
+ }
47
+ std::sort(result.begin(), result.end());
48
+ return result;
49
+ }
50
+
51
+ private:
52
+ std::unordered_map<std::string, T> table;
53
+ };
54
+
55
+ } // namespace torch::jit
vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/parse_string_literal.h ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <torch/csrc/jit/frontend/error_report.h>
3
+ #include <torch/csrc/jit/frontend/lexer.h>
4
+ #include <optional>
5
+
6
+ namespace torch::jit {
7
+
8
+ inline bool isCharCount(char c, const std::string& str, size_t start, int len) {
9
+ // count checks from [start, start + len)
10
+ return start + len <= str.size() &&
11
+ std::count(
12
+ str.begin() + static_cast<ptrdiff_t>(start),
13
+ str.begin() + static_cast<ptrdiff_t>(start + len),
14
+ c) == len;
15
+ }
16
+
17
+ inline std::optional<char> parseOctal(const std::string& str, size_t pos) {
18
+ //\xxx where x are 0-7
19
+ if (pos + 3 >= str.size())
20
+ return std::nullopt;
21
+ size_t c = 0;
22
+ for (size_t i = 1, b = 64; i < 4; ++i, b /= 8) {
23
+ auto d = str[pos + i];
24
+ if (d < '0' || d > '7')
25
+ return std::nullopt;
26
+ c += b * (d - '0');
27
+ }
28
+ if (c >= 256)
29
+ return std::nullopt;
30
+ return c;
31
+ }
32
+
33
+ inline std::string parseStringLiteral(
34
+ const SourceRange& range,
35
+ const std::string& str) {
36
+ size_t quote_len = isCharCount(str[0], str, 0, 3) ? 3 : 1;
37
+ auto ret_str = str.substr(quote_len, str.size() - quote_len * 2);
38
+ size_t pos = ret_str.find('\\');
39
+ while (pos != std::string::npos) {
40
+ // invariant: pos has to escape a character because it is a valid string
41
+ char c = ret_str[pos + 1];
42
+ size_t to_erase = 2;
43
+ switch (ret_str[pos + 1]) {
44
+ case '\\':
45
+ case '\'':
46
+ case '\"':
47
+ case '\n':
48
+ break;
49
+ case 'a':
50
+ c = '\a';
51
+ break;
52
+ case 'b':
53
+ c = '\b';
54
+ break;
55
+ case 'f':
56
+ c = '\f';
57
+ break;
58
+ case 'n':
59
+ c = '\n';
60
+ break;
61
+ case 'v':
62
+ c = '\v';
63
+ break;
64
+ case 't':
65
+ c = '\t';
66
+ break;
67
+ case 'x':
68
+ throw(ErrorReport(range) << "unsupported hex specifier");
69
+ case 'u':
70
+ case 'U':
71
+ throw(ErrorReport(range) << "unsupported unicode specifier");
72
+ default:
73
+ // octal value in format \nnn, n is [0-7]
74
+ if (auto v = parseOctal(ret_str, pos)) {
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 torch::jit
vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/script_type_parser.h ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <ATen/core/jit_type.h>
3
+ #include <torch/csrc/Export.h>
4
+ #include <torch/csrc/jit/frontend/resolver.h>
5
+ #include <torch/csrc/jit/frontend/tree_views.h>
6
+
7
+ namespace torch::jit {
8
+
9
+ /**
10
+ * class ScriptTypeParser
11
+ *
12
+ * Parses expressions in our typed AST format (TreeView) into types and
13
+ * typenames.
14
+ */
15
+ class TORCH_API ScriptTypeParser {
16
+ public:
17
+ explicit ScriptTypeParser() = default;
18
+ explicit ScriptTypeParser(ResolverPtr resolver)
19
+ : resolver_(std::move(resolver)) {}
20
+
21
+ c10::TypePtr parseTypeFromExpr(const Expr& expr) const;
22
+
23
+ std::optional<std::pair<c10::TypePtr, int32_t>> parseBroadcastList(
24
+ const Expr& expr) const;
25
+
26
+ c10::TypePtr parseType(const std::string& str);
27
+
28
+ FunctionSchema parseSchemaFromDef(const Def& def, bool skip_self);
29
+
30
+ c10::IValue parseClassConstant(const Assign& assign);
31
+
32
+ private:
33
+ c10::TypePtr parseTypeFromExprImpl(const Expr& expr) const;
34
+
35
+ std::optional<std::string> parseBaseTypeName(const Expr& expr) const;
36
+ at::TypePtr subscriptToType(
37
+ const std::string& typeName,
38
+ const Subscript& subscript) const;
39
+ std::vector<IValue> evaluateDefaults(
40
+ const SourceRange& r,
41
+ const std::vector<Expr>& default_types,
42
+ const std::vector<Expr>& default_exprs);
43
+ std::vector<Argument> parseArgsFromDecl(const Decl& decl, bool skip_self);
44
+
45
+ std::vector<Argument> parseReturnFromDecl(const Decl& decl);
46
+
47
+ ResolverPtr resolver_ = nullptr;
48
+
49
+ // Need to use `evaluateDefaults` in serialization
50
+ friend struct ConstantTableValue;
51
+ friend struct SourceImporterImpl;
52
+ };
53
+ } // namespace torch::jit
vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/sugared_value.h ADDED
@@ -0,0 +1,861 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <memory>
3
+ #include <optional>
4
+ #include <string>
5
+ #include <utility>
6
+
7
+ #include <ATen/core/symbol.h>
8
+ #include <caffe2/serialize/versions.h>
9
+ #include <torch/csrc/jit/api/module.h>
10
+ #include <torch/csrc/jit/frontend/error_report.h>
11
+ #include <torch/csrc/jit/frontend/schema_matching.h>
12
+ #include <torch/csrc/jit/frontend/versioned_symbols.h>
13
+ #include <torch/csrc/jit/ir/ir.h>
14
+
15
+ namespace torch::jit {
16
+
17
+ using SugaredValuePtr = std::shared_ptr<SugaredValue>;
18
+
19
+ // The AST can contain nodes like `self`, `self.b` or `python_fn` that
20
+ // are not first-class values in the graph representation, but instead
21
+ // will be desugared based on how they are used in the AST.
22
+
23
+ // SugaredValue is used to temporarily represent these values in a way
24
+ // that separates their behavior from the AST -> IR converter itself.
25
+ // This allows us to keep dependencies on python minimal.
26
+
27
+ struct TORCH_API SugaredValue
28
+ : public std::enable_shared_from_this<SugaredValue> {
29
+ // what is this node? for error reporting (e.g. Module, python function)
30
+ virtual std::string kind() const = 0;
31
+
32
+ // what can we do with this thing?
33
+ // use it as a value e.g. `this + 4`
34
+ virtual Value* asValue(const SourceRange& loc, GraphFunction& m) {
35
+ throw(ErrorReport(loc) << kind() << " cannot be used as a value");
36
+ }
37
+
38
+ // select an attribute on it, e.g. `this.field`
39
+ virtual std::shared_ptr<SugaredValue> attr(
40
+ const SourceRange& loc,
41
+ GraphFunction& m,
42
+ const std::string& field) {
43
+ throw(ErrorReport(loc) << "attribute lookup is not defined on " << kind());
44
+ }
45
+
46
+ virtual bool hasAttr(
47
+ const SourceRange& loc,
48
+ GraphFunction& m,
49
+ const std::string& field) {
50
+ throw(ErrorReport(loc) << "attribute lookup is not defined on " << kind());
51
+ }
52
+
53
+ // assign an attribute on it, e.g. `this.field = newValue`
54
+ virtual void setAttr(
55
+ const SourceRange& loc,
56
+ GraphFunction& m,
57
+ const std::string& field,
58
+ Value* newValue) {
59
+ throw(
60
+ ErrorReport(loc) << "attribute assignment is not defined on "
61
+ << kind());
62
+ }
63
+
64
+ // use it as a vector of values, e.g. a tuple of values as return value from
65
+ // a method invocation
66
+ virtual std::vector<std::shared_ptr<SugaredValue>> asTuple(
67
+ const SourceRange& loc,
68
+ GraphFunction& m,
69
+ const std::optional<size_t>& size_hint = {}) {
70
+ throw(ErrorReport(loc) << kind() << " cannot be used as a tuple");
71
+ }
72
+
73
+ // TODO @wconstab refactor to use ModuleValue::asTuple instead of new API
74
+ virtual SugaredValuePtr asTupleValue(
75
+ const SourceRange& loc,
76
+ GraphFunction& m) {
77
+ throw(ErrorReport(loc) << kind() << " cannot be used as a tuplevalue");
78
+ }
79
+
80
+ virtual std::vector<std::shared_ptr<SugaredValue>> asType(
81
+ const SourceRange& loc,
82
+ Method& m) {
83
+ throw(ErrorReport(loc) << kind() << " cannot be used as a type");
84
+ }
85
+
86
+ // call it like a function, e.g. `outputs = this(inputs)`
87
+ virtual std::shared_ptr<SugaredValue> call(
88
+ const SourceRange& loc,
89
+ GraphFunction& m,
90
+ // note: names for args will be 'argument 0', 'argument 1', etc..
91
+ at::ArrayRef<NamedValue> args,
92
+ at::ArrayRef<NamedValue> kwargs,
93
+ size_t n_binders) {
94
+ // n_binders is always set to the number of variables an expression is
95
+ // syntactically bound to:
96
+ // a = foo() # 1 binder (note in this case the single binder might be a
97
+ // tuple) a, * b = foo() # 1 binder a, b = foo() # 2 binders foo() # 0
98
+ // binders
99
+ //
100
+ // In subexpressions, like bar() in foo(bar()), n_binders is always set to
101
+ // 1. n_binders is used as a hint to subexpressions to determine how many
102
+ // values they should return when that number is ambiguous statically. In
103
+ // particular it is currently used to decide how many tensors a call to a
104
+ // python function will return. It is only a hint, functions do not have to
105
+ // check that n_binders match the number of things they are returning, the
106
+ // assignment logic will do that anyway.
107
+
108
+ throw(ErrorReport(loc) << "cannot call a " << kind());
109
+ }
110
+
111
+ // This function is called when to convert a SugaredValue to its iterator.
112
+ // For example, when iterating through a Dict we iterate over its keys
113
+ virtual std::shared_ptr<SugaredValue> iter(
114
+ const SourceRange& loc,
115
+ GraphFunction& m) {
116
+ throw(ErrorReport(loc) << kind() << " cannot be used as an iterable");
117
+ }
118
+
119
+ // If we are iterating over a Sugared Value and it returns a value from this
120
+ // function, then we emit an unrolled loop over the variable. This allows us
121
+ // to support containers of Heterogenous types, like Module Containers &
122
+ // Tuples
123
+ virtual std::optional<int64_t> staticLen() {
124
+ return std::nullopt;
125
+ }
126
+
127
+ // When iterating over this SugaredValue, should we emit the for loop as an
128
+ // unrolled loop.
129
+ bool shouldEmitUnrolled() {
130
+ return staticLen() != std::nullopt;
131
+ }
132
+
133
+ // return length of this thing, if not then it can't be iterated.
134
+ // If it does not have a statically-determinable length, then it cannot
135
+ // be iterated over with a modulelist. If it does it must return a constant
136
+ // Value *
137
+ virtual Value* len(const SourceRange& loc, GraphFunction& m) {
138
+ throw(
139
+ ErrorReport(loc) << "'" << kind() << "'"
140
+ << " object is not iterable");
141
+ }
142
+
143
+ // expression for ith elemement for iterable value
144
+ virtual std::shared_ptr<SugaredValue> getitem(
145
+ const SourceRange& loc,
146
+ GraphFunction& m,
147
+ Value* idx,
148
+ TypePtr type_hint = nullptr) {
149
+ throw(
150
+ ErrorReport(loc) << "'" << kind() << "'"
151
+ << " object is not subscriptable");
152
+ }
153
+
154
+ virtual ~SugaredValue() = default;
155
+ };
156
+
157
+ // most things in the environment are just simple value types
158
+ // and not special python syntax sugar types
159
+ struct TORCH_API SimpleValue : public SugaredValue {
160
+ SimpleValue(Value* value) : value_(value) {}
161
+ std::string kind() const override {
162
+ std::stringstream ss;
163
+ // NOLINTNEXTLINE(clang-analyzer-core.CallAndMessage)
164
+ ss << "value of type '" << value_->type()->annotation_str() << "'";
165
+ return ss.str();
166
+ }
167
+ Value* asValue(const SourceRange& range, GraphFunction& m) override {
168
+ return value_;
169
+ }
170
+ std::vector<std::shared_ptr<SugaredValue>> asTuple(
171
+ const SourceRange& loc,
172
+ GraphFunction& m,
173
+ const std::optional<size_t>& size_hint = {}) override;
174
+ std::shared_ptr<SugaredValue> attr(
175
+ const SourceRange& loc,
176
+ GraphFunction& m,
177
+ const std::string& field) override;
178
+
179
+ bool hasAttr(
180
+ const SourceRange& loc,
181
+ GraphFunction& m,
182
+ const std::string& field) override;
183
+
184
+ void setAttr(
185
+ const SourceRange& loc,
186
+ GraphFunction& m,
187
+ const std::string& field,
188
+ Value* newValue) override;
189
+
190
+ std::shared_ptr<SugaredValue> call(
191
+ const SourceRange& loc,
192
+ GraphFunction& m,
193
+ // note: names for args will be 'argument 0', 'argument 1', etc..
194
+ at::ArrayRef<NamedValue> args,
195
+ at::ArrayRef<NamedValue> kwargs,
196
+ size_t n_binders) override;
197
+
198
+ std::shared_ptr<SugaredValue> iter(const SourceRange& loc, GraphFunction& m)
199
+ override;
200
+
201
+ Value* getValue() const {
202
+ return value_;
203
+ }
204
+
205
+ Value* len(const SourceRange& loc, GraphFunction& m) override;
206
+ SugaredValuePtr getitem(
207
+ const SourceRange& loc,
208
+ GraphFunction& m,
209
+ Value* idx,
210
+ TypePtr type_hint = nullptr) override;
211
+
212
+ private:
213
+ Value* value_;
214
+ };
215
+
216
+ struct TORCH_API BuiltinFunction : public SugaredValue {
217
+ BuiltinFunction(Symbol symbol, std::optional<NamedValue> self)
218
+ : symbol(symbol), self(std::move(self)) {}
219
+
220
+ // The symbol of the function (e.g. `aten::relu`).
221
+ Symbol symbol;
222
+
223
+ // if this is method, then this is the self argument.
224
+ std::optional<NamedValue> self;
225
+ std::string kind() const override {
226
+ return "builtin";
227
+ }
228
+ std::shared_ptr<SugaredValue> call(
229
+ const SourceRange& loc,
230
+ GraphFunction& m,
231
+ at::ArrayRef<NamedValue> args,
232
+ at::ArrayRef<NamedValue> kwargs,
233
+ size_t n_binders) override;
234
+
235
+ // try to create this builtin but if it doesn't exist or the self argument
236
+ // cannot possibly match, then return nullptr. Use in situations where it is
237
+ // not clear if it is a valid builtin
238
+ static std::shared_ptr<BuiltinFunction> tryCreate(
239
+ Symbol symbol,
240
+ std::optional<NamedValue> self);
241
+ };
242
+
243
+ struct TORCH_API SugaredTupleValue : public SugaredValue {
244
+ explicit SugaredTupleValue(std::vector<std::shared_ptr<SugaredValue>> tup)
245
+ : tup_(std::move(tup)){};
246
+
247
+ std::vector<std::shared_ptr<SugaredValue>> asTuple(
248
+ const SourceRange& loc,
249
+ GraphFunction& m,
250
+ const std::optional<size_t>& size_hint = {}) override {
251
+ return tup_;
252
+ };
253
+
254
+ Value* asValue(const SourceRange& loc, GraphFunction& m) override {
255
+ std::vector<Value*> vec;
256
+ vec.reserve(tup_.size());
257
+ for (const auto& sv : tup_) {
258
+ vec.push_back(sv->asValue(loc, m));
259
+ }
260
+ Graph& g = *m.graph();
261
+ return g.insertNode(g.createTuple(vec))->output();
262
+ }
263
+
264
+ std::string kind() const override {
265
+ return "Tuple";
266
+ }
267
+
268
+ SugaredValuePtr getitem(
269
+ const SourceRange& loc,
270
+ GraphFunction& m,
271
+ Value* idx,
272
+ TypePtr type_hint = nullptr) override {
273
+ if (!(idx->type()->cast<IntType>() && toIValue(idx))) {
274
+ throw(
275
+ ErrorReport(loc)
276
+ << "Expected integer literal for index but got a variable or non-integer. "
277
+ << "ModuleList/Sequential indexing is only supported with integer literals. "
278
+ << "For example, 'i = 4; self.layers[i](x)' will fail because i is not a literal. "
279
+ << "Enumeration is supported, e.g. 'for index, v in enumerate(self): out = v(inp)'");
280
+ }
281
+ auto index = toIValue(idx)->toInt();
282
+ int64_t adj_index =
283
+ (index < 0) ? index + static_cast<int64_t>(tup_.size()) : index;
284
+ if (!(adj_index >= 0 && adj_index < static_cast<int64_t>(tup_.size()))) {
285
+ throw(
286
+ ErrorReport(loc) << "Index " << index << " out of range of length "
287
+ << tup_.size());
288
+ }
289
+ return tup_.at(adj_index);
290
+ }
291
+
292
+ // This function is called when a SugaredValue is used to convert a
293
+ // SugaredValue to its iterator. For example, when iterating through a Dict we
294
+ // iterate over its keys
295
+ std::shared_ptr<SugaredValue> iter(const SourceRange& loc, GraphFunction& m)
296
+ override {
297
+ return shared_from_this();
298
+ };
299
+
300
+ // Because this is used to contain SugaredValues of Heterogenous types,
301
+ // we define staticLen() so that when this is iterated over it is emitted
302
+ // as an unrolled loop.
303
+ std::optional<int64_t> staticLen() override {
304
+ return static_cast<int64_t>(tup_.size());
305
+ }
306
+
307
+ std::vector<std::shared_ptr<SugaredValue>> tup_;
308
+ };
309
+
310
+ struct TORCH_API BuiltinModule : public SugaredValue {
311
+ BuiltinModule(std::string name, std::optional<int64_t> version = std::nullopt)
312
+ : name(std::move(name)), version(version) {}
313
+
314
+ std::string kind() const override {
315
+ return "builtin module";
316
+ }
317
+ std::shared_ptr<SugaredValue> attr(
318
+ const SourceRange& loc,
319
+ GraphFunction& m,
320
+ const std::string& field) override {
321
+ if (field == "autograd") {
322
+ // When refering torch.autograd, it is also considered to be a
323
+ // BuiltinModule and we will dispatch to the aten operators for the
324
+ // methods under its module.
325
+ return std::make_shared<BuiltinModule>("aten", version);
326
+ }
327
+
328
+ auto sym = Symbol::fromQualString(name + "::" + field);
329
+ return std::make_shared<BuiltinFunction>(sym, std::nullopt);
330
+ }
331
+
332
+ private:
333
+ std::string name;
334
+ // when we add operator versioning, emit this op as it exising at 'version'
335
+ // if not set, use the latest version
336
+ std::optional<int64_t> version;
337
+ };
338
+
339
+ // Represents a class, analagous to `int` or `dict`. Instances of classes,
340
+ // like `1` or `{"foo": 5}`, are represented as SimpleValues
341
+ struct TORCH_API ClassValue : public SugaredValue {
342
+ explicit ClassValue(ClassTypePtr type) : type_(std::move(type)) {}
343
+
344
+ // Call the type's constructor, as in:
345
+ // n = Foo(constructor_arg)
346
+ std::shared_ptr<SugaredValue> call(
347
+ const SourceRange& loc,
348
+ GraphFunction& m,
349
+ at::ArrayRef<NamedValue> args,
350
+ at::ArrayRef<NamedValue> kwargs,
351
+ size_t n_binders) override;
352
+
353
+ std::shared_ptr<SugaredValue> attr(
354
+ const SourceRange& loc,
355
+ GraphFunction& m,
356
+ const std::string& field) override;
357
+
358
+ std::string kind() const override {
359
+ return type_->str();
360
+ }
361
+
362
+ ClassTypePtr type_;
363
+ };
364
+
365
+ struct TORCH_API NamedTupleConstructor : public SugaredValue {
366
+ explicit NamedTupleConstructor(TupleTypePtr type) : type_(std::move(type)) {}
367
+
368
+ std::shared_ptr<SugaredValue> call(
369
+ const SourceRange& loc,
370
+ GraphFunction& m,
371
+ at::ArrayRef<NamedValue> args,
372
+ at::ArrayRef<NamedValue> kwargs,
373
+ size_t n_binders) override;
374
+
375
+ std::string kind() const override {
376
+ return type_->str();
377
+ }
378
+
379
+ TupleTypePtr type_;
380
+ };
381
+
382
+ struct FunctionValue : public SugaredValue {
383
+ FunctionValue(Function* callee) : callees_({callee}) {}
384
+ FunctionValue(const StrongFunctionPtr& p)
385
+ : callees_({p.function_}), cu_(p.cu_) {}
386
+ FunctionValue(const std::vector<StrongFunctionPtr>& callees) {
387
+ for (const StrongFunctionPtr& callee : callees) {
388
+ cu_ = cu_ ? cu_ : callee.cu_;
389
+ TORCH_INTERNAL_ASSERT(callee.cu_ == cu_);
390
+ callees_.push_back(callee.function_);
391
+ }
392
+ }
393
+
394
+ std::string kind() const override {
395
+ return "function";
396
+ }
397
+
398
+ std::shared_ptr<SugaredValue> call(
399
+ const SourceRange& loc,
400
+ GraphFunction& f,
401
+ at::ArrayRef<NamedValue> args,
402
+ at::ArrayRef<NamedValue> kwargs,
403
+ size_t n_binders) override {
404
+ std::vector<const FunctionSchema*> schemas;
405
+ for (Function* callee : callees_) {
406
+ try {
407
+ callee->ensure_defined();
408
+ } catch (const RecursiveMethodCallError&) {
409
+ throw(
410
+ ErrorReport(loc)
411
+ << " function '" << callee->name() << "' is called recursively. "
412
+ << "Recursive calls are not supported");
413
+ }
414
+ schemas.push_back(&callee->getSchema());
415
+ }
416
+ auto match = matchSchemas(schemas, loc, *f.graph(), args, kwargs);
417
+ Value* output =
418
+ f.graph()->insertFunctionCall(callees_[match.first], match.second);
419
+ output->node()->setSourceRange(loc);
420
+ return std::make_shared<SimpleValue>(output);
421
+ }
422
+
423
+ const std::vector<Function*>& callees() {
424
+ return callees_;
425
+ }
426
+
427
+ private:
428
+ std::vector<Function*> callees_;
429
+ // TODO holding this thing is creepy
430
+ std::shared_ptr<CompilationUnit> cu_;
431
+ };
432
+
433
+ struct TORCH_API ClosureValue : public SugaredValue {
434
+ ClosureValue(Value* value) : value_(value) {
435
+ TORCH_INTERNAL_ASSERT(value_->node()->kind() == prim::Closure);
436
+ }
437
+ std::string kind() const override {
438
+ return "closure";
439
+ }
440
+ Value* asValue(const SourceRange& range, GraphFunction& m) override {
441
+ return value_;
442
+ }
443
+ Value* value_;
444
+ };
445
+
446
+ // defines how a method obtained from a module/class/interface behaves in script
447
+ struct MethodValue : public SugaredValue {
448
+ MethodValue(Value* self, std::vector<std::string> method_names)
449
+ : self_(self), method_names_(std::move(method_names)) {}
450
+ MethodValue(Value* self, std::string method_name)
451
+ : MethodValue(self, std::vector<std::string>({std::move(method_name)})) {}
452
+
453
+ std::string kind() const override {
454
+ return "method";
455
+ }
456
+
457
+ std::shared_ptr<SugaredValue> call(
458
+ const SourceRange& loc,
459
+ GraphFunction& f,
460
+ at::ArrayRef<NamedValue> args,
461
+ at::ArrayRef<NamedValue> kwargs,
462
+ size_t n_binders) override {
463
+ std::vector<NamedValue> argsWithSelf = {self_};
464
+ argsWithSelf.insert(argsWithSelf.end(), args.begin(), args.end());
465
+ std::vector<const FunctionSchema*> schemas;
466
+ for (const std::string& method_name : method_names_) {
467
+ if (auto class_type = self_->type()->cast<ClassType>()) {
468
+ Function& method = class_type->getMethod(method_name);
469
+ try {
470
+ method.ensure_defined();
471
+ } catch (const RecursiveMethodCallError&) {
472
+ throw(
473
+ ErrorReport(loc)
474
+ << " method '" << method.name() << "' is called recursively. "
475
+ << "Recursive calls are not supported");
476
+ }
477
+ schemas.push_back(&method.getSchema());
478
+ } else if (auto interface_type = self_->type()->cast<InterfaceType>()) {
479
+ schemas.push_back(interface_type->getMethod(method_name));
480
+ } else {
481
+ TORCH_INTERNAL_ASSERT(
482
+ false, "method constructed that is not a class or interface");
483
+ }
484
+ }
485
+ auto match = matchSchemas(schemas, loc, *f.graph(), argsWithSelf, kwargs);
486
+ Value* output =
487
+ f.graph()->insertMethodCall(method_names_[match.first], match.second);
488
+ output->node()->setSourceRange(loc);
489
+ return std::make_shared<SimpleValue>(output);
490
+ }
491
+
492
+ private:
493
+ Value* self_;
494
+ std::vector<std::string> method_names_;
495
+ };
496
+
497
+ struct TORCH_API PrintValue : public SugaredValue {
498
+ std::string kind() const override {
499
+ return "print";
500
+ }
501
+ std::shared_ptr<SugaredValue> call(
502
+ const SourceRange& loc,
503
+ GraphFunction& m,
504
+ at::ArrayRef<NamedValue> args,
505
+ at::ArrayRef<NamedValue> kwargs,
506
+ size_t n_binders) override;
507
+ };
508
+
509
+ // expressions like int(x)
510
+ // these are the same as call prim::Int or equivalent except it
511
+ // is a noop when the input is a subtype of 'type'
512
+ struct TORCH_API CastValue : public BuiltinFunction {
513
+ CastValue(TypePtr type, c10::Symbol method)
514
+ : BuiltinFunction(method, std::nullopt), type_(std::move(type)) {}
515
+ std::shared_ptr<SugaredValue> call(
516
+ const SourceRange& loc,
517
+ GraphFunction& m,
518
+ at::ArrayRef<NamedValue> args,
519
+ at::ArrayRef<NamedValue> kwargs,
520
+ size_t n_binders) override {
521
+ if (args.size() == 1 && kwargs.empty()) {
522
+ auto len_op = std::make_shared<BuiltinFunction>(aten::len, std::nullopt);
523
+ auto gt_op = std::make_shared<BuiltinFunction>(aten::gt, std::nullopt);
524
+ auto zero = m.graph()->insertConstant(0);
525
+
526
+ auto v = args[0].value(*m.graph());
527
+ if (v->type()->isSubtypeOf(*type_)) {
528
+ return std::make_shared<SimpleValue>(v);
529
+ } else if (
530
+ *type_ == *BoolType::get() &&
531
+ (v->type()->isSubtypeOf(*AnyListType::get()) ||
532
+ v->type()->isSubtypeOf(*StringType::get()) ||
533
+ v->type()->cast<DictType>())) {
534
+ auto len = len_op->call(loc, m, {v}, {}, 1);
535
+ return gt_op->call(loc, m, {len->asValue(loc, m), zero}, {}, 1);
536
+ }
537
+ }
538
+ return BuiltinFunction::call(loc, m, args, kwargs, n_binders);
539
+ }
540
+
541
+ private:
542
+ TypePtr type_;
543
+ };
544
+
545
+ struct TORCH_API TensorCastValue : public SugaredValue {
546
+ TensorCastValue(at::ScalarType type, NamedValue self)
547
+ : dtype_(type), self_(std::move(self)) {}
548
+
549
+ std::string kind() const override {
550
+ return "Cast";
551
+ }
552
+
553
+ std::shared_ptr<SugaredValue> call(
554
+ const SourceRange& loc,
555
+ GraphFunction& m,
556
+ at::ArrayRef<NamedValue> args,
557
+ at::ArrayRef<NamedValue> kwargs,
558
+ size_t n_binders) override {
559
+ TORCH_INTERNAL_ASSERT(args.empty() && kwargs.empty());
560
+ Value* dtype_const = m.graph()->insertConstant(dtype_, loc);
561
+ std::vector<NamedValue> kwargs_{
562
+ self_, NamedValue(loc, "dtype", dtype_const)};
563
+ Value* casted_val = m.graph()->insert(
564
+ /*opname=*/Symbol::fromQualString("aten::to"),
565
+ /*args=*/args,
566
+ /*kwargs=*/kwargs_,
567
+ /*range=*/loc);
568
+ return std::make_shared<SimpleValue>(casted_val);
569
+ }
570
+
571
+ at::ScalarType dtype_;
572
+ NamedValue self_;
573
+ };
574
+
575
+ // builtins operators and functions that call a method if it exists
576
+ // on a class type, like 'len(x)' and 'x + y'
577
+ struct TORCH_API MagicMethod : public SugaredValue {
578
+ MagicMethod(std::string desugared_name, SugaredValuePtr base)
579
+ : base_value_(std::move(base)),
580
+ desugared_name_(std::move(desugared_name)) {}
581
+
582
+ std::string kind() const override {
583
+ return desugared_name_;
584
+ }
585
+
586
+ std::shared_ptr<SugaredValue> call(
587
+ const SourceRange& loc,
588
+ GraphFunction& m,
589
+ at::ArrayRef<NamedValue> args,
590
+ at::ArrayRef<NamedValue> kwargs,
591
+ size_t n_binders) override;
592
+
593
+ private:
594
+ SugaredValuePtr base_value_;
595
+ std::string desugared_name_;
596
+ };
597
+
598
+ // things that look like function applications, but
599
+ // perform non-standard evaluation are represented
600
+ // with SpecialFormValues, e.g.
601
+ // isinstance(x, int)
602
+ // fork(fn)
603
+ // annotate(int, 3)
604
+ // The implementation of each value is handled by a case inside emitApplyExpr
605
+ struct TORCH_API SpecialFormValue : public SugaredValue {
606
+ SpecialFormValue(Symbol form) : form_(form) {}
607
+ std::string kind() const override {
608
+ return form_.toUnqualString();
609
+ }
610
+ Symbol form() const {
611
+ return form_;
612
+ }
613
+ static std::shared_ptr<SpecialFormValue> create(Symbol form) {
614
+ return std::make_shared<SpecialFormValue>(form);
615
+ }
616
+
617
+ private:
618
+ Symbol form_;
619
+ };
620
+
621
+ struct TORCH_API LegacyTensorConstructor : public SpecialFormValue {
622
+ LegacyTensorConstructor(Symbol form, at::ScalarType dtype, at::Device device)
623
+ : SpecialFormValue(form), device_(device), dtype_(dtype) {}
624
+
625
+ static std::shared_ptr<LegacyTensorConstructor> create(
626
+ Symbol form,
627
+ at::ScalarType dtype,
628
+ at::Device device) {
629
+ return std::make_shared<LegacyTensorConstructor>(form, dtype, device);
630
+ }
631
+ at::ScalarType dtype() const {
632
+ return dtype_;
633
+ }
634
+
635
+ private:
636
+ at::Device device_;
637
+ at::ScalarType dtype_;
638
+ };
639
+
640
+ // matched against for special handling of range expressions
641
+ struct TORCH_API RangeValue : SugaredValue {
642
+ RangeValue(
643
+ const SourceRange& loc,
644
+ GraphFunction& m,
645
+ std::vector<Value*> input,
646
+ std::optional<int64_t> static_len = std::nullopt);
647
+
648
+ std::string kind() const override {
649
+ return "range";
650
+ }
651
+ Value* len(const SourceRange& loc, GraphFunction& m) override;
652
+ SugaredValuePtr getitem(
653
+ const SourceRange& loc,
654
+ GraphFunction& m,
655
+ Value* idx,
656
+ TypePtr type_hint = nullptr) override;
657
+ std::shared_ptr<SugaredValue> iter(const SourceRange& loc, GraphFunction& m)
658
+ override;
659
+
660
+ // When Range is instantiated via enumerate(iterable_with_static_len),
661
+ // then it takes the static length of the iterable
662
+ std::optional<int64_t> staticLen() override {
663
+ return static_len_;
664
+ }
665
+
666
+ private:
667
+ Value* start_{};
668
+ Value* end_{};
669
+ Value* step_{};
670
+ // a flag to determine if it's a simple range() call with only end_ from
671
+ // arguments If true, we will not insert length calculation and index
672
+ // derivation nodes to simplify the graph and enable more possible
673
+ // optimizations
674
+ bool has_only_end_{};
675
+ std::optional<int64_t> static_len_;
676
+ };
677
+
678
+ // Specialized Tree structure to matched against for special handling
679
+ // of builtin functions iterables expressions like zip(), enumerate(), etc.
680
+ // zip and enumerate can be modeled as a tree of SimpleValue/RangeValue:
681
+ // zip(x, y) -> (x, y) with tuple assignment to each loop target
682
+ // enumerate(x) -> (range(0, math.inf, 1), x)
683
+ // So a complicated expression like zip(a, enumerate(b), range(0, 100)) will be:
684
+ // (a, (range(0, math.inf, 1), b), range(0, 100))
685
+ // We use those base iterables to fill in the loop information like
686
+ // max_trip_count and set the value table for loop targets
687
+ // Iterables can contain lists of SugaredValues like ModuleLists. If it
688
+ // does, then we emit it unrolled and require that all values it contains
689
+ // have a statically-determinable length.
690
+ struct TORCH_API IterableTree : SugaredValue {
691
+ IterableTree() = default;
692
+ IterableTree(
693
+ const SourceRange& range,
694
+ GraphFunction& m,
695
+ at::ArrayRef<SugaredValuePtr> children) {
696
+ for (const auto& child : children) {
697
+ addChild(range, m, child);
698
+ }
699
+ }
700
+ std::string kind() const override {
701
+ return "iterabletree";
702
+ }
703
+
704
+ std::shared_ptr<SugaredValue> iter(const SourceRange& loc, GraphFunction& m)
705
+ override {
706
+ return shared_from_this();
707
+ }
708
+
709
+ void addChild(
710
+ const SourceRange& range,
711
+ GraphFunction& m,
712
+ const SugaredValuePtr& iter_value);
713
+
714
+ std::vector<SugaredValuePtr> get_children() {
715
+ return children_;
716
+ }
717
+
718
+ // If this iterable contains a ModuleList or Tuple, then it will have a
719
+ // static length, and we will emit it as an unrolled for loop.
720
+ std::optional<int64_t> staticLen() override {
721
+ return unroll_length_;
722
+ }
723
+
724
+ // given a IterableTree node, get all the base iterables/leaves under the
725
+ // IterableTree node. This enables
726
+ // us to get all the basic SugaredValues that contains valid loop information
727
+ // with len() and getitem()
728
+ std::vector<SugaredValuePtr> get_base_iterables();
729
+
730
+ Value* len(const SourceRange& loc, GraphFunction& m) override;
731
+ SugaredValuePtr getitem(
732
+ const SourceRange& loc,
733
+ GraphFunction& m,
734
+ Value* idx,
735
+ TypePtr type_hint = nullptr) override;
736
+
737
+ private:
738
+ std::optional<int64_t> unroll_length_ = std::nullopt;
739
+ std::vector<SugaredValuePtr> children_;
740
+ };
741
+
742
+ static inline std::vector<Value*> toValues(
743
+ Graph& g,
744
+ at::ArrayRef<NamedValue> nvs) {
745
+ return fmap(nvs, [&](const NamedValue& v) { return v.value(g); });
746
+ }
747
+
748
+ struct SimpleSelf : public Self {
749
+ explicit SimpleSelf(ClassTypePtr classType)
750
+ : Self(), classType_(std::move(classType)) {}
751
+ std::shared_ptr<SugaredValue> makeSugared(Value* v) const override {
752
+ v->setType(classType_);
753
+ return std::make_shared<SimpleValue>(v);
754
+ }
755
+ ClassTypePtr getClassType() const override {
756
+ return classType_;
757
+ }
758
+
759
+ private:
760
+ ClassTypePtr classType_;
761
+ };
762
+
763
+ // This is not a SimpleValue so it can not pass through the code paths that
764
+ // expect a SimpleValue as a sugared value.
765
+ struct TORCH_API ExceptionMessageValue : public SugaredValue {
766
+ explicit ExceptionMessageValue(
767
+ Value* value,
768
+ Value* qualified_class_name = nullptr)
769
+ : value_(value), qualified_class_name_(qualified_class_name) {}
770
+
771
+ std::string kind() const override {
772
+ return "exception message";
773
+ }
774
+
775
+ Value* getValue() {
776
+ return value_;
777
+ }
778
+
779
+ // qualified python class name
780
+ Value* getQualifiedClassName() {
781
+ return qualified_class_name_;
782
+ }
783
+
784
+ private:
785
+ Value* value_;
786
+ Value* qualified_class_name_;
787
+ };
788
+
789
+ struct TORCH_API ExceptionValue : public SugaredValue {
790
+ explicit ExceptionValue(std::string message) : message_(std::move(message)) {}
791
+
792
+ std::string kind() const override {
793
+ return "exception";
794
+ }
795
+
796
+ std::shared_ptr<SugaredValue> call(
797
+ const SourceRange& loc,
798
+ GraphFunction& m,
799
+ at::ArrayRef<NamedValue> args,
800
+ at::ArrayRef<NamedValue> /*attributes*/,
801
+ size_t /*n_binders*/) override {
802
+ auto exception_message = insertConstant(*m.graph(), message_ + ": ", loc);
803
+ for (auto& input : args) {
804
+ auto input_str = input.value(*m.graph());
805
+ if (!input_str->type()->isSubtypeOf(*StringType::get())) {
806
+ input_str =
807
+ emitBuiltinCall(loc, *m.graph(), aten::str, {input_str}, {});
808
+ }
809
+ exception_message = emitBuiltinCall(
810
+ loc, *m.graph(), aten::add, {exception_message, input_str}, {});
811
+ }
812
+ return std::make_shared<ExceptionMessageValue>(exception_message);
813
+ }
814
+
815
+ std::string message_;
816
+ };
817
+
818
+ struct TORCH_API SugaredEnumClass : public SugaredValue {
819
+ explicit SugaredEnumClass(EnumTypePtr enum_type)
820
+ : enum_type_(std::move(enum_type)) {}
821
+
822
+ std::string kind() const override {
823
+ return "EnumClass";
824
+ }
825
+
826
+ SugaredValuePtr attr(
827
+ const SourceRange& loc,
828
+ GraphFunction& m,
829
+ const std::string& field) override;
830
+
831
+ SugaredValuePtr iter(const SourceRange& loc, GraphFunction& m) override;
832
+
833
+ private:
834
+ EnumTypePtr enum_type_;
835
+ };
836
+
837
+ struct TORCH_API SliceValue : public SugaredValue {
838
+ explicit SliceValue(Value* start, Value* stop, Value* step)
839
+ : start_(start), stop_(stop), step_(step) {}
840
+
841
+ std::string kind() const override {
842
+ return "Python slice value";
843
+ }
844
+
845
+ Value* start() {
846
+ return start_;
847
+ };
848
+ Value* stop() {
849
+ return stop_;
850
+ };
851
+ Value* step() {
852
+ return step_;
853
+ };
854
+
855
+ private:
856
+ Value* start_;
857
+ Value* stop_;
858
+ Value* step_;
859
+ };
860
+
861
+ } // namespace torch::jit
vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/tree.h ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <functional>
4
+ #include <memory>
5
+ #include <unordered_map>
6
+ #include <vector>
7
+
8
+ #include <c10/util/SmallVector.h>
9
+ #include <c10/util/intrusive_ptr.h>
10
+ #include <torch/csrc/jit/frontend/lexer.h>
11
+
12
+ namespace torch::jit {
13
+
14
+ // Trees are used to represent all forms of TC IR, pre- and post-typechecking.
15
+ // Rather than have a full class hierarchy for all TC statements, trees are a
16
+ // slight variation of Lisp s-expressions. For instance, the expression a*b+1
17
+ // is represented as:
18
+ // (+ (* (ident a) (ident b)) (const 1))
19
+ // Atoms like 'a', 'b', and '1' are represented by subclasses of Tree which
20
+ // define stringValue(). Everything else is a Compound object, which has a
21
+ // 'kind' that is a token from lexer.h's TokenKind enum. Single-character
22
+ // operators like '+' are represented using the character itself (so, add.kind()
23
+ // would be '+'). Each Compound object also contains a list of subtrees and is
24
+ // associated with a SourceRange for error reporting.
25
+ // Memory management of trees is done using intrusive_ptr.
26
+
27
+ struct Tree;
28
+ using TreeRef = c10::intrusive_ptr<Tree>;
29
+ using TreeList = at::SmallVector<TreeRef, 4>;
30
+
31
+ struct Tree : c10::intrusive_ptr_target {
32
+ Tree(int kind_) : kind_(kind_) {}
33
+ int kind() const {
34
+ return kind_;
35
+ }
36
+ virtual bool isAtom() const {
37
+ return true;
38
+ }
39
+ virtual const SourceRange& range() const {
40
+ throw std::runtime_error("is an Atom");
41
+ }
42
+ virtual const std::string& stringValue() const {
43
+ throw std::runtime_error("stringValue can only be called on TK_STRING");
44
+ }
45
+ virtual const TreeList& trees() const {
46
+ static const TreeList empty_trees = {};
47
+ return empty_trees;
48
+ }
49
+ const TreeRef& tree(size_t i) const {
50
+ return trees().at(i);
51
+ }
52
+ virtual TreeRef map(const std::function<TreeRef(TreeRef)>& fn) {
53
+ (void)fn;
54
+ c10::raw::intrusive_ptr::incref(this); // we are creating a new pointer
55
+ // from a raw `this` pointer
56
+ // so we need to bump the refcount
57
+ // to account for this ownership
58
+ return TreeRef::reclaim(this);
59
+ }
60
+ template <typename... Args>
61
+ void match(int k, Args&... args) const {
62
+ matchD(k, "unknown", 0, args...);
63
+ }
64
+ template <typename... Args>
65
+ void matchD(int k, const char* filename, int lineno, Args&... args) const {
66
+ std::initializer_list<TreeRef*> vars = {args...};
67
+ matchNumSubtreesD(k, filename, lineno, vars.size(), true);
68
+ size_t i = 0;
69
+ for (TreeRef* v : vars) {
70
+ *v = trees()[i++];
71
+ }
72
+ }
73
+ void matchNumSubtrees(int k, size_t expected_subtrees) {
74
+ return matchNumSubtreesD(k, "unknown", 0, expected_subtrees, false);
75
+ }
76
+ void matchNumSubtreesD(
77
+ int k,
78
+ const char* filename,
79
+ int lineno,
80
+ size_t expected_subtrees,
81
+ bool allow_more) const {
82
+ if (kind() != k) {
83
+ std::stringstream ss;
84
+ ss << filename << ":" << lineno << ": expecting kind '" << kindToString(k)
85
+ << "' but found '" << kindToString(kind()) << "'\n";
86
+ range().highlight(ss);
87
+ throw std::runtime_error(ss.str());
88
+ }
89
+ if (trees().size() < expected_subtrees ||
90
+ (!allow_more && trees().size() != expected_subtrees)) {
91
+ std::stringstream ss;
92
+ ss << filename << ":" << lineno << ": expected at least "
93
+ << expected_subtrees << " subtrees, but found only " << trees().size()
94
+ << "\n";
95
+ range().highlight(ss);
96
+ throw std::runtime_error(ss.str());
97
+ }
98
+ }
99
+ ~Tree() override = default;
100
+
101
+ private:
102
+ int kind_;
103
+ };
104
+
105
+ struct String : public Tree {
106
+ String(std::string value) : Tree(TK_STRING), value_(std::move(value)) {}
107
+ const std::string& stringValue() const override {
108
+ return value_;
109
+ }
110
+ template <typename... Args>
111
+ static TreeRef create(Args&&... args) {
112
+ return c10::make_intrusive<String>(std::forward<Args>(args)...);
113
+ }
114
+
115
+ private:
116
+ std::string value_;
117
+ };
118
+
119
+ static SourceRange mergeRanges(SourceRange c, const TreeList& others) {
120
+ for (const auto& t : others) {
121
+ if (t->isAtom())
122
+ continue;
123
+ size_t s = std::min(c.start(), t->range().start());
124
+ size_t e = std::max(c.end(), t->range().end());
125
+ c = SourceRange(c.source(), s, e);
126
+ }
127
+ return c;
128
+ }
129
+
130
+ struct Compound : public Tree {
131
+ Compound(int kind, SourceRange range)
132
+ : Tree(kind), range_(std::move(range)) {}
133
+ Compound(int kind, const SourceRange& range_, TreeList&& trees_)
134
+ : Tree(kind),
135
+ range_(mergeRanges(range_, trees_)),
136
+ trees_(std::move(trees_)) {}
137
+ const TreeList& trees() const override {
138
+ return trees_;
139
+ }
140
+ static TreeRef create(
141
+ int kind,
142
+ const SourceRange& range_,
143
+ TreeList&& trees_) {
144
+ return c10::make_intrusive<Compound>(kind, range_, std::move(trees_));
145
+ }
146
+ bool isAtom() const override {
147
+ return false;
148
+ }
149
+ TreeRef map(const std::function<TreeRef(TreeRef)>& fn) override {
150
+ TreeList ret;
151
+ for (auto& t : trees()) {
152
+ ret.push_back(fn(t));
153
+ }
154
+ return Compound::create(kind(), range(), std::move(ret));
155
+ }
156
+
157
+ const SourceRange& range() const override {
158
+ return range_;
159
+ }
160
+
161
+ private:
162
+ SourceRange range_;
163
+ TreeList trees_;
164
+ };
165
+
166
+ // tree pretty printer
167
+ struct pretty_tree {
168
+ pretty_tree(const TreeRef& tree, size_t col = 40) : tree(tree), col(col) {}
169
+ const TreeRef& tree;
170
+ size_t col;
171
+ std::unordered_map<TreeRef, std::string> flat_strings;
172
+ const std::string& get_flat(const TreeRef& t) {
173
+ auto it = flat_strings.find(t);
174
+ if (it != flat_strings.end())
175
+ return it->second;
176
+
177
+ std::stringstream out;
178
+ switch (t->kind()) {
179
+ case TK_STRING:
180
+ out << t->stringValue();
181
+ break;
182
+ default:
183
+ out << "(" << kindToString(t->kind());
184
+ for (const auto& e : t->trees()) {
185
+ out << " " << get_flat(e);
186
+ }
187
+ out << ")";
188
+ break;
189
+ }
190
+ auto it_ = flat_strings.emplace(t, out.str());
191
+ return it_.first->second;
192
+ }
193
+ void print(std::ostream& out, const TreeRef& t, int indent) {
194
+ const std::string& s = get_flat(t);
195
+ if (indent + s.size() < col || t->isAtom()) {
196
+ out << s;
197
+ return;
198
+ }
199
+ std::string k = kindToString(t->kind());
200
+ out << "(" << k;
201
+ for (const auto& e : t->trees()) {
202
+ out << "\n" << std::string(indent + 2, ' ');
203
+ print(out, e, indent + 2);
204
+ }
205
+ out << ")";
206
+ }
207
+ };
208
+
209
+ static inline std::ostream& operator<<(std::ostream& out, pretty_tree t_) {
210
+ t_.print(out, t_.tree, 0);
211
+ return out << '\n';
212
+ }
213
+
214
+ static inline std::ostream& operator<<(std::ostream& out, const TreeRef& t) {
215
+ return out << pretty_tree(t);
216
+ }
217
+
218
+ } // namespace torch::jit
vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/frontend/tree_views.h ADDED
@@ -0,0 +1,1276 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <torch/csrc/jit/frontend/error_report.h>
3
+ #include <torch/csrc/jit/frontend/strtod.h>
4
+ #include <torch/csrc/jit/frontend/tree.h>
5
+
6
+ #include <c10/util/complex.h>
7
+ #include <functional>
8
+ #include <iostream>
9
+ #include <string>
10
+ #include <utility>
11
+
12
+ namespace torch::jit {
13
+
14
+ // clang-format off
15
+ // TreeView provides a statically-typed way to traverse the tree, which should
16
+ // be formed according to the grammar below.
17
+ //
18
+ // A few notes on types and their aliases:
19
+ // - List<T> is really a Tree with kind TK_LIST and elements as subtrees
20
+ // - Maybe<T> is really a Tree with kind TK_OPTION that has 0 or 1 subtree of type T
21
+ // - Builtin types are: Ident (TK_IDENT), String (TK_STRING)
22
+ //
23
+ // Param = Param(Maybe<Expr> type, Ident name) TK_PARAM
24
+ //
25
+ // Decl = Decl(List<Param> params, Maybe<Expr> return_type) TK_DECL
26
+ // Def = Def(Ident name, Decl decl, List<Stmt> body) TK_DEF
27
+ // ClassDef = ClassDef(Ident name, TK_CLASS_DEF
28
+ // Maybe<Expr> superclass,
29
+ // List<Stmt> body)
30
+ //
31
+ // Stmt = If(Expr cond, List<Stmt> true_body, List<Stmt> false_body) TK_IF
32
+ // | For(List<Expr> targets, List<Expr> iters, List<Stmt> body) TK_FOR
33
+ // | While(Expr cond, List<Stmt> body) TK_WHILE
34
+ // | Global(List<Ident> idents) TK_GLOBAL
35
+ // -- NB: the only type of Expr's allowed on lhs are Var
36
+ // Or a tuple containing Var with an optional terminating Starred
37
+ // | Assign(Expr lhs, Maybe<Expr> rhs, Maybe<Expr> type) TK_ASSIGN
38
+ // | AugAssign(Expr lhs, AugAssignKind aug_op, Expr rhs) TK_AUG_ASSIGN
39
+ // | Return(List<Expr> values) TK_RETURN
40
+ // | ExprStmt(List<Expr> expr) TK_EXPR_STMT
41
+ // | Raise(Expr expr) TK_RAISE
42
+ // | Def TK_DEF
43
+ // | With(List<WithItem> targets, List<Stmt> body) TK_WITH
44
+ //
45
+ // Expr = TernaryIf(Expr cond, Expr true_expr, Expr false_expr) TK_IF_EXPR
46
+ // | BinOp(Expr lhs, Expr rhs)
47
+ // | And TK_AND
48
+ // | Or TK_OR
49
+ // | Lt '<'
50
+ // | Gt '>'
51
+ // | Eq TK_EQ
52
+ // | Le TK_LE
53
+ // | Ge TK_GE
54
+ // | Ne TK_NE
55
+ // | Is TK_IS
56
+ // | IsNot TK_ISNOT
57
+ // | Add '+'
58
+ // | Sub '-'
59
+ // | Mul '*'
60
+ // | Div '/'
61
+ // | Mod '%'
62
+ // | MatMult '@'
63
+ // | Pow TK_POW
64
+ // | UnaryOp(Expr expr)
65
+ // | Not TK_NOT
66
+ // | USub '-'
67
+ // | Const(String value) TK_CONST
68
+ // -- NB: x.name(y) is desugared into name(x, y)
69
+ // | Apply(Ident name, List<Expr> args, List<Attribute> kwargs) TK_APPLY
70
+ // | Select(Expr value, Ident selector) '.'
71
+ // | Subscript(Expr value, List<Expr> subscript_exprs) TK_SUBSCRIPT
72
+ // | SliceExpr(Maybe<Expr> start, Maybe<Expr> end) TK_SLICE_EXPR
73
+ // | Var(Ident name) TK_VAR
74
+ // | ListLiteral(List<Expr> inputs) TK_LIST_LITERAL
75
+ // | TupleLiteral(List<Expr> inputs) TK_TUPLE_LITERAL
76
+ // | Starred(Expr expr) TK_STARRED
77
+ // | WithItem(Expr target, Maybe<Var> var) TK_WITH_ITEM
78
+ // -- NB: only allowed expressions are Const or List(Const)
79
+ // (List as a value, not type constructor)
80
+ // Attribute = Attribute(Ident name, Expr value) TK_ATTRIBUTE
81
+ //
82
+ // AugAssignKind =
83
+ // | Add() TK_PLUS_EQ
84
+ // | Sub() TK_MINUS_EQ
85
+ // | Mul() TK_TIMES_EQ
86
+ // | Div() TK_DIV_EQ
87
+ // | Mod() TK_MOD_EQ
88
+ //
89
+
90
+ // Each subclass of TreeView should provide:
91
+ // 1. Constructor that takes a TreeRef, and checks that it's of the right type.
92
+ // 2. Accessors that get underlying information out of the object. If they
93
+ // return subtrees, they should wrap them in appropriate views too.
94
+ // 3. Static method 'create' that creates the underlying TreeRef object
95
+ // for every TreeRef kind that has a TreeView, the parser always uses
96
+ // (e.g.) Ident::create rather than Compound::Create, this means that
97
+ // changes to the structure of Ident are always made right here rather
98
+ // than both in the parser and in this code.
99
+ // XXX: these structs should have no fields to prevent slicing when passing by value
100
+ // clang-format on
101
+ struct TreeView {
102
+ explicit TreeView(TreeRef tree) : tree_(std::move(tree)) {}
103
+ TreeRef tree() const {
104
+ return tree_;
105
+ }
106
+ const SourceRange& range() const {
107
+ return tree_->range();
108
+ }
109
+ operator TreeRef() const {
110
+ return tree_;
111
+ }
112
+ const TreeRef& get() const {
113
+ return tree_;
114
+ }
115
+ int kind() const {
116
+ return tree_->kind();
117
+ }
118
+ void dump() const {
119
+ std::cout << tree_;
120
+ }
121
+
122
+ protected:
123
+ const TreeRef& subtree(size_t i) const {
124
+ return tree_->trees().at(i);
125
+ }
126
+ // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
127
+ TreeRef tree_;
128
+ };
129
+
130
+ template <typename T>
131
+ struct ListIterator {
132
+ ListIterator(TreeList::const_iterator it) : it(it) {}
133
+ bool operator!=(const ListIterator& rhs) const {
134
+ return it != rhs.it;
135
+ }
136
+ bool operator==(const ListIterator& rhs) const {
137
+ return it == rhs.it;
138
+ }
139
+ T operator*() const {
140
+ return T(*it);
141
+ }
142
+ ListIterator& operator+=(std::ptrdiff_t n) {
143
+ it += n;
144
+ return *this;
145
+ }
146
+ ListIterator& operator++() {
147
+ ++it;
148
+ return *this;
149
+ }
150
+ ListIterator& operator--() {
151
+ --it;
152
+ return *this;
153
+ }
154
+
155
+ private:
156
+ TreeList::const_iterator it;
157
+ };
158
+
159
+ template <typename T>
160
+ struct List : public TreeView {
161
+ using iterator = ListIterator<T>;
162
+ using const_iterator = ListIterator<T>;
163
+
164
+ List(const TreeRef& tree) : TreeView(tree) {
165
+ tree->match(TK_LIST);
166
+ // Iterate over list to temporarily instantiate Ts that will check the type
167
+ for (const T& elem : *this) {
168
+ (void)elem; // silence unused warning
169
+ }
170
+ }
171
+ iterator begin() const {
172
+ return iterator(tree_->trees().begin());
173
+ }
174
+ iterator end() const {
175
+ return iterator(tree_->trees().end());
176
+ }
177
+ bool empty() const {
178
+ return tree_->trees().begin() == tree_->trees().end();
179
+ }
180
+ T operator[](size_t i) const {
181
+ return T(subtree(i));
182
+ }
183
+ TreeRef map(const std::function<TreeRef(const T&)>& fn) {
184
+ return tree_->map([&](TreeRef v) { return fn(T(v)); });
185
+ }
186
+ static List create(const SourceRange& range, const std::vector<T>& subtrees) {
187
+ TreeList type_erased_sub{subtrees.begin(), subtrees.end()};
188
+ return List(Compound::create(TK_LIST, range, std::move(type_erased_sub)));
189
+ }
190
+ static List unsafeCreate(const SourceRange& range, TreeList&& subtrees) {
191
+ return List(Compound::create(TK_LIST, range, std::move(subtrees)));
192
+ }
193
+ size_t size() const {
194
+ return tree_->trees().size();
195
+ }
196
+ };
197
+
198
+ template <typename T>
199
+ struct Maybe : public TreeView {
200
+ explicit Maybe(const TreeRef& tree) : TreeView(tree) {
201
+ tree_->match(TK_OPTION);
202
+ if (tree_->trees().size() > 1)
203
+ throw(ErrorReport(tree) << "Maybe trees can have at most one subtree");
204
+ }
205
+ /* implicit */ Maybe(const T& tree) : TreeView(tree) {}
206
+ bool present() const {
207
+ return tree_->trees().size() > 0;
208
+ }
209
+ T get() const {
210
+ return T(tree_->trees().at(0));
211
+ }
212
+ TreeRef map(const std::function<TreeRef(const T&)>& fn) {
213
+ return tree_->map([&](TreeRef v) { return fn(T(v)); });
214
+ }
215
+ static Maybe<T> create(const SourceRange& range) {
216
+ return Maybe<T>(Compound::create(TK_OPTION, range, {}));
217
+ }
218
+ static Maybe<T> create(const SourceRange& range, const T& value) {
219
+ return Maybe<T>(Compound::create(TK_OPTION, range, {value}));
220
+ }
221
+ };
222
+
223
+ struct Ident : public TreeView {
224
+ explicit Ident(const TreeRef& tree) : TreeView(tree) {
225
+ tree_->match(TK_IDENT);
226
+ }
227
+ const std::string& name() const {
228
+ return subtree(0)->stringValue();
229
+ }
230
+ static Ident create(const SourceRange& range, std::string name) {
231
+ return Ident(
232
+ Compound::create(TK_IDENT, range, {String::create(std::move(name))}));
233
+ }
234
+ };
235
+
236
+ ////////////////////////////////////////////////////////////////////////////////
237
+ // Base types (production LHS)
238
+ ////////////////////////////////////////////////////////////////////////////////
239
+
240
+ struct Stmt : public TreeView {
241
+ explicit Stmt(const TreeRef& tree) : TreeView(tree) {
242
+ switch (tree->kind()) {
243
+ case TK_IF:
244
+ case TK_FOR:
245
+ case TK_WHILE:
246
+ case TK_GLOBAL:
247
+ case TK_ASSIGN:
248
+ case TK_AUG_ASSIGN:
249
+ case TK_RETURN:
250
+ case TK_EXPR_STMT:
251
+ case TK_RAISE:
252
+ case TK_ASSERT:
253
+ case TK_PASS:
254
+ case TK_BREAK:
255
+ case TK_DELETE:
256
+ case TK_CONTINUE:
257
+ case TK_DEF:
258
+ case TK_WITH:
259
+ return;
260
+ default:
261
+ throw(
262
+ ErrorReport(tree)
263
+ << kindToString(tree->kind()) << " is not a valid Stmt");
264
+ }
265
+ }
266
+ };
267
+
268
+ struct Expr : public TreeView {
269
+ explicit Expr(const TreeRef& tree) : TreeView(tree) {
270
+ switch (tree->kind()) {
271
+ case TK_IF_EXPR:
272
+ case TK_AND:
273
+ case TK_OR:
274
+ case '<':
275
+ case '>':
276
+ case TK_IS:
277
+ case TK_ISNOT:
278
+ case TK_EQ:
279
+ case TK_LE:
280
+ case TK_GE:
281
+ case TK_NE:
282
+ case '+':
283
+ case '-':
284
+ case TK_UNARY_MINUS:
285
+ case '~':
286
+ case '*':
287
+ case TK_STARRED:
288
+ case '/':
289
+ case '%':
290
+ case TK_NOT:
291
+ case TK_CONST:
292
+ case TK_STRINGLITERAL:
293
+ case TK_TRUE:
294
+ case TK_FALSE:
295
+ case TK_NONE:
296
+ case TK_NONE_TYPE:
297
+ case TK_CAST:
298
+ case TK_APPLY:
299
+ case '.':
300
+ case TK_SUBSCRIPT:
301
+ case TK_SLICE_EXPR:
302
+ case TK_VAR:
303
+ case TK_LIST_LITERAL:
304
+ case TK_TUPLE_LITERAL:
305
+ case TK_DICT_LITERAL:
306
+ case '@':
307
+ case TK_POW:
308
+ case TK_LSHIFT:
309
+ case TK_RSHIFT:
310
+ case TK_FLOOR_DIV:
311
+ case '&':
312
+ case '^':
313
+ case '|':
314
+ case TK_LIST_COMP:
315
+ case TK_DICT_COMP:
316
+ case TK_DOTS:
317
+ case TK_IN:
318
+ case TK_WITH_ITEM:
319
+ return;
320
+ default:
321
+ throw(
322
+ ErrorReport(tree)
323
+ << kindToString(tree->kind()) << " is not a valid Expr");
324
+ }
325
+ }
326
+ };
327
+
328
+ ////////////////////////////////////////////////////////////////////////////////
329
+ // Helper nodes (mostly for function arguments)
330
+ ////////////////////////////////////////////////////////////////////////////////
331
+
332
+ struct Attribute : public TreeView {
333
+ explicit Attribute(const TreeRef& tree) : TreeView(tree) {
334
+ tree_->match(TK_ATTRIBUTE);
335
+ }
336
+ Ident name() const {
337
+ return Ident(subtree(0));
338
+ }
339
+ Expr value() const {
340
+ return Expr(subtree(1));
341
+ }
342
+ static Attribute create(
343
+ const SourceRange& range,
344
+ const Ident& name,
345
+ const TreeRef& value) {
346
+ return Attribute(Compound::create(TK_ATTRIBUTE, range, {name, value}));
347
+ }
348
+ };
349
+
350
+ struct Param : public TreeView {
351
+ explicit Param(const TreeRef& tree) : TreeView(tree) {
352
+ tree_->match(TK_PARAM);
353
+ }
354
+ static Param create(
355
+ const SourceRange& range,
356
+ const Ident& ident,
357
+ const Maybe<Expr>& type,
358
+ const Maybe<Expr>& def,
359
+ bool kwarg_only) {
360
+ TreeRef kwarg_only_tree =
361
+ Compound::create(kwarg_only ? TK_TRUE : TK_FALSE, range, {});
362
+ return Param(Compound::create(
363
+ TK_PARAM, range, {ident, type, def, std::move(kwarg_only_tree)}));
364
+ }
365
+ Ident ident() const {
366
+ return Ident(subtree(0));
367
+ }
368
+ Maybe<Expr> type() const {
369
+ return Maybe<Expr>(subtree(1));
370
+ }
371
+ Maybe<Expr> defaultValue() const {
372
+ return Maybe<Expr>(subtree(2));
373
+ }
374
+ bool kwarg_only() const {
375
+ return TK_TRUE == subtree(3)->kind();
376
+ }
377
+ Param withType(const Maybe<Expr>& typ) const {
378
+ return Param::create(range(), ident(), typ, defaultValue(), kwarg_only());
379
+ }
380
+ };
381
+
382
+ ////////////////////////////////////////////////////////////////////////////////
383
+ // Top level definitions
384
+ ////////////////////////////////////////////////////////////////////////////////
385
+
386
+ struct Decl : public TreeView {
387
+ explicit Decl(const TreeRef& tree) : TreeView(tree) {
388
+ tree->match(TK_DECL);
389
+ }
390
+ List<Param> params() const {
391
+ return List<Param>(subtree(0));
392
+ }
393
+ Maybe<Expr> return_type() const {
394
+ return Maybe<Expr>(subtree(1));
395
+ }
396
+ static Decl create(
397
+ const SourceRange& range,
398
+ const List<Param>& params,
399
+ const Maybe<Expr>& return_type) {
400
+ return Decl(Compound::create(TK_DECL, range, {params, return_type}));
401
+ }
402
+ };
403
+
404
+ struct Def : public TreeView {
405
+ explicit Def(const TreeRef& tree) : TreeView(tree) {
406
+ tree->match(TK_DEF);
407
+ }
408
+ Def withName(std::string new_name) const {
409
+ auto new_ident = Ident::create(name().range(), std::move(new_name));
410
+ return create(range(), new_ident, decl(), statements());
411
+ }
412
+ Def withDecl(const Decl& decl) const {
413
+ return create(range(), name(), decl, statements());
414
+ }
415
+ Ident name() const {
416
+ return Ident(subtree(0));
417
+ }
418
+ Decl decl() const {
419
+ return Decl(subtree(1));
420
+ }
421
+ List<Stmt> statements() const {
422
+ return List<Stmt>(subtree(2));
423
+ }
424
+ static Def create(
425
+ const SourceRange& range,
426
+ const Ident& name,
427
+ const Decl& decl,
428
+ const List<Stmt>& stmts) {
429
+ return Def(Compound::create(TK_DEF, range, {name, decl, stmts}));
430
+ }
431
+ };
432
+
433
+ // Property represents a named attribute combined with a getter and setter
434
+ // method to access and mutate that attribute.
435
+ struct Property : public TreeView {
436
+ explicit Property(const TreeRef& tree) : TreeView(tree) {
437
+ tree->match(TK_PROP);
438
+ }
439
+ Ident name() const {
440
+ return Ident(subtree(0));
441
+ }
442
+ Def getter() const {
443
+ return Def(subtree(1));
444
+ }
445
+ Maybe<Def> setter() const {
446
+ return Maybe<Def>(subtree(2));
447
+ }
448
+ static Property create(
449
+ const SourceRange& range,
450
+ const Ident& name,
451
+ const Def& getter,
452
+ const Maybe<Def>& setter) {
453
+ return Property(Compound::create(TK_PROP, range, {name, getter, setter}));
454
+ }
455
+ };
456
+
457
+ struct Assign;
458
+
459
+ struct ClassDef : public TreeView {
460
+ explicit ClassDef(const TreeRef& tree) : TreeView(tree) {
461
+ tree->match(TK_CLASS_DEF);
462
+ }
463
+ explicit ClassDef(TreeRef&& tree) : TreeView(std::move(tree)) {
464
+ tree_->match(TK_CLASS_DEF);
465
+ }
466
+ ClassDef withName(std::string new_name) const {
467
+ auto new_ident = Ident::create(name().range(), std::move(new_name));
468
+ return create(range(), new_ident, superclass(), body());
469
+ }
470
+ Ident name() const {
471
+ return Ident(subtree(0));
472
+ }
473
+ Maybe<Expr> superclass() const {
474
+ return Maybe<Expr>(subtree(1));
475
+ }
476
+ List<Stmt> body() const {
477
+ return List<Stmt>(subtree(2));
478
+ }
479
+ Maybe<List<Property>> properties() const {
480
+ return Maybe<List<Property>>(subtree(3));
481
+ }
482
+ Maybe<List<Assign>> assigns() const {
483
+ return Maybe<List<Assign>>(subtree(4));
484
+ }
485
+ static ClassDef create(
486
+ const SourceRange& range,
487
+ const Ident& name,
488
+ const Maybe<Expr>& superclass,
489
+ const List<Stmt>& body) {
490
+ return ClassDef(Compound::create(
491
+ TK_CLASS_DEF,
492
+ range,
493
+ {name,
494
+ superclass,
495
+ body,
496
+ Maybe<List<Property>>::create(range),
497
+ Maybe<List<Assign>>::create(range)}));
498
+ }
499
+ static ClassDef create(
500
+ const SourceRange& range,
501
+ const Ident& name,
502
+ const Maybe<Expr>& superclass,
503
+ const List<Stmt>& body,
504
+ const List<Property>& properties,
505
+ const List<Assign>& assigns);
506
+ };
507
+
508
+ TORCH_API std::vector<std::string> getUnresolvedClassAttributes(
509
+ const ClassDef& def);
510
+
511
+ ////////////////////////////////////////////////////////////////////////////////
512
+ // Statements
513
+ ////////////////////////////////////////////////////////////////////////////////
514
+
515
+ struct If : public Stmt {
516
+ explicit If(const TreeRef& tree) : Stmt(tree) {
517
+ tree_->match(TK_IF);
518
+ }
519
+ Expr cond() const {
520
+ return Expr(subtree(0));
521
+ }
522
+ List<Stmt> trueBranch() const {
523
+ return List<Stmt>(subtree(1));
524
+ }
525
+ List<Stmt> falseBranch() const {
526
+ return List<Stmt>(subtree(2));
527
+ }
528
+ If withNewBranches(
529
+ const List<Stmt>& true_branch,
530
+ const List<Stmt>& false_branch) const {
531
+ return create(range(), cond(), true_branch, false_branch);
532
+ }
533
+ static If create(
534
+ const SourceRange& range,
535
+ const Expr& cond,
536
+ const List<Stmt>& true_branch,
537
+ const List<Stmt>& false_branch) {
538
+ return If(
539
+ Compound::create(TK_IF, range, {cond, true_branch, false_branch}));
540
+ }
541
+ };
542
+
543
+ struct While : public Stmt {
544
+ explicit While(const TreeRef& tree) : Stmt(tree) {
545
+ tree_->match(TK_WHILE);
546
+ }
547
+ Expr cond() const {
548
+ return Expr(subtree(0));
549
+ }
550
+ List<Stmt> body() const {
551
+ return List<Stmt>(subtree(1));
552
+ }
553
+ static While create(
554
+ const SourceRange& range,
555
+ const Expr& cond,
556
+ const List<Stmt>& body) {
557
+ return While(Compound::create(TK_WHILE, range, {cond, body}));
558
+ }
559
+ };
560
+
561
+ struct For : public Stmt {
562
+ explicit For(const TreeRef& tree) : Stmt(tree) {
563
+ tree->match(TK_FOR);
564
+ }
565
+ List<Expr> targets() const {
566
+ return List<Expr>(subtree(0));
567
+ }
568
+ List<Expr> itrs() const {
569
+ return List<Expr>(subtree(1));
570
+ }
571
+ List<Stmt> body() const {
572
+ return List<Stmt>(subtree(2));
573
+ }
574
+ static For create(
575
+ const SourceRange& range,
576
+ const List<Expr>& targets,
577
+ const List<Expr>& itrs,
578
+ const List<Stmt>& body) {
579
+ return For(Compound::create(TK_FOR, range, {targets, itrs, body}));
580
+ }
581
+ };
582
+
583
+ // TODO: supports only single comprehension for now
584
+ struct ListComp : public Expr {
585
+ explicit ListComp(const TreeRef& tree) : Expr(tree) {
586
+ tree->match(TK_LIST_COMP);
587
+ }
588
+ Expr elt() const {
589
+ return Expr(subtree(0));
590
+ }
591
+ Expr target() const {
592
+ return Expr(subtree(1));
593
+ }
594
+ Expr iter() const {
595
+ return Expr(subtree(2));
596
+ }
597
+ // TODO: no ifs for now
598
+ static ListComp create(
599
+ const SourceRange& range,
600
+ const Expr& elt,
601
+ const Expr& target,
602
+ const Expr& iter) {
603
+ return ListComp(Compound::create(TK_LIST_COMP, range, {elt, target, iter}));
604
+ }
605
+ };
606
+
607
+ // TODO: supports only single comprehension for now
608
+ struct DictComp : public Expr {
609
+ explicit DictComp(const TreeRef& tree) : Expr(tree) {
610
+ tree->match(TK_DICT_COMP);
611
+ }
612
+ Expr key() const {
613
+ return Expr(subtree(0));
614
+ }
615
+ Expr value() const {
616
+ return Expr(subtree(1));
617
+ }
618
+ Expr target() const {
619
+ return Expr(subtree(2));
620
+ }
621
+ Expr iter() const {
622
+ return Expr(subtree(3));
623
+ }
624
+ // TODO: no ifs for now
625
+ static DictComp create(
626
+ const SourceRange& range,
627
+ const Expr& key,
628
+ const Expr& value,
629
+ const Expr& target,
630
+ const Expr& iter) {
631
+ return DictComp(
632
+ Compound::create(TK_DICT_COMP, range, {key, value, target, iter}));
633
+ }
634
+ };
635
+
636
+ struct Global : public Stmt {
637
+ explicit Global(const TreeRef& tree) : Stmt(tree) {
638
+ tree_->match(TK_GLOBAL);
639
+ }
640
+ List<Ident> names() {
641
+ return List<Ident>(subtree(0));
642
+ }
643
+ static Global create(const SourceRange& range, const List<Ident>& names) {
644
+ return Global(Compound::create(TK_GLOBAL, range, {names}));
645
+ }
646
+ };
647
+
648
+ struct AugAssignKind : public TreeView {
649
+ explicit AugAssignKind(const TreeRef& tree) : TreeView(tree) {
650
+ switch (tree->kind()) {
651
+ case '+':
652
+ case '-':
653
+ case '*':
654
+ case '/':
655
+ case '%':
656
+ case '|':
657
+ case '&':
658
+ case '^':
659
+ case TK_POW:
660
+ case TK_LSHIFT:
661
+ case TK_RSHIFT:
662
+ return;
663
+ default:
664
+ throw(ErrorReport(tree) << "is not a valid AugAssignKind");
665
+ }
666
+ }
667
+ };
668
+
669
+ // Augmented assignment, like "foo += bar"
670
+ struct AugAssign : public Stmt {
671
+ explicit AugAssign(const TreeRef& tree) : Stmt(tree) {
672
+ tree_->match(TK_AUG_ASSIGN);
673
+ }
674
+ static AugAssign create(
675
+ const SourceRange& range,
676
+ const Expr& lhs,
677
+ const AugAssignKind& aug_op,
678
+ const Expr& rhs) {
679
+ return AugAssign(
680
+ Compound::create(TK_AUG_ASSIGN, range, {lhs, aug_op, rhs}));
681
+ }
682
+ Expr lhs() const {
683
+ return Expr(subtree(0));
684
+ }
685
+ int aug_op() const {
686
+ return subtree(1)->kind();
687
+ }
688
+ Expr rhs() const {
689
+ return Expr(subtree(2));
690
+ }
691
+ };
692
+
693
+ struct Assign : public Stmt {
694
+ explicit Assign(const TreeRef& tree) : Stmt(tree) {
695
+ tree_->match(TK_ASSIGN);
696
+ }
697
+ static Assign create(
698
+ const SourceRange& range,
699
+ const List<Expr>& lhs,
700
+ const Maybe<Expr>& rhs,
701
+ const Maybe<Expr>& type) {
702
+ return Assign(Compound::create(TK_ASSIGN, range, {lhs, rhs, type}));
703
+ }
704
+
705
+ List<Expr> lhs_list() const {
706
+ return List<Expr>(subtree(0));
707
+ }
708
+
709
+ Expr lhs() const {
710
+ const auto& li = lhs_list();
711
+ TORCH_INTERNAL_ASSERT(li.size() == 1);
712
+ return *li.begin();
713
+ }
714
+
715
+ Maybe<Expr> rhs() const {
716
+ return Maybe<Expr>(subtree(1));
717
+ }
718
+
719
+ Maybe<Expr> type() const {
720
+ return Maybe<Expr>(subtree(2));
721
+ }
722
+ };
723
+
724
+ struct Return : public Stmt {
725
+ explicit Return(const TreeRef& tree) : Stmt(tree) {
726
+ tree_->match(TK_RETURN);
727
+ }
728
+ Expr expr() const {
729
+ return Expr(subtree(0));
730
+ }
731
+ static Return create(const SourceRange& range, const Expr& value) {
732
+ return Return(Compound::create(TK_RETURN, range, {value}));
733
+ }
734
+ };
735
+
736
+ struct Raise : public Stmt {
737
+ explicit Raise(const TreeRef& tree) : Stmt(tree) {
738
+ tree_->match(TK_RAISE);
739
+ }
740
+ Expr expr() const {
741
+ return Expr(subtree(0));
742
+ }
743
+ static Raise create(const SourceRange& range, const Expr& expr) {
744
+ return Raise(Compound::create(TK_RAISE, range, {expr}));
745
+ }
746
+ };
747
+
748
+ struct Assert : public Stmt {
749
+ explicit Assert(const TreeRef& tree) : Stmt(tree) {
750
+ tree_->match(TK_ASSERT);
751
+ }
752
+ Expr test() const {
753
+ return Expr(subtree(0));
754
+ }
755
+ Maybe<Expr> msg() const {
756
+ return Maybe<Expr>(subtree(1));
757
+ }
758
+ static Assert create(
759
+ const SourceRange& range,
760
+ const Expr& test,
761
+ const Maybe<Expr>& msg) {
762
+ return Assert(Compound::create(TK_ASSERT, range, {test, msg}));
763
+ }
764
+ };
765
+
766
+ struct Pass : public Stmt {
767
+ explicit Pass(const TreeRef& tree) : Stmt(tree) {
768
+ tree_->match(TK_PASS);
769
+ }
770
+ static Pass create(const SourceRange& range) {
771
+ return Pass(Compound::create(TK_PASS, range, {}));
772
+ }
773
+ };
774
+
775
+ struct Dots : public Expr {
776
+ explicit Dots(const TreeRef& tree) : Expr(tree) {
777
+ tree_->match(TK_DOTS);
778
+ }
779
+ static Dots create(const SourceRange& range) {
780
+ return Dots(Compound::create(TK_DOTS, range, {}));
781
+ }
782
+ };
783
+
784
+ struct Break : public Stmt {
785
+ explicit Break(const TreeRef& tree) : Stmt(tree) {
786
+ tree_->match(TK_BREAK);
787
+ }
788
+ static Break create(const SourceRange& range) {
789
+ return Break(Compound::create(TK_BREAK, range, {}));
790
+ }
791
+ };
792
+
793
+ struct Continue : public Stmt {
794
+ explicit Continue(const TreeRef& tree) : Stmt(tree) {
795
+ tree_->match(TK_CONTINUE);
796
+ }
797
+ static Continue create(const SourceRange& range) {
798
+ return Continue(Compound::create(TK_CONTINUE, range, {}));
799
+ }
800
+ };
801
+
802
+ struct ExprStmt : public Stmt {
803
+ explicit ExprStmt(const TreeRef& tree) : Stmt(tree) {
804
+ tree_->match(TK_EXPR_STMT);
805
+ }
806
+ Expr expr() {
807
+ return Expr(subtree(0));
808
+ }
809
+ static ExprStmt create(const SourceRange& range, const Expr& list) {
810
+ return ExprStmt(Compound::create(TK_EXPR_STMT, range, {list}));
811
+ }
812
+ };
813
+
814
+ ////////////////////////////////////////////////////////////////////////////////
815
+ // Expressions
816
+ ////////////////////////////////////////////////////////////////////////////////
817
+
818
+ struct BinOp : public Expr {
819
+ explicit BinOp(const TreeRef& tree) : Expr(tree) {
820
+ switch (tree->kind()) {
821
+ case TK_AND:
822
+ case TK_OR:
823
+ case '<':
824
+ case '>':
825
+ case TK_IS:
826
+ case TK_ISNOT:
827
+ case TK_EQ:
828
+ case TK_LE:
829
+ case TK_GE:
830
+ case TK_NE:
831
+ case '+':
832
+ case '*':
833
+ case '/':
834
+ case '-':
835
+ case '@':
836
+ case TK_POW:
837
+ case TK_LSHIFT:
838
+ case TK_RSHIFT:
839
+ case '%':
840
+ case '&':
841
+ case '^':
842
+ case '|':
843
+ case TK_FLOOR_DIV:
844
+ case TK_IN:
845
+ if (tree->trees().size() != 2)
846
+ throw(
847
+ ErrorReport(tree)
848
+ << "BinOp expected 2 subtrees, found " << tree->trees().size());
849
+ return;
850
+ default:
851
+ throw(
852
+ ErrorReport(tree)
853
+ << kindToString(tree->kind()) << " is not a valid BinOp");
854
+ }
855
+ }
856
+ Expr lhs() const {
857
+ return Expr(subtree(0));
858
+ }
859
+ Expr rhs() const {
860
+ return Expr(subtree(1));
861
+ }
862
+ static BinOp create(
863
+ const SourceRange& range,
864
+ int kind,
865
+ const Expr& lhs,
866
+ const Expr& rhs) {
867
+ return BinOp(Compound::create(kind, range, {lhs, rhs}));
868
+ }
869
+ };
870
+
871
+ struct UnaryOp : public Expr {
872
+ explicit UnaryOp(const TreeRef& tree) : Expr(tree) {
873
+ switch (tree->kind()) {
874
+ case TK_UNARY_MINUS:
875
+ case '~':
876
+ case TK_NOT:
877
+ if (tree->trees().size() != 1)
878
+ throw(
879
+ ErrorReport(tree)
880
+ << "UnaryOp expected 1 subtree, found " << tree->trees().size());
881
+ return;
882
+ default:
883
+ throw(
884
+ ErrorReport(tree)
885
+ << kindToString(tree->kind()) << " is not a valid UnaryOp");
886
+ }
887
+ }
888
+ static UnaryOp create(const SourceRange& range, int kind, const Expr& expr) {
889
+ return UnaryOp(Compound::create(kind, range, {expr}));
890
+ }
891
+ };
892
+
893
+ struct Const : public Expr {
894
+ explicit Const(const TreeRef& tree) : Expr(tree) {
895
+ tree_->matchNumSubtrees(TK_CONST, 1);
896
+ }
897
+ bool isFloatingPoint() const {
898
+ if (isComplex())
899
+ return false;
900
+
901
+ bool is_inf = subtree(0)->stringValue() == "inf";
902
+ return is_inf ||
903
+ subtree(0)->stringValue().find_first_of(".eE") != std::string::npos;
904
+ }
905
+ bool isIntegral() const {
906
+ return !isFloatingPoint() && !isComplex();
907
+ }
908
+ bool isComplex() const {
909
+ return subtree(0)->stringValue().find_first_of('j') != std::string::npos;
910
+ }
911
+ int64_t asIntegral() const {
912
+ try {
913
+ return std::stoll(subtree(0)->stringValue(), nullptr, 0);
914
+ } catch (const std::out_of_range&) {
915
+ throw(
916
+ ErrorReport(range()) << "Integral constant out of range "
917
+ "(must fit in a signed 64 bit integer)");
918
+ }
919
+ }
920
+ double asFloatingPoint() const {
921
+ // We can't pass in nullptr as the dummy pointer gets dereferenced for
922
+ // Android version of strtod_c().
923
+ char* dummy = nullptr;
924
+ return torch::jit::strtod_c(subtree(0)->stringValue().c_str(), &dummy);
925
+ }
926
+ c10::complex<double> asComplex() const {
927
+ char* dummy = nullptr;
928
+ auto str = subtree(0)->stringValue();
929
+ // Complex numbers (a+bj, where a is non-zero) are parsed as an addition
930
+ // between float/int a and a complex number "bj". When a is 0, a complex
931
+ // number bj is created as above. So, while parsing the string, we don't
932
+ // have to worry about the real component of the complex number.
933
+ auto imag =
934
+ torch::jit::strtod_c(str.substr(0, str.size() - 1).c_str(), &dummy);
935
+ return c10::complex<double>(0, imag);
936
+ }
937
+ const std::string& text() const {
938
+ return subtree(0)->stringValue();
939
+ }
940
+ static Const create(const SourceRange& range, const std::string& value) {
941
+ return Const(Compound::create(TK_CONST, range, {String::create(value)}));
942
+ }
943
+ };
944
+
945
+ struct StringLiteral : public Expr {
946
+ explicit StringLiteral(const TreeRef& tree) : Expr(tree) {
947
+ tree_->matchNumSubtrees(TK_STRINGLITERAL, 1);
948
+ }
949
+ const std::string& text() const {
950
+ return subtree(0)->stringValue();
951
+ }
952
+ static StringLiteral create(
953
+ const SourceRange& range,
954
+ const std::string& value) {
955
+ return StringLiteral(
956
+ Compound::create(TK_STRINGLITERAL, range, {String::create(value)}));
957
+ }
958
+ };
959
+
960
+ struct Apply : public Expr {
961
+ explicit Apply(const TreeRef& tree) : Expr(tree) {
962
+ tree_->match(TK_APPLY);
963
+ }
964
+ Expr callee() const {
965
+ return Expr(subtree(0));
966
+ }
967
+ List<Expr> inputs() const {
968
+ return List<Expr>(subtree(1));
969
+ }
970
+ List<Attribute> attributes() const {
971
+ return List<Attribute>(subtree(2));
972
+ }
973
+ static Apply create(
974
+ const SourceRange& range,
975
+ const Expr& callee,
976
+ const List<Expr>& inputs,
977
+ const List<Attribute>& attributes) {
978
+ return Apply(
979
+ Compound::create(TK_APPLY, range, {callee, inputs, attributes}));
980
+ }
981
+ };
982
+
983
+ struct Select : public Expr {
984
+ explicit Select(const TreeRef& tree) : Expr(tree) {
985
+ tree_->match('.');
986
+ }
987
+ Expr value() const {
988
+ return Expr(subtree(0));
989
+ }
990
+ Ident selector() const {
991
+ return Ident(subtree(1));
992
+ }
993
+ static Select create(
994
+ const SourceRange& range,
995
+ const Expr& value,
996
+ const Ident& selector) {
997
+ return Select(Compound::create('.', range, {value, selector}));
998
+ }
999
+ };
1000
+
1001
+ struct SliceExpr : public Expr {
1002
+ explicit SliceExpr(const TreeRef& tree) : Expr(tree) {
1003
+ tree_->match(TK_SLICE_EXPR);
1004
+ }
1005
+ Maybe<Expr> start() const {
1006
+ return Maybe<Expr>(subtree(0));
1007
+ }
1008
+ Maybe<Expr> end() const {
1009
+ return Maybe<Expr>(subtree(1));
1010
+ }
1011
+ Maybe<Expr> step() const {
1012
+ return Maybe<Expr>(subtree(2));
1013
+ }
1014
+ Expr startOr(int64_t alternative) const {
1015
+ const auto startOption = start();
1016
+ return startOption.present() ? startOption.get() : createInt(alternative);
1017
+ }
1018
+ Expr endOr(int64_t alternative) const {
1019
+ const auto endOption = end();
1020
+ return endOption.present() ? endOption.get() : createInt(alternative);
1021
+ }
1022
+ Expr stepOr(int64_t alternative) const {
1023
+ const auto stepOption = step();
1024
+ return stepOption.present() ? stepOption.get() : createInt(alternative);
1025
+ }
1026
+ static SliceExpr create(
1027
+ const SourceRange& range,
1028
+ const Maybe<Expr>& start,
1029
+ const Maybe<Expr>& end,
1030
+ const Maybe<Expr>& step) {
1031
+ return SliceExpr(
1032
+ Compound::create(TK_SLICE_EXPR, range, {start, end, step}));
1033
+ }
1034
+
1035
+ private:
1036
+ Expr createInt(int64_t value) const {
1037
+ return Expr(Const::create(range(), std::to_string(value)));
1038
+ }
1039
+ };
1040
+
1041
+ struct Subscript : public Expr {
1042
+ explicit Subscript(const TreeRef& tree) : Expr(tree) {
1043
+ tree_->match(TK_SUBSCRIPT);
1044
+ }
1045
+ Expr value() const {
1046
+ return Expr(subtree(0));
1047
+ }
1048
+ List<Expr> subscript_exprs() const {
1049
+ return List<Expr>(subtree(1));
1050
+ }
1051
+ static Subscript create(
1052
+ const SourceRange& range,
1053
+ const Expr& value,
1054
+ const List<Expr>& subscript_exprs) {
1055
+ auto whole_range = SourceRange(
1056
+ range.source(), range.start(), subscript_exprs.range().end() + 1);
1057
+ return Subscript(
1058
+ Compound::create(TK_SUBSCRIPT, whole_range, {value, subscript_exprs}));
1059
+ }
1060
+ };
1061
+
1062
+ struct Var : public Expr {
1063
+ explicit Var(const TreeRef& tree) : Expr(tree) {
1064
+ tree_->match(TK_VAR);
1065
+ };
1066
+ Ident name() const {
1067
+ return Ident(subtree(0));
1068
+ }
1069
+ static Var create(const SourceRange& range, const Ident& name) {
1070
+ return Var(Compound::create(TK_VAR, range, {name}));
1071
+ }
1072
+ };
1073
+
1074
+ // WithItem represents an item using with a WithStmt.
1075
+ struct WithItem : public Expr {
1076
+ explicit WithItem(const TreeRef& tree) : Expr(tree) {
1077
+ tree_->match(TK_WITH_ITEM);
1078
+ }
1079
+
1080
+ Expr target() const {
1081
+ return Expr(subtree(0));
1082
+ }
1083
+
1084
+ Maybe<Var> var() const {
1085
+ return Maybe<Var>(subtree(1));
1086
+ }
1087
+
1088
+ static WithItem create(
1089
+ const SourceRange& range,
1090
+ const Expr& target,
1091
+ const Maybe<Var>& var) {
1092
+ return WithItem(Compound::create(TK_WITH_ITEM, range, {target, var}));
1093
+ }
1094
+ };
1095
+
1096
+ // With represents a with statement consisting of a list of with items and a
1097
+ // body of statements.
1098
+ struct With : public Stmt {
1099
+ explicit With(const TreeRef& tree) : Stmt(tree) {
1100
+ tree_->match(TK_WITH);
1101
+ }
1102
+
1103
+ List<WithItem> targets() const {
1104
+ return List<WithItem>(subtree(0));
1105
+ }
1106
+
1107
+ List<Stmt> body() const {
1108
+ return List<Stmt>(subtree(1));
1109
+ }
1110
+
1111
+ static With create(
1112
+ const SourceRange& range,
1113
+ const List<WithItem>& targets,
1114
+ const List<Stmt>& body) {
1115
+ return With(Compound::create(TK_WITH, range, {targets, body}));
1116
+ }
1117
+ };
1118
+
1119
+ struct TernaryIf : public Expr {
1120
+ explicit TernaryIf(const TreeRef& tree) : Expr(tree) {
1121
+ tree_->matchNumSubtrees(TK_IF_EXPR, 3);
1122
+ };
1123
+ Expr cond() const {
1124
+ return Expr(subtree(0));
1125
+ }
1126
+ Expr true_expr() const {
1127
+ return Expr(subtree(1));
1128
+ }
1129
+ Expr false_expr() const {
1130
+ return Expr(subtree(2));
1131
+ }
1132
+ static TernaryIf create(
1133
+ const SourceRange& range,
1134
+ const Expr& cond,
1135
+ const Expr& true_expr,
1136
+ const Expr& false_expr) {
1137
+ return TernaryIf(
1138
+ Compound::create(TK_IF_EXPR, range, {cond, true_expr, false_expr}));
1139
+ };
1140
+ };
1141
+
1142
+ struct ListLiteral : public Expr {
1143
+ explicit ListLiteral(const TreeRef& tree) : Expr(tree) {
1144
+ tree_->match(TK_LIST_LITERAL);
1145
+ }
1146
+ List<Expr> inputs() const {
1147
+ return subtree(0);
1148
+ }
1149
+ static ListLiteral create(
1150
+ const SourceRange& range,
1151
+ const List<Expr>& inputs) {
1152
+ return ListLiteral(Compound::create(TK_LIST_LITERAL, range, {inputs}));
1153
+ }
1154
+ };
1155
+
1156
+ struct TupleLiteral : public Expr {
1157
+ explicit TupleLiteral(const TreeRef& tree) : Expr(tree) {
1158
+ tree_->match(TK_TUPLE_LITERAL);
1159
+ }
1160
+ List<Expr> inputs() const {
1161
+ return subtree(0);
1162
+ }
1163
+ static TupleLiteral create(
1164
+ const SourceRange& range,
1165
+ const List<Expr>& inputs) {
1166
+ return TupleLiteral(Compound::create(TK_TUPLE_LITERAL, range, {inputs}));
1167
+ }
1168
+ };
1169
+
1170
+ struct DictLiteral : public Expr {
1171
+ explicit DictLiteral(const TreeRef& tree) : Expr(tree) {
1172
+ tree_->match(TK_DICT_LITERAL);
1173
+ }
1174
+ List<Expr> key_inputs() const {
1175
+ return subtree(0);
1176
+ }
1177
+ List<Expr> value_inputs() const {
1178
+ return subtree(1);
1179
+ }
1180
+ static DictLiteral create(
1181
+ const SourceRange& range,
1182
+ const List<Expr>& keys,
1183
+ const List<Expr>& values) {
1184
+ return DictLiteral(
1185
+ Compound::create(TK_DICT_LITERAL, range, {keys, values}));
1186
+ }
1187
+ };
1188
+
1189
+ struct Starred : public Expr {
1190
+ explicit Starred(const TreeRef& tree) : Expr(tree) {
1191
+ tree_->match(TK_STARRED);
1192
+ }
1193
+ Expr expr() const {
1194
+ return Expr(subtree(0));
1195
+ }
1196
+ static Starred create(const SourceRange& range, const Expr& expr) {
1197
+ return Starred(Compound::create(TK_STARRED, range, {expr}));
1198
+ }
1199
+ };
1200
+
1201
+ struct Delete : public Stmt {
1202
+ explicit Delete(const TreeRef& tree) : Stmt(tree) {
1203
+ tree_->match(TK_DELETE);
1204
+ }
1205
+ List<Expr> targets() const {
1206
+ return subtree(0);
1207
+ }
1208
+ static Delete create(const SourceRange& range, const List<Expr>& targets) {
1209
+ return Delete(Compound::create(TK_DELETE, range, {targets}));
1210
+ }
1211
+ };
1212
+
1213
+ /*
1214
+ * NOTE: transforming PEP 604 union into equivalent union type
1215
+ *
1216
+ * NOTE: Union[int, float] parses into:
1217
+ * <EXPR> expr:(subscript
1218
+ * (variable (ident Union))
1219
+ * (list
1220
+ * (variable (ident int))
1221
+ * (variable (ident float))))
1222
+ * <KIND> subscript
1223
+ *
1224
+ * NOTE: (int | float) parses into:
1225
+ * <EXPR> expr:(|
1226
+ * (variable (ident int))
1227
+ * (variable (ident float)))
1228
+ * <KIND> |
1229
+ */
1230
+
1231
+ inline void _flatten_pep604_union(
1232
+ const torch::jit::Expr& node,
1233
+ std::vector<torch::jit::Expr>* result) {
1234
+ // flatten possibly nested union expressions like (int | (float | str))
1235
+ // into a flat list of expressions like [int, float, str]
1236
+ if (node.kind() == '|') {
1237
+ auto as_binop = torch::jit::BinOp(node);
1238
+ _flatten_pep604_union(as_binop.lhs(), result);
1239
+ _flatten_pep604_union(as_binop.rhs(), result);
1240
+ } else {
1241
+ result->push_back(node);
1242
+ }
1243
+ }
1244
+
1245
+ inline std::vector<Expr> get_pep604_union_members(const Expr& node) {
1246
+ std::vector<Expr> result;
1247
+ _flatten_pep604_union(node, &result);
1248
+ return result;
1249
+ }
1250
+
1251
+ // Flattens a PEP 604 union into a classical union.
1252
+ // For example, ((x | y) | z) is transformed into Union[x, y, z].
1253
+ inline Expr pep604union_to_union(const Expr& expr) {
1254
+ // noop if not a pep604 union
1255
+ if (expr.kind() != '|')
1256
+ return expr;
1257
+
1258
+ // In order to support unions with more than 2 operands ((x|y)|z), we need to
1259
+ // recursively flatten the tree of | expressions.
1260
+ auto members = get_pep604_union_members(expr);
1261
+ auto synthesised_union = Subscript::create(
1262
+ expr.range(),
1263
+ Var::create(expr.range(), Ident::create(expr.range(), "Union")),
1264
+ List<Expr>::create(expr.range(), members));
1265
+ return std::move(synthesised_union);
1266
+ }
1267
+
1268
+ } // namespace torch::jit
1269
+
1270
+ namespace std {
1271
+
1272
+ template <typename T>
1273
+ struct iterator_traits<torch::jit::ListIterator<T>>
1274
+ : std::iterator_traits<torch::jit::TreeList::const_iterator> {};
1275
+
1276
+ } // namespace std
vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/mobile/code.h ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <vector>
4
+
5
+ #include <ATen/core/ivalue.h>
6
+ #include <ATen/core/operator_name.h>
7
+ #include <torch/csrc/jit/runtime/instruction.h>
8
+
9
+ namespace torch::jit::mobile {
10
+
11
+ using Stack = std::vector<c10::IValue>;
12
+ using DebugHandle = int64_t;
13
+
14
+ class Function;
15
+
16
+ struct Code {
17
+ std::vector<Instruction> instructions_;
18
+ std::vector<DebugHandle> debug_handles_;
19
+ std::vector<c10::OperatorName> op_names_;
20
+ std::vector<int> operator_input_sizes_;
21
+ std::vector<std::function<void(Stack&)>> operators_;
22
+ std::vector<c10::IValue> constants_;
23
+ std::vector<c10::TypePtr> types_;
24
+ // TODO After we actually export CALL instructions we can remove this.
25
+ // We may need a two-stage importing scheme, where we firstly construct all
26
+ // function objects, and then append referenced function pointers. This could
27
+ // be done in parseMethods().
28
+ std::vector<mobile::Function*> functions_;
29
+ size_t register_size_ = 0; // Aggregated output size.
30
+ // initialized means operators_ array is filled with operators
31
+ bool initialized = false;
32
+ };
33
+
34
+ } // namespace torch::jit::mobile
vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/mobile/debug_info.h ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <c10/util/flat_hash_map.h>
3
+ #include <caffe2/serialize/inline_container.h>
4
+ #include <torch/csrc/jit/api/compilation_unit.h>
5
+ #include <torch/csrc/jit/ir/scope.h>
6
+ #include <torch/csrc/jit/serialization/source_range_serialization.h>
7
+
8
+ namespace torch::jit {
9
+ /*
10
+ * MobileDebugTable:
11
+ * Deserializes debug_pkl and callstack_map records from PT model's zip archive
12
+ * and stores them in a map of debug handles to DebugInfoPair. Debug handles are
13
+ * unique per model and runtime, be in lite interpreter or delegate, an
14
+ * exception of BackendRuntimeException should raised using debug handles.
15
+ * getSourceDebugString method is responsible for translating debug
16
+ * handles to correspond debug information.
17
+ * This debug informatin includes stack trace of model level source code and
18
+ * module hierarchy where the exception occurred.
19
+ */
20
+ class MobileDebugTable {
21
+ public:
22
+ MobileDebugTable() = default;
23
+ MobileDebugTable(
24
+ std::unique_ptr<caffe2::serialize::PyTorchStreamReader>& reader,
25
+ const std::shared_ptr<CompilationUnit>& cu);
26
+
27
+ template <typename It>
28
+ MobileDebugTable(It begin, It end) : callstack_ptr_map_(begin, end) {}
29
+
30
+ std::string getSourceDebugString(
31
+ const int64_t debug_handle,
32
+ const std::string& top_module_type_name = "ModuleTypeUnknown") const;
33
+ std::string getSourceDebugString(
34
+ const std::vector<int64_t>& debug_handles,
35
+ const std::string& top_module_type_name = "ModuleTypeUnknown") const;
36
+ std::string getModuleHierarchyInfo(
37
+ const int64_t debug_handle,
38
+ const std::string& top_module_type_name = "ModuleTypeUnknown") const;
39
+ std::string getModuleHierarchyInfo(
40
+ const std::vector<int64_t>& debug_handles,
41
+ const std::string& top_module_type_name = "ModuleTypeUnknown") const;
42
+
43
+ const ska::flat_hash_map<int64_t, DebugInfoTuple>& getCallStackPtrMap()
44
+ const {
45
+ return callstack_ptr_map_;
46
+ }
47
+
48
+ private:
49
+ std::pair<std::string, std::string> getSourceDebugModuleHierarchyInfo(
50
+ const std::vector<int64_t>& debug_handles,
51
+ const std::string& top_module_type_name = "ModuleTypeUnknown") const;
52
+ ska::flat_hash_map<int64_t, DebugInfoTuple> callstack_ptr_map_;
53
+ };
54
+
55
+ } // namespace torch::jit
vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/mobile/file_format.h ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <array>
4
+ #include <cerrno>
5
+ #include <cstddef>
6
+ #include <cstring>
7
+ #include <fstream>
8
+ #include <istream>
9
+ #include <memory>
10
+
11
+ #include <c10/core/CPUAllocator.h>
12
+ #include <c10/core/impl/alloc_cpu.h>
13
+ #include <caffe2/serialize/read_adapter_interface.h>
14
+
15
+ #if defined(HAVE_MMAP)
16
+ #include <fcntl.h>
17
+ #include <sys/mman.h>
18
+ #include <sys/stat.h>
19
+ #include <sys/types.h>
20
+ #include <unistd.h>
21
+ #endif
22
+
23
+ /**
24
+ * @file
25
+ *
26
+ * Helpers for identifying file formats when reading serialized data.
27
+ *
28
+ * Note that these functions are declared inline because they will typically
29
+ * only be called from one or two locations per binary.
30
+ */
31
+
32
+ namespace torch::jit {
33
+
34
+ /**
35
+ * The format of a file or data stream.
36
+ */
37
+ enum class FileFormat {
38
+ UnknownFileFormat = 0,
39
+ FlatbufferFileFormat,
40
+ ZipFileFormat,
41
+ };
42
+
43
+ /// The size of the buffer to pass to #getFileFormat(), in bytes.
44
+ constexpr size_t kFileFormatHeaderSize = 8;
45
+ constexpr size_t kMaxAlignment = 16;
46
+
47
+ /**
48
+ * Returns the likely file format based on the magic header bytes in @p header,
49
+ * which should contain the first bytes of a file or data stream.
50
+ */
51
+ // NOLINTNEXTLINE(facebook-hte-NamespaceScopedStaticDeclaration)
52
+ static inline FileFormat getFileFormat(const char* data) {
53
+ // The size of magic strings to look for in the buffer.
54
+ static constexpr size_t kMagicSize = 4;
55
+
56
+ // Bytes 4..7 of a Flatbuffer-encoded file produced by
57
+ // `flatbuffer_serializer.h`. (The first four bytes contain an offset to the
58
+ // actual Flatbuffer data.)
59
+ static constexpr std::array<char, kMagicSize> kFlatbufferMagicString = {
60
+ 'P', 'T', 'M', 'F'};
61
+ static constexpr size_t kFlatbufferMagicOffset = 4;
62
+
63
+ // The first four bytes of a ZIP file.
64
+ static constexpr std::array<char, kMagicSize> kZipMagicString = {
65
+ 'P', 'K', '\x03', '\x04'};
66
+
67
+ // Note that we check for Flatbuffer magic first. Since the first four bytes
68
+ // of flatbuffer data contain an offset to the root struct, it's theoretically
69
+ // possible to construct a file whose offset looks like the ZIP magic. On the
70
+ // other hand, bytes 4-7 of ZIP files are constrained to a small set of values
71
+ // that do not typically cross into the printable ASCII range, so a ZIP file
72
+ // should never have a header that looks like a Flatbuffer file.
73
+ if (std::memcmp(
74
+ data + kFlatbufferMagicOffset,
75
+ kFlatbufferMagicString.data(),
76
+ kMagicSize) == 0) {
77
+ // Magic header for a binary file containing a Flatbuffer-serialized mobile
78
+ // Module.
79
+ return FileFormat::FlatbufferFileFormat;
80
+ } else if (std::memcmp(data, kZipMagicString.data(), kMagicSize) == 0) {
81
+ // Magic header for a zip file, which we use to store pickled sub-files.
82
+ return FileFormat::ZipFileFormat;
83
+ }
84
+ return FileFormat::UnknownFileFormat;
85
+ }
86
+
87
+ /**
88
+ * Returns the likely file format based on the magic header bytes of @p data.
89
+ * If the stream position changes while inspecting the data, this function will
90
+ * restore the stream position to its original offset before returning.
91
+ */
92
+ // NOLINTNEXTLINE(facebook-hte-NamespaceScopedStaticDeclaration)
93
+ static inline FileFormat getFileFormat(std::istream& data) {
94
+ FileFormat format = FileFormat::UnknownFileFormat;
95
+ std::streampos orig_pos = data.tellg();
96
+ // NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init)
97
+ std::array<char, kFileFormatHeaderSize> header;
98
+ data.read(header.data(), header.size());
99
+ if (data.good()) {
100
+ format = getFileFormat(header.data());
101
+ }
102
+ data.seekg(orig_pos, data.beg);
103
+ return format;
104
+ }
105
+
106
+ /**
107
+ * Returns the likely file format based on the magic header bytes of the file
108
+ * named @p filename.
109
+ */
110
+ // NOLINTNEXTLINE(facebook-hte-NamespaceScopedStaticDeclaration)
111
+ static inline FileFormat getFileFormat(const std::string& filename) {
112
+ std::ifstream data(filename, std::ifstream::binary);
113
+ return getFileFormat(data);
114
+ }
115
+
116
+ // NOLINTNEXTLINE(facebook-hte-NamespaceScopedStaticDeclaration)
117
+ static void file_not_found_error() {
118
+ std::stringstream message;
119
+ message << "Error while opening file: ";
120
+ if (errno == ENOENT) {
121
+ message << "no such file or directory" << '\n';
122
+ } else {
123
+ message << "error no is: " << errno << '\n';
124
+ }
125
+ TORCH_CHECK(false, message.str());
126
+ }
127
+
128
+ // NOLINTNEXTLINE(facebook-hte-NamespaceScopedStaticDeclaration)
129
+ static inline std::tuple<std::shared_ptr<char>, size_t> get_file_content(
130
+ const char* filename) {
131
+ #if defined(HAVE_MMAP)
132
+ int fd = open(filename, O_RDONLY);
133
+ if (fd < 0) {
134
+ // failed to open file, chances are it's no such file or directory.
135
+ file_not_found_error();
136
+ }
137
+ struct stat statbuf {};
138
+ fstat(fd, &statbuf);
139
+ size_t size = statbuf.st_size;
140
+ void* ptr = mmap(nullptr, statbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
141
+ close(fd);
142
+ auto deleter = [statbuf](char* ptr) { munmap(ptr, statbuf.st_size); };
143
+ std::shared_ptr<char> data(reinterpret_cast<char*>(ptr), deleter);
144
+ #else
145
+ FILE* f = fopen(filename, "rb");
146
+ if (f == nullptr) {
147
+ file_not_found_error();
148
+ }
149
+ fseek(f, 0, SEEK_END);
150
+ size_t size = ftell(f);
151
+ fseek(f, 0, SEEK_SET);
152
+ // make sure buffer size is multiple of alignment
153
+ size_t buffer_size = (size / kMaxAlignment + 1) * kMaxAlignment;
154
+ std::shared_ptr<char> data(
155
+ static_cast<char*>(c10::alloc_cpu(buffer_size)), c10::free_cpu);
156
+ fread(data.get(), size, 1, f);
157
+ fclose(f);
158
+ #endif
159
+ return std::make_tuple(data, size);
160
+ }
161
+
162
+ // NOLINTNEXTLINE(facebook-hte-NamespaceScopedStaticDeclaration)
163
+ static inline std::tuple<std::shared_ptr<char>, size_t> get_stream_content(
164
+ std::istream& in) {
165
+ // get size of the stream and reset to orig
166
+ std::streampos orig_pos = in.tellg();
167
+ in.seekg(orig_pos, std::ios::end);
168
+ const long size = in.tellg();
169
+ in.seekg(orig_pos, in.beg);
170
+
171
+ // read stream
172
+ // NOLINT make sure buffer size is multiple of alignment
173
+ size_t buffer_size = (size / kMaxAlignment + 1) * kMaxAlignment;
174
+ std::shared_ptr<char> data(
175
+ static_cast<char*>(c10::alloc_cpu(buffer_size)), c10::free_cpu);
176
+ in.read(data.get(), size);
177
+
178
+ // reset stream to original position
179
+ in.seekg(orig_pos, in.beg);
180
+ return std::make_tuple(data, size);
181
+ }
182
+
183
+ // NOLINTNEXTLINE(facebook-hte-NamespaceScopedStaticDeclaration)
184
+ static inline std::tuple<std::shared_ptr<char>, size_t> get_rai_content(
185
+ caffe2::serialize::ReadAdapterInterface* rai) {
186
+ size_t buffer_size = (rai->size() / kMaxAlignment + 1) * kMaxAlignment;
187
+ std::shared_ptr<char> data(
188
+ static_cast<char*>(c10::alloc_cpu(buffer_size)), c10::free_cpu);
189
+ rai->read(
190
+ 0, data.get(), rai->size(), "Loading ReadAdapterInterface to bytes");
191
+ return std::make_tuple(data, buffer_size);
192
+ }
193
+
194
+ } // namespace torch::jit
vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/mobile/flatbuffer_loader.h ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <istream>
4
+ #include <memory>
5
+ #include <string>
6
+ #include <unordered_map>
7
+ #include <vector>
8
+
9
+ #include <ATen/core/ivalue.h>
10
+ #include <c10/core/Device.h>
11
+ #include <c10/macros/Macros.h>
12
+ #include <torch/csrc/jit/mobile/module.h>
13
+ #include <optional>
14
+
15
+ /**
16
+ * Defines the public API for loading flatbuffer-serialized mobile modules.
17
+ * Note that this header must not include or depend on flatbuffer-defined
18
+ * types, to avoid leaking those details to PyTorch clients.
19
+ */
20
+
21
+ namespace torch::jit {
22
+
23
+ /// All non-copied data pointers provided to `parse_and_initialize_*` functions
24
+ /// must be aligned to this boundary. Since the Module will point directly into
25
+ /// the data, this alignment is necessary to ensure that certain types/structs
26
+ /// are properly aligned.
27
+ constexpr size_t kFlatbufferDataAlignmentBytes = 16;
28
+
29
+ /// Maps file names to file contents.
30
+ using ExtraFilesMap = std::unordered_map<std::string, std::string>;
31
+
32
+ // On high level, to produce a Module from a file on disk, we need to go
33
+ // through the follow steps:
34
+ // 1. Read: Read the file from disk -> memory
35
+ // 2. Deserialize: Parse the bytes to produce some in memory manipulable
36
+ // structure
37
+ // 3. Module initialization: Produce mobile::Module out of the structure
38
+ // produced in 2.
39
+ // Under this context, the structure described in 2. is the flatbuffer-defined
40
+ // type mobile::serialization::Module. However, this step/type is not visible in
41
+ // the public API.
42
+
43
+ // Parse a mobile::Module from raw bytes.
44
+ //
45
+ // This function does steps 2+3 described above.
46
+ //
47
+ // Does not take ownership of `data`; if you want it to take ownership, see the
48
+ // shared_ptr overload of this function.
49
+ //
50
+ // If should_copy_tensor_memory is true, then the returned module will NOT have
51
+ // refences to `data`, so `data` can be freed immediately.
52
+ //
53
+ // If should_copy_tensor_memory is false, then returned module will have tensors
54
+ // that points inside of `data`; the caller will need to make sure that `data`
55
+ // outlives the returned Module. Also, `data` must be aligned to
56
+ // kFlatbufferDataAlignmentBytes.
57
+ TORCH_API mobile::Module parse_and_initialize_mobile_module(
58
+ void* data,
59
+ size_t size, // of `data`, in bytes.
60
+ std::optional<at::Device> device = std::nullopt,
61
+ ExtraFilesMap* extra_files = nullptr,
62
+ bool should_copy_tensor_memory = false);
63
+
64
+ // Parse a mobile::Module from raw bytes.
65
+ //
66
+ // This function does steps 2+3 described above.
67
+ //
68
+ // The returned Module holds a reference to `data`, which must be aligned to
69
+ // kFlatbufferDataAlignmentBytes.
70
+ //
71
+ // If you do not want the Module to hold a reference to `data`, see the raw
72
+ // pointer overload of this function.
73
+ TORCH_API mobile::Module parse_and_initialize_mobile_module(
74
+ std::shared_ptr<char> data,
75
+ size_t size, // of `data`, in bytes.
76
+ std::optional<at::Device> device = std::nullopt,
77
+ ExtraFilesMap* extra_files = nullptr);
78
+
79
+ // Parse a mobile::Module from raw bytes, also returning JIT-related metadata.
80
+ //
81
+ // This is the same as parse_and_initialize_mobile_module() except that it also
82
+ // extracts JIT source files and constants. Can be used to construct a
83
+ // jit::Module.
84
+ TORCH_API mobile::Module parse_and_initialize_mobile_module_for_jit(
85
+ void* data,
86
+ size_t size, // of `data`, in bytes.
87
+ ExtraFilesMap& jit_sources,
88
+ std::vector<IValue>& jit_constants,
89
+ std::optional<at::Device> device = std::nullopt,
90
+ ExtraFilesMap* extra_files = nullptr);
91
+
92
+ // Load a mobile::Module from a filepath.
93
+ //
94
+ // This function does steps 1+2+3 described above.
95
+ //
96
+ // We need to have this as a convienience because Python API will need to wrap
97
+ // this. C++ clients should use one of the versions of
98
+ // parse_and_initialize_mobile_module() so they can manage the raw data more
99
+ // directly.
100
+ TORCH_API mobile::Module load_mobile_module_from_file(
101
+ const std::string& filename,
102
+ std::optional<at::Device> device = std::nullopt,
103
+ ExtraFilesMap* extra_files = nullptr);
104
+
105
+ TORCH_API uint64_t get_bytecode_version(std::istream& in);
106
+ TORCH_API uint64_t get_bytecode_version(const std::string& filename);
107
+ TORCH_API uint64_t get_bytecode_version_from_bytes(char* flatbuffer_content);
108
+
109
+ TORCH_API mobile::ModuleInfo get_module_info_from_flatbuffer(
110
+ char* flatbuffer_content);
111
+
112
+ // The methods below are less efficient because it need to read the stream in
113
+ // its entirity to a buffer
114
+ TORCH_API mobile::Module load_mobile_module_from_stream_with_copy(
115
+ std::istream& in,
116
+ std::optional<at::Device> device = std::nullopt,
117
+ ExtraFilesMap* extra_files = nullptr);
118
+
119
+ TORCH_API mobile::Module parse_flatbuffer_no_object(
120
+ std::shared_ptr<char> data,
121
+ size_t size,
122
+ std::optional<at::Device> device);
123
+
124
+ TORCH_API mobile::Module parse_and_initialize_mobile_module(
125
+ void* data,
126
+ size_t,
127
+ std::optional<at::Device>,
128
+ ExtraFilesMap* extra_files,
129
+ bool should_copy_tensor_memory);
130
+
131
+ // no op, TODO(qihan) delete
132
+ TORCH_API bool register_flatbuffer_loader();
133
+
134
+ } // namespace torch::jit
vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/mobile/frame.h ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <cstddef>
4
+
5
+ #include <torch/csrc/jit/mobile/code.h>
6
+ #include <optional>
7
+
8
+ namespace torch::jit::mobile {
9
+
10
+ class Frame {
11
+ public:
12
+ explicit Frame(const Code& code) : code_(code) {}
13
+ const Code& getCode() const {
14
+ return code_;
15
+ }
16
+
17
+ void step() {
18
+ pc_++;
19
+ }
20
+
21
+ void jump(size_t n) {
22
+ pc_ += n;
23
+ }
24
+
25
+ size_t getPC() const {
26
+ return pc_;
27
+ }
28
+
29
+ const Instruction& getInstruction() const {
30
+ return code_.instructions_.at(pc_);
31
+ }
32
+
33
+ std::optional<int64_t> getDebugHandle() const {
34
+ return getDebugHandle(pc_);
35
+ }
36
+
37
+ std::optional<int64_t> getDebugHandle(size_t pc) const {
38
+ if (pc >= code_.debug_handles_.size()) {
39
+ return {};
40
+ }
41
+ return code_.debug_handles_[pc];
42
+ }
43
+
44
+ private:
45
+ const Code& code_;
46
+ size_t pc_{0};
47
+ };
48
+
49
+ } // namespace torch::jit::mobile
vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/mobile/function.h ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <vector>
4
+
5
+ #include <ATen/core/function.h>
6
+ #include <ATen/core/function_schema.h>
7
+ #include <ATen/core/ivalue.h>
8
+ #include <torch/csrc/jit/mobile/code.h>
9
+
10
+ namespace torch::jit {
11
+ enum OpCode : uint8_t;
12
+ struct Instruction;
13
+ struct OperatorString;
14
+
15
+ namespace mobile {
16
+
17
+ class TORCH_API Function : public torch::jit::Function {
18
+ public:
19
+ explicit Function(c10::QualifiedName name);
20
+ Function(
21
+ c10::QualifiedName name,
22
+ Code code,
23
+ std::optional<c10::FunctionSchema> schema);
24
+ void run(Stack& stack) override;
25
+ at::IValue operator()(Stack& stack);
26
+ void ensure_defined() override {}
27
+ size_t num_inputs() const override;
28
+ const c10::QualifiedName& qualname() const override;
29
+ bool call(Stack&, c10::function_ref<void(const mobile::Code&)>) override;
30
+
31
+ // NOTE: the APIs below is dangerous: if you call append_instruction with
32
+ // dbg_handle and then call it without; then the dbg_handle will become
33
+ // misaligned. Therefore only use ONE variant at time.
34
+ void append_instruction(OpCode op, int64_t X, int64_t N, int64_t dbg_handle);
35
+ void append_instruction(OpCode op, int64_t X, int64_t N);
36
+ void append_operator(
37
+ const std::string& name,
38
+ const std::string& overload_name,
39
+ const std::optional<int>& num_specified_args);
40
+ void append_constant(const c10::IValue& constant);
41
+ void append_type(const c10::TypePtr& type);
42
+ void append_function(mobile::Function& func);
43
+
44
+ void set_register_size(size_t size);
45
+
46
+ int64_t get_debug_handle(size_t pc) const;
47
+ const Code& get_code() const;
48
+ Code& get_code();
49
+
50
+ torch::jit::Function& setSchema(c10::FunctionSchema schema) override;
51
+ bool hasSchema() const;
52
+ const c10::FunctionSchema& getSchema() const override;
53
+
54
+ // Returns the debug handle corresponding to where the execution
55
+ // is halted due to exception.
56
+ // If no corresponding debug handle is found then -1 is returned.
57
+ const std::vector<int64_t>& getExceptionDebugHandles() const;
58
+ static Function& registerFunc(
59
+ const std::string& qualified_name,
60
+ const std::vector<Instruction>& instructions,
61
+ const std::vector<c10::IValue>& constants,
62
+ const std::vector<c10::TypePtr>& types,
63
+ const size_t register_size);
64
+
65
+ // if not initialize, initialize by loading operators.
66
+ // return true of all op loaded, return false if some op is not found
67
+ // in the current runtime. Then, the ops that did not found will be filled
68
+ // in unsupported_op_names
69
+ bool initialize_operators(bool should_check_operators);
70
+
71
+ private:
72
+ c10::QualifiedName name_;
73
+ Code code_;
74
+ std::optional<c10::FunctionSchema> schema_; // (byte-code version 4+)
75
+ };
76
+
77
+ std::optional<std::function<void(Stack&)>> makeOperatorFunction(
78
+ const c10::OperatorName& opname,
79
+ std::optional<int> num_specified_args);
80
+
81
+ TORCH_API std::string operator_str(const c10::OperatorName& opname);
82
+
83
+ } // namespace mobile
84
+ } // namespace torch::jit
vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/mobile/import.h ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <torch/csrc/jit/mobile/module.h>
3
+ #include <torch/csrc/jit/mobile/parse_operators.h>
4
+
5
+ #include <istream>
6
+ #include <memory>
7
+
8
+ #include <caffe2/serialize/file_adapter.h>
9
+
10
+ namespace torch::jit {
11
+ using caffe2::serialize::ReadAdapterInterface;
12
+ using ExtraFilesMap = std::unordered_map<std::string, std::string>;
13
+
14
+ constexpr const char* kArchiveNameBytecode = "bytecode";
15
+ constexpr const char* kArchiveNameConstants = "constants";
16
+ constexpr const char* kArchiveNameVersion = "version";
17
+
18
+ // The family of methods below load a serialized Mobile Module
19
+ // into a mobile::Module object.
20
+ TORCH_API mobile::Module _load_for_mobile(
21
+ std::istream& in,
22
+ std::optional<at::Device> device,
23
+ ExtraFilesMap& extra_file,
24
+ uint64_t module_load_options = kDefaultMobileLoadOptions);
25
+
26
+ TORCH_API mobile::Module _load_for_mobile(
27
+ const std::string& filename,
28
+ std::optional<at::Device> device,
29
+ ExtraFilesMap& extra_files);
30
+
31
+ TORCH_API mobile::Module _load_for_mobile(
32
+ std::unique_ptr<ReadAdapterInterface> rai,
33
+ std::optional<c10::Device> device,
34
+ ExtraFilesMap& extra_files,
35
+ uint64_t module_load_options = kDefaultMobileLoadOptions);
36
+
37
+ TORCH_API mobile::Module _load_for_mobile(
38
+ const std::string& filename,
39
+ std::optional<at::Device> device,
40
+ ExtraFilesMap& extra_files,
41
+ uint64_t module_load_options);
42
+
43
+ TORCH_API mobile::Module _load_for_mobile(
44
+ std::istream& in,
45
+ std::optional<at::Device> device = std::nullopt);
46
+
47
+ TORCH_API mobile::Module _load_for_mobile(
48
+ const std::string& filename,
49
+ std::optional<at::Device> device = std::nullopt);
50
+
51
+ TORCH_API mobile::Module _load_for_mobile(
52
+ std::unique_ptr<ReadAdapterInterface> rai,
53
+ std::optional<c10::Device> device = std::nullopt);
54
+
55
+ /**
56
+ * Load only the contents of the "extra/" files whose names are
57
+ * passed in the map (extra_files). Populate the corresponding values
58
+ * with the contents of those files. Do not attempt to load the entire
59
+ * model, and stop once the extra files have been extracted.
60
+ *
61
+ * This API is needed to be able to load GPU models on linux CPU
62
+ * machines and extract only the extra files so that we can inspect
63
+ * the metadata that was added to the .ptl archive when it was
64
+ * generated.
65
+ *
66
+ */
67
+ void _load_extra_only_for_mobile(
68
+ const std::string& filename,
69
+ std::optional<at::Device> device,
70
+ ExtraFilesMap& extra_files);
71
+
72
+ // Currently used by both mobile/import.cpp and model_compatibility.cpp.
73
+ // Should be removed after model_compatibility.cpp start using simplified
74
+ // version type_resolver and obj_loader.
75
+ at::TypePtr resolveTypeNameMobile(
76
+ const c10::QualifiedName& qn,
77
+ const std::shared_ptr<CompilationUnit>& compilation_unit);
78
+ c10::StrongTypePtr typeResolverMobile(
79
+ const c10::QualifiedName& qn,
80
+ const std::shared_ptr<CompilationUnit>& compilation_unit);
81
+ c10::intrusive_ptr<c10::ivalue::Object> objLoaderMobile(
82
+ const at::StrongTypePtr& type,
83
+ const at::IValue& input,
84
+ mobile::CompilationUnit& mobile_compilation_unit);
85
+
86
+ // Given a reader, which has access to a model file,
87
+ // return true if there exists tensors in `bytecode` archive
88
+ bool isTensorInBytecodeArchive(
89
+ caffe2::serialize::PyTorchStreamReader& stream_reader);
90
+
91
+ namespace mobile {
92
+
93
+ /**
94
+ * Given a torch::jit::mobile::Module, return a set of operator names
95
+ * (with overload name) that are used by any method in this mobile
96
+ * Mobile. This method runs through the bytecode for all methods
97
+ * in the specified model (module), and extracts all the root
98
+ * operator names. Root operators are operators that are called
99
+ * directly by the model (as opposed to non-root operators, which
100
+ * may be called transitively by the root operators).
101
+ *
102
+ */
103
+ TORCH_API std::set<std::string> _export_operator_list(
104
+ torch::jit::mobile::Module& module);
105
+
106
+ } // namespace mobile
107
+
108
+ } // namespace torch::jit
vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/mobile/import_export_common.h ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ /**
4
+ * @file
5
+ * Declarations shared between import_data.cpp and export_data.cpp
6
+ */
7
+
8
+ namespace torch::jit::mobile::internal {
9
+ /**
10
+ * The name of the mobile::Module attribute which contains saved parameters, as
11
+ * a Dict of names to Tensors. Only used for Flatbuffer serialization.
12
+ */
13
+ // NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays,modernize-avoid-c-arrays)
14
+ constexpr char kSavedParametersAttributeName[] = "data";
15
+ } // namespace torch::jit::mobile::internal
vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/mobile/method.h ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/ivalue.h>
4
+ #include <torch/csrc/jit/mobile/function.h>
5
+
6
+ namespace torch::jit::mobile {
7
+
8
+ class Module;
9
+
10
+ struct TORCH_API Method {
11
+ Method(const Module* owner, Function* function);
12
+
13
+ void run(Stack& stack) const;
14
+ void run(Stack&& stack) const {
15
+ run(stack);
16
+ }
17
+
18
+ c10::IValue operator()(std::vector<c10::IValue> stack) const;
19
+
20
+ const std::string& name() const {
21
+ return function_->name();
22
+ }
23
+
24
+ int64_t get_debug_handle(size_t pc) const {
25
+ return function_->get_debug_handle(pc);
26
+ }
27
+
28
+ Function& function() const {
29
+ return *function_;
30
+ }
31
+
32
+ private:
33
+ // Methods are uniquely owned by a single module.
34
+ // This raw pointer allows referencing the module
35
+ const Module* owner_;
36
+
37
+ // Underlying unbound function
38
+ Function* function_;
39
+ };
40
+
41
+ } // namespace torch::jit::mobile
vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/mobile/module.h ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <ATen/core/jit_type.h>
3
+ #include <torch/csrc/jit/mobile/debug_info.h>
4
+ #include <torch/csrc/jit/mobile/function.h>
5
+ #include <torch/csrc/jit/mobile/method.h>
6
+ #include <torch/csrc/jit/mobile/quantization.h>
7
+
8
+ #include <utility>
9
+
10
+ namespace torch::jit::mobile {
11
+ using Stack = std::vector<c10::IValue>;
12
+
13
+ // A CompilationUnit object is the one that gets executed by the lite
14
+ // interpreter.
15
+ //
16
+ // A CompilationUnit object contains a list of Method Objects. These are methods
17
+ // that appear in the original PyTorch Model. These method correspond to Python
18
+ // member functions of the Model class.
19
+ //
20
+ // Methods in turn contain a Function, and a back-pointer to the Module that
21
+ // owns this Method instance.
22
+ //
23
+ // A Function contains a Code Object (code_) which is defined in interpreter.h
24
+ //
25
+ // A Code object contains the following:
26
+ //
27
+ // std::vector<Instruction> instructions_;
28
+ // std::vector<c10::OperatorName> op_names_;
29
+ // std::vector<std::function<void(Stack&)>> operators_;
30
+ // std::vector<c10::IValue> constants_;
31
+ // std::vector<c10::TypePtr> types_;
32
+ // size_t register_size_; // Aggregated output size.
33
+ //
34
+ class CompilationUnit {
35
+ public:
36
+ void register_function(std::unique_ptr<Function> fn);
37
+ std::vector<std::unique_ptr<Function>>& methods() {
38
+ return methods_;
39
+ }
40
+ const std::vector<std::unique_ptr<Function>>& methods() const {
41
+ return methods_;
42
+ }
43
+ Function* find_function(const c10::QualifiedName& qn);
44
+ const Function* find_function(const c10::QualifiedName& qn) const;
45
+
46
+ void unsafeRemoveFunction(const int64_t index) {
47
+ methods_.erase(methods_.begin() + index);
48
+ }
49
+
50
+ private:
51
+ std::vector<std::unique_ptr<Function>> methods_;
52
+ };
53
+
54
+ // A Torch Mobile Module is a representation of the model (trained in case
55
+ // of inference). A Mobile Module contains
56
+ //
57
+ // 1. data (object_)
58
+ // 2. metadata (optional) about the model (metadata_ from the metadata.pkl
59
+ // file added after training)
60
+ // 3. Compilation Unit (cu_)
61
+ //
62
+ class TORCH_API Module {
63
+ public:
64
+ Module(
65
+ c10::intrusive_ptr<c10::ivalue::Object> object,
66
+ std::shared_ptr<CompilationUnit> cu)
67
+ : object_(std::move(object)), cu_(std::move(cu)) {}
68
+ Module() = default;
69
+ Method get_method(const std::string& method_name) const;
70
+ template <typename... Types>
71
+ c10::IValue run_method(const std::string& method_name, Types&&... args) {
72
+ return get_method(method_name)({IValue(std::forward<Types>(args))...});
73
+ }
74
+ c10::IValue forward(std::vector<c10::IValue> inputs) {
75
+ return get_method("forward")(std::move(inputs));
76
+ }
77
+ std::optional<Method> find_method(const std::string& basename) const;
78
+
79
+ const std::string name() const {
80
+ return object_->name();
81
+ }
82
+ const std::vector<at::IValue>& slots() const {
83
+ return object_->slots();
84
+ }
85
+ const c10::intrusive_ptr<c10::ivalue::Object> _ivalue() const {
86
+ return object_;
87
+ }
88
+ const std::vector<at::Tensor> parameters() const;
89
+ const std::map<std::string, at::Tensor> named_parameters() const;
90
+ std::string get_forward_method_debug_info(int64_t debug_handle) const;
91
+ std::string getModuleHierarchy(const int64_t debug_handle) const;
92
+ std::string getCallStack(const int64_t debug_handle) const;
93
+ /// Enables "training" mode.
94
+ void train(bool on = true);
95
+ /// Calls train(false) to enable "eval" mode.
96
+ void eval() {
97
+ train(/*on=*/false);
98
+ }
99
+ /// True if the module is in training mode.
100
+ bool is_training() const;
101
+ const std::unordered_map<std::string, std::string> getMetadata() const {
102
+ return metadata_;
103
+ }
104
+ void setMetadata(
105
+ const std::unordered_map<std::string, std::string>& metadata) {
106
+ metadata_ = metadata;
107
+ }
108
+ const std::vector<Method> get_methods() const;
109
+
110
+ c10::IValue attr(const std::string& name, c10::IValue or_else) const {
111
+ if (auto r = object_->type()->findAttributeSlot(name)) {
112
+ return object_->getSlot(*r);
113
+ }
114
+ if (auto r = object_->type()->findConstantSlot(name)) {
115
+ return object_->type()->getConstant(*r);
116
+ }
117
+ return or_else;
118
+ }
119
+
120
+ void setDebugTable(MobileDebugTable&& debug_table) {
121
+ debug_table_ = std::move(debug_table);
122
+ }
123
+ const MobileDebugTable& getDebugTable() const {
124
+ return debug_table_;
125
+ }
126
+
127
+ void setHasDebugHandles(bool has_debug_handles) {
128
+ has_debug_handles_ = has_debug_handles;
129
+ }
130
+
131
+ bool hasDebugHandles() const {
132
+ return has_debug_handles_;
133
+ }
134
+
135
+ const CompilationUnit& compilation_unit() const {
136
+ return *cu_;
137
+ }
138
+
139
+ void set_delete_memory(std::shared_ptr<char> delete_mem) {
140
+ mem_to_delete_ = std::move(delete_mem);
141
+ }
142
+
143
+ void set_min_operator_version(int64_t version) {
144
+ min_operator_version_ = version;
145
+ }
146
+
147
+ int64_t min_operator_version() const {
148
+ return min_operator_version_;
149
+ }
150
+
151
+ void set_bytecode_version(int64_t version) {
152
+ bytecode_version_ = version;
153
+ }
154
+
155
+ int64_t bytecode_version() const {
156
+ return bytecode_version_;
157
+ }
158
+
159
+ private:
160
+ friend class quantization::PTQQuanizationHelper;
161
+
162
+ bool compareMethodSchemas(
163
+ const std::string& name_1,
164
+ const std::string& name_2);
165
+
166
+ void unsafeRemoveMethod(const std::string& basename);
167
+
168
+ void unsafeCopyMethod(
169
+ const std::string& new_method_name,
170
+ const Function& to_be_copied);
171
+
172
+ c10::intrusive_ptr<c10::ivalue::Object> object_;
173
+ std::unordered_map<std::string, std::string> metadata_;
174
+ std::shared_ptr<CompilationUnit> cu_;
175
+ MobileDebugTable debug_table_;
176
+ bool has_debug_handles_ = false;
177
+ int64_t min_operator_version_ = 4;
178
+ int64_t bytecode_version_ = 4;
179
+
180
+ // Extra handle for the module to delete when itself is deleted
181
+ std::shared_ptr<char> mem_to_delete_;
182
+ };
183
+
184
+ struct TORCH_API ModuleInfo {
185
+ uint64_t bytecode_version;
186
+ uint64_t operator_version;
187
+ std::unordered_map<std::string, int> opname_to_num_args;
188
+ std::unordered_set<std::string> function_names;
189
+ std::unordered_set<std::string> type_names;
190
+ };
191
+ TORCH_API ModuleInfo get_module_info(const mobile::Module& module);
192
+
193
+ } // namespace torch::jit::mobile
vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/mobile/observer.h ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/util/ThreadLocalDebugInfo.h>
4
+ #include <string>
5
+ #include <unordered_map>
6
+ #include <vector>
7
+
8
+ namespace torch {
9
+
10
+ class MobileDebugInfo : public c10::DebugInfoBase {
11
+ public:
12
+ const std::string& getModelName() {
13
+ return model_name_;
14
+ }
15
+
16
+ void setModelName(const std::string& model_name) {
17
+ model_name_ = model_name;
18
+ }
19
+
20
+ const std::string& getMethodName() {
21
+ return method_name_;
22
+ }
23
+
24
+ void setMethodName(const std::string& method_name) {
25
+ method_name_ = method_name;
26
+ }
27
+
28
+ size_t getOpIdx() {
29
+ return op_idx_;
30
+ }
31
+
32
+ void setOpIdx(size_t op_idx) {
33
+ op_idx_ = op_idx;
34
+ }
35
+
36
+ private:
37
+ std::string model_name_;
38
+ std::string method_name_;
39
+ // TODO: Kimish
40
+ // If we launch a thread such as for at::launch, interepter continuation
41
+ // and if the caching allocator is enabled in the base thread
42
+ // then, in order to propagate this information, that is caching allocator
43
+ // is enabled, across thread boundaries we can use the mechanism provided
44
+ // by ThreadLocalDebugInfo
45
+ // Once the thread local MobileDebugInfo is accessible in the launched
46
+ // thread, it can be accessed in that thread and that thread can set
47
+ // its own thread local CachingAllocatorInfo.
48
+ // However, we cannot expect every launched thread to extract and set
49
+ // its own thread local copy of CachingAllocatorInfo.
50
+ // But this can be done in lite interpreter, where in the run method
51
+ // it can do info =
52
+ // c10::ThreadLocalDebugInfo::get(c10::DebugInfoKind::MOBILE_RUNTIME_INFO))
53
+ // .get_caching_allocator_info();
54
+ // GetThreadLocalCachingAllocatorInfo() = info;
55
+ // Other option is to have MobileDebugInfo itself be the place where thread
56
+ // local copy of CachingAllocatorInfo is stored. Then
57
+ // DefaultMobileCPUAllocator inspects this to decide if to use
58
+ // CachingAllocator. However, current lite interpreter does not support FORK,
59
+ // thus from the run method of lite interpreter we are not really gonna launch
60
+ // another instance of lite interpreter in a different thread. So for now not
61
+ // getting bothered about passing CachingAllocatorInfo across thread
62
+ // boundaries. c10::CachingAllocatorInfo caching_allocator_info;
63
+ size_t op_idx_ = 0;
64
+ };
65
+
66
+ class MobileModuleObserver {
67
+ public:
68
+ virtual ~MobileModuleObserver() = default;
69
+
70
+ virtual void onEnterRunMethod(const int32_t) {}
71
+ virtual void onExitRunMethod(
72
+ const std::unordered_map<std::string, std::string>&,
73
+ const std::string&,
74
+ const int32_t) {}
75
+ virtual void onFailRunMethod(
76
+ const std::unordered_map<std::string, std::string>&,
77
+ const std::string&,
78
+ const int32_t,
79
+ const char*) {}
80
+ virtual void onEnterLoadModel(const int32_t) {}
81
+ virtual void onExitLoadModel(
82
+ const int32_t,
83
+ const std::unordered_map<std::string, std::string>&) {
84
+ } // key: filename, value: file content
85
+ virtual void onFailLoadModel(const int32_t, const char*) {}
86
+ virtual void onFailLoadModel(
87
+ const int32_t,
88
+ const char*,
89
+ const std::unordered_map<std::string, std::string>&) {}
90
+ virtual std::vector<std::string> getDefaultExtraFiles() = 0;
91
+ virtual std::unordered_map<std::string, std::string> processMetadataFromExtra(
92
+ const std::unordered_map<std::string, std::string>&) = 0;
93
+ };
94
+
95
+ class MobileObserverConfig {
96
+ public:
97
+ void setModuleObserver(std::unique_ptr<MobileModuleObserver> reporter) {
98
+ module_observer_ = std::move(reporter);
99
+ }
100
+ MobileModuleObserver* getModuleObserver() {
101
+ return module_observer_.get();
102
+ }
103
+
104
+ private:
105
+ std::unique_ptr<MobileModuleObserver> module_observer_;
106
+ };
107
+
108
+ MobileObserverConfig& observerConfig();
109
+
110
+ } // namespace torch
vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/mobile/prim_ops_registery.h ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/ivalue.h>
4
+ #include <functional>
5
+ #include <vector>
6
+
7
+ namespace torch::jit::mobile {
8
+
9
+ using Stack = std::vector<c10::IValue>;
10
+
11
+ void registerPrimOpsFunction(
12
+ const std::string& name,
13
+ const std::function<void(Stack&)>& fn);
14
+
15
+ bool hasPrimOpsFn(const std::string& name);
16
+
17
+ std::function<void(Stack&)>& getPrimOpsFn(const std::string& name);
18
+
19
+ class prim_op_fn_register {
20
+ public:
21
+ prim_op_fn_register(
22
+ const std::string& name,
23
+ const std::function<void(Stack&)>& fn) {
24
+ registerPrimOpsFunction(name, fn);
25
+ }
26
+ };
27
+
28
+ } // namespace torch::jit::mobile
vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/mobile/profiler_edge.h ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <torch/csrc/autograd/profiler_kineto.h>
3
+ #include <torch/csrc/jit/mobile/module.h>
4
+
5
+ namespace torch::jit::mobile {
6
+
7
+ // If we dont have kineto available then edge profiler does not
8
+ // work since it relies on Kineto
9
+ #ifdef USE_KINETO
10
+ class TORCH_API KinetoEdgeCPUProfiler {
11
+ public:
12
+ // This profiler only profiles KINETO events
13
+ // No GPU_FALLBACK or NVTX
14
+ /*
15
+ * @param m is the instance of mobile Module which is being profiled.
16
+ * Note that this implies that KinetoEdgeCPUProfiler can be used
17
+ * to profile specific Module (see usage below), unliked ProfilerKineto
18
+ * which can profile pytorch runtime in arbitrary scope.
19
+ * @param fname is the name of the file to which chrome trace is written.
20
+ * @param report_input_shapes: whether to record shapes of op's inputs.
21
+ * @param with_stack: whether to record model's python stacktrace for the op.
22
+ * @param with_flops: whether to report flops corresponding to the op.
23
+ * @param with_modules: whether to report original python module
24
+ * hierarchy to which the op belongs.
25
+ * @param events
26
+ * @param adjust_vulkan_timestamps: whether to adjust vulkan timestamps from
27
+ * query pool to align with cpu event times
28
+ *
29
+ * Usage pattern for this profiler must be as follows:
30
+ *
31
+ * {
32
+ * KinetoEdgeCPUProfiler(m, filename, args);
33
+ * m.forward(...);
34
+ * }
35
+ *
36
+ * The reason being that KinetoEdgeCPUProfiler has a dependency on Module
37
+ * and thus it must not outlive it.
38
+ *
39
+ * Thus, when KinetoEdgeCPUProfiler is used as RAII to do profiling
40
+ * within certain scope. In that scope, the captured reference to
41
+ * Module will outlive KinetoEdgeCPUProfiler. This is gauranteed because
42
+ * KinetoEdgeCPUProfiler must be constructed later than Module, on stack.
43
+ *
44
+ * An example of the anti-pattern and wrong usage is:
45
+ *
46
+ * std::shared_ptr<KinetoMobileCPUProfiler> profiler(m, filename, args);
47
+ * m.forward(...);
48
+ *
49
+ * Since KinetoEdgeCPUProfiler object would then be constructed on heap
50
+ * with its lifetime managed manually or via smart pointers.
51
+ */
52
+ KinetoEdgeCPUProfiler(
53
+ const torch::jit::mobile::Module& m,
54
+ const std::string& fname,
55
+ const bool report_input_shapes = false,
56
+ const bool profile_memory = false,
57
+ const bool with_stack = false,
58
+ const bool with_flops = false,
59
+ const bool with_modules = false,
60
+ std::vector<std::string> events = {},
61
+ const bool adjust_vulkan_timestamps = false);
62
+
63
+ const std::unique_ptr<torch::autograd::profiler::ProfilerResult>&
64
+ disableProfiler();
65
+ const std::unique_ptr<torch::autograd::profiler::ProfilerResult>&
66
+ getProfilerResult();
67
+ void recordBackendEvent(
68
+ const int64_t start_time_us,
69
+ const int64_t end_time_us,
70
+ const int64_t debug_handle,
71
+ const std::string& event_name,
72
+ const std::string& backend_name);
73
+ void recordBackendMemoryEvent(
74
+ void* ptr,
75
+ int64_t alloc_size,
76
+ size_t total_allocated,
77
+ size_t total_reserved,
78
+ c10::Device device);
79
+
80
+ ~KinetoEdgeCPUProfiler();
81
+
82
+ private:
83
+ /*
84
+ * We store a reference to Module to make such dependency explicit, since
85
+ * a Module reference is already stored in a functor.
86
+ */
87
+ const mobile::Module& m_;
88
+ std::string trace_file_name_;
89
+ std::unique_ptr<torch::autograd::profiler::ProfilerResult> profiler_result_;
90
+ };
91
+
92
+ TORCH_API KinetoEdgeCPUProfiler* getCurrentEdgeProfiler();
93
+
94
+ #define RECORD_BACKEND_EVENT_TO_EDGE_PROFILER( \
95
+ start_time_us, end_time_us, debug_handle, event_name, backend_name) \
96
+ if (mobile::getCurrentEdgeProfiler()) { \
97
+ mobile::getCurrentEdgeProfiler()->recordBackendEvent( \
98
+ start_time_us, end_time_us, debug_handle, event_name, backend_name); \
99
+ }
100
+
101
+ #define RECORD_BACKEND_MEMORY_EVENT_TO_EDGE_PROFILER( \
102
+ ptr, alloc_size, total_allocated, total_reserved, device) \
103
+ if (mobile::getCurrentEdgeProfiler()) { \
104
+ mobile::getCurrentEdgeProfiler()->recordBackendMemoryEvent( \
105
+ ptr, alloc_size, total_allocated, total_reserved, device); \
106
+ }
107
+ #else
108
+
109
+ #define RECORD_BACKEND_EVENT_TO_EDGE_PROFILER( \
110
+ start_time_us, end_time_us, debug_handle, event_name, backend_name)
111
+
112
+ #define RECORD_BACKEND_MEMORY_EVENT_TO_EDGE_PROFILER( \
113
+ ptr, alloc_size, total_allocated, total_reserved, device)
114
+ #endif
115
+ } // namespace torch::jit::mobile
vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/mobile/register_ops_common_utils.h ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/Context.h>
4
+ #include <ATen/NativeFunctions.h>
5
+ #include <ATen/core/ivalue.h>
6
+ #include <ATen/core/stack.h>
7
+ #include <torch/csrc/jit/runtime/jit_exception.h>
8
+ #include <torch/csrc/jit/runtime/vararg_functions.h>
9
+
10
+ namespace torch::jit {
11
+
12
+ inline void noop(Stack& n) {}
13
+
14
+ int64_t normalizeIndex(int64_t idx, int64_t list_size);
15
+
16
+ // reference function THPVariable_to in python_variable_methods.cpp
17
+ static C10_UNUSED at::Tensor to_dispatch(
18
+ at::Tensor self,
19
+ std::optional<at::Device> device,
20
+ std::optional<at::ScalarType> scalarType,
21
+ bool non_blocking,
22
+ bool copy) {
23
+ if (device && device->is_cuda()) {
24
+ at::globalContext().lazyInitCUDA();
25
+ }
26
+ if (!device && !scalarType && !copy) {
27
+ return self;
28
+ } else if (!device) {
29
+ return self.to(*scalarType, non_blocking, copy);
30
+ } else if (!scalarType) {
31
+ return self.to(*device, non_blocking, copy);
32
+ } else {
33
+ return self.to(*device, *scalarType, non_blocking, copy);
34
+ }
35
+ }
36
+
37
+ // Convert the tensor pointed to by \p data to a nested list. \p dim is the
38
+ // number of dimensions in the tensor and \p cur_dim is the dimension being
39
+ // processed by the current invocation. \p ty is the expected output IR type of
40
+ // the operation. \p is the scalar type of \p data. \p sizes and \p strides are
41
+ // the sizes and strides of the tensor operand and \p element_size is the size
42
+ // in bytes of one tensor element.
43
+ IValue tensorToListRecursive(
44
+ char* data,
45
+ int64_t cur_dim,
46
+ int64_t num_tensor_dims,
47
+ at::TypePtr ty,
48
+ at::ScalarType scalar_ty,
49
+ at::IntArrayRef sizes,
50
+ at::IntArrayRef strides,
51
+ size_t element_size);
52
+
53
+ } // namespace torch::jit
vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/mobile/type_parser.h ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/dynamic_type.h>
4
+ #include <ATen/core/jit_type.h>
5
+ #include <unordered_set>
6
+
7
+ namespace c10 {
8
+
9
+ class TORCH_API TypeParser {
10
+ public:
11
+ explicit TypeParser(std::string pythonStr);
12
+ explicit TypeParser(std::vector<std::string>& pythonStrs);
13
+
14
+ TypePtr parse();
15
+ std::vector<TypePtr> parseList();
16
+ static const std::unordered_set<std::string>& getNonSimpleType();
17
+ static const std::unordered_set<std::string>& getCustomType();
18
+ std::unordered_set<std::string> getContainedTypes();
19
+
20
+ private:
21
+ TypePtr parseNamedTuple(const std::string& qualified_name);
22
+ TypePtr parseCustomType();
23
+ TypePtr parseTorchbindClassType();
24
+ TypePtr parseNonSimple(const std::string& token);
25
+
26
+ void expect(const char* s);
27
+ void expectChar(char c);
28
+ template <typename T>
29
+ TypePtr parseSingleElementType();
30
+
31
+ void lex();
32
+
33
+ std::string next();
34
+ c10::string_view nextView();
35
+ void advance();
36
+ C10_NODISCARD c10::string_view cur() const;
37
+
38
+ std::string pythonStr_;
39
+ size_t start_;
40
+ c10::string_view next_token_;
41
+
42
+ // Used for parsing string list
43
+ std::vector<std::string> pythonStrs_;
44
+ std::unordered_map<std::string, c10::TypePtr> str_type_ptr_map_;
45
+
46
+ // Store all contained types when parsing a string
47
+ std::unordered_set<std::string> contained_types_;
48
+ };
49
+
50
+ TORCH_API TypePtr parseType(const std::string& pythonStr);
51
+
52
+ TORCH_API std::vector<TypePtr> parseType(std::vector<std::string>& pythonStr);
53
+
54
+ } // namespace c10
vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/mobile/upgrader_mobile.h ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/ivalue_inl.h>
4
+
5
+ #include <torch/csrc/jit/mobile/code.h>
6
+ #include <torch/csrc/jit/mobile/function.h>
7
+ #include <torch/csrc/jit/serialization/import_export_functions.h>
8
+ #include <string>
9
+ #include <unordered_map>
10
+ #include <vector>
11
+
12
+ namespace torch::jit {
13
+ struct Instruction;
14
+ struct Upgrader {
15
+ int min_version;
16
+ int max_version;
17
+ std::string upgrader_name;
18
+ int index;
19
+ };
20
+
21
+ // From operator_versions.yaml
22
+ TORCH_API const std::unordered_map<std::string, std::vector<Upgrader>>
23
+ getOperatorVersionMapForMobile();
24
+
25
+ struct OperatorString {
26
+ const std::string name;
27
+ const std::string overload_name;
28
+ const std::optional<int> num_specified_args;
29
+ };
30
+
31
+ struct ByteCodeFunctionWithOperator {
32
+ mobile::Function& function;
33
+ std::vector<OperatorString> operators;
34
+ };
35
+
36
+ TORCH_API const std::vector<ByteCodeFunctionWithOperator>&
37
+ getUpgraderBytecodeList();
38
+
39
+ } // namespace torch::jit
vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/init.h ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <torch/csrc/utils/pybind.h>
4
+
5
+ namespace torch::jit {
6
+
7
+ void initJITBindings(PyObject* module);
8
+
9
+ } // namespace torch::jit
vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/pybind.h ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <torch/csrc/python_headers.h>
4
+
5
+ #include <ATen/core/ivalue.h>
6
+ #include <ATen/core/symbol.h>
7
+ #include <c10/util/irange.h>
8
+ #include <torch/csrc/DynamicTypes.h>
9
+ #include <torch/csrc/THP.h>
10
+ #include <torch/csrc/autograd/variable.h>
11
+ #include <torch/csrc/jit/frontend/tracer.h>
12
+ #include <torch/csrc/jit/python/pybind_utils.h>
13
+ #include <torch/csrc/utils/pybind.h>
14
+
15
+ #include <pybind11/functional.h>
16
+ #include <pybind11/pybind11.h>
17
+ #include <pybind11/stl.h>
18
+
19
+ namespace py = pybind11;
20
+
21
+ namespace torch::jit {
22
+
23
+ // This is a variant of shared_ptr that "sees through" a wrapper.
24
+ // We use it to convert Value, Node, Block and node to "wrapped" Python
25
+ // values. When we destruct the C++ object, the wrapper's pointer will
26
+ // be set to 0 and any future dereferencing will throw. We need this
27
+ // because the Python objects may hang around after the C++ object
28
+ // has already been destroyed.
29
+ // This also needs the magic type_caster below, which is from the
30
+ // workaround offered in https://github.com/pybind/pybind11/issues/2751
31
+ template <typename T>
32
+ class unwrapping_shared_ptr {
33
+ static_assert(
34
+ std::is_same_v<T, torch::jit::Value> ||
35
+ std::is_same_v<T, torch::jit::Node> ||
36
+ std::is_same_v<T, torch::jit::Block>,
37
+ "unwrapping type only defined for Graph object types");
38
+
39
+ private:
40
+ std::shared_ptr<torch::jit::Wrap<T>> impl;
41
+
42
+ public:
43
+ unwrapping_shared_ptr() : impl({}) {}
44
+ explicit unwrapping_shared_ptr(T* p) : impl(p->wrap()) {
45
+ impl->clear_cb = &clear_registered_instances;
46
+ }
47
+ T* get() const {
48
+ if (!impl->elem) {
49
+ throw std::logic_error("has been invalidated");
50
+ }
51
+ return impl->elem;
52
+ }
53
+ // we need to disable the overloaded & for PyBind11 < 2.3 due.
54
+ // see https://github.com/pybind/pybind11/pull/1435
55
+ #if (PYBIND11_VERSION_MAJOR > 2) || \
56
+ ((PYBIND11_VERSION_MAJOR == 2) && (PYBIND11_VERSION_MINOR >= 3))
57
+ T** operator&() {
58
+ if (!impl->elem) {
59
+ throw std::logic_error("has been invalidated");
60
+ }
61
+ return &(impl->elem);
62
+ }
63
+ #endif
64
+ };
65
+
66
+ } // namespace torch::jit
67
+
68
+ PYBIND11_DECLARE_HOLDER_TYPE(T, torch::jit::unwrapping_shared_ptr<T>, true);
69
+
70
+ namespace pybind11::detail {
71
+
72
+ #define CREATE_UNWRAPPING_CASTER(Class) \
73
+ template <> \
74
+ struct type_caster<Class> : public type_caster_base<Class> { \
75
+ public: \
76
+ using type = Class; \
77
+ using holder_type = torch::jit::unwrapping_shared_ptr<Class>; \
78
+ \
79
+ bool load(handle src, bool convert) { \
80
+ return load_impl<type_caster<Class>>(src, convert); \
81
+ } \
82
+ \
83
+ explicit operator type*() { \
84
+ return static_cast<type*>(value); \
85
+ } \
86
+ explicit operator type&() { \
87
+ return *static_cast<type*>(value); \
88
+ } \
89
+ \
90
+ protected: \
91
+ friend class type_caster_generic; \
92
+ \
93
+ bool load_value(const value_and_holder& v_h) { \
94
+ if (v_h.holder_constructed()) { \
95
+ value = v_h.template holder<holder_type>().get(); \
96
+ return true; \
97
+ } else { \
98
+ throw cast_error( \
99
+ "Unable to cast from non-held to held instance (#Class& to Holder<#Class>)"); \
100
+ } \
101
+ } \
102
+ }
103
+
104
+ CREATE_UNWRAPPING_CASTER(torch::jit::Node);
105
+ CREATE_UNWRAPPING_CASTER(torch::jit::Value);
106
+ CREATE_UNWRAPPING_CASTER(torch::jit::Block);
107
+
108
+ #undef CREATE_UNWRAPPING_CASTER
109
+
110
+ template <>
111
+ struct type_caster<torch::jit::IValue> {
112
+ public:
113
+ // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
114
+ PYBIND11_TYPE_CASTER(torch::jit::IValue, _("IValue"));
115
+
116
+ bool load(handle src, bool) {
117
+ try {
118
+ value = torch::jit::toTypeInferredIValue(src);
119
+ return true;
120
+ } catch (std::exception& e) {
121
+ return false;
122
+ }
123
+ }
124
+
125
+ static handle cast(
126
+ torch::jit::IValue src,
127
+ return_value_policy /* policy */,
128
+ handle /* parent */) {
129
+ return torch::jit::toPyObject(std::move(src)).release();
130
+ }
131
+ };
132
+
133
+ template <>
134
+ struct type_caster<torch::jit::Symbol> {
135
+ public:
136
+ // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
137
+ PYBIND11_TYPE_CASTER(torch::jit::Symbol, _("Symbol"));
138
+
139
+ bool load(handle src, bool) {
140
+ // TODO: Is there a way to py::cast that doesn't raise an exception on
141
+ // failure? Can we catch pybind11::cast_error here instead?
142
+ std::string src_str;
143
+ try {
144
+ src_str = py::cast<std::string>(src);
145
+ } catch (std::exception& e) {
146
+ return false;
147
+ }
148
+ value = torch::jit::Symbol::fromQualString(src_str);
149
+ return true;
150
+ }
151
+
152
+ static handle cast(
153
+ torch::jit::Symbol src,
154
+ return_value_policy /* policy */,
155
+ handle /* parent */) {
156
+ return py::cast(std::string(src.toQualString()), return_value_policy::copy)
157
+ .release();
158
+ }
159
+ };
160
+
161
+ template <>
162
+ struct type_caster<torch::jit::AttributeKind> {
163
+ public:
164
+ // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
165
+ PYBIND11_TYPE_CASTER(torch::jit::AttributeKind, _("AttributeKind"));
166
+
167
+ bool load(handle src, bool) {
168
+ return false;
169
+ }
170
+
171
+ static handle cast(
172
+ torch::jit::AttributeKind src,
173
+ return_value_policy /* policy */,
174
+ handle /* parent */) {
175
+ return py::cast(
176
+ std::string(torch::jit::toString(src)),
177
+ return_value_policy::copy)
178
+ .release();
179
+ }
180
+ };
181
+
182
+ // See https://github.com/pybind/pybind11/issues/637
183
+ using ListCasterBase = pybind11::detail::
184
+ list_caster<std::vector<torch::jit::Node*>, torch::jit::Node*>;
185
+ template <>
186
+ struct type_caster<std::vector<torch::jit::Node*>> : ListCasterBase {
187
+ static handle cast(
188
+ const std::vector<torch::jit::Node*>& src,
189
+ return_value_policy,
190
+ handle parent) {
191
+ return ListCasterBase::cast(src, return_value_policy::reference, parent);
192
+ }
193
+ static handle cast(
194
+ const std::vector<torch::jit::Node*>* src,
195
+ return_value_policy pol,
196
+ handle parent) {
197
+ return cast(*src, pol, parent);
198
+ }
199
+ };
200
+
201
+ } // namespace pybind11::detail
202
+
203
+ namespace torch::jit {
204
+
205
+ static inline py::tuple tuple_tail(const py::tuple& tup) {
206
+ py::tuple r(tup.size() - 1);
207
+ for (const auto i : c10::irange(1, tup.size())) {
208
+ r[i - 1] = tup[i];
209
+ }
210
+ return r;
211
+ }
212
+
213
+ } // namespace torch::jit
vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/python_arg_flatten.h ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/util/hash.h>
4
+ #include <c10/util/irange.h>
5
+ #include <torch/csrc/autograd/variable.h>
6
+ #include <torch/csrc/jit/python/pybind.h>
7
+
8
+ #include <ATen/ATen.h>
9
+ #include <functional>
10
+ #include <tuple>
11
+ #include <vector>
12
+
13
+ namespace torch::jit::python {
14
+
15
+ struct IODescriptor {
16
+ struct VariableMetadata {
17
+ VariableMetadata(const autograd::Variable& var)
18
+ : sizes(var.sizes().vec()),
19
+ type(var.scalar_type()),
20
+ device(var.device()),
21
+ requires_grad(var.requires_grad()) {}
22
+
23
+ bool operator==(const VariableMetadata& o) const {
24
+ return std::tie(device, requires_grad, type, sizes) ==
25
+ std::tie(o.device, o.requires_grad, o.type, o.sizes);
26
+ }
27
+
28
+ static size_t hash(const VariableMetadata& m) {
29
+ return c10::get_hash(m.sizes, m.device, m.requires_grad, m.type);
30
+ }
31
+
32
+ std::vector<int64_t> sizes;
33
+ at::ScalarType type;
34
+ at::Device device;
35
+ bool requires_grad;
36
+ };
37
+
38
+ bool operator==(const IODescriptor& o) const {
39
+ return std::tie(structure, metadata, grad_enabled) ==
40
+ std::tie(o.structure, o.metadata, o.grad_enabled);
41
+ }
42
+
43
+ static size_t hash(const IODescriptor& o) {
44
+ return c10::get_hash(o.structure, o.metadata, o.grad_enabled);
45
+ }
46
+
47
+ void extend(const autograd::variable_list& list) {
48
+ metadata.reserve(metadata.size() + list.size());
49
+ for (auto& var : list)
50
+ metadata.emplace_back(var);
51
+ }
52
+
53
+ // Description of argument structure. Variables are replaced with
54
+ // different characters, depending on their flags, beginnings and
55
+ // ends of tuples and lists are denoted by a pair of parenthesis
56
+ // of their corresponding kind. They should always be paired.
57
+ // Example desc: (vv[v(v)v])
58
+ // NOTE: if extend() was ever called then metadata.size() can be
59
+ // different than the number of 'v's in structure.
60
+ std::string structure;
61
+ std::vector<std::string> strings;
62
+ std::vector<VariableMetadata> metadata;
63
+ bool grad_enabled = false;
64
+ };
65
+
66
+ static inline std::ostream& operator<<(
67
+ std::ostream& out,
68
+ const IODescriptor::VariableMetadata& meta) {
69
+ at::Device meta_device = meta.device;
70
+ auto& t = at::getDeprecatedTypeProperties(
71
+ meta_device.is_cpu() ? at::Backend::CPU : at::Backend::CUDA, meta.type);
72
+ out << t << "(requires_grad=" << meta.requires_grad;
73
+ if (meta_device.is_cuda()) {
74
+ out << ", device=" << meta_device.index();
75
+ }
76
+ out << ") {";
77
+ for (const auto i : c10::irange(meta.sizes.size())) {
78
+ if (i > 0)
79
+ out << ", ";
80
+ out << meta.sizes[i];
81
+ }
82
+ out << "}";
83
+ return out;
84
+ }
85
+
86
+ static inline std::ostream& operator<<(
87
+ std::ostream& out,
88
+ const IODescriptor& desc) {
89
+ out << desc.structure << "\n";
90
+ out << " with grad_enabled=" << desc.grad_enabled << "\n";
91
+ for (const auto i : c10::irange(desc.metadata.size())) {
92
+ out << " with v" << i << " having type " << desc.metadata[i] << "\n";
93
+ }
94
+ return out;
95
+ }
96
+
97
+ struct ParsedArgs {
98
+ // Flat vector of Variables found in arguments
99
+ autograd::variable_list vars;
100
+ // Metadata describing nesting of objects received from Python and
101
+ // metadata of vars and whether grad is enabled.
102
+ IODescriptor desc;
103
+
104
+ void extend(const autograd::variable_list& list) {
105
+ if (list.empty())
106
+ return;
107
+ vars.reserve(vars.size() + list.size());
108
+ for (auto& var : list)
109
+ vars.emplace_back(var);
110
+ desc.extend(list);
111
+ }
112
+ };
113
+
114
+ ParsedArgs flatten(py::handle obj);
115
+ PyObject* unflatten(
116
+ at::ArrayRef<autograd::Variable> vars,
117
+ const IODescriptor& structure);
118
+
119
+ } // namespace torch::jit::python
vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/python/python_custom_class.h ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <torch/csrc/utils/pybind.h>
4
+ #include <torch/custom_class.h>
5
+
6
+ namespace torch::jit {
7
+
8
+ void initPythonCustomClassBindings(PyObject* module);
9
+
10
+ struct ScriptClass {
11
+ ScriptClass(c10::StrongTypePtr class_type)
12
+ : class_type_(std::move(class_type)) {}
13
+
14
+ py::object __call__(const py::args& args, const py::kwargs& kwargs);
15
+
16
+ c10::StrongTypePtr class_type_;
17
+ };
18
+
19
+ } // namespace torch::jit