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