Mercurial > vim
view README_VIM9.md @ 32936:c517845bd10e v9.0.1776
patch 9.0.1776: No support for stable Python 3 ABI
Commit: https://github.com/vim/vim/commit/c13b3d1350b60b94fe87f0761ea31c0e7fb6ebf3
Author: Yee Cheng Chin <ychin.git@gmail.com>
Date: Sun Aug 20 21:18:38 2023 +0200
patch 9.0.1776: No support for stable Python 3 ABI
Problem: No support for stable Python 3 ABI
Solution: Support Python 3 stable ABI
Commits:
1) Support Python 3 stable ABI to allow mixed version interoperatbility
Vim currently supports embedding Python for use with plugins, and the
"dynamic" linking option allows the user to specify a locally installed
version of Python by setting `pythonthreedll`. However, one caveat is
that the Python 3 libs are not binary compatible across minor versions,
and mixing versions can potentially be dangerous (e.g. let's say Vim was
linked against the Python 3.10 SDK, but the user sets `pythonthreedll`
to a 3.11 lib). Usually, nothing bad happens, but in theory this could
lead to crashes, memory corruption, and other unpredictable behaviors.
It's also difficult for the user to tell something is wrong because Vim
has no way of reporting what Python 3 version Vim was linked with.
For Vim installed via a package manager, this usually isn't an issue
because all the dependencies would already be figured out. For prebuilt
Vim binaries like MacVim (my motivation for working on this), AppImage,
and Win32 installer this could potentially be an issue as usually a
single binary is distributed. This is more tricky when a new Python
version is released, as there's a chicken-and-egg issue with deciding
what Python version to build against and hard to keep in sync when a new
Python version just drops and we have a mix of users of different Python
versions, and a user just blindly upgrading to a new Python could lead to
bad interactions with Vim.
Python 3 does have a solution for this problem: stable ABI / limited API
(see https://docs.python.org/3/c-api/stable.html). The C SDK limits the
API to a set of functions that are promised to be stable across
versions. This pull request adds an ifdef config that allows us to turn
it on when building Vim. Vim binaries built with this option should be
safe to freely link with any Python 3 libraies without having the
constraint of having to use the same minor version.
Note: Python 2 has no such concept and this doesn't change how Python 2
integration works (not that there is going to be a new version of Python
2 that would cause compatibility issues in the future anyway).
---
Technical details:
======
The stable ABI can be accessed when we compile with the Python 3 limited
API (by defining `Py_LIMITED_API`). The Python 3 code (in `if_python3.c`
and `if_py_both.h`) would now handle this and switch to limited API
mode. Without it set, Vim will still use the full API as before so this
is an opt-in change.
The main difference is that `PyType_Object` is now an opaque struct that
we can't directly create "static types" out of, and we have to create
type objects as "heap types" instead. This is because the struct is not
stable and changes from version to version (e.g. 3.8 added a
`tp_vectorcall` field to it). I had to change all the types to be
allocated on the heap instead with just a pointer to them.
Other functions are also simply missing in limited API, or they are
introduced too late (e.g. `PyUnicode_AsUTF8AndSize` in 3.10) to it that
we need some other ways to do the same thing, so I had to abstract a few
things into macros, and sometimes re-implement functions like
`PyObject_NEW`.
One caveat is that in limited API, `OutputType` (used for replacing
`sys.stdout`) no longer inherits from `PyStdPrinter_Type` which I don't
think has any real issue other than minor differences in how they
convert to a string and missing a couple functions like `mode()` and
`fileno()`.
Also fixed an existing bug where `tp_basicsize` was set incorrectly for
`BufferObject`, `TabListObject, `WinListObject`.
Technically, there could be a small performance drop, there is a little
more indirection with accessing type objects, and some APIs like
`PyUnicode_AsUTF8AndSize` are missing, but in practice I didn't see any
difference, and any well-written Python plugin should try to avoid
excessing callbacks to the `vim` module in Python anyway.
I only tested limited API mode down to Python 3.7, which seemes to
compile and work fine. I haven't tried earlier Python versions.
2) Fix PyIter_Check on older Python vers / type##Ptr unused warning
For PyIter_Check, older versions exposed them as either macros (used in
full API), or a function (for use in limited API). A previous change
exposed PyIter_Check to the dynamic build because Python just moved it
to function-only in 3.10 anyway. Because of that, just make sure we
always grab the function in dynamic builds in earlier versions since
that's what Python eventually did anyway.
3) Move Py_LIMITED_API define to configure script
Can now use --with-python-stable-abi flag to customize what stable ABI
version to target. Can also use an env var to do so as well.
4) Show +python/dyn-stable in :version, and allow has() feature query
Not sure if the "/dyn-stable" suffix would break things, or whether we
should do it another way. Or just don't show it in version and rely on
has() feature checking.
5) Documentation first draft. Still need to implement v:python3_version
6) Fix PyIter_Check build breaks when compiling against Python 3.8
7) Add CI coverage stable ABI on Linux/Windows / make configurable on Windows
This adds configurable options for Windows make files (both MinGW and
MSVC). CI will also now exercise both traditional full API and stable
ABI for Linux and Windows in the matrix for coverage.
Also added a "dynamic" option to Linux matrix as a drive-by change to
make other scripting languages like Ruby / Perl testable under both
static and dynamic builds.
8) Fix inaccuracy in Windows docs
Python's own docs are confusing but you don't actually want to use
`python3.dll` for the dynamic linkage.
9) Add generated autoconf file
10) Add v:python3_version support
This variable indicates the version of Python3 that Vim was built
against (PY_VERSION_HEX), and will be useful to check whether the Python
library you are loading in dynamically actually fits it. When built with
stable ABI, it will be the limited ABI version instead
(`Py_LIMITED_API`), which indicates the minimum version of Python 3 the
user should have, rather than the exact match. When stable ABI is used,
we won't be exposing PY_VERSION_HEX in this var because it just doesn't
seem necessary to do so (the whole point of stable ABI is the promise
that it will work across versions), and I don't want to confuse the user
with too many variables.
Also, cleaned up some documentation, and added help tags.
11) Fix Python 3.7 compat issues
Fix a couple issues when using limited API < 3.8
- Crash on exit: In Python 3.7, if a heap-allocated type is destroyed
before all instances are, it would cause a crash later. This happens
when we destroyed `OptionsType` before calling `Py_Finalize` when
using the limited API. To make it worse, later versions changed the
semantics and now each instance has a strong reference to its own type
and the recommendation has changed to have each instance de-ref its
own type and have its type in GC traversal. To avoid dealing with
these cross-version variations, we just don't free the heap type. They
are static types in non-limited-API anyway and are designed to last
through the entirety of the app, and we also don't restart the Python
runtime and therefore do not need it to have absolutely 0 leaks.
See:
- https://docs.python.org/3/whatsnew/3.8.html#changes-in-the-c-api
- https://docs.python.org/3/whatsnew/3.9.html#changes-in-the-c-api
- PyIter_Check: This function is not provided in limited APIs older than
3.8. Previously I was trying to mock it out using manual
PyType_GetSlot() but it was brittle and also does not actually work
properly for static types (it will generate a Python error). Just
return false. It does mean using limited API < 3.8 is not recommended
as you lose the functionality to handle iterators, but from playing
with plugins I couldn't find it to be an issue.
- Fix loading of PyIter_Check so it will be done when limited API < 3.8.
Otherwise loading a 3.7 Python lib will fail even if limited API was
specified to use it.
12) Make sure to only load `PyUnicode_AsUTF8AndSize` in needed in limited API
We don't use this function unless limited API >= 3.10, but we were
loading it regardless. Usually it's ok in Unix-like systems where Python
just has a single lib that we load from, but in Windows where there is a
separate python3.dll this would not work as the symbol would not have
been exposed in this more limited DLL file. This makes it much clearer
under what condition is this function needed.
closes: #12032
Signed-off-by: Christian Brabandt <cb@256bit.org>
Co-authored-by: Yee Cheng Chin <ychin.git@gmail.com>
author | Christian Brabandt <cb@256bit.org> |
---|---|
date | Sun, 20 Aug 2023 21:30:04 +0200 |
parents | cc751d944b7e |
children |
line wrap: on
line source
![Vim Logo](https://github.com/vim/vim/blob/master/runtime/vimlogo.gif) # What is Vim9? This is a new syntax for Vim script that was introduced with Vim 9.0. It intends making Vim script faster and better. # Why Vim9? ## 1. FASTER VIM SCRIPT The third item on the poll results of 2018, after popup windows and text properties, both of which have been implemented, is faster Vim script. So how do we do that? I have been throwing some ideas around, and soon came to the conclusion that the current way functions are called and executed, with dictionaries for the arguments and local variables, is never going to be very fast. We're lucky if we can make it twice as fast. The overhead of a function call and executing every line is just too high. So what then? We can only make something fast by having a new way of defining a function, with similar but different properties of the old way: * Arguments are only available by name, not through the a: dictionary or the a:000 list. * Local variables are not available in an l: dictionary. * A few more things that slow us down, such as exception handling details. I Implemented a "proof of concept" and measured the time to run a simple for loop with an addition (Justin used this example in his presentation, full code is below): ``` vim let sum = 0 for i in range(1, 2999999) let sum += i endfor ``` | how | time in sec | | --------| -------- | | Vim old | 5.018541 | | Python | 0.369598 | | Lua | 0.078817 | | LuaJit | 0.004245 | | Vim new | 0.073595 | That looks very promising! It's just one example, but it shows how much we can gain, and also that Vim script can be faster than builtin interfaces. LuaJit is much faster at Lua-only instructions. In practice the script would not do something useless counting, but change the text. For example, reindent all the lines: ``` vim let totallen = 0 for i in range(1, 100000) call setline(i, ' ' .. getline(i)) let totallen += len(getline(i)) endfor ``` | how | time in sec | | --------| -------- | | Vim old | 0.578598 | | Python | 0.152040 | | Lua | 0.164917 | | LuaJit | 0.128400 | | Vim new | 0.079692 | [These times were measured on a different system by Dominique Pelle] The differences are smaller, but Vim 9 script is clearly the fastest. Using LuaJIT is only a little bit faster than plain Lua here, clearly the call back to the Vim code is costly. How does Vim9 script work? The function is first compiled into a sequence of instructions. Each instruction has one or two parameters and a stack is used to store intermediate results. Local variables are also on the stack, space is reserved during compilation. This is a fairly normal way of compilation into an intermediate format, specialized for Vim, e.g. each stack item is a typeval_T. And one of the instructions is "execute Ex command", for commands that are not compiled. ## 2. DEPRIORITIZE INTERFACES Attempts have been made to implement functionality with built-in script languages such as Python, Perl, Lua, Tcl and Ruby. This never gained much foothold, for various reasons. Instead of using script language support in Vim: * Encourage implementing external tools in any language and communicate with them. The job and channel support already makes this possible. Really any language can be used, also Java and Go, which are not available built-in. * No priority for the built-in language interfaces. They will have to be kept for backwards compatibility, but many users won't need a Vim build with these interfaces. * Improve the Vim script language, it is used to communicate with the external tool and implements the Vim side of the interface. Also, it can be used when an external tool is undesired. Altogether this creates a clear situation: Vim with the +eval feature will be sufficient for most plugins, while some plugins require installing a tool that can be written in any language. No confusion about having Vim but the plugin not working because some specific language is missing. This is a good long term goal. Rationale: Why is it better to run a tool separately from Vim than using a built-in interface and interpreter? Take for example something that is written in Python: * The built-in interface uses the embedded python interpreter. This is less well maintained than the python command. Building Vim with it requires installing developer packages. If loaded dynamically there can be a version mismatch. * When running the tool externally the standard python command can be used, which is quite often available by default or can be easily installed. * The built-in interface has an API that is unique for Vim with Python. This is an extra API to learn. * A .py file can be compiled into a .pyc file and execute much faster. * Inside Vim multi-threading can cause problems, since the Vim core is single threaded. In an external tool there are no such problems. * The Vim part is written in .vim files, the Python part is in .py files, this is nicely separated. * Disadvantage: An interface needs to be made between Vim and Python. JSON is available for this, and it's fairly easy to use. But it still requires implementing asynchronous communication. ## 3. BETTER VIM SCRIPT To make Vim faster a new way of defining a function needs to be added. While we are doing that, since the lines in this function won't be fully backwards compatible anyway, we can also make Vim script easier to use. In other words: "less weird". Making it work more like modern programming languages will help. No surprises. A good example is how in a function the arguments are prefixed with "a:". No other language I know does that, so let's drop it. Taking this one step further is also dropping "s:" for script-local variables; everything at the script level is script-local by default. Since this is not backwards compatible it requires a new script style: Vim9 script! To avoid having more variations, the syntax inside a compiled function is the same as in Vim9 script. Thus you have legacy syntax and Vim9 syntax. It should be possible to convert code from other languages to Vim script. We can add functionality to make this easier. This still needs to be discussed, but we can consider adding type checking and a simple form of classes. If you look at JavaScript for example, it has gone through these stages over time, adding real class support and now TypeScript adds type checking. But we'll have to see how much of that we actually want to include in Vim script. Ideally a conversion tool can take Python, JavaScript or TypeScript code and convert it to Vim script, with only some things that cannot be converted. Vim script won't work the same as any specific language, but we can use mechanisms that are commonly known, ideally with the same syntax. One thing I have been thinking of is assignments without ":let". I often make that mistake (after writing JavaScript especially). I think it is possible, if we make local variables shadow commands. That should be OK, if you shadow a command you want to use, just rename the variable. Using "var" and "const" to declare a variable, like in JavaScript and TypeScript, can work: ``` vim def MyFunction(arg: number): number var local = 1 var todo = arg const ADD = 88 while todo > 0 local += ADD todo -= 1 endwhile return local enddef ``` The similarity with JavaScript/TypeScript can also be used for dependencies between files. Vim currently uses the `:source` command, which has several disadvantages: * In the sourced script, is not clear what it provides. By default all functions are global and can be used elsewhere. * In a script that sources other scripts, it is not clear what function comes from what sourced script. Finding the implementation is a hassle. * Prevention of loading the whole script twice must be manually implemented. We can use the `:import` and `:export` commands from the JavaScript standard to make this much better. For example, in script "myfunction.vim" define a function and export it: ``` vim vim9script " Vim9 script syntax used here var local = 'local variable is not exported, script-local' export def MyFunction() " exported function ... def LocalFunction() " not exported, script-local ... ``` And in another script import the function: ``` vim vim9script " Vim9 script syntax used here import MyFunction from 'myfunction.vim' ``` This looks like JavaScript/TypeScript, thus many users will understand the syntax. These are ideas, this will take time to design, discuss and implement. Eventually this will lead to Vim 9! ## Code for sum time measurements Vim was build with -O2. ``` vim func VimOld() let sum = 0 for i in range(1, 2999999) let sum += i endfor return sum endfunc func Python() py3 << END sum = 0 for i in range(1, 3000000): sum += i END return py3eval('sum') endfunc func Lua() lua << END sum = 0 for i = 1, 2999999 do sum = sum + i end END return luaeval('sum') endfunc def VimNew(): number var sum = 0 for i in range(1, 2999999) sum += i endfor return sum enddef let start = reltime() echo VimOld() echo 'Vim old: ' .. reltimestr(reltime(start)) let start = reltime() echo Python() echo 'Python: ' .. reltimestr(reltime(start)) let start = reltime() echo Lua() echo 'Lua: ' .. reltimestr(reltime(start)) let start = reltime() echo VimNew() echo 'Vim new: ' .. reltimestr(reltime(start)) ``` ## Code for indent time measurements ``` vim def VimNew(): number var totallen = 0 for i in range(1, 100000) setline(i, ' ' .. getline(i)) totallen += len(getline(i)) endfor return totallen enddef func VimOld() let totallen = 0 for i in range(1, 100000) call setline(i, ' ' .. getline(i)) let totallen += len(getline(i)) endfor return totallen endfunc func Lua() lua << END b = vim.buffer() totallen = 0 for i = 1, 100000 do b[i] = " " .. b[i] totallen = totallen + string.len(b[i]) end END return luaeval('totallen') endfunc func Python() py3 << END cb = vim.current.buffer totallen = 0 for i in range(0, 100000): cb[i] = ' ' + cb[i] totallen += len(cb[i]) END return py3eval('totallen') endfunc new call setline(1, range(100000)) let start = reltime() echo VimOld() echo 'Vim old: ' .. reltimestr(reltime(start)) bwipe! new call setline(1, range(100000)) let start = reltime() echo Python() echo 'Python: ' .. reltimestr(reltime(start)) bwipe! new call setline(1, range(100000)) let start = reltime() echo Lua() echo 'Lua: ' .. reltimestr(reltime(start)) bwipe! new call setline(1, range(100000)) let start = reltime() echo VimNew() echo 'Vim new: ' .. reltimestr(reltime(start)) bwipe! ```