xref: /vim-8.2.3635/src/if_ruby.c (revision e99be0e6)
1 /* vi:set ts=8 sts=4 sw=4 noet:
2  *
3  * VIM - Vi IMproved	by Bram Moolenaar
4  *
5  * Ruby interface by Shugo Maeda
6  *   with improvements by SegPhault (Ryan Paul)
7  *   with improvements by Jon Maken
8  *
9  * Do ":help uganda"  in Vim to read copying and usage conditions.
10  * Do ":help credits" in Vim to see a list of people who contributed.
11  * See README.txt for an overview of the Vim source code.
12  */
13 
14 #include "protodef.h"
15 #ifdef HAVE_CONFIG_H
16 # include "auto/config.h"
17 #endif
18 
19 #include <stdio.h>
20 #include <string.h>
21 
22 #ifdef _WIN32
23 # if !defined(DYNAMIC_RUBY_VER) || (DYNAMIC_RUBY_VER < 18)
24 #   define NT
25 # endif
26 # ifndef DYNAMIC_RUBY
27 #  define IMPORT /* For static dll usage __declspec(dllimport) */
28 #  define RUBYEXTERN __declspec(dllimport)
29 # endif
30 #endif
31 #ifndef RUBYEXTERN
32 # define RUBYEXTERN extern
33 #endif
34 
35 #if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 24
36 # define USE_RUBY_INTEGER
37 #endif
38 
39 #ifdef DYNAMIC_RUBY
40 /*
41  * This is tricky.  In ruby.h there is (inline) function rb_class_of()
42  * definition.  This function use these variables.  But we want function to
43  * use dll_* variables.
44  */
45 # define rb_cFalseClass		(*dll_rb_cFalseClass)
46 # define rb_cFixnum		(*dll_rb_cFixnum)
47 # if defined(USE_RUBY_INTEGER)
48 #  define rb_cInteger		(*dll_rb_cInteger)
49 # endif
50 # if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 20
51 #  define rb_cFloat		(*dll_rb_cFloat)
52 # endif
53 # define rb_cNilClass		(*dll_rb_cNilClass)
54 # define rb_cString		(*dll_rb_cString)
55 # define rb_cSymbol		(*dll_rb_cSymbol)
56 # define rb_cTrueClass		(*dll_rb_cTrueClass)
57 # if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 18
58 /*
59  * On ver 1.8, all Ruby functions are exported with "__declspec(dllimport)"
60  * in ruby.h.  But it causes trouble for these variables, because it is
61  * defined in this file.  When defined this RUBY_EXPORT it modified to
62  * "extern" and be able to avoid this problem.
63  */
64 #  define RUBY_EXPORT
65 # endif
66 
67 #endif  // ifdef DYNAMIC_RUBY
68 
69 // suggested by Ariya Mizutani
70 #if (_MSC_VER == 1200)
71 # undef _WIN32_WINNT
72 #endif
73 
74 #if (defined(RUBY_VERSION) && RUBY_VERSION >= 19) \
75     || (defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 19)
76 # define RUBY19_OR_LATER 1
77 #endif
78 
79 #if (defined(RUBY_VERSION) && RUBY_VERSION >= 20) \
80     || (defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 20)
81 # define RUBY20_OR_LATER 1
82 #endif
83 
84 #if (defined(RUBY_VERSION) && RUBY_VERSION >= 21) \
85     || (defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 21)
86 # define RUBY21_OR_LATER 1
87 #endif
88 
89 #if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 19
90 /* Ruby 1.9 defines a number of static functions which use rb_num2long and
91  * rb_int2big */
92 # define rb_num2long rb_num2long_stub
93 # define rb_int2big rb_int2big_stub
94 #endif
95 
96 #if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 19 \
97 	&& VIM_SIZEOF_INT < VIM_SIZEOF_LONG
98 /* Ruby 1.9 defines a number of static functions which use rb_fix2int and
99  * rb_num2int if VIM_SIZEOF_INT < VIM_SIZEOF_LONG (64bit) */
100 # define rb_fix2int rb_fix2int_stub
101 # define rb_num2int rb_num2int_stub
102 #endif
103 
104 #if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER == 21
105 /* Ruby 2.1 adds new GC called RGenGC and RARRAY_PTR uses
106  * rb_gc_writebarrier_unprotect_promoted if USE_RGENGC  */
107 # define rb_gc_writebarrier_unprotect_promoted rb_gc_writebarrier_unprotect_promoted_stub
108 #endif
109 #if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 22
110 # define rb_gc_writebarrier_unprotect rb_gc_writebarrier_unprotect_stub
111 #endif
112 
113 #if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 26
114 # define rb_ary_detransient rb_ary_detransient_stub
115 #endif
116 
117 #include <ruby.h>
118 #ifdef RUBY19_OR_LATER
119 # include <ruby/encoding.h>
120 #endif
121 
122 #undef off_t	/* ruby defines off_t as _int64, Mingw uses long */
123 #undef EXTERN
124 #undef _
125 
126 /* T_DATA defined both by Ruby and Mac header files, hack around it... */
127 #if defined(MACOS_X)
128 # define __OPENTRANSPORT__
129 # define __OPENTRANSPORTPROTOCOL__
130 # define __OPENTRANSPORTPROVIDERS__
131 #endif
132 
133 /*
134  * The TypedData_XXX macro family can be used since Ruby 1.9.2 but
135  * rb_data_type_t changed in 1.9.3, therefore require at least 2.0.
136  * The old Data_XXX macro family was deprecated on Ruby 2.2.
137  * Use TypedData_XXX if available.
138  */
139 #if defined(TypedData_Wrap_Struct) && defined(RUBY20_OR_LATER)
140 # define USE_TYPEDDATA	1
141 #endif
142 
143 /*
144  * Backward compatibility for Ruby 1.8 and earlier.
145  * Ruby 1.9 does not provide STR2CSTR, instead StringValuePtr is provided.
146  * Ruby 1.9 does not provide RXXX(s)->len and RXXX(s)->ptr, instead
147  * RXXX_LEN(s) and RXXX_PTR(s) are provided.
148  */
149 #ifndef StringValuePtr
150 # define StringValuePtr(s) STR2CSTR(s)
151 #endif
152 #ifndef RARRAY_LEN
153 # define RARRAY_LEN(s) RARRAY(s)->len
154 #endif
155 #ifndef RARRAY_PTR
156 # define RARRAY_PTR(s) RARRAY(s)->ptr
157 #endif
158 #ifndef RSTRING_LEN
159 # define RSTRING_LEN(s) RSTRING(s)->len
160 #endif
161 #ifndef RSTRING_PTR
162 # define RSTRING_PTR(s) RSTRING(s)->ptr
163 #endif
164 
165 #ifdef HAVE_DUP
166 # undef HAVE_DUP
167 #endif
168 
169 #include "vim.h"
170 #include "version.h"
171 
172 #ifdef DYNAMIC_RUBY
173 # if !defined(MSWIN)  // must come after including vim.h, where it is defined
174 #  include <dlfcn.h>
175 #  define HINSTANCE void*
176 #  define RUBY_PROC void*
177 #  define load_dll(n) dlopen((n), RTLD_LAZY|RTLD_GLOBAL)
178 #  define symbol_from_dll dlsym
179 #  define close_dll dlclose
180 # else
181 #  define RUBY_PROC FARPROC
182 #  define load_dll vimLoadLib
183 #  define symbol_from_dll GetProcAddress
184 #  define close_dll FreeLibrary
185 # endif
186 #endif
187 
188 #if defined(PROTO) && !defined(FEAT_RUBY)
189 /* Define these to be able to generate the function prototypes. */
190 # define VALUE int
191 # define RUBY_DATA_FUNC int
192 #endif
193 
194 static int ruby_initialized = 0;
195 static void *ruby_stack_start;
196 static VALUE objtbl;
197 
198 static VALUE mVIM;
199 static VALUE cBuffer;
200 static VALUE cVimWindow;
201 static VALUE eDeletedBufferError;
202 static VALUE eDeletedWindowError;
203 
204 static int ensure_ruby_initialized(void);
205 static void error_print(int);
206 static void ruby_io_init(void);
207 static void ruby_vim_init(void);
208 static int ruby_convert_to_vim_value(VALUE val, typval_T *rettv);
209 
210 #if defined(RUBY19_OR_LATER) || defined(RUBY_INIT_STACK)
211 # if defined(__ia64) && !defined(ruby_init_stack)
212 #  define ruby_init_stack(addr) ruby_init_stack((addr), rb_ia64_bsp())
213 # endif
214 #endif
215 
216 #if defined(DYNAMIC_RUBY) || defined(PROTO)
217 # if defined(PROTO) && !defined(HINSTANCE)
218 #  define HINSTANCE int		/* for generating prototypes */
219 # endif
220 
221 /*
222  * Wrapper defines
223  */
224 # define rb_assoc_new			dll_rb_assoc_new
225 # define rb_cObject			(*dll_rb_cObject)
226 # define rb_class_new_instance		dll_rb_class_new_instance
227 # define rb_check_type			dll_rb_check_type
228 # ifdef USE_TYPEDDATA
229 #  define rb_check_typeddata		dll_rb_check_typeddata
230 # endif
231 # define rb_class_path			dll_rb_class_path
232 # ifdef USE_TYPEDDATA
233 #  if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 23
234 #   define rb_data_typed_object_wrap	dll_rb_data_typed_object_wrap
235 #  else
236 #   define rb_data_typed_object_alloc	dll_rb_data_typed_object_alloc
237 #  endif
238 # else
239 #  define rb_data_object_alloc		dll_rb_data_object_alloc
240 # endif
241 # define rb_define_class_under		dll_rb_define_class_under
242 # define rb_define_const			dll_rb_define_const
243 # define rb_define_global_function	dll_rb_define_global_function
244 # define rb_define_method		dll_rb_define_method
245 # define rb_define_module		dll_rb_define_module
246 # define rb_define_module_function	dll_rb_define_module_function
247 # define rb_define_singleton_method	dll_rb_define_singleton_method
248 # define rb_define_virtual_variable	dll_rb_define_virtual_variable
249 # define rb_stdout			(*dll_rb_stdout)
250 # define rb_stderr			(*dll_rb_stderr)
251 # define rb_eArgError			(*dll_rb_eArgError)
252 # define rb_eIndexError			(*dll_rb_eIndexError)
253 # define rb_eRuntimeError		(*dll_rb_eRuntimeError)
254 # define rb_eStandardError		(*dll_rb_eStandardError)
255 # define rb_eval_string_protect		dll_rb_eval_string_protect
256 # ifdef RUBY21_OR_LATER
257 #  define rb_funcallv			dll_rb_funcallv
258 # else
259 #  define rb_funcall2			dll_rb_funcall2
260 # endif
261 # define rb_global_variable		dll_rb_global_variable
262 # define rb_hash_aset			dll_rb_hash_aset
263 # define rb_hash_foreach		dll_rb_hash_foreach
264 # define rb_hash_new			dll_rb_hash_new
265 # define rb_inspect			dll_rb_inspect
266 # define rb_int2inum			dll_rb_int2inum
267 
268 // ruby.h may redefine rb_intern to use RUBY_CONST_ID_CACHE(), but that won't
269 // work.  Not using the cache appears to be the best solution.
270 # undef rb_intern
271 # define rb_intern			dll_rb_intern
272 
273 # if VIM_SIZEOF_INT < VIM_SIZEOF_LONG /* 64 bits only */
274 #  if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER <= 18
275 #   define rb_fix2int			dll_rb_fix2int
276 #   define rb_num2int			dll_rb_num2int
277 #  endif
278 #  define rb_num2uint			dll_rb_num2uint
279 # endif
280 # define rb_num2dbl			dll_rb_num2dbl
281 # define rb_lastline_get			dll_rb_lastline_get
282 # define rb_lastline_set			dll_rb_lastline_set
283 # define rb_protect			dll_rb_protect
284 # define rb_load			dll_rb_load
285 # ifndef RUBY19_OR_LATER
286 #  define rb_num2long			dll_rb_num2long
287 # endif
288 # if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER <= 19
289 #  define rb_num2ulong			dll_rb_num2ulong
290 # endif
291 # define rb_obj_alloc			dll_rb_obj_alloc
292 # define rb_obj_as_string		dll_rb_obj_as_string
293 # define rb_obj_id			dll_rb_obj_id
294 # define rb_raise			dll_rb_raise
295 # define rb_str_cat			dll_rb_str_cat
296 # define rb_str_concat			dll_rb_str_concat
297 # undef rb_str_new
298 # define rb_str_new			dll_rb_str_new
299 # ifdef rb_str_new2
300 /* Ruby may #define rb_str_new2 to use rb_str_new_cstr. */
301 #  define need_rb_str_new_cstr 1
302 /* Ruby's headers #define rb_str_new_cstr to make use of GCC's
303  * __builtin_constant_p extension. */
304 #  undef rb_str_new_cstr
305 #  define rb_str_new_cstr		dll_rb_str_new_cstr
306 # else
307 #  define rb_str_new2			dll_rb_str_new2
308 # endif
309 # if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 18
310 #  define rb_string_value		dll_rb_string_value
311 #  define rb_string_value_ptr		dll_rb_string_value_ptr
312 #  define rb_float_new			dll_rb_float_new
313 #  define rb_ary_new			dll_rb_ary_new
314 #  ifdef rb_ary_new4
315 #    define RB_ARY_NEW4_MACRO 1
316 #    undef rb_ary_new4
317 #  endif
318 #  define rb_ary_new4			dll_rb_ary_new4
319 #  define rb_ary_push			dll_rb_ary_push
320 #  if defined(RUBY19_OR_LATER) || defined(RUBY_INIT_STACK)
321 #   ifdef __ia64
322 #    define rb_ia64_bsp			dll_rb_ia64_bsp
323 #    undef ruby_init_stack
324 #    define ruby_init_stack(addr)	dll_ruby_init_stack((addr), rb_ia64_bsp())
325 #   else
326 #    define ruby_init_stack		dll_ruby_init_stack
327 #   endif
328 #  endif
329 # else
330 #  define rb_str2cstr			dll_rb_str2cstr
331 # endif
332 # ifdef RUBY19_OR_LATER
333 #  define rb_errinfo			dll_rb_errinfo
334 # else
335 #  define ruby_errinfo			(*dll_ruby_errinfo)
336 # endif
337 # define ruby_init			dll_ruby_init
338 # define ruby_init_loadpath		dll_ruby_init_loadpath
339 # ifdef MSWIN
340 #  ifdef RUBY19_OR_LATER
341 #   define ruby_sysinit			dll_ruby_sysinit
342 #  else
343 #   define NtInitialize			dll_NtInitialize
344 #  endif
345 #  if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 18
346 #   define rb_w32_snprintf		dll_rb_w32_snprintf
347 #  endif
348 # endif
349 
350 # ifdef RUBY19_OR_LATER
351 #  define ruby_script			dll_ruby_script
352 #  define rb_enc_find_index		dll_rb_enc_find_index
353 #  define rb_enc_find			dll_rb_enc_find
354 #  undef rb_enc_str_new
355 #  define rb_enc_str_new		dll_rb_enc_str_new
356 #  define rb_sprintf			dll_rb_sprintf
357 #  define rb_require			dll_rb_require
358 #  define ruby_options			dll_ruby_options
359 # endif
360 
361 /*
362  * Pointers for dynamic link
363  */
364 static VALUE (*dll_rb_assoc_new) (VALUE, VALUE);
365 VALUE *dll_rb_cFalseClass;
366 VALUE *dll_rb_cFixnum;
367 # if defined(USE_RUBY_INTEGER)
368 VALUE *dll_rb_cInteger;
369 # endif
370 # if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 20
371 VALUE *dll_rb_cFloat;
372 # endif
373 VALUE *dll_rb_cNilClass;
374 static VALUE *dll_rb_cObject;
375 VALUE *dll_rb_cString;
376 VALUE *dll_rb_cSymbol;
377 VALUE *dll_rb_cTrueClass;
378 static VALUE (*dll_rb_class_new_instance) (int,VALUE*,VALUE);
379 static void (*dll_rb_check_type) (VALUE,int);
380 # ifdef USE_TYPEDDATA
381 static void *(*dll_rb_check_typeddata) (VALUE,const rb_data_type_t *);
382 # endif
383 static VALUE (*dll_rb_class_path) (VALUE);
384 # ifdef USE_TYPEDDATA
385 #  if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 23
386 static VALUE (*dll_rb_data_typed_object_wrap) (VALUE, void*, const rb_data_type_t *);
387 #  else
388 static VALUE (*dll_rb_data_typed_object_alloc) (VALUE, void*, const rb_data_type_t *);
389 #  endif
390 # else
391 static VALUE (*dll_rb_data_object_alloc) (VALUE, void*, RUBY_DATA_FUNC, RUBY_DATA_FUNC);
392 # endif
393 static VALUE (*dll_rb_define_class_under) (VALUE, const char*, VALUE);
394 static void (*dll_rb_define_const) (VALUE,const char*,VALUE);
395 static void (*dll_rb_define_global_function) (const char*,VALUE(*)(),int);
396 static void (*dll_rb_define_method) (VALUE,const char*,VALUE(*)(),int);
397 static VALUE (*dll_rb_define_module) (const char*);
398 static void (*dll_rb_define_module_function) (VALUE,const char*,VALUE(*)(),int);
399 static void (*dll_rb_define_singleton_method) (VALUE,const char*,VALUE(*)(),int);
400 static void (*dll_rb_define_virtual_variable) (const char*,VALUE(*)(),void(*)());
401 static VALUE *dll_rb_stdout;
402 static VALUE *dll_rb_stderr;
403 static VALUE *dll_rb_eArgError;
404 static VALUE *dll_rb_eIndexError;
405 static VALUE *dll_rb_eRuntimeError;
406 static VALUE *dll_rb_eStandardError;
407 static VALUE (*dll_rb_eval_string_protect) (const char*, int*);
408 # ifdef RUBY21_OR_LATER
409 static VALUE (*dll_rb_funcallv) (VALUE, ID, int, const VALUE*);
410 # else
411 static VALUE (*dll_rb_funcall2) (VALUE, ID, int, const VALUE*);
412 # endif
413 static void (*dll_rb_global_variable) (VALUE*);
414 static VALUE (*dll_rb_hash_aset) (VALUE, VALUE, VALUE);
415 static VALUE (*dll_rb_hash_foreach) (VALUE, int (*)(VALUE, VALUE, VALUE), VALUE);
416 static VALUE (*dll_rb_hash_new) (void);
417 static VALUE (*dll_rb_inspect) (VALUE);
418 static VALUE (*dll_rb_int2inum) (long);
419 static ID (*dll_rb_intern) (const char*);
420 # if VIM_SIZEOF_INT < VIM_SIZEOF_LONG /* 64 bits only */
421 static long (*dll_rb_fix2int) (VALUE);
422 static long (*dll_rb_num2int) (VALUE);
423 static unsigned long (*dll_rb_num2uint) (VALUE);
424 # endif
425 static double (*dll_rb_num2dbl) (VALUE);
426 static VALUE (*dll_rb_lastline_get) (void);
427 static void (*dll_rb_lastline_set) (VALUE);
428 static VALUE (*dll_rb_protect) (VALUE (*)(VALUE), VALUE, int*);
429 static void (*dll_rb_load) (VALUE, int);
430 static long (*dll_rb_num2long) (VALUE);
431 static unsigned long (*dll_rb_num2ulong) (VALUE);
432 static VALUE (*dll_rb_obj_alloc) (VALUE);
433 static VALUE (*dll_rb_obj_as_string) (VALUE);
434 static VALUE (*dll_rb_obj_id) (VALUE);
435 static void (*dll_rb_raise) (VALUE, const char*, ...);
436 # if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 18
437 static VALUE (*dll_rb_string_value) (volatile VALUE*);
438 # else
439 static char *(*dll_rb_str2cstr) (VALUE,int*);
440 # endif
441 static VALUE (*dll_rb_str_cat) (VALUE, const char*, long);
442 static VALUE (*dll_rb_str_concat) (VALUE, VALUE);
443 static VALUE (*dll_rb_str_new) (const char*, long);
444 # ifdef need_rb_str_new_cstr
445 /* Ruby may #define rb_str_new2 to use rb_str_new_cstr. */
446 static VALUE (*dll_rb_str_new_cstr) (const char*);
447 # else
448 static VALUE (*dll_rb_str_new2) (const char*);
449 # endif
450 # ifdef RUBY19_OR_LATER
451 static VALUE (*dll_rb_errinfo) (void);
452 # else
453 static VALUE *dll_ruby_errinfo;
454 # endif
455 static void (*dll_ruby_init) (void);
456 static void (*dll_ruby_init_loadpath) (void);
457 # ifdef MSWIN
458 #  ifdef RUBY19_OR_LATER
459 static void (*dll_ruby_sysinit) (int*, char***);
460 #  else
461 static void (*dll_NtInitialize) (int*, char***);
462 #  endif
463 #  if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 18
464 static int (*dll_rb_w32_snprintf)(char*, size_t, const char*, ...);
465 #  endif
466 # endif
467 # if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 18
468 static char * (*dll_rb_string_value_ptr) (volatile VALUE*);
469 static VALUE (*dll_rb_float_new) (double);
470 static VALUE (*dll_rb_ary_new) (void);
471 static VALUE (*dll_rb_ary_new4) (long n, const VALUE *elts);
472 static VALUE (*dll_rb_ary_push) (VALUE, VALUE);
473 #  if DYNAMIC_RUBY_VER >= 26
474 static void (*dll_rb_ary_detransient) (VALUE);
475 #  endif
476 #  if defined(RUBY19_OR_LATER) || defined(RUBY_INIT_STACK)
477 #   ifdef __ia64
478 static void * (*dll_rb_ia64_bsp) (void);
479 static void (*dll_ruby_init_stack)(VALUE*, void*);
480 #   else
481 static void (*dll_ruby_init_stack)(VALUE*);
482 #   endif
483 #  endif
484 # endif
485 # ifdef RUBY19_OR_LATER
486 static VALUE (*dll_rb_int2big)(SIGNED_VALUE);
487 # endif
488 
489 # ifdef RUBY19_OR_LATER
490 static void (*dll_ruby_script) (const char*);
491 static int (*dll_rb_enc_find_index) (const char*);
492 static rb_encoding* (*dll_rb_enc_find) (const char*);
493 static VALUE (*dll_rb_enc_str_new) (const char*, long, rb_encoding*);
494 static VALUE (*dll_rb_sprintf) (const char*, ...);
495 static VALUE (*dll_rb_require) (const char*);
496 static void* (*ruby_options)(int, char**);
497 # endif
498 
499 # if defined(USE_RGENGC) && USE_RGENGC
500 #  if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER == 21
501 static void (*dll_rb_gc_writebarrier_unprotect_promoted)(VALUE);
502 #  else
503 static void (*dll_rb_gc_writebarrier_unprotect)(VALUE obj);
504 #  endif
505 # endif
506 
507 # if defined(RUBY19_OR_LATER) && !defined(PROTO)
508 #  if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 22
509     long
510 rb_num2long_stub(VALUE x)
511 #  else
512     SIGNED_VALUE
513 rb_num2long_stub(VALUE x)
514 #  endif
515 {
516     return dll_rb_num2long(x);
517 }
518 #  if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 26
519     VALUE
520 rb_int2big_stub(intptr_t x)
521 #  else
522     VALUE
523 rb_int2big_stub(SIGNED_VALUE x)
524 #  endif
525 {
526     return dll_rb_int2big(x);
527 }
528 #  if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 19 \
529 	&& VIM_SIZEOF_INT < VIM_SIZEOF_LONG
530     long
531 rb_fix2int_stub(VALUE x)
532 {
533     return dll_rb_fix2int(x);
534 }
535     long
536 rb_num2int_stub(VALUE x)
537 {
538     return dll_rb_num2int(x);
539 }
540 #  endif
541 #  if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 20
542     VALUE
543 rb_float_new_in_heap(double d)
544 {
545     return dll_rb_float_new(d);
546 }
547 #   if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 22
548     unsigned long
549 rb_num2ulong(VALUE x)
550 #   else
551     VALUE
552 rb_num2ulong(VALUE x)
553 #   endif
554 {
555     return (long)RSHIFT((SIGNED_VALUE)(x),1);
556 }
557 #  endif
558 # endif
559 
560    /* Do not generate a prototype here, VALUE isn't always defined. */
561 # if defined(USE_RGENGC) && USE_RGENGC && !defined(PROTO)
562 #  if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER == 21
563     void
564 rb_gc_writebarrier_unprotect_promoted_stub(VALUE obj)
565 {
566     dll_rb_gc_writebarrier_unprotect_promoted(obj);
567 }
568 #  else
569     void
570 rb_gc_writebarrier_unprotect_stub(VALUE obj)
571 {
572     dll_rb_gc_writebarrier_unprotect(obj);
573 }
574 #  endif
575 # endif
576 
577 # if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 26
578     void
579 rb_ary_detransient_stub(VALUE x)
580 {
581     dll_rb_ary_detransient(x);
582 }
583 # endif
584 
585 static HINSTANCE hinstRuby = NULL; /* Instance of ruby.dll */
586 
587 /*
588  * Table of name to function pointer of ruby.
589  */
590 static struct
591 {
592     char *name;
593     RUBY_PROC *ptr;
594 } ruby_funcname_table[] =
595 {
596     {"rb_assoc_new", (RUBY_PROC*)&dll_rb_assoc_new},
597     {"rb_cFalseClass", (RUBY_PROC*)&dll_rb_cFalseClass},
598 # if defined(USE_RUBY_INTEGER)
599     {"rb_cInteger", (RUBY_PROC*)&dll_rb_cInteger},
600 # else
601     {"rb_cFixnum", (RUBY_PROC*)&dll_rb_cFixnum},
602 # endif
603 # if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 20
604     {"rb_cFloat", (RUBY_PROC*)&dll_rb_cFloat},
605 # endif
606     {"rb_cNilClass", (RUBY_PROC*)&dll_rb_cNilClass},
607     {"rb_cObject", (RUBY_PROC*)&dll_rb_cObject},
608     {"rb_cString", (RUBY_PROC*)&dll_rb_cString},
609     {"rb_cSymbol", (RUBY_PROC*)&dll_rb_cSymbol},
610     {"rb_cTrueClass", (RUBY_PROC*)&dll_rb_cTrueClass},
611     {"rb_class_new_instance", (RUBY_PROC*)&dll_rb_class_new_instance},
612     {"rb_check_type", (RUBY_PROC*)&dll_rb_check_type},
613 # ifdef USE_TYPEDDATA
614     {"rb_check_typeddata", (RUBY_PROC*)&dll_rb_check_typeddata},
615 # endif
616     {"rb_class_path", (RUBY_PROC*)&dll_rb_class_path},
617 # ifdef USE_TYPEDDATA
618 #  if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 23
619     {"rb_data_typed_object_wrap", (RUBY_PROC*)&dll_rb_data_typed_object_wrap},
620 #  else
621     {"rb_data_typed_object_alloc", (RUBY_PROC*)&dll_rb_data_typed_object_alloc},
622 #  endif
623 # else
624     {"rb_data_object_alloc", (RUBY_PROC*)&dll_rb_data_object_alloc},
625 # endif
626     {"rb_define_class_under", (RUBY_PROC*)&dll_rb_define_class_under},
627     {"rb_define_const", (RUBY_PROC*)&dll_rb_define_const},
628     {"rb_define_global_function", (RUBY_PROC*)&dll_rb_define_global_function},
629     {"rb_define_method", (RUBY_PROC*)&dll_rb_define_method},
630     {"rb_define_module", (RUBY_PROC*)&dll_rb_define_module},
631     {"rb_define_module_function", (RUBY_PROC*)&dll_rb_define_module_function},
632     {"rb_define_singleton_method", (RUBY_PROC*)&dll_rb_define_singleton_method},
633     {"rb_define_virtual_variable", (RUBY_PROC*)&dll_rb_define_virtual_variable},
634     {"rb_stdout", (RUBY_PROC*)&dll_rb_stdout},
635     {"rb_stderr", (RUBY_PROC*)&dll_rb_stderr},
636     {"rb_eArgError", (RUBY_PROC*)&dll_rb_eArgError},
637     {"rb_eIndexError", (RUBY_PROC*)&dll_rb_eIndexError},
638     {"rb_eRuntimeError", (RUBY_PROC*)&dll_rb_eRuntimeError},
639     {"rb_eStandardError", (RUBY_PROC*)&dll_rb_eStandardError},
640     {"rb_eval_string_protect", (RUBY_PROC*)&dll_rb_eval_string_protect},
641 # ifdef RUBY21_OR_LATER
642     {"rb_funcallv", (RUBY_PROC*)&dll_rb_funcallv},
643 # else
644     {"rb_funcall2", (RUBY_PROC*)&dll_rb_funcall2},
645 # endif
646     {"rb_global_variable", (RUBY_PROC*)&dll_rb_global_variable},
647     {"rb_hash_aset", (RUBY_PROC*)&dll_rb_hash_aset},
648     {"rb_hash_foreach", (RUBY_PROC*)&dll_rb_hash_foreach},
649     {"rb_hash_new", (RUBY_PROC*)&dll_rb_hash_new},
650     {"rb_inspect", (RUBY_PROC*)&dll_rb_inspect},
651     {"rb_int2inum", (RUBY_PROC*)&dll_rb_int2inum},
652     {"rb_intern", (RUBY_PROC*)&dll_rb_intern},
653 # if VIM_SIZEOF_INT < VIM_SIZEOF_LONG /* 64 bits only */
654     {"rb_fix2int", (RUBY_PROC*)&dll_rb_fix2int},
655     {"rb_num2int", (RUBY_PROC*)&dll_rb_num2int},
656     {"rb_num2uint", (RUBY_PROC*)&dll_rb_num2uint},
657 # endif
658     {"rb_num2dbl", (RUBY_PROC*)&dll_rb_num2dbl},
659     {"rb_lastline_get", (RUBY_PROC*)&dll_rb_lastline_get},
660     {"rb_lastline_set", (RUBY_PROC*)&dll_rb_lastline_set},
661     {"rb_protect", (RUBY_PROC*)&dll_rb_protect},
662     {"rb_load", (RUBY_PROC*)&dll_rb_load},
663     {"rb_num2long", (RUBY_PROC*)&dll_rb_num2long},
664     {"rb_num2ulong", (RUBY_PROC*)&dll_rb_num2ulong},
665     {"rb_obj_alloc", (RUBY_PROC*)&dll_rb_obj_alloc},
666     {"rb_obj_as_string", (RUBY_PROC*)&dll_rb_obj_as_string},
667     {"rb_obj_id", (RUBY_PROC*)&dll_rb_obj_id},
668     {"rb_raise", (RUBY_PROC*)&dll_rb_raise},
669 # if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 18
670     {"rb_string_value", (RUBY_PROC*)&dll_rb_string_value},
671 # else
672     {"rb_str2cstr", (RUBY_PROC*)&dll_rb_str2cstr},
673 # endif
674     {"rb_str_cat", (RUBY_PROC*)&dll_rb_str_cat},
675     {"rb_str_concat", (RUBY_PROC*)&dll_rb_str_concat},
676     {"rb_str_new", (RUBY_PROC*)&dll_rb_str_new},
677 # ifdef need_rb_str_new_cstr
678     {"rb_str_new_cstr", (RUBY_PROC*)&dll_rb_str_new_cstr},
679 # else
680     {"rb_str_new2", (RUBY_PROC*)&dll_rb_str_new2},
681 # endif
682 # ifdef RUBY19_OR_LATER
683     {"rb_errinfo", (RUBY_PROC*)&dll_rb_errinfo},
684 # else
685     {"ruby_errinfo", (RUBY_PROC*)&dll_ruby_errinfo},
686 # endif
687     {"ruby_init", (RUBY_PROC*)&dll_ruby_init},
688     {"ruby_init_loadpath", (RUBY_PROC*)&dll_ruby_init_loadpath},
689 # ifdef MSWIN
690 #  ifdef RUBY19_OR_LATER
691     {"ruby_sysinit", (RUBY_PROC*)&dll_ruby_sysinit},
692 #  else
693     {"NtInitialize", (RUBY_PROC*)&dll_NtInitialize},
694 #  endif
695 #  if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 18
696     {"rb_w32_snprintf", (RUBY_PROC*)&dll_rb_w32_snprintf},
697 #  endif
698 # endif
699 # if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 18
700     {"rb_string_value_ptr", (RUBY_PROC*)&dll_rb_string_value_ptr},
701 #  if DYNAMIC_RUBY_VER <= 19
702     {"rb_float_new", (RUBY_PROC*)&dll_rb_float_new},
703 #  else
704     {"rb_float_new_in_heap", (RUBY_PROC*)&dll_rb_float_new},
705 #  endif
706     {"rb_ary_new", (RUBY_PROC*)&dll_rb_ary_new},
707 #  ifdef RB_ARY_NEW4_MACRO
708     {"rb_ary_new_from_values", (RUBY_PROC*)&dll_rb_ary_new4},
709 #  else
710     {"rb_ary_new4", (RUBY_PROC*)&dll_rb_ary_new4},
711 #  endif
712     {"rb_ary_push", (RUBY_PROC*)&dll_rb_ary_push},
713 #  if DYNAMIC_RUBY_VER >= 26
714     {"rb_ary_detransient", (RUBY_PROC*)&dll_rb_ary_detransient},
715 #  endif
716 # endif
717 # ifdef RUBY19_OR_LATER
718     {"rb_int2big", (RUBY_PROC*)&dll_rb_int2big},
719     {"ruby_script", (RUBY_PROC*)&dll_ruby_script},
720     {"rb_enc_find_index", (RUBY_PROC*)&dll_rb_enc_find_index},
721     {"rb_enc_find", (RUBY_PROC*)&dll_rb_enc_find},
722     {"rb_enc_str_new", (RUBY_PROC*)&dll_rb_enc_str_new},
723     {"rb_sprintf", (RUBY_PROC*)&dll_rb_sprintf},
724     {"rb_require", (RUBY_PROC*)&dll_rb_require},
725     {"ruby_options", (RUBY_PROC*)&dll_ruby_options},
726 # endif
727 # if defined(RUBY19_OR_LATER) || defined(RUBY_INIT_STACK)
728 #  ifdef __ia64
729     {"rb_ia64_bsp", (RUBY_PROC*)&dll_rb_ia64_bsp},
730 #  endif
731     {"ruby_init_stack", (RUBY_PROC*)&dll_ruby_init_stack},
732 # endif
733 # if defined(USE_RGENGC) && USE_RGENGC
734 #  if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER == 21
735     {"rb_gc_writebarrier_unprotect_promoted", (RUBY_PROC*)&dll_rb_gc_writebarrier_unprotect_promoted},
736 #  else
737     {"rb_gc_writebarrier_unprotect", (RUBY_PROC*)&dll_rb_gc_writebarrier_unprotect},
738 #  endif
739 # endif
740     {"", NULL},
741 };
742 
743 /*
744  * Free ruby.dll
745  */
746     static void
747 end_dynamic_ruby(void)
748 {
749     if (hinstRuby)
750     {
751 	close_dll(hinstRuby);
752 	hinstRuby = NULL;
753     }
754 }
755 
756 /*
757  * Load library and get all pointers.
758  * Parameter 'libname' provides name of DLL.
759  * Return OK or FAIL.
760  */
761     static int
762 ruby_runtime_link_init(char *libname, int verbose)
763 {
764     int i;
765 
766     if (hinstRuby)
767 	return OK;
768     hinstRuby = load_dll(libname);
769     if (!hinstRuby)
770     {
771 	if (verbose)
772 	    semsg(_(e_loadlib), libname);
773 	return FAIL;
774     }
775 
776     for (i = 0; ruby_funcname_table[i].ptr; ++i)
777     {
778 	if (!(*ruby_funcname_table[i].ptr = symbol_from_dll(hinstRuby,
779 			ruby_funcname_table[i].name)))
780 	{
781 	    close_dll(hinstRuby);
782 	    hinstRuby = NULL;
783 	    if (verbose)
784 		semsg(_(e_loadfunc), ruby_funcname_table[i].name);
785 	    return FAIL;
786 	}
787     }
788     return OK;
789 }
790 
791 /*
792  * If ruby is enabled (there is installed ruby on Windows system) return TRUE,
793  * else FALSE.
794  */
795     int
796 ruby_enabled(int verbose)
797 {
798     return ruby_runtime_link_init((char *)p_rubydll, verbose) == OK;
799 }
800 #endif /* defined(DYNAMIC_RUBY) || defined(PROTO) */
801 
802     void
803 ruby_end(void)
804 {
805 #ifdef DYNAMIC_RUBY
806     end_dynamic_ruby();
807 #endif
808 }
809 
810     void
811 ex_ruby(exarg_T *eap)
812 {
813     int state;
814     char *script = NULL;
815 
816     script = (char *)script_get(eap, eap->arg);
817     if (!eap->skip && ensure_ruby_initialized())
818     {
819 	if (script == NULL)
820 	    rb_eval_string_protect((char *)eap->arg, &state);
821 	else
822 	    rb_eval_string_protect(script, &state);
823 	if (state)
824 	    error_print(state);
825     }
826     vim_free(script);
827 }
828 
829 /*
830  *  In Ruby 1.9 or later, ruby String object has encoding.
831  *  conversion buffer string of vim to ruby String object using
832  *  VIM encoding option.
833  */
834     static VALUE
835 vim_str2rb_enc_str(const char *s)
836 {
837 #ifdef RUBY19_OR_LATER
838     int isnum;
839     long lval;
840     char_u *sval;
841     rb_encoding *enc;
842 
843     isnum = get_option_value((char_u *)"enc", &lval, &sval, 0);
844     if (isnum == 0)
845     {
846 	enc = rb_enc_find((char *)sval);
847 	vim_free(sval);
848 	if (enc)
849 	{
850 	    return rb_enc_str_new(s, (long)strlen(s), enc);
851 	}
852     }
853 #endif
854     return rb_str_new2(s);
855 }
856 
857     static VALUE
858 eval_enc_string_protect(const char *str, int *state)
859 {
860 #ifdef RUBY19_OR_LATER
861     int isnum;
862     long lval;
863     char_u *sval;
864     rb_encoding *enc;
865     VALUE v;
866 
867     isnum = get_option_value((char_u *)"enc", &lval, &sval, 0);
868     if (isnum == 0)
869     {
870 	enc = rb_enc_find((char *)sval);
871 	vim_free(sval);
872 	if (enc)
873 	{
874 	    v = rb_sprintf("#-*- coding:%s -*-\n%s", rb_enc_name(enc), str);
875 	    return rb_eval_string_protect(StringValuePtr(v), state);
876 	}
877     }
878 #endif
879     return rb_eval_string_protect(str, state);
880 }
881 
882     void
883 ex_rubydo(exarg_T *eap)
884 {
885     int state;
886     linenr_T i;
887     buf_T   *was_curbuf = curbuf;
888 
889     if (ensure_ruby_initialized())
890     {
891 	if (u_save(eap->line1 - 1, eap->line2 + 1) != OK)
892 	    return;
893 	for (i = eap->line1; i <= eap->line2; i++)
894 	{
895 	    VALUE line;
896 
897 	    if (i > curbuf->b_ml.ml_line_count)
898 		break;
899 	    line = vim_str2rb_enc_str((char *)ml_get(i));
900 	    rb_lastline_set(line);
901 	    eval_enc_string_protect((char *) eap->arg, &state);
902 	    if (state)
903 	    {
904 		error_print(state);
905 		break;
906 	    }
907 	    if (was_curbuf != curbuf)
908 		break;
909 	    line = rb_lastline_get();
910 	    if (!NIL_P(line))
911 	    {
912 		if (TYPE(line) != T_STRING)
913 		{
914 		    emsg(_("E265: $_ must be an instance of String"));
915 		    return;
916 		}
917 		ml_replace(i, (char_u *) StringValuePtr(line), 1);
918 		changed();
919 #ifdef SYNTAX_HL
920 		syn_changed(i); /* recompute syntax hl. for this line */
921 #endif
922 	    }
923 	}
924 	check_cursor();
925 	update_curbuf(NOT_VALID);
926     }
927 }
928 
929     static VALUE
930 rb_load_wrap(VALUE file_to_load)
931 {
932     rb_load(file_to_load, 0);
933     return Qnil;
934 }
935 
936     void
937 ex_rubyfile(exarg_T *eap)
938 {
939     int state;
940 
941     if (ensure_ruby_initialized())
942     {
943 	VALUE file_to_load = rb_str_new2((const char *)eap->arg);
944 	rb_protect(rb_load_wrap, file_to_load, &state);
945 	if (state)
946 	    error_print(state);
947     }
948 }
949 
950     void
951 ruby_buffer_free(buf_T *buf)
952 {
953     if (buf->b_ruby_ref)
954     {
955 	rb_hash_aset(objtbl, rb_obj_id((VALUE) buf->b_ruby_ref), Qnil);
956 	RDATA(buf->b_ruby_ref)->data = NULL;
957     }
958 }
959 
960     void
961 ruby_window_free(win_T *win)
962 {
963     if (win->w_ruby_ref)
964     {
965 	rb_hash_aset(objtbl, rb_obj_id((VALUE) win->w_ruby_ref), Qnil);
966 	RDATA(win->w_ruby_ref)->data = NULL;
967     }
968 }
969 
970     static int
971 ensure_ruby_initialized(void)
972 {
973     if (!ruby_initialized)
974     {
975 #ifdef DYNAMIC_RUBY
976 	if (ruby_enabled(TRUE))
977 	{
978 #endif
979 #ifdef MSWIN
980 	    /* suggested by Ariya Mizutani */
981 	    int argc = 1;
982 	    char *argv[] = {"gvim.exe"};
983 	    char **argvp = argv;
984 # ifdef RUBY19_OR_LATER
985 	    ruby_sysinit(&argc, &argvp);
986 # else
987 	    NtInitialize(&argc, &argvp);
988 # endif
989 #endif
990 	    {
991 #if defined(RUBY19_OR_LATER) || defined(RUBY_INIT_STACK)
992 		ruby_init_stack(ruby_stack_start);
993 #endif
994 		ruby_init();
995 	    }
996 #ifdef RUBY19_OR_LATER
997 	    {
998 		int dummy_argc = 2;
999 		char *dummy_argv[] = {"vim-ruby", "-e_=0"};
1000 		ruby_options(dummy_argc, dummy_argv);
1001 	    }
1002 	    ruby_script("vim-ruby");
1003 #else
1004 	    ruby_init_loadpath();
1005 #endif
1006 	    ruby_io_init();
1007 	    ruby_vim_init();
1008 	    ruby_initialized = 1;
1009 #ifdef DYNAMIC_RUBY
1010 	}
1011 	else
1012 	{
1013 	    emsg(_("E266: Sorry, this command is disabled, the Ruby library could not be loaded."));
1014 	    return 0;
1015 	}
1016 #endif
1017     }
1018     return ruby_initialized;
1019 }
1020 
1021     static void
1022 error_print(int state)
1023 {
1024 #if !defined(DYNAMIC_RUBY) && !defined(RUBY19_OR_LATER)
1025     RUBYEXTERN VALUE ruby_errinfo;
1026 #endif
1027     VALUE error;
1028     VALUE eclass;
1029     VALUE einfo;
1030     VALUE bt;
1031     int attr;
1032     char buff[BUFSIZ];
1033     long i;
1034 
1035 #define TAG_RETURN	0x1
1036 #define TAG_BREAK	0x2
1037 #define TAG_NEXT	0x3
1038 #define TAG_RETRY	0x4
1039 #define TAG_REDO	0x5
1040 #define TAG_RAISE	0x6
1041 #define TAG_THROW	0x7
1042 #define TAG_FATAL	0x8
1043 #define TAG_MASK	0xf
1044 
1045     switch (state)
1046     {
1047 	case TAG_RETURN:
1048 	    emsg(_("E267: unexpected return"));
1049 	    break;
1050 	case TAG_NEXT:
1051 	    emsg(_("E268: unexpected next"));
1052 	    break;
1053 	case TAG_BREAK:
1054 	    emsg(_("E269: unexpected break"));
1055 	    break;
1056 	case TAG_REDO:
1057 	    emsg(_("E270: unexpected redo"));
1058 	    break;
1059 	case TAG_RETRY:
1060 	    emsg(_("E271: retry outside of rescue clause"));
1061 	    break;
1062 	case TAG_RAISE:
1063 	case TAG_FATAL:
1064 #ifdef RUBY19_OR_LATER
1065 	    error = rb_errinfo();
1066 #else
1067 	    error = ruby_errinfo;
1068 #endif
1069 	    eclass = CLASS_OF(error);
1070 	    einfo = rb_obj_as_string(error);
1071 	    if (eclass == rb_eRuntimeError && RSTRING_LEN(einfo) == 0)
1072 	    {
1073 		emsg(_("E272: unhandled exception"));
1074 	    }
1075 	    else
1076 	    {
1077 		VALUE epath;
1078 		char *p;
1079 
1080 		epath = rb_class_path(eclass);
1081 		vim_snprintf(buff, BUFSIZ, "%s: %s",
1082 			 RSTRING_PTR(epath), RSTRING_PTR(einfo));
1083 		p = strchr(buff, '\n');
1084 		if (p) *p = '\0';
1085 		emsg(buff);
1086 	    }
1087 
1088 	    attr = syn_name2attr((char_u *)"Error");
1089 # ifdef RUBY21_OR_LATER
1090 	    bt = rb_funcallv(error, rb_intern("backtrace"), 0, 0);
1091 	    for (i = 0; i < RARRAY_LEN(bt); i++)
1092 		msg_attr(RSTRING_PTR(RARRAY_AREF(bt, i)), attr);
1093 # else
1094 	    bt = rb_funcall2(error, rb_intern("backtrace"), 0, 0);
1095 	    for (i = 0; i < RARRAY_LEN(bt); i++)
1096 		msg_attr(RSTRING_PTR(RARRAY_PTR(bt)[i]), attr);
1097 # endif
1098 	    break;
1099 	default:
1100 	    vim_snprintf(buff, BUFSIZ, _("E273: unknown longjmp status %d"), state);
1101 	    emsg(buff);
1102 	    break;
1103     }
1104 }
1105 
1106     static VALUE
1107 vim_message(VALUE self UNUSED, VALUE str)
1108 {
1109     char *buff, *p;
1110 
1111     str = rb_obj_as_string(str);
1112     if (RSTRING_LEN(str) > 0)
1113     {
1114 	/* Only do this when the string isn't empty, alloc(0) causes trouble. */
1115 	buff = ALLOCA_N(char, RSTRING_LEN(str) + 1);
1116 	strcpy(buff, RSTRING_PTR(str));
1117 	p = strchr(buff, '\n');
1118 	if (p) *p = '\0';
1119 	msg(buff);
1120     }
1121     else
1122     {
1123 	msg("");
1124     }
1125     return Qnil;
1126 }
1127 
1128     static VALUE
1129 vim_set_option(VALUE self UNUSED, VALUE str)
1130 {
1131     do_set((char_u *)StringValuePtr(str), 0);
1132     update_screen(NOT_VALID);
1133     return Qnil;
1134 }
1135 
1136     static VALUE
1137 vim_command(VALUE self UNUSED, VALUE str)
1138 {
1139     do_cmdline_cmd((char_u *)StringValuePtr(str));
1140     return Qnil;
1141 }
1142 
1143 #ifdef FEAT_EVAL
1144     static VALUE
1145 vim_to_ruby(typval_T *tv)
1146 {
1147     VALUE result = Qnil;
1148 
1149     if (tv->v_type == VAR_STRING)
1150     {
1151 	result = rb_str_new2(tv->vval.v_string == NULL
1152 					  ? "" : (char *)(tv->vval.v_string));
1153     }
1154     else if (tv->v_type == VAR_NUMBER)
1155     {
1156 	result = INT2NUM(tv->vval.v_number);
1157     }
1158 # ifdef FEAT_FLOAT
1159     else if (tv->v_type == VAR_FLOAT)
1160     {
1161 	result = rb_float_new(tv->vval.v_float);
1162     }
1163 # endif
1164     else if (tv->v_type == VAR_LIST)
1165     {
1166 	list_T      *list = tv->vval.v_list;
1167 	listitem_T  *curr;
1168 
1169 	result = rb_ary_new();
1170 
1171 	if (list != NULL)
1172 	{
1173 	    for (curr = list->lv_first; curr != NULL; curr = curr->li_next)
1174 	    {
1175 		rb_ary_push(result, vim_to_ruby(&curr->li_tv));
1176 	    }
1177 	}
1178     }
1179     else if (tv->v_type == VAR_DICT)
1180     {
1181 	result = rb_hash_new();
1182 
1183 	if (tv->vval.v_dict != NULL)
1184 	{
1185 	    hashtab_T   *ht = &tv->vval.v_dict->dv_hashtab;
1186 	    long_u      todo = ht->ht_used;
1187 	    hashitem_T  *hi;
1188 	    dictitem_T  *di;
1189 
1190 	    for (hi = ht->ht_array; todo > 0; ++hi)
1191 	    {
1192 		if (!HASHITEM_EMPTY(hi))
1193 		{
1194 		    --todo;
1195 
1196 		    di = dict_lookup(hi);
1197 		    rb_hash_aset(result, rb_str_new2((char *)hi->hi_key),
1198 						     vim_to_ruby(&di->di_tv));
1199 		}
1200 	    }
1201 	}
1202     }
1203     else if (tv->v_type == VAR_SPECIAL)
1204     {
1205 	if (tv->vval.v_number == VVAL_TRUE)
1206 	    result = Qtrue;
1207 	else if (tv->vval.v_number == VVAL_FALSE)
1208 	    result = Qfalse;
1209     }
1210     else if (tv->v_type == VAR_BLOB)
1211     {
1212 	result = rb_str_new(tv->vval.v_blob->bv_ga.ga_data,
1213 		tv->vval.v_blob->bv_ga.ga_len);
1214     }
1215     /* else return Qnil; */
1216 
1217     return result;
1218 }
1219 #endif
1220 
1221     static VALUE
1222 vim_evaluate(VALUE self UNUSED, VALUE str)
1223 {
1224 #ifdef FEAT_EVAL
1225     typval_T    *tv;
1226     VALUE       result;
1227 
1228     tv = eval_expr((char_u *)StringValuePtr(str), NULL);
1229     if (tv == NULL)
1230     {
1231 	return Qnil;
1232     }
1233     result = vim_to_ruby(tv);
1234 
1235     free_tv(tv);
1236 
1237     return result;
1238 #else
1239     return Qnil;
1240 #endif
1241 }
1242 
1243 #ifdef USE_TYPEDDATA
1244 static size_t buffer_dsize(const void *buf);
1245 
1246 static const rb_data_type_t buffer_type = {
1247     "vim_buffer",
1248     {0, 0, buffer_dsize, {0, 0}},
1249     0, 0,
1250 # ifdef RUBY_TYPED_FREE_IMMEDIATELY
1251     0,
1252 # endif
1253 };
1254 
1255     static size_t
1256 buffer_dsize(const void *buf UNUSED)
1257 {
1258     return sizeof(buf_T);
1259 }
1260 #endif
1261 
1262     static VALUE
1263 buffer_new(buf_T *buf)
1264 {
1265     if (buf->b_ruby_ref)
1266     {
1267 	return (VALUE) buf->b_ruby_ref;
1268     }
1269     else
1270     {
1271 #ifdef USE_TYPEDDATA
1272 	VALUE obj = TypedData_Wrap_Struct(cBuffer, &buffer_type, buf);
1273 #else
1274 	VALUE obj = Data_Wrap_Struct(cBuffer, 0, 0, buf);
1275 #endif
1276 	buf->b_ruby_ref = (void *) obj;
1277 	rb_hash_aset(objtbl, rb_obj_id(obj), obj);
1278 	return obj;
1279     }
1280 }
1281 
1282     static buf_T *
1283 get_buf(VALUE obj)
1284 {
1285     buf_T *buf;
1286 
1287 #ifdef USE_TYPEDDATA
1288     TypedData_Get_Struct(obj, buf_T, &buffer_type, buf);
1289 #else
1290     Data_Get_Struct(obj, buf_T, buf);
1291 #endif
1292     if (buf == NULL)
1293 	rb_raise(eDeletedBufferError, "attempt to refer to deleted buffer");
1294     return buf;
1295 }
1296 
1297     static VALUE
1298 vim_blob(VALUE self UNUSED, VALUE str)
1299 {
1300     VALUE result = rb_str_new("0z", 2);
1301     char    buf[4];
1302     int	i;
1303     for (i = 0; i < RSTRING_LEN(str); i++)
1304     {
1305 	sprintf(buf, "%02X", (unsigned char)(RSTRING_PTR(str)[i]));
1306 	rb_str_concat(result, rb_str_new2(buf));
1307     }
1308     return result;
1309 }
1310 
1311     static VALUE
1312 buffer_s_current(void)
1313 {
1314     return buffer_new(curbuf);
1315 }
1316 
1317     static VALUE
1318 buffer_s_count(void)
1319 {
1320     buf_T *b;
1321     int n = 0;
1322 
1323     FOR_ALL_BUFFERS(b)
1324     {
1325 	/*  Deleted buffers should not be counted
1326 	 *    SegPhault - 01/07/05 */
1327 	if (b->b_p_bl)
1328 	    n++;
1329     }
1330 
1331     return INT2NUM(n);
1332 }
1333 
1334     static VALUE
1335 buffer_s_aref(VALUE self UNUSED, VALUE num)
1336 {
1337     buf_T *b;
1338     int n = NUM2INT(num);
1339 
1340     FOR_ALL_BUFFERS(b)
1341     {
1342 	/*  Deleted buffers should not be counted
1343 	 *    SegPhault - 01/07/05 */
1344 	if (!b->b_p_bl)
1345 	    continue;
1346 
1347 	if (n == 0)
1348 	    return buffer_new(b);
1349 
1350 	n--;
1351     }
1352     return Qnil;
1353 }
1354 
1355     static VALUE
1356 buffer_name(VALUE self)
1357 {
1358     buf_T *buf = get_buf(self);
1359 
1360     return buf->b_ffname ? rb_str_new2((char *)buf->b_ffname) : Qnil;
1361 }
1362 
1363     static VALUE
1364 buffer_number(VALUE self)
1365 {
1366     buf_T *buf = get_buf(self);
1367 
1368     return INT2NUM(buf->b_fnum);
1369 }
1370 
1371     static VALUE
1372 buffer_count(VALUE self)
1373 {
1374     buf_T *buf = get_buf(self);
1375 
1376     return INT2NUM(buf->b_ml.ml_line_count);
1377 }
1378 
1379     static VALUE
1380 get_buffer_line(buf_T *buf, linenr_T n)
1381 {
1382     if (n <= 0 || n > buf->b_ml.ml_line_count)
1383 	rb_raise(rb_eIndexError, "line number %ld out of range", (long)n);
1384     return vim_str2rb_enc_str((char *)ml_get_buf(buf, n, FALSE));
1385 }
1386 
1387     static VALUE
1388 buffer_aref(VALUE self, VALUE num)
1389 {
1390     buf_T *buf = get_buf(self);
1391 
1392     if (buf != NULL)
1393 	return get_buffer_line(buf, (linenr_T)NUM2LONG(num));
1394     return Qnil; /* For stop warning */
1395 }
1396 
1397     static VALUE
1398 set_buffer_line(buf_T *buf, linenr_T n, VALUE str)
1399 {
1400     char	*line = StringValuePtr(str);
1401     aco_save_T	aco;
1402 
1403     if (n > 0 && n <= buf->b_ml.ml_line_count && line != NULL)
1404     {
1405 	/* set curwin/curbuf for "buf" and save some things */
1406 	aucmd_prepbuf(&aco, buf);
1407 
1408 	if (u_savesub(n) == OK)
1409 	{
1410 	    ml_replace(n, (char_u *)line, TRUE);
1411 	    changed();
1412 #ifdef SYNTAX_HL
1413 	    syn_changed(n); /* recompute syntax hl. for this line */
1414 #endif
1415 	}
1416 
1417 	/* restore curwin/curbuf and a few other things */
1418 	aucmd_restbuf(&aco);
1419 	/* Careful: autocommands may have made "buf" invalid! */
1420 
1421 	update_curbuf(NOT_VALID);
1422     }
1423     else
1424     {
1425 	rb_raise(rb_eIndexError, "line number %ld out of range", (long)n);
1426     }
1427     return str;
1428 }
1429 
1430     static VALUE
1431 buffer_aset(VALUE self, VALUE num, VALUE str)
1432 {
1433     buf_T *buf = get_buf(self);
1434 
1435     if (buf != NULL)
1436 	return set_buffer_line(buf, (linenr_T)NUM2LONG(num), str);
1437     return str;
1438 }
1439 
1440     static VALUE
1441 buffer_delete(VALUE self, VALUE num)
1442 {
1443     buf_T	*buf = get_buf(self);
1444     long	n = NUM2LONG(num);
1445     aco_save_T	aco;
1446 
1447     if (n > 0 && n <= buf->b_ml.ml_line_count)
1448     {
1449 	/* set curwin/curbuf for "buf" and save some things */
1450 	aucmd_prepbuf(&aco, buf);
1451 
1452 	if (u_savedel(n, 1) == OK)
1453 	{
1454 	    ml_delete(n, 0);
1455 
1456 	    /* Changes to non-active buffers should properly refresh
1457 	     *   SegPhault - 01/09/05 */
1458 	    deleted_lines_mark(n, 1L);
1459 
1460 	    changed();
1461 	}
1462 
1463 	/* restore curwin/curbuf and a few other things */
1464 	aucmd_restbuf(&aco);
1465 	/* Careful: autocommands may have made "buf" invalid! */
1466 
1467 	update_curbuf(NOT_VALID);
1468     }
1469     else
1470     {
1471 	rb_raise(rb_eIndexError, "line number %ld out of range", n);
1472     }
1473     return Qnil;
1474 }
1475 
1476     static VALUE
1477 buffer_append(VALUE self, VALUE num, VALUE str)
1478 {
1479     buf_T	*buf = get_buf(self);
1480     char	*line = StringValuePtr(str);
1481     long	n = NUM2LONG(num);
1482     aco_save_T	aco;
1483 
1484     if (line == NULL)
1485     {
1486 	rb_raise(rb_eIndexError, "NULL line");
1487     }
1488     else if (n >= 0 && n <= buf->b_ml.ml_line_count)
1489     {
1490 	/* set curwin/curbuf for "buf" and save some things */
1491 	aucmd_prepbuf(&aco, buf);
1492 
1493 	if (u_inssub(n + 1) == OK)
1494 	{
1495 	    ml_append(n, (char_u *) line, (colnr_T) 0, FALSE);
1496 
1497 	    /*  Changes to non-active buffers should properly refresh screen
1498 	     *    SegPhault - 12/20/04 */
1499 	    appended_lines_mark(n, 1L);
1500 
1501 	    changed();
1502 	}
1503 
1504 	/* restore curwin/curbuf and a few other things */
1505 	aucmd_restbuf(&aco);
1506 	/* Careful: autocommands may have made "buf" invalid! */
1507 
1508 	update_curbuf(NOT_VALID);
1509     }
1510     else
1511     {
1512 	rb_raise(rb_eIndexError, "line number %ld out of range", n);
1513     }
1514     return str;
1515 }
1516 
1517 #ifdef USE_TYPEDDATA
1518 static size_t window_dsize(const void *buf);
1519 
1520 static const rb_data_type_t window_type = {
1521     "vim_window",
1522     {0, 0, window_dsize, {0, 0}},
1523     0, 0,
1524 # ifdef RUBY_TYPED_FREE_IMMEDIATELY
1525     0,
1526 # endif
1527 };
1528 
1529     static size_t
1530 window_dsize(const void *win UNUSED)
1531 {
1532     return sizeof(win_T);
1533 }
1534 #endif
1535 
1536     static VALUE
1537 window_new(win_T *win)
1538 {
1539     if (win->w_ruby_ref)
1540     {
1541 	return (VALUE) win->w_ruby_ref;
1542     }
1543     else
1544     {
1545 #ifdef USE_TYPEDDATA
1546 	VALUE obj = TypedData_Wrap_Struct(cVimWindow, &window_type, win);
1547 #else
1548 	VALUE obj = Data_Wrap_Struct(cVimWindow, 0, 0, win);
1549 #endif
1550 	win->w_ruby_ref = (void *) obj;
1551 	rb_hash_aset(objtbl, rb_obj_id(obj), obj);
1552 	return obj;
1553     }
1554 }
1555 
1556     static win_T *
1557 get_win(VALUE obj)
1558 {
1559     win_T *win;
1560 
1561 #ifdef USE_TYPEDDATA
1562     TypedData_Get_Struct(obj, win_T, &window_type, win);
1563 #else
1564     Data_Get_Struct(obj, win_T, win);
1565 #endif
1566     if (win == NULL)
1567 	rb_raise(eDeletedWindowError, "attempt to refer to deleted window");
1568     return win;
1569 }
1570 
1571     static VALUE
1572 window_s_current(void)
1573 {
1574     return window_new(curwin);
1575 }
1576 
1577 /*
1578  * Added line manipulation functions
1579  *    SegPhault - 03/07/05
1580  */
1581     static VALUE
1582 line_s_current(void)
1583 {
1584     return get_buffer_line(curbuf, curwin->w_cursor.lnum);
1585 }
1586 
1587     static VALUE
1588 set_current_line(VALUE self UNUSED, VALUE str)
1589 {
1590     return set_buffer_line(curbuf, curwin->w_cursor.lnum, str);
1591 }
1592 
1593     static VALUE
1594 current_line_number(void)
1595 {
1596     return INT2FIX((int)curwin->w_cursor.lnum);
1597 }
1598 
1599     static VALUE
1600 window_s_count(void)
1601 {
1602     win_T	*w;
1603     int n = 0;
1604 
1605     FOR_ALL_WINDOWS(w)
1606 	n++;
1607     return INT2NUM(n);
1608 }
1609 
1610     static VALUE
1611 window_s_aref(VALUE self UNUSED, VALUE num)
1612 {
1613     win_T *w;
1614     int n = NUM2INT(num);
1615 
1616     for (w = firstwin; w != NULL; w = w->w_next, --n)
1617 	if (n == 0)
1618 	    return window_new(w);
1619     return Qnil;
1620 }
1621 
1622     static VALUE
1623 window_buffer(VALUE self)
1624 {
1625     win_T *win = get_win(self);
1626 
1627     return buffer_new(win->w_buffer);
1628 }
1629 
1630     static VALUE
1631 window_height(VALUE self)
1632 {
1633     win_T *win = get_win(self);
1634 
1635     return INT2NUM(win->w_height);
1636 }
1637 
1638     static VALUE
1639 window_set_height(VALUE self, VALUE height)
1640 {
1641     win_T *win = get_win(self);
1642     win_T *savewin = curwin;
1643 
1644     curwin = win;
1645     win_setheight(NUM2INT(height));
1646     curwin = savewin;
1647     return height;
1648 }
1649 
1650     static VALUE
1651 window_width(VALUE self UNUSED)
1652 {
1653     return INT2NUM(get_win(self)->w_width);
1654 }
1655 
1656     static VALUE
1657 window_set_width(VALUE self UNUSED, VALUE width)
1658 {
1659     win_T *win = get_win(self);
1660     win_T *savewin = curwin;
1661 
1662     curwin = win;
1663     win_setwidth(NUM2INT(width));
1664     curwin = savewin;
1665     return width;
1666 }
1667 
1668     static VALUE
1669 window_cursor(VALUE self)
1670 {
1671     win_T *win = get_win(self);
1672 
1673     return rb_assoc_new(INT2NUM(win->w_cursor.lnum), INT2NUM(win->w_cursor.col));
1674 }
1675 
1676     static VALUE
1677 window_set_cursor(VALUE self, VALUE pos)
1678 {
1679     VALUE lnum, col;
1680     win_T *win = get_win(self);
1681 
1682     Check_Type(pos, T_ARRAY);
1683     if (RARRAY_LEN(pos) != 2)
1684 	rb_raise(rb_eArgError, "array length must be 2");
1685     lnum = RARRAY_PTR(pos)[0];
1686     col = RARRAY_PTR(pos)[1];
1687     win->w_cursor.lnum = NUM2LONG(lnum);
1688     win->w_cursor.col = NUM2UINT(col);
1689     win->w_set_curswant = TRUE;
1690     check_cursor();		    /* put cursor on an existing line */
1691     update_screen(NOT_VALID);
1692     return Qnil;
1693 }
1694 
1695     static VALUE
1696 f_nop(VALUE self UNUSED)
1697 {
1698     return Qnil;
1699 }
1700 
1701     static VALUE
1702 f_p(int argc, VALUE *argv, VALUE self UNUSED)
1703 {
1704     int i;
1705     VALUE str = rb_str_new("", 0);
1706     VALUE ret = Qnil;
1707 
1708     for (i = 0; i < argc; i++)
1709     {
1710 	if (i > 0) rb_str_cat(str, ", ", 2);
1711 	rb_str_concat(str, rb_inspect(argv[i]));
1712     }
1713     msg(RSTRING_PTR(str));
1714 
1715     if (argc == 1)
1716 	ret = argv[0];
1717     else if (argc > 1)
1718 	ret = rb_ary_new4(argc, argv);
1719     return ret;
1720 }
1721 
1722     static void
1723 ruby_io_init(void)
1724 {
1725 #ifndef DYNAMIC_RUBY
1726     RUBYEXTERN VALUE rb_stdout;
1727     RUBYEXTERN VALUE rb_stderr;
1728 #endif
1729 
1730     rb_stdout = rb_obj_alloc(rb_cObject);
1731     rb_stderr = rb_obj_alloc(rb_cObject);
1732     rb_define_singleton_method(rb_stdout, "write", vim_message, 1);
1733     rb_define_singleton_method(rb_stdout, "flush", f_nop, 0);
1734     rb_define_singleton_method(rb_stderr, "write", vim_message, 1);
1735     rb_define_singleton_method(rb_stderr, "flush", f_nop, 0);
1736     rb_define_global_function("p", f_p, -1);
1737 }
1738 
1739     static void
1740 ruby_vim_init(void)
1741 {
1742     objtbl = rb_hash_new();
1743     rb_global_variable(&objtbl);
1744 
1745     /* The Vim module used to be called "VIM", but "Vim" is better.  Make an
1746      * alias "VIM" for backwards compatibility. */
1747     mVIM = rb_define_module("Vim");
1748     rb_define_const(rb_cObject, "VIM", mVIM);
1749     rb_define_const(mVIM, "VERSION_MAJOR", INT2NUM(VIM_VERSION_MAJOR));
1750     rb_define_const(mVIM, "VERSION_MINOR", INT2NUM(VIM_VERSION_MINOR));
1751     rb_define_const(mVIM, "VERSION_BUILD", INT2NUM(VIM_VERSION_BUILD));
1752     rb_define_const(mVIM, "VERSION_PATCHLEVEL", INT2NUM(VIM_VERSION_PATCHLEVEL));
1753     rb_define_const(mVIM, "VERSION_SHORT", rb_str_new2(VIM_VERSION_SHORT));
1754     rb_define_const(mVIM, "VERSION_MEDIUM", rb_str_new2(VIM_VERSION_MEDIUM));
1755     rb_define_const(mVIM, "VERSION_LONG", rb_str_new2(VIM_VERSION_LONG));
1756     rb_define_const(mVIM, "VERSION_LONG_DATE", rb_str_new2(VIM_VERSION_LONG_DATE));
1757     rb_define_module_function(mVIM, "message", vim_message, 1);
1758     rb_define_module_function(mVIM, "set_option", vim_set_option, 1);
1759     rb_define_module_function(mVIM, "command", vim_command, 1);
1760     rb_define_module_function(mVIM, "evaluate", vim_evaluate, 1);
1761     rb_define_module_function(mVIM, "blob", vim_blob, 1);
1762 
1763     eDeletedBufferError = rb_define_class_under(mVIM, "DeletedBufferError",
1764 						rb_eStandardError);
1765     eDeletedWindowError = rb_define_class_under(mVIM, "DeletedWindowError",
1766 						rb_eStandardError);
1767 
1768     cBuffer = rb_define_class_under(mVIM, "Buffer", rb_cObject);
1769     rb_define_singleton_method(cBuffer, "current", buffer_s_current, 0);
1770     rb_define_singleton_method(cBuffer, "count", buffer_s_count, 0);
1771     rb_define_singleton_method(cBuffer, "[]", buffer_s_aref, 1);
1772     rb_define_method(cBuffer, "name", buffer_name, 0);
1773     rb_define_method(cBuffer, "number", buffer_number, 0);
1774     rb_define_method(cBuffer, "count", buffer_count, 0);
1775     rb_define_method(cBuffer, "length", buffer_count, 0);
1776     rb_define_method(cBuffer, "[]", buffer_aref, 1);
1777     rb_define_method(cBuffer, "[]=", buffer_aset, 2);
1778     rb_define_method(cBuffer, "delete", buffer_delete, 1);
1779     rb_define_method(cBuffer, "append", buffer_append, 2);
1780 
1781     /* Added line manipulation functions
1782      *   SegPhault - 03/07/05 */
1783     rb_define_method(cBuffer, "line_number", current_line_number, 0);
1784     rb_define_method(cBuffer, "line", line_s_current, 0);
1785     rb_define_method(cBuffer, "line=", set_current_line, 1);
1786 
1787 
1788     cVimWindow = rb_define_class_under(mVIM, "Window", rb_cObject);
1789     rb_define_singleton_method(cVimWindow, "current", window_s_current, 0);
1790     rb_define_singleton_method(cVimWindow, "count", window_s_count, 0);
1791     rb_define_singleton_method(cVimWindow, "[]", window_s_aref, 1);
1792     rb_define_method(cVimWindow, "buffer", window_buffer, 0);
1793     rb_define_method(cVimWindow, "height", window_height, 0);
1794     rb_define_method(cVimWindow, "height=", window_set_height, 1);
1795     rb_define_method(cVimWindow, "width", window_width, 0);
1796     rb_define_method(cVimWindow, "width=", window_set_width, 1);
1797     rb_define_method(cVimWindow, "cursor", window_cursor, 0);
1798     rb_define_method(cVimWindow, "cursor=", window_set_cursor, 1);
1799 
1800     rb_define_virtual_variable("$curbuf", buffer_s_current, 0);
1801     rb_define_virtual_variable("$curwin", window_s_current, 0);
1802 }
1803 
1804     void
1805 vim_ruby_init(void *stack_start)
1806 {
1807     /* should get machine stack start address early in main function */
1808     ruby_stack_start = stack_start;
1809 }
1810 
1811     static int
1812 convert_hash2dict(VALUE key, VALUE val, VALUE arg)
1813 {
1814     dict_T *d = (dict_T *)arg;
1815     dictitem_T *di;
1816 
1817     di = dictitem_alloc((char_u *)RSTRING_PTR(RSTRING(rb_obj_as_string(key))));
1818     if (di == NULL || ruby_convert_to_vim_value(val, &di->di_tv) != OK
1819 						     || dict_add(d, di) != OK)
1820     {
1821 	d->dv_hashtab.ht_error = TRUE;
1822 	return ST_STOP;
1823     }
1824     return ST_CONTINUE;
1825 }
1826 
1827     static int
1828 ruby_convert_to_vim_value(VALUE val, typval_T *rettv)
1829 {
1830     switch (TYPE(val))
1831     {
1832 	case T_NIL:
1833 	    rettv->v_type = VAR_SPECIAL;
1834 	    rettv->vval.v_number = VVAL_NULL;
1835 	    break;
1836 	case T_TRUE:
1837 	    rettv->v_type = VAR_SPECIAL;
1838 	    rettv->vval.v_number = VVAL_TRUE;
1839 	    break;
1840 	case T_FALSE:
1841 	    rettv->v_type = VAR_SPECIAL;
1842 	    rettv->vval.v_number = VVAL_FALSE;
1843 	    break;
1844 	case T_BIGNUM:
1845 	case T_FIXNUM:
1846 	    rettv->v_type = VAR_NUMBER;
1847 	    rettv->vval.v_number = (varnumber_T)NUM2LONG(val);
1848 	    break;
1849 #ifdef FEAT_FLOAT
1850 	case T_FLOAT:
1851 	    rettv->v_type = VAR_FLOAT;
1852 	    rettv->vval.v_float = (float_T)NUM2DBL(val);
1853 	    break;
1854 #endif
1855 	default:
1856 	    val = rb_obj_as_string(val);
1857 	    // FALLTHROUGH
1858 	case T_STRING:
1859 	    {
1860 		VALUE str = (VALUE)RSTRING(val);
1861 
1862 		rettv->v_type = VAR_STRING;
1863 		rettv->vval.v_string = vim_strnsave((char_u *)RSTRING_PTR(str),
1864 							 (int)RSTRING_LEN(str));
1865 	    }
1866 	    break;
1867 	case T_ARRAY:
1868 	    {
1869 		list_T *l;
1870 		long i;
1871 		typval_T v;
1872 
1873 		l = list_alloc();
1874 		if (l == NULL)
1875 		    return FAIL;
1876 
1877 		for (i = 0; i < RARRAY_LEN(val); ++i)
1878 		{
1879 		    if (ruby_convert_to_vim_value((VALUE)RARRAY_PTR(val)[i],
1880 									&v) != OK)
1881 		    {
1882 			list_unref(l);
1883 			return FAIL;
1884 		    }
1885 		    list_append_tv(l, &v);
1886 		    clear_tv(&v);
1887 		}
1888 
1889 		rettv->v_type = VAR_LIST;
1890 		rettv->vval.v_list = l;
1891 		++l->lv_refcount;
1892 	    }
1893 	    break;
1894 	case T_HASH:
1895 	    {
1896 		dict_T *d;
1897 
1898 		d = dict_alloc();
1899 		if (d == NULL)
1900 		    return FAIL;
1901 
1902 		rb_hash_foreach(val, convert_hash2dict, (VALUE)d);
1903 		if (d->dv_hashtab.ht_error)
1904 		{
1905 		    dict_unref(d);
1906 		    return FAIL;
1907 		}
1908 
1909 		rettv->v_type = VAR_DICT;
1910 		rettv->vval.v_dict = d;
1911 		++d->dv_refcount;
1912 	    }
1913 	    break;
1914     }
1915     return OK;
1916 }
1917 
1918     void
1919 do_rubyeval(char_u *str, typval_T *rettv)
1920 {
1921     int retval = FAIL;
1922 
1923     if (ensure_ruby_initialized())
1924     {
1925 	int state;
1926 	VALUE obj;
1927 
1928 	obj = rb_eval_string_protect((const char *)str, &state);
1929 	if (state)
1930 	    error_print(state);
1931 	else
1932 	    retval = ruby_convert_to_vim_value(obj, rettv);
1933     }
1934     if (retval == FAIL)
1935     {
1936 	rettv->v_type = VAR_NUMBER;
1937 	rettv->vval.v_number = 0;
1938     }
1939 }
1940