Debian Codegraph @

lib_pypy/_tkinter/tclobj.py

raw symbols SCIP
1 # Tcl_Obj, conversions with Python objects
2
3 from .tklib_cffi import ffi as tkffi, lib as tklib
4 import binascii
5
6 class TypeCache(object):
7 def __init__(self):
8 self.OldBooleanType = tklib.Tcl_GetObjType(b"boolean")
9 self.BooleanType = None
10 self.ByteArrayType = tklib.Tcl_GetObjType(b"bytearray")
11 self.DoubleType = tklib.Tcl_GetObjType(b"double")
12 self.IntType = tklib.Tcl_GetObjType(b"int")
13 self.WideIntType = tklib.Tcl_GetObjType(b"wideInt")
14 self.BigNumType = None
15 self.ListType = tklib.Tcl_GetObjType(b"list")
16 self.ProcBodyType = tklib.Tcl_GetObjType(b"procbody")
17 self.StringType = tklib.Tcl_GetObjType(b"string")
18
19 def add_extra_types(self, app):
20 # Some types are not registered in Tcl.
21 result = app.call('expr', 'true')
22 typePtr = AsObj(result).typePtr
23 if tkffi.string(typePtr.name) == b"booleanString":
24 self.BooleanType = typePtr
25
26 result = app.call('expr', '2**63')
27 typePtr = AsObj(result).typePtr
28 if tkffi.string(typePtr.name) == b"bignum":
29 self.BigNumType = typePtr
30
31
32 def FromTclString(s):
33 try:
34 return s.decode('utf-8')
35 except UnicodeDecodeError:
36 # Tcl encodes null character as \xc0\x80
37 r = s.replace(b'\xc0\x80', b'\x00').decode('utf-8', 'surrogateescape')
38 # now we need to deal with cesu-8
39 result = []
40 prevpos = 0
41 while 1:
42 pos = r.find("\udced", prevpos)
43 if pos == -1:
44 result.append(r[prevpos:])
45 return "".join(result)
46
47 assert pos + 6 <= len(r)
48 result.append(r[prevpos:pos])
49 # High surrogates U+d800 - U+dbff are encoded as
50 # \xed\xa0\x80 - \xed\xaf\xbf.
51 ch1 = ord(r[pos + 0])
52 assert ch1 == 0xdced
53 ch2 = ord(r[pos + 1])
54 assert 0xdca0 <= ch2 <= 0xdcaf
55 ch3 = ord(r[pos + 2])
56 assert 0xdc80 <= ch3 <= 0xdcbf
57 high = 0xd000 | ((ch2 & 0x3f) << 6) | (ch3 & 0x3f)
58 # Low surrogates U+DC00 - U+DFFF are encoded as
59 # \xed\xb0\x80 - \xed\xbf\xbf
60 ch1 = ord(r[pos + 3])
61 assert ch1 == 0xdced
62 ch2 = ch5 = ord(r[pos + 4])
63 assert 0xdcb0 <= ch2 <= 0xdcbf
64 ch3 = ch6 = ord(r[pos + 5])
65 assert 0xdc80 <= ch3 <= 0xdcbf
66 low = 0xd000 | ((ch2 & 0x3f) << 6) | (ch3 & 0x3f)
67 assert 0xd800 <= high <= 0xdbff # valid high surrogate
68 # combine to chararcter
69 res = chr((((high & 0x03ff) << 10) | (low & 0x03ff)) + 0x10000)
70 result.append(res)
71 prevpos = pos + 6
72 return s
73
74
75 # Only when tklib.HAVE_WIDE_INT_TYPE.
76 def FromWideIntObj(app, value):
77 wide = tkffi.new("Tcl_WideInt*")
78 if tklib.Tcl_GetWideIntFromObj(app.interp, value, wide) != tklib.TCL_OK:
79 app.raiseTclError()
80 return wide[0]
81
82 # Only when tklib.HAVE_LIBTOMMATH!
83 def FromBignumObj(app, value):
84 bigValue = tkffi.new("mp_int*")
85 if tklib.Tcl_GetBignumFromObj(app.interp, value, bigValue) != tklib.TCL_OK:
86 app.raiseTclError()
87 try:
88 numBytes = tklib.mp_unsigned_bin_size(bigValue)
89 buf = tkffi.new("unsigned char[]", numBytes)
90 bufSize_ptr = tkffi.new("unsigned long*", numBytes)
91 if tklib.mp_to_unsigned_bin_n(
92 bigValue, buf, bufSize_ptr) != tklib.MP_OKAY:
93 raise MemoryError
94 if bufSize_ptr[0] == 0:
95 return 0
96 bytes = tkffi.buffer(buf)[0:bufSize_ptr[0]]
97 sign = -1 if bigValue.sign == tklib.MP_NEG else 1
98 return int(sign * int(binascii.hexlify(bytes), 16))
99 finally:
100 tklib.mp_clear(bigValue)
101
102 def AsBignumObj(value):
103 sign = -1 if value < 0 else 1
104 hexstr = b'%x' % abs(value)
105 bigValue = tkffi.new("mp_int*")
106 tklib.mp_init(bigValue)
107 try:
108 if tklib.mp_read_radix(bigValue, hexstr, 16) != tklib.MP_OKAY:
109 raise MemoryError
110 bigValue.sign = tklib.MP_NEG if value < 0 else tklib.MP_ZPOS
111 return tklib.Tcl_NewBignumObj(bigValue)
112 finally:
113 tklib.mp_clear(bigValue)
114
115
116 def FromObj(app, value):
117 """Convert a TclObj pointer into a Python object."""
118 typeCache = app._typeCache
119 if not value.typePtr:
120 buf = tkffi.buffer(value.bytes, value.length)
121 return FromTclString(buf[:])
122
123 if value.typePtr in (typeCache.BooleanType, typeCache.OldBooleanType):
124 value_ptr = tkffi.new("int*")
125 if tklib.Tcl_GetBooleanFromObj(
126 app.interp, value, value_ptr) == tklib.TCL_ERROR:
127 app.raiseTclError()
128 return bool(value_ptr[0])
129 if value.typePtr == typeCache.ByteArrayType:
130 size = tkffi.new('int*')
131 data = tklib.Tcl_GetByteArrayFromObj(value, size)
132 return tkffi.buffer(data, size[0])[:]
133 if value.typePtr == typeCache.DoubleType:
134 return value.internalRep.doubleValue
135 if value.typePtr == typeCache.IntType:
136 return value.internalRep.longValue
137 if value.typePtr == typeCache.WideIntType:
138 return FromWideIntObj(app, value)
139 if value.typePtr == typeCache.BigNumType and tklib.HAVE_LIBTOMMATH:
140 return FromBignumObj(app, value)
141 if value.typePtr == typeCache.ListType:
142 size = tkffi.new('int*')
143 status = tklib.Tcl_ListObjLength(app.interp, value, size)
144 if status == tklib.TCL_ERROR:
145 app.raiseTclError()
146 result = []
147 tcl_elem = tkffi.new("Tcl_Obj**")
148 for i in range(size[0]):
149 status = tklib.Tcl_ListObjIndex(app.interp,
150 value, i, tcl_elem)
151 if status == tklib.TCL_ERROR:
152 app.raiseTclError()
153 result.append(FromObj(app, tcl_elem[0]))
154 return tuple(result)
155 if value.typePtr == typeCache.ProcBodyType:
156 pass # fall through and return tcl object.
157 if value.typePtr == typeCache.StringType:
158 buf = tklib.Tcl_GetUnicode(value)
159 length = tklib.Tcl_GetCharLength(value)
160 buf = tkffi.buffer(tkffi.cast("char*", buf), length*2)[:]
161 return buf.decode('utf-16', 'surrogatepass')
162
163 return Tcl_Obj(value)
164
165 def AsObj(value):
166 if isinstance(value, bytes):
167 return tklib.Tcl_NewByteArrayObj(value, len(value))
168 if isinstance(value, bool):
169 return tklib.Tcl_NewBooleanObj(value)
170 if isinstance(value, int):
171 try:
172 return tklib.Tcl_NewLongObj(value)
173 except OverflowError:
174 if tklib.HAVE_WIDE_INT_TYPE:
175 try:
176 tkffi.new("Tcl_WideInt[]", [value])
177 except OverflowError:
178 pass
179 else:
180 return tklib.Tcl_NewWideIntObj(value)
181 if tklib.HAVE_LIBTOMMATH:
182 return AsBignumObj(value)
183 if isinstance(value, float):
184 return tklib.Tcl_NewDoubleObj(value)
185 if isinstance(value, (tuple, list)):
186 argv = tkffi.new("Tcl_Obj*[]", len(value))
187 for i in range(len(value)):
188 argv[i] = AsObj(value[i])
189 return tklib.Tcl_NewListObj(len(value), argv)
190 if isinstance(value, str):
191 try:
192 encoded_utf8 = value.encode('utf-8')
193 except UnicodeEncodeError:
194 # String contains surrogate-escaped bytes (U+DC80-U+DCFF).
195 # Pass as raw bytes so Tcl sees the original byte values
196 # rather than storing the surrogates as Unicode characters.
197 encoded_utf8 = value.encode('utf-8', 'surrogateescape')
198 return tklib.Tcl_NewStringObj(encoded_utf8, len(encoded_utf8))
199 encoded = value.encode('utf-16', 'surrogatepass')[2:]
200 buf = tkffi.new("char[]", encoded)
201 inbuf = tkffi.cast("Tcl_UniChar*", buf)
202 return tklib.Tcl_NewUnicodeObj(inbuf, len(encoded)//2)
203 if isinstance(value, Tcl_Obj):
204 return value._value
205
206 return AsObj(str(value))
207
208 class Tcl_Obj(object):
209 def __new__(cls, value):
210 self = object.__new__(cls)
211 tklib.Tcl_IncrRefCount(value)
212 self._value = value
213 self._string = None
214 return self
215
216 def __del__(self):
217 tklib.Tcl_DecrRefCount(self._value)
218
219 def __str__(self):
220 if self._string and isinstance(self._string, str):
221 return self._string
222 return tkffi.string(tklib.Tcl_GetString(self._value)).decode('utf-8')
223
224 def __repr__(self):
225 return "<%s object at 0x%x>" % (
226 self.typename, int(tkffi.cast("intptr_t", self._value)))
227
228 def __eq__(self, other):
229 if not isinstance(other, Tcl_Obj):
230 return NotImplemented
231 return self._value == other._value
232
233 @property
234 def typename(self):
235 return FromTclString(tkffi.string(self._value.typePtr.name))
236
237 @property
238 def string(self):
239 "the string representation of this object, either as str or bytes"
240 if self._string is None:
241 length = tkffi.new("int*")
242 s = tklib.Tcl_GetStringFromObj(self._value, length)
243 value = tkffi.buffer(s, length[0])[:]
244 value = value.decode('utf-8')
245 self._string = value
246 return self._string