view src/testdir/test_ruby.vim @ 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 029c59bf78f1
children dbe616160092
line wrap: on
line source

" Tests for ruby interface

source check.vim
CheckFeature ruby

func Test_ruby_change_buffer()
  call setline(line('$'), ['1 line 1'])
  ruby Vim.command("normal /^1\n")
  ruby $curbuf.line = "1 changed line 1"
  call assert_equal('1 changed line 1', getline('$'))
endfunc

func Test_rubydo()
  " Check deleting lines does not trigger ml_get error.
  new
  call setline(1, ['one', 'two', 'three'])
  rubydo Vim.command("%d_")
  bwipe!

  " Check switching to another buffer does not trigger ml_get error.
  new
  let wincount = winnr('$')
  call setline(1, ['one', 'two', 'three'])
  rubydo Vim.command("new")
  call assert_equal(wincount + 1, winnr('$'))
  %bwipe!
endfunc

func Test_rubydo_dollar_underscore()
  new
  call setline(1, ['one', 'two', 'three', 'four'])
  2,3rubydo $_ = '[' + $_  + ']'
  call assert_equal(['one', '[two]', '[three]', 'four'], getline(1, '$'))
  bwipe!

  call assert_fails('rubydo $_ = 0', 'E265:')
  call assert_fails('rubydo (')
  bwipe!
endfunc

func Test_rubyfile()
  " Check :rubyfile does not SEGV with Ruby level exception but just fails
  let tempfile = tempname() . '.rb'
  call writefile(['raise "vim!"'], tempfile)
  call assert_fails('rubyfile ' . tempfile)
  call delete(tempfile)
endfunc

func Test_ruby_set_cursor()
  " Check that setting the cursor position works.
  new
  call setline(1, ['first line', 'second line'])
  normal gg
  rubydo $curwin.cursor = [1, 5]
  call assert_equal([1, 6], [line('.'), col('.')])
  call assert_equal([1, 5], rubyeval('$curwin.cursor'))

  " Check that movement after setting cursor position keeps current column.
  normal j
  call assert_equal([2, 6], [line('.'), col('.')])
  call assert_equal([2, 5], '$curwin.cursor'->rubyeval())

  call assert_fails('ruby $curwin.cursor = [1]',
        \           'ArgumentError: array length must be 2')
  bwipe!
endfunc

" Test buffer.count and buffer.length (number of lines in buffer)
func Test_ruby_buffer_count()
  new
  call setline(1, ['one', 'two', 'three'])
  call assert_equal(3, rubyeval('$curbuf.count'))
  call assert_equal(3, rubyeval('$curbuf.length'))
  bwipe!
endfunc

" Test buffer.name (buffer name)
func Test_ruby_buffer_name()
  new Xfoo
  call assert_equal(expand('%:p'), rubyeval('$curbuf.name'))
  bwipe
  call assert_equal(v:null, rubyeval('$curbuf.name'))
endfunc

" Test buffer.number (number of the buffer).
func Test_ruby_buffer_number()
  new
  call assert_equal(bufnr('%'), rubyeval('$curbuf.number'))
  new
  call assert_equal(bufnr('%'), rubyeval('$curbuf.number'))

  %bwipe
endfunc

" Test buffer.delete({n}) (delete line {n})
func Test_ruby_buffer_delete()
  new
  call setline(1, ['one', 'two', 'three'])
  ruby $curbuf.delete(2)
  call assert_equal(['one', 'three'], getline(1, '$'))

  call assert_fails('ruby $curbuf.delete(0)', 'IndexError: line number 0 out of range')
  call assert_fails('ruby $curbuf.delete(3)', 'IndexError: line number 3 out of range')

  bwipe!
endfunc

" Test buffer.append({str}, str) (append line {str} after line {n})
func Test_ruby_buffer_append()
  new
  ruby $curbuf.append(0, 'one')
  ruby $curbuf.append(1, 'three')
  ruby $curbuf.append(1, 'two')
  ruby $curbuf.append(4, 'four')

  call assert_equal(['one', 'two', 'three', '', 'four'], getline(1, '$'))

  call assert_fails('ruby $curbuf.append(-1, "x")',
        \           'IndexError: line number -1 out of range')
  call assert_fails('ruby $curbuf.append(6, "x")',
        \           'IndexError: line number 6 out of range')

  bwipe!
endfunc

" Test buffer.line (get or set the current line)
func Test_ruby_buffer_line()
  new
  call setline(1, ['one', 'two', 'three'])
  2
  call assert_equal('two', rubyeval('$curbuf.line'))

  ruby $curbuf.line = 'TWO'
  call assert_equal(['one', 'TWO', 'three'], getline(1, '$'))

  bwipe!
endfunc

" Test buffer.line_number (get current line number)
func Test_ruby_buffer_line_number()
  new
  call setline(1, ['one', 'two', 'three'])
  2
  call assert_equal(2, rubyeval('$curbuf.line_number'))

  bwipe!
endfunc

func Test_ruby_buffer_get()
  new
  call setline(1, ['one', 'two'])
  call assert_equal('one', rubyeval('$curbuf[1]'))
  call assert_equal('two', rubyeval('$curbuf[2]'))

  call assert_fails('ruby $curbuf[0]',
        \           'IndexError: line number 0 out of range')
  call assert_fails('ruby $curbuf[3]',
        \           'IndexError: line number 3 out of range')

  bwipe!
endfunc

func Test_ruby_buffer_set()
  new
  call setline(1, ['one', 'two'])
  ruby $curbuf[2] = 'TWO'
  ruby $curbuf[1] = 'ONE'

  call assert_fails('ruby $curbuf[0] = "ZERO"',
        \           'IndexError: line number 0 out of range')
  call assert_fails('ruby $curbuf[3] = "THREE"',
        \           'IndexError: line number 3 out of range')
  bwipe!
endfunc

" Test window.width (get or set window height).
func Test_ruby_window_height()
  new

  " Test setting window height
  ruby $curwin.height = 2
  call assert_equal(2, winheight(0))

  " Test getting window height
  call assert_equal(2, rubyeval('$curwin.height'))

  bwipe
endfunc

" Test window.width (get or set window width).
func Test_ruby_window_width()
  vnew

  " Test setting window width
  ruby $curwin.width = 2
  call assert_equal(2, winwidth(0))

  " Test getting window width
  call assert_equal(2, rubyeval('$curwin.width'))

  bwipe
endfunc

" Test window.buffer (get buffer object of a window object).
func Test_ruby_window_buffer()
  new Xfoo1
  new Xfoo2
  ruby $b2 = $curwin.buffer
  ruby $w2 = $curwin
  wincmd j
  ruby $b1 = $curwin.buffer
  ruby $w1 = $curwin

  call assert_equal(rubyeval('$b1'), rubyeval('$w1.buffer'))
  call assert_equal(rubyeval('$b2'), rubyeval('$w2.buffer'))
  call assert_equal(bufnr('Xfoo1'), rubyeval('$w1.buffer.number'))
  call assert_equal(bufnr('Xfoo2'), rubyeval('$w2.buffer.number'))

  ruby $b1, $w1, $b2, $w2 = nil
  %bwipe
endfunc

" Test Vim::Window.current (get current window object)
func Test_ruby_Vim_window_current()
  let cw = rubyeval('$curwin')
  call assert_equal(cw, rubyeval('Vim::Window.current'))
  call assert_match('^#<Vim::Window:0x\x\+>$', cw)
endfunc

" Test Vim::Window.count (number of windows)
func Test_ruby_Vim_window_count()
  new Xfoo1
  new Xfoo2
  split
  call assert_equal(4, rubyeval('Vim::Window.count'))
  %bwipe
  call assert_equal(1, rubyeval('Vim::Window.count'))
endfunc

" Test Vim::Window[n] (get window object of window n)
func Test_ruby_Vim_window_get()
  new Xfoo1
  new Xfoo2
  call assert_match('Xfoo2$', rubyeval('Vim::Window[0].buffer.name'))
  wincmd j
  call assert_match('Xfoo1$', rubyeval('Vim::Window[1].buffer.name'))
  wincmd j
  call assert_equal(v:null,   rubyeval('Vim::Window[2].buffer.name'))
  %bwipe
endfunc

" Test Vim::Buffer.current (return the buffer object of current buffer)
func Test_ruby_Vim_buffer_current()
  let cb = rubyeval('$curbuf')
  call assert_equal(cb, rubyeval('Vim::Buffer.current'))
  call assert_match('^#<Vim::Buffer:0x\x\+>$', cb)
endfunc

" Test Vim::Buffer:.count (return the number of buffers)
func Test_ruby_Vim_buffer_count()
  new Xfoo1
  new Xfoo2
  call assert_equal(3, rubyeval('Vim::Buffer.count'))
  %bwipe
  call assert_equal(1, rubyeval('Vim::Buffer.count'))
endfunc

" Test Vim::buffer[n] (return the buffer object of buffer number n)
func Test_ruby_Vim_buffer_get()
  new Xfoo1
  new Xfoo2

  " Index of Vim::Buffer[n] goes from 0 to the number of buffers.
  call assert_equal(v:null,   rubyeval('Vim::Buffer[0].name'))
  call assert_match('Xfoo1$', rubyeval('Vim::Buffer[1].name'))
  call assert_match('Xfoo2$', rubyeval('Vim::Buffer[2].name'))
  call assert_fails('ruby print Vim::Buffer[3].name',
        \           "NoMethodError: undefined method `name' for nil:NilClass")
  %bwipe
endfunc

" Test Vim::command({cmd}) (execute a Ex command))
" Test Vim::command({cmd})
func Test_ruby_Vim_command()
  new
  call setline(1, ['one', 'two', 'three', 'four'])
  ruby Vim::command('2,3d')
  call assert_equal(['one', 'four'], getline(1, '$'))
  bwipe!
endfunc

" Test Vim::set_option (set a vim option)
func Test_ruby_Vim_set_option()
  call assert_equal(0, &number)
  ruby Vim::set_option('number')
  call assert_equal(1, &number)
  ruby Vim::set_option('nonumber')
  call assert_equal(0, &number)
endfunc

func Test_ruby_Vim_evaluate()
  call assert_equal(123,        rubyeval('Vim::evaluate("123")'))
  " Vim::evaluate("123").class gives Integer or Fixnum depending
  " on versions of Ruby.
  call assert_match('^Integer\|Fixnum$', rubyeval('Vim::evaluate("123").class'))

  call assert_equal(1.23,       rubyeval('Vim::evaluate("1.23")'))
  call assert_equal('Float',    rubyeval('Vim::evaluate("1.23").class'))

  call assert_equal('foo',      rubyeval('Vim::evaluate("\"foo\"")'))
  call assert_equal('String',   rubyeval('Vim::evaluate("\"foo\"").class'))

  call assert_equal(["\x01\xAB"],   rubyeval('Vim::evaluate("0z01ab").unpack("M")'))
  call assert_equal('String',       rubyeval('Vim::evaluate("0z01ab").class'))

  call assert_equal([1, 2],     rubyeval('Vim::evaluate("[1, 2]")'))
  call assert_equal('Array',    rubyeval('Vim::evaluate("[1, 2]").class'))

  call assert_equal({'1': 2},   rubyeval('Vim::evaluate("{1:2}")'))
  call assert_equal('Hash',     rubyeval('Vim::evaluate("{1:2}").class'))

  call assert_equal(v:null,     rubyeval('Vim::evaluate("v:null")'))
  call assert_equal('NilClass', rubyeval('Vim::evaluate("v:null").class'))

  call assert_equal(v:null,     rubyeval('Vim::evaluate("v:none")'))
  call assert_equal('NilClass', rubyeval('Vim::evaluate("v:none").class'))

  call assert_equal(v:true,      rubyeval('Vim::evaluate("v:true")'))
  call assert_equal('TrueClass', rubyeval('Vim::evaluate("v:true").class'))
  call assert_equal(v:false,     rubyeval('Vim::evaluate("v:false")'))
  call assert_equal('FalseClass',rubyeval('Vim::evaluate("v:false").class'))
endfunc

func Test_ruby_Vim_blob()
  call assert_equal('0z',         rubyeval('Vim::blob("")'))
  call assert_equal('0z31326162', rubyeval('Vim::blob("12ab")'))
  call assert_equal('0z00010203', rubyeval('Vim::blob("\x00\x01\x02\x03")'))
  call assert_equal('0z8081FEFF', rubyeval('Vim::blob("\x80\x81\xfe\xff")'))
endfunc

func Test_ruby_Vim_evaluate_list()
  call setline(line('$'), ['2 line 2'])
  ruby Vim.command("normal /^2\n")
  let l = ["abc", "def"]
  ruby << trim EOF
    curline = $curbuf.line_number
    l = Vim.evaluate("l");
    $curbuf.append(curline, l.join("\n"))
  EOF
  normal j
  .rubydo $_ = $_.gsub(/\n/, '/')
  call assert_equal('abc/def', getline('$'))
endfunc

func Test_ruby_Vim_evaluate_dict()
  let d = {'a': 'foo', 'b': 123}
  redir => l:out
  ruby d = Vim.evaluate("d"); print d
  redir END
  call assert_equal(['{"a"=>"foo", "b"=>123}'], split(l:out, "\n"))
endfunc

" Test Vim::message({msg}) (display message {msg})
func Test_ruby_Vim_message()
  ruby Vim::message('A message')
  let messages = split(execute('message'), "\n")
  call assert_equal('A message', messages[-1])
endfunc

func Test_ruby_print()
  func RubyPrint(expr)
    return trim(execute('ruby print ' . a:expr))
  endfunc

  call assert_equal('123', RubyPrint('123'))
  call assert_equal('1.23', RubyPrint('1.23'))
  call assert_equal('Hello World!', RubyPrint('"Hello World!"'))
  call assert_equal('[1, 2]', RubyPrint('[1, 2]'))
  call assert_equal('{"k1"=>"v1", "k2"=>"v2"}', RubyPrint('({"k1" => "v1", "k2" => "v2"})'))
  call assert_equal('true', RubyPrint('true'))
  call assert_equal('false', RubyPrint('false'))
  call assert_equal('', RubyPrint('nil'))
  call assert_match('Vim', RubyPrint('Vim'))
  call assert_match('Module', RubyPrint('Vim.class'))

  delfunc RubyPrint
endfunc

func Test_ruby_p()
  ruby p 'Just a test'
  let messages = GetMessages()
  call assert_equal('"Just a test"', messages[-1])

  " Check return values of p method

  call assert_equal(123, rubyeval('p(123)'))
  call assert_equal([1, 2, 3], rubyeval('p(1, 2, 3)'))

  " Avoid the "message maintainer" line.
  let $LANG = ''
  messages clear
  call assert_equal(v:true, rubyeval('p() == nil'))

  let messages = GetMessages()
  call assert_equal(0, len(messages))
endfunc

func Test_rubyeval_error()
  " On Linux or Windows the error matches:
  "   "syntax error, unexpected end-of-input"
  " whereas on macOS in CI, the error message makes less sense:
  "   "SyntaxError: array length must be 2"
  " Unclear why. The test does not check the error message.
  call assert_fails('call rubyeval("(")')
endfunc

" Test for various heredoc syntax
func Test_ruby_heredoc()
  ruby << END
Vim.command('let s = "A"')
END
  ruby <<
Vim.command('let s ..= "B"')
.
  ruby << trim END
    Vim.command('let s ..= "C"')
  END
  ruby << trim
    Vim.command('let s ..= "D"')
  .
  ruby << trim eof
    Vim.command('let s ..= "E"')
  eof
  call assert_equal('ABCDE', s)
endfunc

" vim: shiftwidth=2 sts=2 expandtab