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