xref: /vim-8.2.3635/src/if_python3.c (revision f3caeb63)
1 /* vi:set ts=8 sts=4 sw=4 noet:
2  *
3  * VIM - Vi IMproved    by Bram Moolenaar
4  *
5  * Do ":help uganda"  in Vim to read copying and usage conditions.
6  * Do ":help credits" in Vim to see a list of people who contributed.
7  * See README.txt for an overview of the Vim source code.
8  */
9 /*
10  * Python extensions by Paul Moore.
11  * Changes for Unix by David Leonard.
12  *
13  * This consists of four parts:
14  * 1. Python interpreter main program
15  * 2. Python output stream: writes output via [e]msg().
16  * 3. Implementation of the Vim module for Python
17  * 4. Utility functions for handling the interface between Vim and Python.
18  */
19 
20 /*
21  * Roland Puntaier 2009/sept/16:
22  * Adaptations to support both python3.x and python2.x
23  */
24 
25 // uncomment this if used with the debug version of python
26 // #define Py_DEBUG
27 // Note: most of time you can add -DPy_DEBUG to CFLAGS in place of uncommenting
28 // uncomment this if used with the debug version of python, but without its
29 // allocator
30 // #define Py_DEBUG_NO_PYMALLOC
31 
32 #include "vim.h"
33 
34 #include <limits.h>
35 
36 #if defined(MSWIN) && defined(HAVE_FCNTL_H)
37 # undef HAVE_FCNTL_H
38 #endif
39 
40 #ifdef _DEBUG
41 # undef _DEBUG
42 #endif
43 
44 #ifdef F_BLANK
45 # undef F_BLANK
46 #endif
47 
48 #ifdef HAVE_STRFTIME
49 # undef HAVE_STRFTIME
50 #endif
51 #ifdef HAVE_STRING_H
52 # undef HAVE_STRING_H
53 #endif
54 #ifdef HAVE_PUTENV
55 # undef HAVE_PUTENV
56 #endif
57 #ifdef HAVE_STDARG_H
58 # undef HAVE_STDARG_H   // Python's config.h defines it as well.
59 #endif
60 #ifdef _POSIX_C_SOURCE  // defined in feature.h
61 # undef _POSIX_C_SOURCE
62 #endif
63 #ifdef _XOPEN_SOURCE
64 # undef _XOPEN_SOURCE	// pyconfig.h defines it as well.
65 #endif
66 
67 #define PY_SSIZE_T_CLEAN
68 
69 #include <Python.h>
70 
71 #undef main // Defined in python.h - aargh
72 #undef HAVE_FCNTL_H // Clash with os_win32.h
73 
74 // The "surrogateescape" error handler is new in Python 3.1
75 #if PY_VERSION_HEX >= 0x030100f0
76 # define CODEC_ERROR_HANDLER "surrogateescape"
77 #else
78 # define CODEC_ERROR_HANDLER NULL
79 #endif
80 
81 // Python 3 does not support CObjects, always use Capsules
82 #define PY_USE_CAPSULE
83 
84 #define ERRORS_DECODE_ARG CODEC_ERROR_HANDLER
85 #define ERRORS_ENCODE_ARG ERRORS_DECODE_ARG
86 
87 #define PyInt Py_ssize_t
88 #ifndef PyString_Check
89 # define PyString_Check(obj) PyUnicode_Check(obj)
90 #endif
91 #define PyString_FromString(repr) \
92     PyUnicode_Decode(repr, STRLEN(repr), ENC_OPT, ERRORS_DECODE_ARG)
93 #define PyString_FromFormat PyUnicode_FromFormat
94 #ifndef PyInt_Check
95 # define PyInt_Check(obj) PyLong_Check(obj)
96 #endif
97 #define PyInt_FromLong(i) PyLong_FromLong(i)
98 #define PyInt_AsLong(obj) PyLong_AsLong(obj)
99 #define Py_ssize_t_fmt "n"
100 #define Py_bytes_fmt "y"
101 
102 #define PyIntArgFunc	ssizeargfunc
103 #define PyIntObjArgProc	ssizeobjargproc
104 
105 /*
106  * PySlice_GetIndicesEx(): first argument type changed from PySliceObject
107  * to PyObject in Python 3.2 or later.
108  */
109 #if PY_VERSION_HEX >= 0x030200f0
110 typedef PyObject PySliceObject_T;
111 #else
112 typedef PySliceObject PySliceObject_T;
113 #endif
114 
115 #if defined(DYNAMIC_PYTHON3) || defined(PROTO)
116 
117 # ifndef MSWIN
118 #  include <dlfcn.h>
119 #  define FARPROC void*
120 #  define HINSTANCE void*
121 #  if defined(PY_NO_RTLD_GLOBAL) && defined(PY3_NO_RTLD_GLOBAL)
122 #   define load_dll(n) dlopen((n), RTLD_LAZY)
123 #  else
124 #   define load_dll(n) dlopen((n), RTLD_LAZY|RTLD_GLOBAL)
125 #  endif
126 #  define close_dll dlclose
127 #  define symbol_from_dll dlsym
128 # else
129 #  define load_dll vimLoadLib
130 #  define close_dll FreeLibrary
131 #  define symbol_from_dll GetProcAddress
132 # endif
133 /*
134  * Wrapper defines
135  */
136 # undef PyArg_Parse
137 # define PyArg_Parse py3_PyArg_Parse
138 # undef PyArg_ParseTuple
139 # define PyArg_ParseTuple py3_PyArg_ParseTuple
140 # define PyMem_Free py3_PyMem_Free
141 # define PyMem_Malloc py3_PyMem_Malloc
142 # define PyDict_SetItemString py3_PyDict_SetItemString
143 # define PyErr_BadArgument py3_PyErr_BadArgument
144 # define PyErr_Clear py3_PyErr_Clear
145 # define PyErr_Format py3_PyErr_Format
146 # define PyErr_PrintEx py3_PyErr_PrintEx
147 # define PyErr_NoMemory py3_PyErr_NoMemory
148 # define PyErr_Occurred py3_PyErr_Occurred
149 # define PyErr_SetNone py3_PyErr_SetNone
150 # define PyErr_SetString py3_PyErr_SetString
151 # define PyErr_SetObject py3_PyErr_SetObject
152 # define PyErr_ExceptionMatches py3_PyErr_ExceptionMatches
153 # define PyEval_InitThreads py3_PyEval_InitThreads
154 # define PyEval_RestoreThread py3_PyEval_RestoreThread
155 # define PyEval_SaveThread py3_PyEval_SaveThread
156 # define PyGILState_Ensure py3_PyGILState_Ensure
157 # define PyGILState_Release py3_PyGILState_Release
158 # define PyLong_AsLong py3_PyLong_AsLong
159 # define PyLong_FromLong py3_PyLong_FromLong
160 # define PyList_GetItem py3_PyList_GetItem
161 # define PyList_Append py3_PyList_Append
162 # define PyList_Insert py3_PyList_Insert
163 # define PyList_New py3_PyList_New
164 # define PyList_SetItem py3_PyList_SetItem
165 # define PyList_Size py3_PyList_Size
166 # define PySequence_Check py3_PySequence_Check
167 # define PySequence_Size py3_PySequence_Size
168 # define PySequence_GetItem py3_PySequence_GetItem
169 # define PySequence_Fast py3_PySequence_Fast
170 # define PyTuple_Size py3_PyTuple_Size
171 # define PyTuple_GetItem py3_PyTuple_GetItem
172 # if PY_VERSION_HEX >= 0x030601f0
173 #  define PySlice_AdjustIndices py3_PySlice_AdjustIndices
174 #  define PySlice_Unpack py3_PySlice_Unpack
175 # endif
176 # undef PySlice_GetIndicesEx
177 # define PySlice_GetIndicesEx py3_PySlice_GetIndicesEx
178 # define PyImport_ImportModule py3_PyImport_ImportModule
179 # define PyObject_Init py3__PyObject_Init
180 # define PyDict_New py3_PyDict_New
181 # define PyDict_GetItemString py3_PyDict_GetItemString
182 # define PyDict_Next py3_PyDict_Next
183 # define PyMapping_Check py3_PyMapping_Check
184 # ifndef PyMapping_Keys
185 #  define PyMapping_Keys py3_PyMapping_Keys
186 # endif
187 # if PY_VERSION_HEX >= 0x030a00b2
188 #  define PyIter_Check py3_PyIter_Check
189 # endif
190 # define PyIter_Next py3_PyIter_Next
191 # define PyObject_GetIter py3_PyObject_GetIter
192 # define PyObject_Repr py3_PyObject_Repr
193 # define PyObject_GetItem py3_PyObject_GetItem
194 # define PyObject_IsTrue py3_PyObject_IsTrue
195 # define PyModule_GetDict py3_PyModule_GetDict
196 #undef PyRun_SimpleString
197 # define PyRun_SimpleString py3_PyRun_SimpleString
198 #undef PyRun_String
199 # define PyRun_String py3_PyRun_String
200 # define PyObject_GetAttrString py3_PyObject_GetAttrString
201 # define PyObject_HasAttrString py3_PyObject_HasAttrString
202 # define PyObject_SetAttrString py3_PyObject_SetAttrString
203 # define PyObject_CallFunctionObjArgs py3_PyObject_CallFunctionObjArgs
204 # define _PyObject_CallFunction_SizeT py3__PyObject_CallFunction_SizeT
205 # define PyObject_Call py3_PyObject_Call
206 # define PyEval_GetLocals py3_PyEval_GetLocals
207 # define PyEval_GetGlobals py3_PyEval_GetGlobals
208 # define PySys_SetObject py3_PySys_SetObject
209 # define PySys_GetObject py3_PySys_GetObject
210 # define PySys_SetArgv py3_PySys_SetArgv
211 # define PyType_Ready py3_PyType_Ready
212 # if PY_VERSION_HEX >= 0x030900b0
213 #  define PyType_GetFlags py3_PyType_GetFlags
214 # endif
215 #undef Py_BuildValue
216 # define Py_BuildValue py3_Py_BuildValue
217 # define Py_SetPythonHome py3_Py_SetPythonHome
218 # define Py_Initialize py3_Py_Initialize
219 # define Py_Finalize py3_Py_Finalize
220 # define Py_IsInitialized py3_Py_IsInitialized
221 # define _Py_NoneStruct (*py3__Py_NoneStruct)
222 # define _Py_FalseStruct (*py3__Py_FalseStruct)
223 # define _Py_TrueStruct (*py3__Py_TrueStruct)
224 # define _PyObject_NextNotImplemented (*py3__PyObject_NextNotImplemented)
225 # define PyModule_AddObject py3_PyModule_AddObject
226 # define PyImport_AppendInittab py3_PyImport_AppendInittab
227 # define PyImport_AddModule py3_PyImport_AddModule
228 # if PY_VERSION_HEX >= 0x030300f0
229 #  undef _PyUnicode_AsString
230 #  define _PyUnicode_AsString py3_PyUnicode_AsUTF8
231 # else
232 #  define _PyUnicode_AsString py3__PyUnicode_AsString
233 # endif
234 # undef PyUnicode_AsEncodedString
235 # define PyUnicode_AsEncodedString py3_PyUnicode_AsEncodedString
236 # undef PyBytes_AsString
237 # define PyBytes_AsString py3_PyBytes_AsString
238 # ifndef PyBytes_AsStringAndSize
239 #  define PyBytes_AsStringAndSize py3_PyBytes_AsStringAndSize
240 # endif
241 # undef PyBytes_FromString
242 # define PyBytes_FromString py3_PyBytes_FromString
243 # undef PyBytes_FromStringAndSize
244 # define PyBytes_FromStringAndSize py3_PyBytes_FromStringAndSize
245 # if defined(Py_DEBUG) || PY_VERSION_HEX >= 0x030900b0
246 #  define _Py_Dealloc py3__Py_Dealloc
247 # endif
248 # define PyFloat_FromDouble py3_PyFloat_FromDouble
249 # define PyFloat_AsDouble py3_PyFloat_AsDouble
250 # define PyObject_GenericGetAttr py3_PyObject_GenericGetAttr
251 # define PyType_Type (*py3_PyType_Type)
252 # define PyStdPrinter_Type (*py3_PyStdPrinter_Type)
253 # define PySlice_Type (*py3_PySlice_Type)
254 # define PyFloat_Type (*py3_PyFloat_Type)
255 # define PyNumber_Check (*py3_PyNumber_Check)
256 # define PyNumber_Long (*py3_PyNumber_Long)
257 # define PyBool_Type (*py3_PyBool_Type)
258 # define PyErr_NewException py3_PyErr_NewException
259 # ifdef Py_DEBUG
260 #  define _Py_NegativeRefcount py3__Py_NegativeRefcount
261 #  define _Py_RefTotal (*py3__Py_RefTotal)
262 #  define PyModule_Create2TraceRefs py3_PyModule_Create2TraceRefs
263 # else
264 #  define PyModule_Create2 py3_PyModule_Create2
265 # endif
266 # if defined(Py_DEBUG) && !defined(Py_DEBUG_NO_PYMALLOC)
267 #  define _PyObject_DebugMalloc py3__PyObject_DebugMalloc
268 #  define _PyObject_DebugFree py3__PyObject_DebugFree
269 # else
270 #  define PyObject_Malloc py3_PyObject_Malloc
271 #  define PyObject_Free py3_PyObject_Free
272 # endif
273 # define _PyObject_GC_New py3__PyObject_GC_New
274 # define PyObject_GC_Del py3_PyObject_GC_Del
275 # define PyObject_GC_UnTrack py3_PyObject_GC_UnTrack
276 # define PyType_GenericAlloc py3_PyType_GenericAlloc
277 # define PyType_GenericNew py3_PyType_GenericNew
278 # undef PyUnicode_FromString
279 # define PyUnicode_FromString py3_PyUnicode_FromString
280 # ifndef PyUnicode_FromFormat
281 #  define PyUnicode_FromFormat py3_PyUnicode_FromFormat
282 # else
283 #  define Py_UNICODE_USE_UCS_FUNCTIONS
284 #  ifdef Py_UNICODE_WIDE
285 #   define PyUnicodeUCS4_FromFormat py3_PyUnicodeUCS4_FromFormat
286 #  else
287 #   define PyUnicodeUCS2_FromFormat py3_PyUnicodeUCS2_FromFormat
288 #  endif
289 # endif
290 # undef PyUnicode_Decode
291 # define PyUnicode_Decode py3_PyUnicode_Decode
292 # define PyType_IsSubtype py3_PyType_IsSubtype
293 # define PyCapsule_New py3_PyCapsule_New
294 # define PyCapsule_GetPointer py3_PyCapsule_GetPointer
295 
296 # if defined(Py_DEBUG) && !defined(Py_DEBUG_NO_PYMALLOC)
297 #  undef PyObject_NEW
298 #  define PyObject_NEW(type, typeobj) \
299 ( (type *) PyObject_Init( \
300 	(PyObject *) _PyObject_DebugMalloc( _PyObject_SIZE(typeobj) ), (typeobj)) )
301 # elif PY_VERSION_HEX >= 0x030900b0
302 #  undef PyObject_NEW
303 #  define PyObject_NEW(type, typeobj) \
304 	((type *)py3__PyObject_New(typeobj))
305 # endif
306 
307 /*
308  * Pointers for dynamic link
309  */
310 static int (*py3_PySys_SetArgv)(int, wchar_t **);
311 static void (*py3_Py_SetPythonHome)(wchar_t *home);
312 static void (*py3_Py_Initialize)(void);
313 static PyObject* (*py3_PyList_New)(Py_ssize_t size);
314 static PyGILState_STATE (*py3_PyGILState_Ensure)(void);
315 static void (*py3_PyGILState_Release)(PyGILState_STATE);
316 static int (*py3_PySys_SetObject)(char *, PyObject *);
317 static PyObject* (*py3_PySys_GetObject)(char *);
318 static int (*py3_PyList_Append)(PyObject *, PyObject *);
319 static int (*py3_PyList_Insert)(PyObject *, int, PyObject *);
320 static Py_ssize_t (*py3_PyList_Size)(PyObject *);
321 static int (*py3_PySequence_Check)(PyObject *);
322 static Py_ssize_t (*py3_PySequence_Size)(PyObject *);
323 static PyObject* (*py3_PySequence_GetItem)(PyObject *, Py_ssize_t);
324 static PyObject* (*py3_PySequence_Fast)(PyObject *, const char *);
325 static Py_ssize_t (*py3_PyTuple_Size)(PyObject *);
326 static PyObject* (*py3_PyTuple_GetItem)(PyObject *, Py_ssize_t);
327 static int (*py3_PyMapping_Check)(PyObject *);
328 static PyObject* (*py3_PyMapping_Keys)(PyObject *);
329 # if PY_VERSION_HEX >= 0x030601f0
330 static int (*py3_PySlice_AdjustIndices)(Py_ssize_t length,
331 		     Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t step);
332 static int (*py3_PySlice_Unpack)(PyObject *slice,
333 		     Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step);
334 # endif
335 static int (*py3_PySlice_GetIndicesEx)(PySliceObject_T *r, Py_ssize_t length,
336 		     Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step,
337 		     Py_ssize_t *slicelen);
338 static PyObject* (*py3_PyErr_NoMemory)(void);
339 static void (*py3_Py_Finalize)(void);
340 static void (*py3_PyErr_SetString)(PyObject *, const char *);
341 static void (*py3_PyErr_SetObject)(PyObject *, PyObject *);
342 static int (*py3_PyErr_ExceptionMatches)(PyObject *);
343 static int (*py3_PyRun_SimpleString)(char *);
344 static PyObject* (*py3_PyRun_String)(char *, int, PyObject *, PyObject *);
345 static PyObject* (*py3_PyObject_GetAttrString)(PyObject *, const char *);
346 static int (*py3_PyObject_HasAttrString)(PyObject *, const char *);
347 static int (*py3_PyObject_SetAttrString)(PyObject *, const char *, PyObject *);
348 static PyObject* (*py3_PyObject_CallFunctionObjArgs)(PyObject *, ...);
349 static PyObject* (*py3__PyObject_CallFunction_SizeT)(PyObject *, char *, ...);
350 static PyObject* (*py3_PyObject_Call)(PyObject *, PyObject *, PyObject *);
351 static PyObject* (*py3_PyEval_GetGlobals)();
352 static PyObject* (*py3_PyEval_GetLocals)();
353 static PyObject* (*py3_PyList_GetItem)(PyObject *, Py_ssize_t);
354 static PyObject* (*py3_PyImport_ImportModule)(const char *);
355 static PyObject* (*py3_PyImport_AddModule)(const char *);
356 static int (*py3_PyErr_BadArgument)(void);
357 static PyObject* (*py3_PyErr_Occurred)(void);
358 static PyObject* (*py3_PyModule_GetDict)(PyObject *);
359 static int (*py3_PyList_SetItem)(PyObject *, Py_ssize_t, PyObject *);
360 static PyObject* (*py3_PyDict_GetItemString)(PyObject *, const char *);
361 static int (*py3_PyDict_Next)(PyObject *, Py_ssize_t *, PyObject **, PyObject **);
362 static PyObject* (*py3_PyLong_FromLong)(long);
363 static PyObject* (*py3_PyDict_New)(void);
364 # if PY_VERSION_HEX >= 0x030a00b2
365 static int (*py3_PyIter_Check)(PyObject *o);
366 # endif
367 static PyObject* (*py3_PyIter_Next)(PyObject *);
368 static PyObject* (*py3_PyObject_GetIter)(PyObject *);
369 static PyObject* (*py3_PyObject_Repr)(PyObject *);
370 static PyObject* (*py3_PyObject_GetItem)(PyObject *, PyObject *);
371 static int (*py3_PyObject_IsTrue)(PyObject *);
372 static PyObject* (*py3_Py_BuildValue)(char *, ...);
373 # if PY_VERSION_HEX >= 0x030900b0
374 static int (*py3_PyType_GetFlags)(PyTypeObject *o);
375 # endif
376 static int (*py3_PyType_Ready)(PyTypeObject *type);
377 static int (*py3_PyDict_SetItemString)(PyObject *dp, char *key, PyObject *item);
378 static PyObject* (*py3_PyUnicode_FromString)(const char *u);
379 # ifndef Py_UNICODE_USE_UCS_FUNCTIONS
380 static PyObject* (*py3_PyUnicode_FromFormat)(const char *u, ...);
381 # else
382 #  ifdef Py_UNICODE_WIDE
383 static PyObject* (*py3_PyUnicodeUCS4_FromFormat)(const char *u, ...);
384 #  else
385 static PyObject* (*py3_PyUnicodeUCS2_FromFormat)(const char *u, ...);
386 #  endif
387 # endif
388 static PyObject* (*py3_PyUnicode_Decode)(const char *u, Py_ssize_t size,
389 	const char *encoding, const char *errors);
390 static long (*py3_PyLong_AsLong)(PyObject *);
391 static void (*py3_PyErr_SetNone)(PyObject *);
392 static void (*py3_PyEval_InitThreads)(void);
393 static void(*py3_PyEval_RestoreThread)(PyThreadState *);
394 static PyThreadState*(*py3_PyEval_SaveThread)(void);
395 static int (*py3_PyArg_Parse)(PyObject *, char *, ...);
396 static int (*py3_PyArg_ParseTuple)(PyObject *, char *, ...);
397 static int (*py3_PyMem_Free)(void *);
398 static void* (*py3_PyMem_Malloc)(size_t);
399 static int (*py3_Py_IsInitialized)(void);
400 static void (*py3_PyErr_Clear)(void);
401 static PyObject* (*py3_PyErr_Format)(PyObject *, const char *, ...);
402 static void (*py3_PyErr_PrintEx)(int);
403 static PyObject*(*py3__PyObject_Init)(PyObject *, PyTypeObject *);
404 static iternextfunc py3__PyObject_NextNotImplemented;
405 static PyObject* py3__Py_NoneStruct;
406 static PyObject* py3__Py_FalseStruct;
407 static PyObject* py3__Py_TrueStruct;
408 static int (*py3_PyModule_AddObject)(PyObject *m, const char *name, PyObject *o);
409 static int (*py3_PyImport_AppendInittab)(const char *name, PyObject* (*initfunc)(void));
410 # if PY_VERSION_HEX >= 0x030300f0
411 static char* (*py3_PyUnicode_AsUTF8)(PyObject *unicode);
412 # else
413 static char* (*py3__PyUnicode_AsString)(PyObject *unicode);
414 # endif
415 static PyObject* (*py3_PyUnicode_AsEncodedString)(PyObject *unicode, const char* encoding, const char* errors);
416 static char* (*py3_PyBytes_AsString)(PyObject *bytes);
417 static int (*py3_PyBytes_AsStringAndSize)(PyObject *bytes, char **buffer, Py_ssize_t *length);
418 static PyObject* (*py3_PyBytes_FromString)(char *str);
419 static PyObject* (*py3_PyBytes_FromStringAndSize)(char *str, Py_ssize_t length);
420 # if defined(Py_DEBUG) || PY_VERSION_HEX >= 0x030900b0
421 static void (*py3__Py_Dealloc)(PyObject *obj);
422 # endif
423 # if PY_VERSION_HEX >= 0x030900b0
424 static PyObject* (*py3__PyObject_New)(PyTypeObject *);
425 # endif
426 static PyObject* (*py3_PyFloat_FromDouble)(double num);
427 static double (*py3_PyFloat_AsDouble)(PyObject *);
428 static PyObject* (*py3_PyObject_GenericGetAttr)(PyObject *obj, PyObject *name);
429 static PyObject* (*py3_PyType_GenericAlloc)(PyTypeObject *type, Py_ssize_t nitems);
430 static PyObject* (*py3_PyType_GenericNew)(PyTypeObject *type, PyObject *args, PyObject *kwds);
431 static PyTypeObject* py3_PyType_Type;
432 static PyTypeObject* py3_PyStdPrinter_Type;
433 static PyTypeObject* py3_PySlice_Type;
434 static PyTypeObject* py3_PyFloat_Type;
435 static PyTypeObject* py3_PyBool_Type;
436 static int (*py3_PyNumber_Check)(PyObject *);
437 static PyObject* (*py3_PyNumber_Long)(PyObject *);
438 static PyObject* (*py3_PyErr_NewException)(char *name, PyObject *base, PyObject *dict);
439 static PyObject* (*py3_PyCapsule_New)(void *, char *, PyCapsule_Destructor);
440 static void* (*py3_PyCapsule_GetPointer)(PyObject *, char *);
441 # ifdef Py_DEBUG
442 static void (*py3__Py_NegativeRefcount)(const char *fname, int lineno, PyObject *op);
443 static Py_ssize_t* py3__Py_RefTotal;
444 static PyObject* (*py3_PyModule_Create2TraceRefs)(struct PyModuleDef* module, int module_api_version);
445 # else
446 static PyObject* (*py3_PyModule_Create2)(struct PyModuleDef* module, int module_api_version);
447 # endif
448 # if defined(Py_DEBUG) && !defined(Py_DEBUG_NO_PYMALLOC)
449 static void (*py3__PyObject_DebugFree)(void*);
450 static void* (*py3__PyObject_DebugMalloc)(size_t);
451 # else
452 static void (*py3_PyObject_Free)(void*);
453 static void* (*py3_PyObject_Malloc)(size_t);
454 # endif
455 static PyObject*(*py3__PyObject_GC_New)(PyTypeObject *);
456 static void(*py3_PyObject_GC_Del)(void *);
457 static void(*py3_PyObject_GC_UnTrack)(void *);
458 static int (*py3_PyType_IsSubtype)(PyTypeObject *, PyTypeObject *);
459 
460 static HINSTANCE hinstPy3 = 0; // Instance of python.dll
461 
462 // Imported exception objects
463 static PyObject *p3imp_PyExc_AttributeError;
464 static PyObject *p3imp_PyExc_IndexError;
465 static PyObject *p3imp_PyExc_KeyError;
466 static PyObject *p3imp_PyExc_KeyboardInterrupt;
467 static PyObject *p3imp_PyExc_TypeError;
468 static PyObject *p3imp_PyExc_ValueError;
469 static PyObject *p3imp_PyExc_SystemExit;
470 static PyObject *p3imp_PyExc_RuntimeError;
471 static PyObject *p3imp_PyExc_ImportError;
472 static PyObject *p3imp_PyExc_OverflowError;
473 
474 # define PyExc_AttributeError p3imp_PyExc_AttributeError
475 # define PyExc_IndexError p3imp_PyExc_IndexError
476 # define PyExc_KeyError p3imp_PyExc_KeyError
477 # define PyExc_KeyboardInterrupt p3imp_PyExc_KeyboardInterrupt
478 # define PyExc_TypeError p3imp_PyExc_TypeError
479 # define PyExc_ValueError p3imp_PyExc_ValueError
480 # define PyExc_SystemExit p3imp_PyExc_SystemExit
481 # define PyExc_RuntimeError p3imp_PyExc_RuntimeError
482 # define PyExc_ImportError p3imp_PyExc_ImportError
483 # define PyExc_OverflowError p3imp_PyExc_OverflowError
484 
485 /*
486  * Table of name to function pointer of python.
487  */
488 # define PYTHON_PROC FARPROC
489 static struct
490 {
491     char *name;
492     PYTHON_PROC *ptr;
493 } py3_funcname_table[] =
494 {
495     {"PySys_SetArgv", (PYTHON_PROC*)&py3_PySys_SetArgv},
496     {"Py_SetPythonHome", (PYTHON_PROC*)&py3_Py_SetPythonHome},
497     {"Py_Initialize", (PYTHON_PROC*)&py3_Py_Initialize},
498     {"_PyArg_ParseTuple_SizeT", (PYTHON_PROC*)&py3_PyArg_ParseTuple},
499     {"_Py_BuildValue_SizeT", (PYTHON_PROC*)&py3_Py_BuildValue},
500     {"PyMem_Free", (PYTHON_PROC*)&py3_PyMem_Free},
501     {"PyMem_Malloc", (PYTHON_PROC*)&py3_PyMem_Malloc},
502     {"PyList_New", (PYTHON_PROC*)&py3_PyList_New},
503     {"PyGILState_Ensure", (PYTHON_PROC*)&py3_PyGILState_Ensure},
504     {"PyGILState_Release", (PYTHON_PROC*)&py3_PyGILState_Release},
505     {"PySys_SetObject", (PYTHON_PROC*)&py3_PySys_SetObject},
506     {"PySys_GetObject", (PYTHON_PROC*)&py3_PySys_GetObject},
507     {"PyList_Append", (PYTHON_PROC*)&py3_PyList_Append},
508     {"PyList_Insert", (PYTHON_PROC*)&py3_PyList_Insert},
509     {"PyList_Size", (PYTHON_PROC*)&py3_PyList_Size},
510     {"PySequence_Check", (PYTHON_PROC*)&py3_PySequence_Check},
511     {"PySequence_Size", (PYTHON_PROC*)&py3_PySequence_Size},
512     {"PySequence_GetItem", (PYTHON_PROC*)&py3_PySequence_GetItem},
513     {"PySequence_Fast", (PYTHON_PROC*)&py3_PySequence_Fast},
514     {"PyTuple_Size", (PYTHON_PROC*)&py3_PyTuple_Size},
515     {"PyTuple_GetItem", (PYTHON_PROC*)&py3_PyTuple_GetItem},
516 # if PY_VERSION_HEX >= 0x030601f0
517     {"PySlice_AdjustIndices", (PYTHON_PROC*)&py3_PySlice_AdjustIndices},
518     {"PySlice_Unpack", (PYTHON_PROC*)&py3_PySlice_Unpack},
519 # endif
520     {"PySlice_GetIndicesEx", (PYTHON_PROC*)&py3_PySlice_GetIndicesEx},
521     {"PyErr_NoMemory", (PYTHON_PROC*)&py3_PyErr_NoMemory},
522     {"Py_Finalize", (PYTHON_PROC*)&py3_Py_Finalize},
523     {"PyErr_SetString", (PYTHON_PROC*)&py3_PyErr_SetString},
524     {"PyErr_SetObject", (PYTHON_PROC*)&py3_PyErr_SetObject},
525     {"PyErr_ExceptionMatches", (PYTHON_PROC*)&py3_PyErr_ExceptionMatches},
526     {"PyRun_SimpleString", (PYTHON_PROC*)&py3_PyRun_SimpleString},
527     {"PyRun_String", (PYTHON_PROC*)&py3_PyRun_String},
528     {"PyObject_GetAttrString", (PYTHON_PROC*)&py3_PyObject_GetAttrString},
529     {"PyObject_HasAttrString", (PYTHON_PROC*)&py3_PyObject_HasAttrString},
530     {"PyObject_SetAttrString", (PYTHON_PROC*)&py3_PyObject_SetAttrString},
531     {"PyObject_CallFunctionObjArgs", (PYTHON_PROC*)&py3_PyObject_CallFunctionObjArgs},
532     {"_PyObject_CallFunction_SizeT", (PYTHON_PROC*)&py3__PyObject_CallFunction_SizeT},
533     {"PyObject_Call", (PYTHON_PROC*)&py3_PyObject_Call},
534     {"PyEval_GetGlobals", (PYTHON_PROC*)&py3_PyEval_GetGlobals},
535     {"PyEval_GetLocals", (PYTHON_PROC*)&py3_PyEval_GetLocals},
536     {"PyList_GetItem", (PYTHON_PROC*)&py3_PyList_GetItem},
537     {"PyImport_ImportModule", (PYTHON_PROC*)&py3_PyImport_ImportModule},
538     {"PyImport_AddModule", (PYTHON_PROC*)&py3_PyImport_AddModule},
539     {"PyErr_BadArgument", (PYTHON_PROC*)&py3_PyErr_BadArgument},
540     {"PyErr_Occurred", (PYTHON_PROC*)&py3_PyErr_Occurred},
541     {"PyModule_GetDict", (PYTHON_PROC*)&py3_PyModule_GetDict},
542     {"PyList_SetItem", (PYTHON_PROC*)&py3_PyList_SetItem},
543     {"PyDict_GetItemString", (PYTHON_PROC*)&py3_PyDict_GetItemString},
544     {"PyDict_Next", (PYTHON_PROC*)&py3_PyDict_Next},
545     {"PyMapping_Check", (PYTHON_PROC*)&py3_PyMapping_Check},
546     {"PyMapping_Keys", (PYTHON_PROC*)&py3_PyMapping_Keys},
547 # if PY_VERSION_HEX >= 0x030a00b2
548     {"PyIter_Check", (PYTHON_PROC*)&py3_PyIter_Check},
549 # endif
550     {"PyIter_Next", (PYTHON_PROC*)&py3_PyIter_Next},
551     {"PyObject_GetIter", (PYTHON_PROC*)&py3_PyObject_GetIter},
552     {"PyObject_Repr", (PYTHON_PROC*)&py3_PyObject_Repr},
553     {"PyObject_GetItem", (PYTHON_PROC*)&py3_PyObject_GetItem},
554     {"PyObject_IsTrue", (PYTHON_PROC*)&py3_PyObject_IsTrue},
555     {"PyLong_FromLong", (PYTHON_PROC*)&py3_PyLong_FromLong},
556     {"PyDict_New", (PYTHON_PROC*)&py3_PyDict_New},
557 # if PY_VERSION_HEX >= 0x030900b0
558     {"PyType_GetFlags", (PYTHON_PROC*)&py3_PyType_GetFlags},
559 # endif
560     {"PyType_Ready", (PYTHON_PROC*)&py3_PyType_Ready},
561     {"PyDict_SetItemString", (PYTHON_PROC*)&py3_PyDict_SetItemString},
562     {"PyLong_AsLong", (PYTHON_PROC*)&py3_PyLong_AsLong},
563     {"PyErr_SetNone", (PYTHON_PROC*)&py3_PyErr_SetNone},
564     {"PyEval_InitThreads", (PYTHON_PROC*)&py3_PyEval_InitThreads},
565     {"PyEval_RestoreThread", (PYTHON_PROC*)&py3_PyEval_RestoreThread},
566     {"PyEval_SaveThread", (PYTHON_PROC*)&py3_PyEval_SaveThread},
567     {"_PyArg_Parse_SizeT", (PYTHON_PROC*)&py3_PyArg_Parse},
568     {"Py_IsInitialized", (PYTHON_PROC*)&py3_Py_IsInitialized},
569     {"_PyObject_NextNotImplemented", (PYTHON_PROC*)&py3__PyObject_NextNotImplemented},
570     {"_Py_NoneStruct", (PYTHON_PROC*)&py3__Py_NoneStruct},
571     {"_Py_FalseStruct", (PYTHON_PROC*)&py3__Py_FalseStruct},
572     {"_Py_TrueStruct", (PYTHON_PROC*)&py3__Py_TrueStruct},
573     {"PyErr_Clear", (PYTHON_PROC*)&py3_PyErr_Clear},
574     {"PyErr_Format", (PYTHON_PROC*)&py3_PyErr_Format},
575     {"PyErr_PrintEx", (PYTHON_PROC*)&py3_PyErr_PrintEx},
576     {"PyObject_Init", (PYTHON_PROC*)&py3__PyObject_Init},
577     {"PyModule_AddObject", (PYTHON_PROC*)&py3_PyModule_AddObject},
578     {"PyImport_AppendInittab", (PYTHON_PROC*)&py3_PyImport_AppendInittab},
579 # if PY_VERSION_HEX >= 0x030300f0
580     {"PyUnicode_AsUTF8", (PYTHON_PROC*)&py3_PyUnicode_AsUTF8},
581 # else
582     {"_PyUnicode_AsString", (PYTHON_PROC*)&py3__PyUnicode_AsString},
583 # endif
584 # ifndef Py_UNICODE_USE_UCS_FUNCTIONS
585     {"PyUnicode_FromFormat", (PYTHON_PROC*)&py3_PyUnicode_FromFormat},
586 # else
587 #  ifdef Py_UNICODE_WIDE
588     {"PyUnicodeUCS4_FromFormat", (PYTHON_PROC*)&py3_PyUnicodeUCS4_FromFormat},
589 #  else
590     {"PyUnicodeUCS2_FromFormat", (PYTHON_PROC*)&py3_PyUnicodeUCS2_FromFormat},
591 #  endif
592 # endif
593     {"PyBytes_AsString", (PYTHON_PROC*)&py3_PyBytes_AsString},
594     {"PyBytes_AsStringAndSize", (PYTHON_PROC*)&py3_PyBytes_AsStringAndSize},
595     {"PyBytes_FromString", (PYTHON_PROC*)&py3_PyBytes_FromString},
596     {"PyBytes_FromStringAndSize", (PYTHON_PROC*)&py3_PyBytes_FromStringAndSize},
597 # if defined(Py_DEBUG) || PY_VERSION_HEX >= 0x030900b0
598     {"_Py_Dealloc", (PYTHON_PROC*)&py3__Py_Dealloc},
599 # endif
600 # if PY_VERSION_HEX >= 0x030900b0
601     {"_PyObject_New", (PYTHON_PROC*)&py3__PyObject_New},
602 # endif
603     {"PyFloat_FromDouble", (PYTHON_PROC*)&py3_PyFloat_FromDouble},
604     {"PyFloat_AsDouble", (PYTHON_PROC*)&py3_PyFloat_AsDouble},
605     {"PyObject_GenericGetAttr", (PYTHON_PROC*)&py3_PyObject_GenericGetAttr},
606     {"PyType_GenericAlloc", (PYTHON_PROC*)&py3_PyType_GenericAlloc},
607     {"PyType_GenericNew", (PYTHON_PROC*)&py3_PyType_GenericNew},
608     {"PyType_Type", (PYTHON_PROC*)&py3_PyType_Type},
609     {"PyStdPrinter_Type", (PYTHON_PROC*)&py3_PyStdPrinter_Type},
610     {"PySlice_Type", (PYTHON_PROC*)&py3_PySlice_Type},
611     {"PyFloat_Type", (PYTHON_PROC*)&py3_PyFloat_Type},
612     {"PyBool_Type", (PYTHON_PROC*)&py3_PyBool_Type},
613     {"PyNumber_Check", (PYTHON_PROC*)&py3_PyNumber_Check},
614     {"PyNumber_Long", (PYTHON_PROC*)&py3_PyNumber_Long},
615     {"PyErr_NewException", (PYTHON_PROC*)&py3_PyErr_NewException},
616 # ifdef Py_DEBUG
617     {"_Py_NegativeRefcount", (PYTHON_PROC*)&py3__Py_NegativeRefcount},
618     {"_Py_RefTotal", (PYTHON_PROC*)&py3__Py_RefTotal},
619     {"PyModule_Create2TraceRefs", (PYTHON_PROC*)&py3_PyModule_Create2TraceRefs},
620 # else
621     {"PyModule_Create2", (PYTHON_PROC*)&py3_PyModule_Create2},
622 # endif
623 # if defined(Py_DEBUG) && !defined(Py_DEBUG_NO_PYMALLOC)
624     {"_PyObject_DebugFree", (PYTHON_PROC*)&py3__PyObject_DebugFree},
625     {"_PyObject_DebugMalloc", (PYTHON_PROC*)&py3__PyObject_DebugMalloc},
626 # else
627     {"PyObject_Malloc", (PYTHON_PROC*)&py3_PyObject_Malloc},
628     {"PyObject_Free", (PYTHON_PROC*)&py3_PyObject_Free},
629 # endif
630     {"_PyObject_GC_New", (PYTHON_PROC*)&py3__PyObject_GC_New},
631     {"PyObject_GC_Del", (PYTHON_PROC*)&py3_PyObject_GC_Del},
632     {"PyObject_GC_UnTrack", (PYTHON_PROC*)&py3_PyObject_GC_UnTrack},
633     {"PyType_IsSubtype", (PYTHON_PROC*)&py3_PyType_IsSubtype},
634     {"PyCapsule_New", (PYTHON_PROC*)&py3_PyCapsule_New},
635     {"PyCapsule_GetPointer", (PYTHON_PROC*)&py3_PyCapsule_GetPointer},
636     {"", NULL},
637 };
638 
639 # if PY_VERSION_HEX >= 0x030800f0
640     static inline void
641 py3__Py_DECREF(const char *filename UNUSED, int lineno UNUSED, PyObject *op)
642 {
643     if (--op->ob_refcnt != 0)
644     {
645 #  ifdef Py_REF_DEBUG
646 	if (op->ob_refcnt < 0)
647 	{
648 	    _Py_NegativeRefcount(filename, lineno, op);
649 	}
650 #  endif
651     }
652     else
653     {
654 	_Py_Dealloc(op);
655     }
656 }
657 
658 #  undef Py_DECREF
659 #  define Py_DECREF(op) py3__Py_DECREF(__FILE__, __LINE__, _PyObject_CAST(op))
660 
661     static inline void
662 py3__Py_XDECREF(PyObject *op)
663 {
664     if (op != NULL)
665     {
666 	Py_DECREF(op);
667     }
668 }
669 
670 #  undef Py_XDECREF
671 #  define Py_XDECREF(op) py3__Py_XDECREF(_PyObject_CAST(op))
672 # endif
673 
674 # if PY_VERSION_HEX >= 0x030900b0
675     static inline int
676 py3_PyType_HasFeature(PyTypeObject *type, unsigned long feature)
677 {
678     return ((PyType_GetFlags(type) & feature) != 0);
679 }
680 #  define PyType_HasFeature(t,f) py3_PyType_HasFeature(t,f)
681 # endif
682 
683 # if PY_VERSION_HEX >= 0x030a00b2
684     static inline int
685 py3__PyObject_TypeCheck(PyObject *ob, PyTypeObject *type)
686 {
687     return Py_IS_TYPE(ob, type) || PyType_IsSubtype(Py_TYPE(ob), type);
688 }
689 #  define _PyObject_TypeCheck(o,t) py3__PyObject_TypeCheck(o,t)
690 # endif
691 
692 # ifdef MSWIN
693 /*
694  * Look up the library "libname" using the InstallPath registry key.
695  * Return NULL when failed.  Return an allocated string when successful.
696  */
697     static char *
698 py3_get_system_libname(const char *libname)
699 {
700     const char	*cp = libname;
701     char	subkey[128];
702     HKEY	hKey;
703     char	installpath[MAXPATHL];
704     LONG	len = sizeof(installpath);
705     LSTATUS	rc;
706     size_t	sysliblen;
707     char	*syslibname;
708 
709     while (*cp != '\0')
710     {
711 	if (*cp == ':' || *cp == '\\' || *cp == '/')
712 	{
713 	    // Bail out if "libname" contains path separator, assume it is
714 	    // an absolute path.
715 	    return NULL;
716 	}
717 	++cp;
718     }
719     vim_snprintf(subkey, sizeof(subkey),
720 #  ifdef _WIN64
721 		 "Software\\Python\\PythonCore\\%d.%d\\InstallPath",
722 #  else
723 		 "Software\\Python\\PythonCore\\%d.%d-32\\InstallPath",
724 #  endif
725 		 PY_MAJOR_VERSION, PY_MINOR_VERSION);
726     if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, subkey, 0, KEY_QUERY_VALUE, &hKey)
727 							      != ERROR_SUCCESS)
728 	return NULL;
729     rc = RegQueryValueA(hKey, NULL, installpath, &len);
730     RegCloseKey(hKey);
731     if (ERROR_SUCCESS != rc)
732 	return NULL;
733     cp = installpath + len;
734     // Just in case registry value contains null terminators.
735     while (cp > installpath && *(cp-1) == '\0')
736 	--cp;
737     // Remove trailing path separators.
738     while (cp > installpath && (*(cp-1) == '\\' || *(cp-1) == '/'))
739 	--cp;
740     // Ignore if InstallPath is effectively empty.
741     if (cp <= installpath)
742 	return NULL;
743     sysliblen = (cp - installpath) + 1 + STRLEN(libname) + 1;
744     syslibname = alloc(sysliblen);
745     vim_snprintf(syslibname, sysliblen, "%.*s\\%s",
746 				(int)(cp - installpath), installpath, libname);
747     return syslibname;
748 }
749 # endif
750 
751 /*
752  * Load library and get all pointers.
753  * Parameter 'libname' provides name of DLL.
754  * Return OK or FAIL.
755  */
756     static int
757 py3_runtime_link_init(char *libname, int verbose)
758 {
759     int i;
760     PYTHON_PROC *ucs_from_string = (PYTHON_PROC *)&py3_PyUnicode_FromString;
761     PYTHON_PROC *ucs_decode = (PYTHON_PROC *)&py3_PyUnicode_Decode;
762     PYTHON_PROC *ucs_as_encoded_string =
763 				 (PYTHON_PROC *)&py3_PyUnicode_AsEncodedString;
764 
765 # if !(defined(PY_NO_RTLD_GLOBAL) && defined(PY3_NO_RTLD_GLOBAL)) && defined(UNIX) && defined(FEAT_PYTHON)
766     // Can't have Python and Python3 loaded at the same time.
767     // It cause a crash, because RTLD_GLOBAL is needed for
768     // standard C extension libraries of one or both python versions.
769     if (python_loaded())
770     {
771 	if (verbose)
772 	    emsg(_("E837: This Vim cannot execute :py3 after using :python"));
773 	return FAIL;
774     }
775 # endif
776 
777     if (hinstPy3 != 0)
778 	return OK;
779     hinstPy3 = load_dll(libname);
780 
781 # ifdef MSWIN
782     if (!hinstPy3)
783     {
784 	// Attempt to use the path from InstallPath as stored in the registry.
785 	char *syslibname = py3_get_system_libname(libname);
786 
787 	if (syslibname != NULL)
788 	{
789 	    hinstPy3 = load_dll(syslibname);
790 	    vim_free(syslibname);
791 	}
792     }
793 # endif
794 
795     if (!hinstPy3)
796     {
797 	if (verbose)
798 	    semsg(_(e_loadlib), libname);
799 	return FAIL;
800     }
801 
802     for (i = 0; py3_funcname_table[i].ptr; ++i)
803     {
804 	if ((*py3_funcname_table[i].ptr = symbol_from_dll(hinstPy3,
805 			py3_funcname_table[i].name)) == NULL)
806 	{
807 	    close_dll(hinstPy3);
808 	    hinstPy3 = 0;
809 	    if (verbose)
810 		semsg(_(e_loadfunc), py3_funcname_table[i].name);
811 	    return FAIL;
812 	}
813     }
814 
815     // Load unicode functions separately as only the ucs2 or the ucs4 functions
816     // will be present in the library.
817 # if PY_VERSION_HEX >= 0x030300f0
818     *ucs_from_string = symbol_from_dll(hinstPy3, "PyUnicode_FromString");
819     *ucs_decode = symbol_from_dll(hinstPy3, "PyUnicode_Decode");
820     *ucs_as_encoded_string = symbol_from_dll(hinstPy3,
821 	    "PyUnicode_AsEncodedString");
822 # else
823     *ucs_from_string = symbol_from_dll(hinstPy3, "PyUnicodeUCS2_FromString");
824     *ucs_decode = symbol_from_dll(hinstPy3,
825 	    "PyUnicodeUCS2_Decode");
826     *ucs_as_encoded_string = symbol_from_dll(hinstPy3,
827 	    "PyUnicodeUCS2_AsEncodedString");
828     if (*ucs_from_string == NULL || *ucs_decode == NULL
829 					     || *ucs_as_encoded_string == NULL)
830     {
831 	*ucs_from_string = symbol_from_dll(hinstPy3,
832 		"PyUnicodeUCS4_FromString");
833 	*ucs_decode = symbol_from_dll(hinstPy3,
834 		"PyUnicodeUCS4_Decode");
835 	*ucs_as_encoded_string = symbol_from_dll(hinstPy3,
836 		"PyUnicodeUCS4_AsEncodedString");
837     }
838 # endif
839     if (*ucs_from_string == NULL || *ucs_decode == NULL
840 					     || *ucs_as_encoded_string == NULL)
841     {
842 	close_dll(hinstPy3);
843 	hinstPy3 = 0;
844 	if (verbose)
845 	    semsg(_(e_loadfunc), "PyUnicode_UCSX_*");
846 	return FAIL;
847     }
848 
849     return OK;
850 }
851 
852 /*
853  * If python is enabled (there is installed python on Windows system) return
854  * TRUE, else FALSE.
855  */
856     int
857 python3_enabled(int verbose)
858 {
859     return py3_runtime_link_init((char *)p_py3dll, verbose) == OK;
860 }
861 
862 /*
863  * Load the standard Python exceptions - don't import the symbols from the
864  * DLL, as this can cause errors (importing data symbols is not reliable).
865  */
866     static void
867 get_py3_exceptions(void)
868 {
869     PyObject *exmod = PyImport_ImportModule("builtins");
870     PyObject *exdict = PyModule_GetDict(exmod);
871     p3imp_PyExc_AttributeError = PyDict_GetItemString(exdict, "AttributeError");
872     p3imp_PyExc_IndexError = PyDict_GetItemString(exdict, "IndexError");
873     p3imp_PyExc_KeyError = PyDict_GetItemString(exdict, "KeyError");
874     p3imp_PyExc_KeyboardInterrupt = PyDict_GetItemString(exdict, "KeyboardInterrupt");
875     p3imp_PyExc_TypeError = PyDict_GetItemString(exdict, "TypeError");
876     p3imp_PyExc_ValueError = PyDict_GetItemString(exdict, "ValueError");
877     p3imp_PyExc_SystemExit = PyDict_GetItemString(exdict, "SystemExit");
878     p3imp_PyExc_RuntimeError = PyDict_GetItemString(exdict, "RuntimeError");
879     p3imp_PyExc_ImportError = PyDict_GetItemString(exdict, "ImportError");
880     p3imp_PyExc_OverflowError = PyDict_GetItemString(exdict, "OverflowError");
881     Py_XINCREF(p3imp_PyExc_AttributeError);
882     Py_XINCREF(p3imp_PyExc_IndexError);
883     Py_XINCREF(p3imp_PyExc_KeyError);
884     Py_XINCREF(p3imp_PyExc_KeyboardInterrupt);
885     Py_XINCREF(p3imp_PyExc_TypeError);
886     Py_XINCREF(p3imp_PyExc_ValueError);
887     Py_XINCREF(p3imp_PyExc_SystemExit);
888     Py_XINCREF(p3imp_PyExc_RuntimeError);
889     Py_XINCREF(p3imp_PyExc_ImportError);
890     Py_XINCREF(p3imp_PyExc_OverflowError);
891     Py_XDECREF(exmod);
892 }
893 #endif // DYNAMIC_PYTHON3
894 
895 static int py3initialised = 0;
896 #define PYINITIALISED py3initialised
897 static int python_end_called = FALSE;
898 
899 #define DESTRUCTOR_FINISH(self) Py_TYPE(self)->tp_free((PyObject*)self)
900 
901 #define WIN_PYTHON_REF(win) win->w_python3_ref
902 #define BUF_PYTHON_REF(buf) buf->b_python3_ref
903 #define TAB_PYTHON_REF(tab) tab->tp_python3_ref
904 
905     static void
906 call_PyObject_Free(void *p)
907 {
908 #if defined(Py_DEBUG) && !defined(Py_DEBUG_NO_PYMALLOC)
909     _PyObject_DebugFree(p);
910 #else
911     PyObject_Free(p);
912 #endif
913 }
914 
915     static PyObject *
916 call_PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
917 {
918     return PyType_GenericNew(type,args,kwds);
919 }
920 
921     static PyObject *
922 call_PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
923 {
924     return PyType_GenericAlloc(type,nitems);
925 }
926 
927 static PyObject *OutputGetattro(PyObject *, PyObject *);
928 static int OutputSetattro(PyObject *, PyObject *, PyObject *);
929 static PyObject *BufferGetattro(PyObject *, PyObject *);
930 static int BufferSetattro(PyObject *, PyObject *, PyObject *);
931 static PyObject *TabPageGetattro(PyObject *, PyObject *);
932 static PyObject *WindowGetattro(PyObject *, PyObject *);
933 static int WindowSetattro(PyObject *, PyObject *, PyObject *);
934 static PyObject *RangeGetattro(PyObject *, PyObject *);
935 static PyObject *CurrentGetattro(PyObject *, PyObject *);
936 static int CurrentSetattro(PyObject *, PyObject *, PyObject *);
937 static PyObject *DictionaryGetattro(PyObject *, PyObject *);
938 static int DictionarySetattro(PyObject *, PyObject *, PyObject *);
939 static PyObject *ListGetattro(PyObject *, PyObject *);
940 static int ListSetattro(PyObject *, PyObject *, PyObject *);
941 static PyObject *FunctionGetattro(PyObject *, PyObject *);
942 
943 static struct PyModuleDef vimmodule;
944 
945 #define PY_CAN_RECURSE
946 
947 /*
948  * Include the code shared with if_python.c
949  */
950 #include "if_py_both.h"
951 
952 // NOTE: Must always be used at the start of a block, since it declares "name".
953 #define GET_ATTR_STRING(name, nameobj) \
954     char	*name = ""; \
955     if (PyUnicode_Check(nameobj)) \
956 	name = (char *)_PyUnicode_AsString(nameobj)
957 
958 #define PY3OBJ_DELETED(obj) (obj->ob_base.ob_refcnt<=0)
959 
960 ///////////////////////////////////////////////////////
961 // Internal function prototypes.
962 
963 static PyObject *Py3Init_vim(void);
964 
965 ///////////////////////////////////////////////////////
966 // 1. Python interpreter main program.
967 
968     void
969 python3_end(void)
970 {
971     static int recurse = 0;
972 
973     // If a crash occurs while doing this, don't try again.
974     if (recurse != 0)
975 	return;
976 
977     python_end_called = TRUE;
978     ++recurse;
979 
980 #ifdef DYNAMIC_PYTHON3
981     if (hinstPy3)
982 #endif
983     if (Py_IsInitialized())
984     {
985 	// acquire lock before finalizing
986 	PyGILState_Ensure();
987 
988 	Py_Finalize();
989     }
990 
991     --recurse;
992 }
993 
994 #if (defined(DYNAMIC_PYTHON3) && defined(DYNAMIC_PYTHON) && defined(FEAT_PYTHON) && defined(UNIX)) || defined(PROTO)
995     int
996 python3_loaded(void)
997 {
998     return (hinstPy3 != 0);
999 }
1000 #endif
1001 
1002 static wchar_t *py_home_buf = NULL;
1003 
1004 #if defined(MSWIN) && (PY_VERSION_HEX >= 0x030500f0)
1005 /*
1006  * Return TRUE if stdin is readable from Python 3.
1007  */
1008     static BOOL
1009 is_stdin_readable(void)
1010 {
1011     DWORD	    mode, eventnum;
1012     struct _stat    st;
1013     int		    fd = fileno(stdin);
1014     HANDLE	    hstdin = (HANDLE)_get_osfhandle(fd);
1015 
1016     // Check if stdin is connected to the console.
1017     if (GetConsoleMode(hstdin, &mode))
1018 	// Check if it is opened as input.
1019 	return GetNumberOfConsoleInputEvents(hstdin, &eventnum);
1020 
1021     return _fstat(fd, &st) == 0;
1022 }
1023 
1024 // Python 3.5 or later will abort inside Py_Initialize() when stdin has
1025 // been closed (i.e. executed by "vim -").  Reconnect stdin to CONIN$.
1026 // Note that the python DLL is linked to its own stdio DLL which can be
1027 // differ from Vim's stdio.
1028     static void
1029 reset_stdin(void)
1030 {
1031     FILE *(*py__acrt_iob_func)(unsigned) = NULL;
1032     FILE *(*pyfreopen)(const char *, const char *, FILE *) = NULL;
1033     HINSTANCE hinst;
1034 
1035 # ifdef DYNAMIC_PYTHON3
1036     hinst = hinstPy3;
1037 # else
1038     hinst = GetModuleHandle(PYTHON3_DLL);
1039 # endif
1040     if (hinst == NULL || is_stdin_readable())
1041 	return;
1042 
1043     // Get "freopen" and "stdin" which are used in the python DLL.
1044     // "stdin" is defined as "__acrt_iob_func(0)" in VC++ 2015 or later.
1045     py__acrt_iob_func = get_dll_import_func(hinst, "__acrt_iob_func");
1046     if (py__acrt_iob_func)
1047     {
1048 	HINSTANCE hpystdiodll = find_imported_module_by_funcname(hinst,
1049 							    "__acrt_iob_func");
1050 	if (hpystdiodll)
1051 	    pyfreopen = (void *)GetProcAddress(hpystdiodll, "freopen");
1052     }
1053 
1054     // Reconnect stdin to CONIN$.
1055     if (pyfreopen != NULL)
1056 	pyfreopen("CONIN$", "r", py__acrt_iob_func(0));
1057     else
1058 	freopen("CONIN$", "r", stdin);
1059 }
1060 #else
1061 # define reset_stdin()
1062 #endif
1063 
1064     static int
1065 Python3_Init(void)
1066 {
1067     if (!py3initialised)
1068     {
1069 #ifdef DYNAMIC_PYTHON3
1070 	if (!python3_enabled(TRUE))
1071 	{
1072 	    emsg(_("E263: Sorry, this command is disabled, the Python library could not be loaded."));
1073 	    goto fail;
1074 	}
1075 #endif
1076 
1077 	init_structs();
1078 
1079 	if (*p_py3home != NUL)
1080 	{
1081 	    size_t len = mbstowcs(NULL, (char *)p_py3home, 0) + 1;
1082 
1083 	    // The string must not change later, make a copy in static memory.
1084 	    py_home_buf = ALLOC_MULT(wchar_t, len);
1085 	    if (py_home_buf != NULL && mbstowcs(
1086 			    py_home_buf, (char *)p_py3home, len) != (size_t)-1)
1087 		Py_SetPythonHome(py_home_buf);
1088 	}
1089 #ifdef PYTHON3_HOME
1090 	else if (mch_getenv((char_u *)"PYTHONHOME") == NULL)
1091 	    Py_SetPythonHome(PYTHON3_HOME);
1092 #endif
1093 
1094 	PyImport_AppendInittab("vim", Py3Init_vim);
1095 
1096 	reset_stdin();
1097 	Py_Initialize();
1098 
1099 #if PY_VERSION_HEX < 0x03090000
1100 	// Initialise threads.  This is deprecated since Python 3.9.
1101 	PyEval_InitThreads();
1102 #endif
1103 #ifdef DYNAMIC_PYTHON3
1104 	get_py3_exceptions();
1105 #endif
1106 
1107 	if (PythonIO_Init_io())
1108 	    goto fail;
1109 
1110 	globals = PyModule_GetDict(PyImport_AddModule("__main__"));
1111 
1112 	// Remove the element from sys.path that was added because of our
1113 	// argv[0] value in Py3Init_vim().  Previously we used an empty
1114 	// string, but depending on the OS we then get an empty entry or
1115 	// the current directory in sys.path.
1116 	// Only after vim has been imported, the element does exist in
1117 	// sys.path.
1118 	PyRun_SimpleString("import vim; import sys; sys.path = list(filter(lambda x: not x.endswith('must>not&exist'), sys.path))");
1119 
1120 	// Without the call to PyEval_SaveThread, thread specific state (such
1121 	// as the system trace hook), will be lost between invocations of
1122 	// Python code.
1123 	// GIL may have been created and acquired in PyEval_InitThreads() and
1124 	// thread state is created in Py_Initialize(); there
1125 	// _PyGILState_NoteThreadState() also sets gilcounter to 1 (python must
1126 	// have threads enabled!), so the following does both: unlock GIL and
1127 	// save thread state in TLS without deleting thread state
1128 	PyEval_SaveThread();
1129 
1130 	py3initialised = 1;
1131     }
1132 
1133     return 0;
1134 
1135 fail:
1136     // We call PythonIO_Flush() here to print any Python errors.
1137     // This is OK, as it is possible to call this function even
1138     // if PythonIO_Init_io() has not completed successfully (it will
1139     // not do anything in this case).
1140     PythonIO_Flush();
1141     return -1;
1142 }
1143 
1144 /*
1145  * External interface
1146  */
1147     static void
1148 DoPyCommand(const char *cmd, rangeinitializer init_range, runner run, void *arg)
1149 {
1150 #if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
1151     char		*saved_locale;
1152 #endif
1153     PyObject		*cmdstr;
1154     PyObject		*cmdbytes;
1155     PyGILState_STATE	pygilstate;
1156 
1157     if (python_end_called)
1158 	goto theend;
1159 
1160     if (Python3_Init())
1161 	goto theend;
1162 
1163     init_range(arg);
1164 
1165     Python_Release_Vim();	    // leave Vim
1166 
1167 #if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
1168     // Python only works properly when the LC_NUMERIC locale is "C".
1169     saved_locale = setlocale(LC_NUMERIC, NULL);
1170     if (saved_locale == NULL || STRCMP(saved_locale, "C") == 0)
1171 	saved_locale = NULL;
1172     else
1173     {
1174 	// Need to make a copy, value may change when setting new locale.
1175 	saved_locale = (char *)vim_strsave((char_u *)saved_locale);
1176 	(void)setlocale(LC_NUMERIC, "C");
1177     }
1178 #endif
1179 
1180     pygilstate = PyGILState_Ensure();
1181 
1182     // PyRun_SimpleString expects a UTF-8 string. Wrong encoding may cause
1183     // SyntaxError (unicode error).
1184     cmdstr = PyUnicode_Decode(cmd, strlen(cmd),
1185 					(char *)ENC_OPT, ERRORS_DECODE_ARG);
1186     cmdbytes = PyUnicode_AsEncodedString(cmdstr, "utf-8", ERRORS_ENCODE_ARG);
1187     Py_XDECREF(cmdstr);
1188 
1189     run(PyBytes_AsString(cmdbytes), arg, &pygilstate);
1190     Py_XDECREF(cmdbytes);
1191 
1192     PyGILState_Release(pygilstate);
1193 
1194 #if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
1195     if (saved_locale != NULL)
1196     {
1197 	(void)setlocale(LC_NUMERIC, saved_locale);
1198 	vim_free(saved_locale);
1199     }
1200 #endif
1201 
1202     Python_Lock_Vim();		    // enter Vim
1203     PythonIO_Flush();
1204 
1205 theend:
1206     return;	    // keeps lint happy
1207 }
1208 
1209 /*
1210  * ":py3"
1211  */
1212     void
1213 ex_py3(exarg_T *eap)
1214 {
1215     char_u *script;
1216 
1217     script = script_get(eap, eap->arg);
1218     if (!eap->skip)
1219     {
1220 	if (p_pyx == 0)
1221 	    p_pyx = 3;
1222 
1223 	DoPyCommand(script == NULL ? (char *) eap->arg : (char *) script,
1224 		(rangeinitializer) init_range_cmd,
1225 		(runner) run_cmd,
1226 		(void *) eap);
1227     }
1228     vim_free(script);
1229 }
1230 
1231 #define BUFFER_SIZE 2048
1232 
1233 /*
1234  * ":py3file"
1235  */
1236     void
1237 ex_py3file(exarg_T *eap)
1238 {
1239     static char buffer[BUFFER_SIZE];
1240     const char *file;
1241     char *p;
1242     int i;
1243 
1244     if (p_pyx == 0)
1245 	p_pyx = 3;
1246 
1247     // Have to do it like this. PyRun_SimpleFile requires you to pass a
1248     // stdio file pointer, but Vim and the Python DLL are compiled with
1249     // different options under Windows, meaning that stdio pointers aren't
1250     // compatible between the two. Yuk.
1251     //
1252     // construct: exec(compile(open('a_filename', 'rb').read(), 'a_filename', 'exec'))
1253     //
1254     // Using bytes so that Python can detect the source encoding as it normally
1255     // does. The doc does not say "compile" accept bytes, though.
1256     //
1257     // We need to escape any backslashes or single quotes in the file name, so that
1258     // Python won't mangle the file name.
1259 
1260     strcpy(buffer, "exec(compile(open('");
1261     p = buffer + 19; // size of "exec(compile(open('"
1262 
1263     for (i=0; i<2; ++i)
1264     {
1265 	file = (char *)eap->arg;
1266 	while (*file && p < buffer + (BUFFER_SIZE - 3))
1267 	{
1268 	    if (*file == '\\' || *file == '\'')
1269 		*p++ = '\\';
1270 	    *p++ = *file++;
1271 	}
1272 	// If we didn't finish the file name, we hit a buffer overflow
1273 	if (*file != '\0')
1274 	    return;
1275 	if (i==0)
1276 	{
1277 	    strcpy(p,"','rb').read(),'");
1278 	    p += 16;
1279 	}
1280 	else
1281 	{
1282 	    strcpy(p,"','exec'))");
1283 	    p += 10;
1284 	}
1285     }
1286 
1287 
1288     // Execute the file
1289     DoPyCommand(buffer,
1290 	    (rangeinitializer) init_range_cmd,
1291 	    (runner) run_cmd,
1292 	    (void *) eap);
1293 }
1294 
1295     void
1296 ex_py3do(exarg_T *eap)
1297 {
1298     if (p_pyx == 0)
1299 	p_pyx = 3;
1300 
1301     DoPyCommand((char *)eap->arg,
1302 	    (rangeinitializer)init_range_cmd,
1303 	    (runner)run_do,
1304 	    (void *)eap);
1305 }
1306 
1307 ///////////////////////////////////////////////////////
1308 // 2. Python output stream: writes output via [e]msg().
1309 
1310 // Implementation functions
1311 
1312     static PyObject *
1313 OutputGetattro(PyObject *self, PyObject *nameobj)
1314 {
1315     GET_ATTR_STRING(name, nameobj);
1316 
1317     if (strcmp(name, "softspace") == 0)
1318 	return PyLong_FromLong(((OutputObject *)(self))->softspace);
1319     else if (strcmp(name, "errors") == 0)
1320 	return PyString_FromString("strict");
1321     else if (strcmp(name, "encoding") == 0)
1322 	return PyString_FromString(ENC_OPT);
1323 
1324     return PyObject_GenericGetAttr(self, nameobj);
1325 }
1326 
1327     static int
1328 OutputSetattro(PyObject *self, PyObject *nameobj, PyObject *val)
1329 {
1330     GET_ATTR_STRING(name, nameobj);
1331 
1332     return OutputSetattr((OutputObject *)(self), name, val);
1333 }
1334 
1335 ///////////////////////////////////////////////////////
1336 // 3. Implementation of the Vim module for Python
1337 
1338 // Window type - Implementation functions
1339 // --------------------------------------
1340 
1341 #define WindowType_Check(obj) ((obj)->ob_base.ob_type == &WindowType)
1342 
1343 // Buffer type - Implementation functions
1344 // --------------------------------------
1345 
1346 #define BufferType_Check(obj) ((obj)->ob_base.ob_type == &BufferType)
1347 
1348 static PyObject* BufferSubscript(PyObject *self, PyObject *idx);
1349 static int BufferAsSubscript(PyObject *self, PyObject *idx, PyObject *val);
1350 
1351 // Line range type - Implementation functions
1352 // --------------------------------------
1353 
1354 #define RangeType_Check(obj) ((obj)->ob_base.ob_type == &RangeType)
1355 
1356 static PyObject* RangeSubscript(PyObject *self, PyObject *idx);
1357 static int RangeAsItem(PyObject *, Py_ssize_t, PyObject *);
1358 static int RangeAsSubscript(PyObject *self, PyObject *idx, PyObject *val);
1359 
1360 // Current objects type - Implementation functions
1361 // -----------------------------------------------
1362 
1363 static PySequenceMethods BufferAsSeq = {
1364     (lenfunc)		BufferLength,	    // sq_length,    len(x)
1365     (binaryfunc)	0,		    // sq_concat,    x+y
1366     (ssizeargfunc)	0,		    // sq_repeat,    x*n
1367     (ssizeargfunc)	BufferItem,	    // sq_item,      x[i]
1368     0,					    // was_sq_slice,	 x[i:j]
1369     0,					    // sq_ass_item,  x[i]=v
1370     0,					    // sq_ass_slice, x[i:j]=v
1371     0,					    // sq_contains
1372     0,					    // sq_inplace_concat
1373     0,					    // sq_inplace_repeat
1374 };
1375 
1376 static PyMappingMethods BufferAsMapping = {
1377     /* mp_length	*/ (lenfunc)BufferLength,
1378     /* mp_subscript     */ (binaryfunc)BufferSubscript,
1379     /* mp_ass_subscript */ (objobjargproc)BufferAsSubscript,
1380 };
1381 
1382 
1383 // Buffer object
1384 
1385     static PyObject *
1386 BufferGetattro(PyObject *self, PyObject *nameobj)
1387 {
1388     PyObject *r;
1389 
1390     GET_ATTR_STRING(name, nameobj);
1391 
1392     if ((r = BufferAttrValid((BufferObject *)(self), name)))
1393 	return r;
1394 
1395     if (CheckBuffer((BufferObject *)(self)))
1396 	return NULL;
1397 
1398     r = BufferAttr((BufferObject *)(self), name);
1399     if (r || PyErr_Occurred())
1400 	return r;
1401     else
1402 	return PyObject_GenericGetAttr(self, nameobj);
1403 }
1404 
1405     static int
1406 BufferSetattro(PyObject *self, PyObject *nameobj, PyObject *val)
1407 {
1408     GET_ATTR_STRING(name, nameobj);
1409 
1410     return BufferSetattr((BufferObject *)(self), name, val);
1411 }
1412 
1413 //////////////////
1414 
1415     static PyObject *
1416 BufferSubscript(PyObject *self, PyObject* idx)
1417 {
1418     if (PyLong_Check(idx))
1419     {
1420 	long _idx = PyLong_AsLong(idx);
1421 	return BufferItem((BufferObject *)(self), _idx);
1422     } else if (PySlice_Check(idx))
1423     {
1424 	Py_ssize_t start, stop, step, slicelen;
1425 
1426 	if (CheckBuffer((BufferObject *) self))
1427 	    return NULL;
1428 
1429 	if (PySlice_GetIndicesEx((PySliceObject_T *)idx,
1430 	      (Py_ssize_t)((BufferObject *)(self))->buf->b_ml.ml_line_count,
1431 	      &start, &stop,
1432 	      &step, &slicelen) < 0)
1433 	    return NULL;
1434 	return BufferSlice((BufferObject *)(self), start, stop);
1435     }
1436     else
1437     {
1438 	RAISE_INVALID_INDEX_TYPE(idx);
1439 	return NULL;
1440     }
1441 }
1442 
1443     static int
1444 BufferAsSubscript(PyObject *self, PyObject* idx, PyObject* val)
1445 {
1446     if (PyLong_Check(idx))
1447     {
1448 	long n = PyLong_AsLong(idx);
1449 
1450 	if (CheckBuffer((BufferObject *) self))
1451 	    return -1;
1452 
1453 	return RBAsItem((BufferObject *)(self), n, val, 1,
1454 		    (Py_ssize_t)((BufferObject *)(self))->buf->b_ml.ml_line_count,
1455 		    NULL);
1456     } else if (PySlice_Check(idx))
1457     {
1458 	Py_ssize_t start, stop, step, slicelen;
1459 
1460 	if (CheckBuffer((BufferObject *) self))
1461 	    return -1;
1462 
1463 	if (PySlice_GetIndicesEx((PySliceObject_T *)idx,
1464 	      (Py_ssize_t)((BufferObject *)(self))->buf->b_ml.ml_line_count,
1465 	      &start, &stop,
1466 	      &step, &slicelen) < 0)
1467 	    return -1;
1468 	return RBAsSlice((BufferObject *)(self), start, stop, val, 1,
1469 			  (PyInt)((BufferObject *)(self))->buf->b_ml.ml_line_count,
1470 			  NULL);
1471     }
1472     else
1473     {
1474 	RAISE_INVALID_INDEX_TYPE(idx);
1475 	return -1;
1476     }
1477 }
1478 
1479 static PySequenceMethods RangeAsSeq = {
1480     (lenfunc)		RangeLength,	 // sq_length,	  len(x)
1481     (binaryfunc)	0,		 // RangeConcat, sq_concat,  x+y
1482     (ssizeargfunc)	0,		 // RangeRepeat, sq_repeat,  x*n
1483     (ssizeargfunc)	RangeItem,	 // sq_item,	  x[i]
1484     0,					 // was_sq_slice,     x[i:j]
1485     (ssizeobjargproc)	RangeAsItem,	 // sq_as_item,  x[i]=v
1486     0,					 // sq_ass_slice, x[i:j]=v
1487     0,					 // sq_contains
1488     0,					 // sq_inplace_concat
1489     0,					 // sq_inplace_repeat
1490 };
1491 
1492 static PyMappingMethods RangeAsMapping = {
1493     /* mp_length	*/ (lenfunc)RangeLength,
1494     /* mp_subscript     */ (binaryfunc)RangeSubscript,
1495     /* mp_ass_subscript */ (objobjargproc)RangeAsSubscript,
1496 };
1497 
1498 // Line range object - Implementation
1499 
1500     static PyObject *
1501 RangeGetattro(PyObject *self, PyObject *nameobj)
1502 {
1503     GET_ATTR_STRING(name, nameobj);
1504 
1505     if (strcmp(name, "start") == 0)
1506 	return Py_BuildValue("n", ((RangeObject *)(self))->start - 1);
1507     else if (strcmp(name, "end") == 0)
1508 	return Py_BuildValue("n", ((RangeObject *)(self))->end - 1);
1509     else
1510 	return PyObject_GenericGetAttr(self, nameobj);
1511 }
1512 
1513 ////////////////
1514 
1515     static int
1516 RangeAsItem(PyObject *self, Py_ssize_t n, PyObject *val)
1517 {
1518     return RBAsItem(((RangeObject *)(self))->buf, n, val,
1519 		    ((RangeObject *)(self))->start,
1520 		    ((RangeObject *)(self))->end,
1521 		    &((RangeObject *)(self))->end);
1522 }
1523 
1524     static Py_ssize_t
1525 RangeAsSlice(PyObject *self, Py_ssize_t lo, Py_ssize_t hi, PyObject *val)
1526 {
1527     return RBAsSlice(((RangeObject *)(self))->buf, lo, hi, val,
1528 		    ((RangeObject *)(self))->start,
1529 		    ((RangeObject *)(self))->end,
1530 		    &((RangeObject *)(self))->end);
1531 }
1532 
1533     static PyObject *
1534 RangeSubscript(PyObject *self, PyObject* idx)
1535 {
1536     if (PyLong_Check(idx))
1537     {
1538 	long _idx = PyLong_AsLong(idx);
1539 	return RangeItem((RangeObject *)(self), _idx);
1540     } else if (PySlice_Check(idx))
1541     {
1542 	Py_ssize_t start, stop, step, slicelen;
1543 
1544 	if (PySlice_GetIndicesEx((PySliceObject_T *)idx,
1545 		((RangeObject *)(self))->end-((RangeObject *)(self))->start+1,
1546 		&start, &stop,
1547 		&step, &slicelen) < 0)
1548 	    return NULL;
1549 	return RangeSlice((RangeObject *)(self), start, stop);
1550     }
1551     else
1552     {
1553 	RAISE_INVALID_INDEX_TYPE(idx);
1554 	return NULL;
1555     }
1556 }
1557 
1558     static int
1559 RangeAsSubscript(PyObject *self, PyObject *idx, PyObject *val)
1560 {
1561     if (PyLong_Check(idx))
1562     {
1563 	long n = PyLong_AsLong(idx);
1564 	return RangeAsItem(self, n, val);
1565     }
1566     else if (PySlice_Check(idx))
1567     {
1568 	Py_ssize_t start, stop, step, slicelen;
1569 
1570 	if (PySlice_GetIndicesEx((PySliceObject_T *)idx,
1571 		((RangeObject *)(self))->end-((RangeObject *)(self))->start+1,
1572 		&start, &stop,
1573 		&step, &slicelen) < 0)
1574 	    return -1;
1575 	return RangeAsSlice(self, start, stop, val);
1576     }
1577     else
1578     {
1579 	RAISE_INVALID_INDEX_TYPE(idx);
1580 	return -1;
1581     }
1582 }
1583 
1584 // TabPage object - Implementation
1585 
1586     static PyObject *
1587 TabPageGetattro(PyObject *self, PyObject *nameobj)
1588 {
1589     PyObject *r;
1590 
1591     GET_ATTR_STRING(name, nameobj);
1592 
1593     if ((r = TabPageAttrValid((TabPageObject *)(self), name)))
1594 	return r;
1595 
1596     if (CheckTabPage((TabPageObject *)(self)))
1597 	return NULL;
1598 
1599     r = TabPageAttr((TabPageObject *)(self), name);
1600     if (r || PyErr_Occurred())
1601 	return r;
1602     else
1603 	return PyObject_GenericGetAttr(self, nameobj);
1604 }
1605 
1606 // Window object - Implementation
1607 
1608     static PyObject *
1609 WindowGetattro(PyObject *self, PyObject *nameobj)
1610 {
1611     PyObject *r;
1612 
1613     GET_ATTR_STRING(name, nameobj);
1614 
1615     if ((r = WindowAttrValid((WindowObject *)(self), name)))
1616 	return r;
1617 
1618     if (CheckWindow((WindowObject *)(self)))
1619 	return NULL;
1620 
1621     r = WindowAttr((WindowObject *)(self), name);
1622     if (r || PyErr_Occurred())
1623 	return r;
1624     else
1625 	return PyObject_GenericGetAttr(self, nameobj);
1626 }
1627 
1628     static int
1629 WindowSetattro(PyObject *self, PyObject *nameobj, PyObject *val)
1630 {
1631     GET_ATTR_STRING(name, nameobj);
1632 
1633     return WindowSetattr((WindowObject *)(self), name, val);
1634 }
1635 
1636 // Tab page list object - Definitions
1637 
1638 static PySequenceMethods TabListAsSeq = {
1639     (lenfunc)	     TabListLength,	    // sq_length,    len(x)
1640     (binaryfunc)     0,			    // sq_concat,    x+y
1641     (ssizeargfunc)   0,			    // sq_repeat,    x*n
1642     (ssizeargfunc)   TabListItem,	    // sq_item,      x[i]
1643     0,					    // sq_slice,     x[i:j]
1644     (ssizeobjargproc)0,			    // sq_as_item,  x[i]=v
1645     0,					    // sq_ass_slice, x[i:j]=v
1646     0,					    // sq_contains
1647     0,					    // sq_inplace_concat
1648     0,					    // sq_inplace_repeat
1649 };
1650 
1651 // Window list object - Definitions
1652 
1653 static PySequenceMethods WinListAsSeq = {
1654     (lenfunc)	     WinListLength,	    // sq_length,    len(x)
1655     (binaryfunc)     0,			    // sq_concat,    x+y
1656     (ssizeargfunc)   0,			    // sq_repeat,    x*n
1657     (ssizeargfunc)   WinListItem,	    // sq_item,      x[i]
1658     0,					    // sq_slice,     x[i:j]
1659     (ssizeobjargproc)0,			    // sq_as_item,  x[i]=v
1660     0,					    // sq_ass_slice, x[i:j]=v
1661     0,					    // sq_contains
1662     0,					    // sq_inplace_concat
1663     0,					    // sq_inplace_repeat
1664 };
1665 
1666 /*
1667  * Current items object - Implementation
1668  */
1669     static PyObject *
1670 CurrentGetattro(PyObject *self, PyObject *nameobj)
1671 {
1672     PyObject	*r;
1673     GET_ATTR_STRING(name, nameobj);
1674     if (!(r = CurrentGetattr(self, name)))
1675 	return PyObject_GenericGetAttr(self, nameobj);
1676     return r;
1677 }
1678 
1679     static int
1680 CurrentSetattro(PyObject *self, PyObject *nameobj, PyObject *value)
1681 {
1682     GET_ATTR_STRING(name, nameobj);
1683     return CurrentSetattr(self, name, value);
1684 }
1685 
1686 // Dictionary object - Definitions
1687 
1688     static PyObject *
1689 DictionaryGetattro(PyObject *self, PyObject *nameobj)
1690 {
1691     DictionaryObject	*this = ((DictionaryObject *) (self));
1692 
1693     GET_ATTR_STRING(name, nameobj);
1694 
1695     if (strcmp(name, "locked") == 0)
1696 	return PyLong_FromLong(this->dict->dv_lock);
1697     else if (strcmp(name, "scope") == 0)
1698 	return PyLong_FromLong(this->dict->dv_scope);
1699 
1700     return PyObject_GenericGetAttr(self, nameobj);
1701 }
1702 
1703     static int
1704 DictionarySetattro(PyObject *self, PyObject *nameobj, PyObject *val)
1705 {
1706     GET_ATTR_STRING(name, nameobj);
1707     return DictionarySetattr((DictionaryObject *)(self), name, val);
1708 }
1709 
1710 // List object - Definitions
1711 
1712     static PyObject *
1713 ListGetattro(PyObject *self, PyObject *nameobj)
1714 {
1715     GET_ATTR_STRING(name, nameobj);
1716 
1717     if (strcmp(name, "locked") == 0)
1718 	return PyLong_FromLong(((ListObject *) (self))->list->lv_lock);
1719 
1720     return PyObject_GenericGetAttr(self, nameobj);
1721 }
1722 
1723     static int
1724 ListSetattro(PyObject *self, PyObject *nameobj, PyObject *val)
1725 {
1726     GET_ATTR_STRING(name, nameobj);
1727     return ListSetattr((ListObject *)(self), name, val);
1728 }
1729 
1730 // Function object - Definitions
1731 
1732     static PyObject *
1733 FunctionGetattro(PyObject *self, PyObject *nameobj)
1734 {
1735     PyObject		*r;
1736     FunctionObject	*this = (FunctionObject *)(self);
1737 
1738     GET_ATTR_STRING(name, nameobj);
1739 
1740     r = FunctionAttr(this, name);
1741     if (r || PyErr_Occurred())
1742 	return r;
1743     else
1744 	return PyObject_GenericGetAttr(self, nameobj);
1745 }
1746 
1747 // External interface
1748 
1749     void
1750 python3_buffer_free(buf_T *buf)
1751 {
1752     if (BUF_PYTHON_REF(buf) != NULL)
1753     {
1754 	BufferObject *bp = BUF_PYTHON_REF(buf);
1755 	bp->buf = INVALID_BUFFER_VALUE;
1756 	BUF_PYTHON_REF(buf) = NULL;
1757     }
1758 }
1759 
1760     void
1761 python3_window_free(win_T *win)
1762 {
1763     if (WIN_PYTHON_REF(win) != NULL)
1764     {
1765 	WindowObject *wp = WIN_PYTHON_REF(win);
1766 	wp->win = INVALID_WINDOW_VALUE;
1767 	WIN_PYTHON_REF(win) = NULL;
1768     }
1769 }
1770 
1771     void
1772 python3_tabpage_free(tabpage_T *tab)
1773 {
1774     if (TAB_PYTHON_REF(tab) != NULL)
1775     {
1776 	TabPageObject *tp = TAB_PYTHON_REF(tab);
1777 	tp->tab = INVALID_TABPAGE_VALUE;
1778 	TAB_PYTHON_REF(tab) = NULL;
1779     }
1780 }
1781 
1782     static PyObject *
1783 Py3Init_vim(void)
1784 {
1785     // The special value is removed from sys.path in Python3_Init().
1786     static wchar_t *(argv[2]) = {L"/must>not&exist/foo", NULL};
1787 
1788     if (init_types())
1789 	return NULL;
1790 
1791     // Set sys.argv[] to avoid a crash in warn().
1792     PySys_SetArgv(1, argv);
1793 
1794     if ((vim_module = PyModule_Create(&vimmodule)) == NULL)
1795 	return NULL;
1796 
1797     if (populate_module(vim_module))
1798 	return NULL;
1799 
1800     if (init_sys_path())
1801 	return NULL;
1802 
1803     return vim_module;
1804 }
1805 
1806 //////////////////////////////////////////////////////////////////////////
1807 // 4. Utility functions for handling the interface between Vim and Python.
1808 
1809 /*
1810  * Convert a Vim line into a Python string.
1811  * All internal newlines are replaced by null characters.
1812  *
1813  * On errors, the Python exception data is set, and NULL is returned.
1814  */
1815     static PyObject *
1816 LineToString(const char *str)
1817 {
1818     PyObject *result;
1819     Py_ssize_t len = strlen(str);
1820     char *tmp, *p;
1821 
1822     tmp = alloc(len + 1);
1823     p = tmp;
1824     if (p == NULL)
1825     {
1826 	PyErr_NoMemory();
1827 	return NULL;
1828     }
1829 
1830     while (*str)
1831     {
1832 	if (*str == '\n')
1833 	    *p = '\0';
1834 	else
1835 	    *p = *str;
1836 
1837 	++p;
1838 	++str;
1839     }
1840     *p = '\0';
1841 
1842     result = PyUnicode_Decode(tmp, len, (char *)ENC_OPT, ERRORS_DECODE_ARG);
1843 
1844     vim_free(tmp);
1845     return result;
1846 }
1847 
1848     void
1849 do_py3eval(char_u *str, typval_T *rettv)
1850 {
1851     DoPyCommand((char *) str,
1852 	    (rangeinitializer) init_range_eval,
1853 	    (runner) run_eval,
1854 	    (void *) rettv);
1855     if (rettv->v_type == VAR_UNKNOWN)
1856     {
1857 	rettv->v_type = VAR_NUMBER;
1858 	rettv->vval.v_number = 0;
1859     }
1860 }
1861 
1862     int
1863 set_ref_in_python3(int copyID)
1864 {
1865     return set_ref_in_py(copyID);
1866 }
1867