c++-gtk-utils
extension.h
Go to the documentation of this file.
1 /* Copyright (C) 2014 Chris Vine
2 
3 The library comprised in this file or of which this file is part is
4 distributed by Chris Vine under the GNU Lesser General Public
5 License as follows:
6 
7  This library is free software; you can redistribute it and/or
8  modify it under the terms of the GNU Lesser General Public License
9  as published by the Free Software Foundation; either version 2.1 of
10  the License, or (at your option) any later version.
11 
12  This library is distributed in the hope that it will be useful, but
13  WITHOUT ANY WARRANTY; without even the implied warranty of
14  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15  Lesser General Public License, version 2.1, for more details.
16 
17  You should have received a copy of the GNU Lesser General Public
18  License, version 2.1, along with this library (see the file LGPL.TXT
19  which came with this source code package in the c++-gtk-utils
20  sub-directory); if not, write to the Free Software Foundation, Inc.,
21  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22 
23 However, it is not intended that the object code of a program whose
24 source code instantiates a template from this file or uses macros or
25 inline functions (of any length) should by reason only of that
26 instantiation or use be subject to the restrictions of use in the GNU
27 Lesser General Public License. With that in mind, the words "and
28 macros, inline functions and instantiations of templates (of any
29 length)" shall be treated as substituted for the words "and small
30 macros and small inline functions (ten lines or less in length)" in
31 the fourth paragraph of section 5 of that licence. This does not
32 affect any other reason why object code may be subject to the
33 restrictions in that licence (nor for the avoidance of doubt does it
34 affect the application of section 2 of that licence to modifications
35 of the source code in this file).
36 
37 NOTE: If you incorporate this header file in your code, you will have
38 to link with libguile. libguile is released under the LGPL version 3
39 or later. By linking with libguile your code will therefore be
40 governed by the LPGL version 3 or later, not the LGPL version 2.1 or
41 later.
42 
43 */
44 
45 #ifndef CGU_EXTENSION_H
46 #define CGU_EXTENSION_H
47 
48 /**
49  * @namespace Cgu::Extension
50  * @brief This namespace provides functions to execute scheme code on the guile VM.
51  *
52  * \#include <c++-gtk-utils/extension.h>
53  *
54  * The Extension::exec() and Extension::exec_shared() functions
55  * provided by this library allow any C++ program to execute files
56  * written in the scheme language on the guile VM as part of the C++
57  * runtime. There are a number of reasons why this might be useful:
58  *
59  * @par
60  * - to enable the dynamic behaviour of the program to be altered
61  * without recompilation
62  *
63  * @par
64  * - to provide a plugin system
65  *
66  * @par
67  * - because some things are easier or quicker to do when done in
68  * a dynamically typed language such as scheme
69  *
70  * @par
71  * - because scheme is a nice language to use and highly
72  * extensible
73  *
74  * @par
75  * - with Extension::exec(), it is trivial to do (see the example
76  * below)
77  *
78  * To call Extension::exec() or Extension::exec_shared(), guile-2.0 is
79  * required.
80  *
81  * Usage
82  * -----
83  *
84  * Extension::exec() and Extension::exec_shared() take three
85  * arguments. The first is a preamble string, which sets out any top
86  * level definitions which the script file needs to see. This is
87  * mainly intended for argument passing to the script file, but can
88  * comprise any scheme code. It can also be an empty string. The
89  * second is the name of the scheme script file to be executed, with
90  * path. This file can contain scheme code of arbitrary complexity
91  * and length, and can incorporate guile modules and other scheme
92  * files.
93  *
94  * The third argument is a translator. This is a function or callable
95  * object which takes the value to which the scheme file evaluates (in
96  * C++ terms, its return value) as an opaque SCM guile type (it is
97  * actually a pointer to a struct in the guile VM), and converts it to
98  * a suitable C++ representation using functions provided by libguile.
99  * The return value of the translator function comprises the return
100  * value of Extension::exec() and Extension::exec_shared().
101  *
102  * Translators
103  * -----------
104  *
105  * Preformed translators are provided by this library to translate
106  * from scheme's integers, real numbers and strings to C++ longs,
107  * doubles and strings respectively (namely
108  * Extension::integer_to_long(), Extension::real_to_double() and
109  * Extension::string_to_string()), and from any uniform lists of these
110  * to C++ vectors of the corresponding type
111  * (Extension::list_to_vector_long(),
112  * Extension::list_to_vector_double() and
113  * Extension::list_to_vector_string(). There is also a translator for
114  * void return types (Extension::any_to_void()), where the scheme
115  * script is executed for its side effects, perhaps I/O, where the
116  * return value is ignored and any communication necessary is done by
117  * guile exceptions.
118  *
119  * Any guile exception thrown by the code in the scheme file is
120  * trapped by the preformed translators and will be rethrown as an
121  * Extension::GuileException C++ exception. The preformed translators
122  * should suffice for most purposes, but custom translators can be
123  * provided by the user - see further below.
124  *
125  * Example
126  * -------
127  *
128  * Assume the following code is in a file called 'myip.scm'.
129  *
130  * @code
131  * ;; myip.scm
132  *
133  * ;; the following code assumes a top level definition of 'web-ip' is
134  * ;; passed, giving the URL of an IP address reflector
135  *
136  * (use-modules (ice-9 regex)(web uri)(web client))
137  * (let ([uri (build-uri 'http
138  * #:host web-ip
139  * #:port 80
140  * #:path "/")])
141  * (call-with-values
142  * (lambda () (http-get uri))
143  * (lambda (request body)
144  * (match:substring
145  * (string-match "[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+"
146  * body)))))
147  * @endcode
148  *
149  * This code requires guile >= 2.0.3, and makes a http request to the
150  * reflector, reads the body of the reply and then does a regex search
151  * on it to obtain the address. Courtesy of the good folks at DynDNS
152  * we can obtain our address with this:
153  *
154  * @code
155  * using namespace Cgu;
156  * std::cout << "IP address is: "
157  * << Extension::exec_shared("(define web-ip \"checkip.dyndns.com\")",
158  * "./myip.scm",
159  * &Extension::string_to_string)
160  * << std::endl;
161  * @endcode
162  *
163  * This is easier than doing the same in C++ using, say, libsoup and
164  * std::regex. However it is unsatisfying where we do not want the
165  * code to block waiting for the reply. There are a number of
166  * possible approaches to this, but one is to provide the result to a
167  * glib main loop asynchronously via a Thread::TaskManager object. If
168  * that is done, it is necessary to deal with a case where guile
169  * throws an exception (say because the url does not resolve).
170  * Thread::TaskManager::make_task_packaged_compose() would be suitable
171  * for this because any thrown Extension::GuileException would be
172  * stored in the shared state of a std::packaged_task object:
173  *
174  * @code
175  * using namespace Cgu;
176  * Thread::TaskManager tm{1};
177  * tm.make_task_packaged_compose(
178  * [] () {
179  * return Extension::exec_shared("(define web-ip \"checkip.dyndns.com\")",
180  * "./myip.scm",
181  * &Extension::string_to_string);
182  * },
183  * 0, // supply result to default glib main loop
184  * [] (std::future<std::string>& res) { // the 'when' callback
185  * try {
186  * std:string ip{res.get()};
187  * // publish result in some GTK widget
188  * }
189  * catch (Extension::GuileException& e) {
190  * // display GtkMessageDialog object indicating failure
191  * }
192  * }
193  * );
194  * @endcode
195  *
196  * Extension::exec() and Extension::exec_shared()
197  * ----------------------------------------------
198  *
199  * Extension::exec() isolates the top level definitions included in
200  * the preamble of a task, or imported by guile's 'use-modules' or
201  * 'load' procedures in the task, from the top level definitions of
202  * other tasks started by calls to Extension::exec(), by calling
203  * guile's 'make-fresh-user-module' procedure.
204  * Extension::exec_shared() does not do so: with
205  * Extension::exec_shared(), all scheme tasks executed by calls to
206  * that function will share the same top level. In addition,
207  * Extension::exec() loads the file passed to the function using the
208  * guile 'load' procedure, so that the first time the file is executed
209  * it is compiled into bytecode, whereas Extension::exec_shared()
210  * calls the 'primitive-load' procedure instead, which runs the file
211  * through the guile interpreter without converting it to bytecode.
212  *
213  * The reason for this different behaviour of Extension::exec_shared()
214  * is that, as currently implemented in guile both the
215  * 'make-fresh-user-module' and 'load' procedures leak small amounts
216  * of memory. If a particular program is likely to call
217  * Extension::exec() more than about 5,000 or 10,000 times, it would
218  * be better to use Extension::exec_shared() instead.
219  *
220  * From guile-2.0.2, Extension::exec() and Extension::exec_shared() do
221  * not need to be called only in the main program thread - and in the
222  * above example using a Thread::TaskManager object
223  * Extension::exec_shared() was not. However, one of the consequences
224  * of the behaviour mentioned above is that if
225  * Extension::exec_shared() is to be used instead of
226  * Extension::exec(), either concurrent calls to the function from
227  * different threads should be avoided, or (i) the preambles in calls
228  * to Extension::exec_shared() should be empty and (ii) tasks should
229  * not import clashing definitions using 'use-modules' or 'load'. The
230  * need for Extension::exec_shared() to be called only in one thread
231  * in the example above was the reason why the TaskManager object in
232  * that example was set to have a maximum thread count of 1. In
233  * effect the TaskManager object was a dedicated serial dispatcher for
234  * all scheme tasks.
235  *
236  * The calling by Extension::exec_shared() of 'primitive-load' instead
237  * of 'load' may have some small effect on efficiency. It it best for
238  * the file passed to that function to hand off any complex code to
239  * modules prepared using guile's modules interface (which will be
240  * compiled into bytecode), and which are then loaded using
241  * 'use-modules' the first time Extension::exec_shared() is called, or
242  * by having the first call to Extension::exec_shared() (and only the
243  * first call) import any needed files into the top level using
244  * 'load'.
245  *
246  * Note that some guile global state may be shared between tasks
247  * whether Extension::exec() or Extension::exec_shared() is used. For
248  * example, if the guile 'add-to-load-path' procedure is called to add
249  * a local directory to the search path used by 'use-modules' or
250  * 'load', that will have effect for all other tasks.
251  *
252  * Other thread safety points
253  * --------------------------
254  *
255  * Leaving aside what has been said above, there are a few other
256  * issues to keep in mind if executing scheme code in more than one
257  * thread.
258  *
259  * First, the initialization of guile < 2.0.10 is not thread safe.
260  * One thread needs to have called Extension::exec() or
261  * Extension::exec_shared() once and returned before any other threads
262  * call the function. This can be achieved by the simple expedient of
263  * executing the statement:
264  *
265  * @code
266  * Extension::exec_shared("", "", &Extension::any_to_void);
267  * @endcode
268  *
269  * and waiting for it to return before any tasks are added to a
270  * TaskManager object running more than one thread. This issue is
271  * fixed in guile-2.0.10. However there is a further snag. Certain
272  * aspects of guile module loading are not thread safe. One way
273  * around this is to load all the modules that tasks may use in
274  * advance, by loading the modules in the preamble of the above
275  * statement (or to have that statement execute a file which loads the
276  * modules). If that is done, it should be fine afterwards to run
277  * Extension::exec() on a TaskManager object running any number of
278  * threads, or on a Thread::Future object or std::async() task.
279  * (However, note that if using Extension::exec() the modules would
280  * need to be reloaded in each task in order to make them visible to
281  * the task, but that would be done safely if they have previously
282  * been loaded in another task.)
283  *
284  * This issue is likely to be fixed in a future version of guile.
285  *
286  * If a C++ program is to run guile tasks on a TaskManager object
287  * having a maximum thread count greater than one (or in more than one
288  * thread in some other way), one other point should be noted. When a
289  * scheme file is executed for the first time by a user by being
290  * passed as the second argument of Extension::exec() (or by having
291  * 'load' applied to it in some other way), it will be compiled into
292  * byte code, the byte code will then be cached on the file system for
293  * that and subsequent calls, and the byte code then executed. Bad
294  * things might happen if concurrent calls to Extension::exec(), or to
295  * the 'load' or 'use-modules' procedures, are made in respect of the
296  * same scheme file for the "first" time, if there might be a race as
297  * to which of them is the "first" call in respect of the file: that
298  * is, if it causes two or more threads to try to compile the same
299  * file into byte code concurrently. This is only an issue the first
300  * time a particular user executes a scheme file, and can be avoided
301  * (amongst other ways) by having the C++ program concerned
302  * pre-compile the relevant scheme file before Extension::exec() or
303  * Extension::exec_shared() is first called, by means of the 'guild
304  * compile [filename]' command. The following gives more information
305  * about compilation: <A
306  * HREF="http://www.gnu.org/software/guile/manual/html_node/Compilation.html#Compilation">
307  * Compiling Scheme Code</A>
308  *
309  * Licence
310  * -------
311  *
312  * The c++-gtk-utils library (and this c++-gtk-utils/extension.h
313  * header file) follows glib and GTK+ by being released under the LGPL
314  * version 2.1 or later. libguile is released under the LGPL version
315  * 3 or later. The c++-gtk-utils library object code does not link to
316  * libguile, nor does it incorporate anything in the
317  * c++-gtk-utils/extension.h header. Instead
318  * c++-gtk-utils/extension.h contains all its code as a separate
319  * unlinked header for any program which wants to include it (this is
320  * partly because some of it comprises template functions).
321  *
322  * There are two consequences. If you want to use Extension::exec()
323  * or Extension::exec_shared(), the program which calls it will need
324  * to link itself explicitly with libguile as well as c++-gtk-utils,
325  * and to do that will need to use pkg-config to obtain libguile's
326  * cflags and libs particulars (its pkg-config file is guile-2.0.pc).
327  * This library does NOT do that for you. Secondly, by linking with
328  * libguile you will be governed by the LGPL version 3 or later,
329  * instead of the LGPL version 2.1 or later, with respect to that
330  * linking. That's fine (there is nothing wrong with the LGPL version
331  * 3 and this library permits that) but you should be aware of it.
332  * The scheme code in guile's scheme level modules is also in the main
333  * released under the LGPL version 3 or later ("in the main" because
334  * readline.scm, comprised in the readline module, is released under
335  * the GPL version 3 or later).
336  *
337  * Custom translators
338  * ------------------
339  *
340  * Any function or callable object which translates from an opaque SCM
341  * value to a suitable C++ representation can be passed as the third
342  * argument of Extension::exec() or Extension::exec_shared(). C++
343  * type deduction on template resolution will take care of everything
344  * else. The translator can execute any functions offered by
345  * libguile, because when the translator is run the program is still
346  * in guile mode. The fulsome guile documentation sets out the
347  * libguile functions which are callable in C/C++ code.
348  *
349  * The first call in a custom translator should normally be to the
350  * Extension::rethrow_guile_exception() function. This function tests
351  * whether a guile exception arose in executing the scheme file, and
352  * throws a C++ exception if it did. The preformed translators in
353  * extension.h provide worked examples of how a custom translator
354  * might be written.
355  *
356  * If something done in a custom translator were to raise a guile
357  * exception, the library implementation would handle it and a C++
358  * exception would be generated in its place in Extension::exec() or
359  * Extension::exec_shared(). However, a custom translator should not
360  * allow a guile exception arising from calls to libguile made by it
361  * to exit a C++ scope in which the translator has constructed a local
362  * C++ object which is not trivially destructible: that would give
363  * rise to undefined behaviour, with the likely result that the C++
364  * object's destructor would not be called. One approach to this
365  * (adopted in the preformed translators) is to allocate on free store
366  * all local C++ objects to be constructed in the translator which are
367  * not trivially destructible, and to manage their lifetimes manually
368  * using local C++ try/catch blocks rather than RAII, with dynwind
369  * unwind handlers to release memory were there to be a guile
370  * exception (but note that no C++ exception should transit out of a
371  * scm_dynwind_begin()/scm_dynwind_end() pair). It is also a good
372  * idea to test for any condition which might cause a guile exception
373  * to be raised in the translator in the first place, and throw a C++
374  * exception beforehand. Then the only condition which might cause a
375  * guile exception to occur in the translator is an out-of-memory
376  * condition, which is highly improbable in a translator as the
377  * translator is run after the guile task has completed. Heap
378  * exhaustion in such a case probably spells doom for the program
379  * concerned anyway, if it has other work to do.
380  *
381  * Scheme
382  * ------
383  * If you want to learn more about scheme, these are useful sources:
384  * <P>
385  * <A HREF="http://www.gnu.org/software/guile/manual/html_node/Hello-Scheme_0021.html"> Chapter 3 of the Guile Manual</A>
386  * (the rest of the manual is also good reading).</P>
387  * <P>
388  * <A HREF="http://www.scheme.com/tspl4/">The Scheme Programming Language, 4th edition</A></P>
389  */
390 
391 #include <string>
392 #include <vector>
393 #include <exception>
394 #include <memory> // for std::unique_ptr
395 #include <type_traits> // for std::result_of
396 #include <limits> // for std::numeric_limits
397 #include <utility> // for std::forward and std::move
398 #include <new> // for std::bad_alloc
399 
400 #include <stddef.h> // for size_t
401 #include <stdlib.h> // for free()
402 #include <string.h> // for strlen() and strncmp()
403 
404 #include <glib.h>
405 
407 #include <c++-gtk-utils/callback.h>
408 #include <c++-gtk-utils/thread.h>
410 
411 #include <libguile.h>
412 
413 
414 #ifndef DOXYGEN_PARSING
415 namespace Cgu {
416 
417 namespace Extension {
418 
419 struct FormatArgs {
420  SCM text;
421  SCM rest;
422 };
423 
424 enum VectorDeleteType {Long, Double, String};
425 
426 struct VectorDeleteArgs {
427  VectorDeleteType type;
428  void* vec;
429 };
430 
431 } // namespace Extension
432 
433 } // namespace Cgu
434 
435 namespace {
436 extern "C" {
437  inline SCM cgu_format_try_handler(void* data) {
438  using Cgu::Extension::FormatArgs;
439  FormatArgs* format_args = static_cast<FormatArgs*>(data);
440  return scm_simple_format(SCM_BOOL_F, format_args->text, format_args->rest);
441  }
442  inline SCM cgu_format_catch_handler(void*, SCM, SCM) {
443  return SCM_BOOL_F;
444  }
445  inline void* cgu_guile_wrapper(void* data) {
446  try {
447  static_cast<Cgu::Callback::Callback*>(data)->dispatch();
448  }
449  // an elipsis catch block is fine as thread cancellation is
450  // blocked. We can only enter this block if assigning to one of
451  // the exception strings in the callback has thrown
452  // std::bad_alloc. For that case we return a non-NULL pointer to
453  // indicate error (the 'data' argument is convenient and
454  // guaranteed to be standard-conforming for this).
455  catch (...) {
456  return data;
457  }
458  return 0;
459  }
460  inline void cgu_delete_vector(void* data) {
461  using Cgu::Extension::VectorDeleteArgs;
462  VectorDeleteArgs* args = static_cast<VectorDeleteArgs*>(data);
463  switch (args->type) {
464  case Cgu::Extension::Long:
465  delete static_cast<std::vector<long>*>(args->vec);
466  break;
467  case Cgu::Extension::Double:
468  delete static_cast<std::vector<double>*>(args->vec);
469  break;
470  case Cgu::Extension::String:
471  delete static_cast<std::vector<std::string>*>(args->vec);
472  break;
473  default:
474  g_critical("Incorrect argument passed to cgu_delete_vector");
475  }
476  delete args;
477  }
478 } // extern "C"
479 } // unnamed namespace
480 #endif // DOXYGEN_PARSING
481 
482 namespace Cgu {
483 
484 namespace Extension {
485 
486 class GuileException: public std::exception {
487  Cgu::GcharSharedHandle message;
488  Cgu::GcharSharedHandle guile_message;
489 public:
490  virtual const char* what() const throw() {return (const char*)message.get();}
491  const char* guile_text() const throw() {return (const char*)guile_message.get();}
492  GuileException(const char* msg):
493  message(g_strdup_printf(u8"Cgu::Extension::GuileException: %s", msg)),
494  guile_message(g_strdup(msg)) {}
495  ~GuileException() throw() {}
496 };
497 
498 class ReturnValueError: public std::exception {
499  Cgu::GcharSharedHandle message;
500  Cgu::GcharSharedHandle err_message;
501 public:
502  virtual const char* what() const throw() {return (const char*)message.get();}
503  const char* err_text() const throw() {return (const char*)err_message.get();}
504  ReturnValueError(const char* msg):
505  message(g_strdup_printf(u8"Cgu::Extension::ReturnValueError: %s", msg)),
506  err_message(g_strdup(msg)) {}
507  ~ReturnValueError() throw() {}
508 };
509 
510 class WrapperError: public std::exception {
511  Cgu::GcharSharedHandle message;
512 public:
513  virtual const char* what() const throw() {return (const char*)message.get();}
514  WrapperError(const char* msg):
515  message(g_strdup_printf(u8"Cgu::Extension::WrapperError: %s", msg)) {}
516  ~WrapperError() throw() {}
517 };
518 
519 #ifndef DOXYGEN_PARSING
520 
521 // we might as well take 'translator' by collapsible reference. If it
522 // is handed a rvalue function object, it will be implicitly converted
523 // to lvalue (and if necessary constructed as such) in order to take a
524 // lvalue reference on lambda construction. If it is already a
525 // lvalue, it will be passed through seamlessly.
526 template <class Ret, class Translator>
527 Ret exec_impl(const std::string& preamble,
528  const std::string& file,
529  Translator&& translator,
530  bool shared) {
531 
533 
534  std::string loader;
535  if (!shared)
536  loader += u8"(set-current-module (make-fresh-user-module))";
537  loader += preamble;
538  if (!file.empty()) {
539  if (shared)
540  loader += u8"((lambda ()";
541  loader += u8"(catch "
542  "#t"
543  "(lambda ()"
544  "(";
545  if (shared)
546  loader += u8"primitive-load \"";
547  else
548  loader += u8"load \"";
549  loader += file;
550  loader += u8"\"))"
551  "(lambda (key . details)"
552  "(cons \"***cgu-guile-exception***\" (cons key details))))";
553  if (shared)
554  loader += u8"))";
555  }
556 
557  Ret retval;
558  bool result = false;
559  std::string guile_except;
560  std::string guile_ret_val_err;
561  std::string gen_err;
562 
563  // we construct a Callback::Callback object here to perform type
564  // erasure. Otherwise we would have to pass scm_with_guile() a
565  // function pointer to a function templated on Translator and Ret,
566  // which must have C++ language linkage (§14/4 of C++ standard).
567  // Technically this would give undefined behaviour as
568  // scm_with_guile() expects a function pointer with C language
569  // linkage, although gcc and clang would accept it. The whole of
570  // this callback will be executed in guile mode via
571  // cgu_guile_wrapper(), so it can safely call libguile functions
572  // (provided that a translator does not allow any guile exceptions
573  // to escape a C++ scope with local objects which are not trivially
574  // destructible). It is also safe to pass 'translator', 'retval',
575  // 'loader', 'result' and the exception strings to it by reference,
576  // because scm_with_guile() will block until it has completed
577  // executing. cgu_guile_wrapper() will trap any std::bad_alloc
578  // exception thrown by the string assignments in the catch blocks in
579  // this lambda. This lambda is safe against a jump to an exit from
580  // scm_with_guile() arising from a native guile exception in
581  // translator, because its body has no objects in local scope
582  // requiring destruction.
583  std::unique_ptr<Cgu::Callback::Callback> cb(Cgu::Callback::lambda<>([&] () -> void {
584  SCM scm = scm_eval_string(scm_from_utf8_string(loader.c_str()));
585 
586  // have a dynwind context and async block while translator is
587  // executing. This is to cater for the pathological case of
588  // the scheme script having set up a signal handler which
589  // might throw a guile exception, or having chained a series
590  // of system asyncs which are still queued for action, which
591  // might otherwise cause the translator to trigger a guile
592  // exception while a non-trivially destructible object is in
593  // the local scope of translator. (Highly unlikely, but easy
594  // to deal with.) This is entirely safe as no C++ exception
595  // arising from the translator can transit across the dynamic
596  // context in this function - see below. So we have (i) no
597  // C++ exception can transit across a guile dynamic context,
598  // and (ii) no guile exception can escape out of a local C++
599  // scope by virtue of an async executing (it might still
600  // escape with a non-trivially destructible object in
601  // existence if a custom translator has not been written
602  // correctly, but there is nothing we can do about that).
603  // Note that some guile installations do not link
604  // scm_dynwind_block_asyncs() correctly - this is tested at
605  // configuration time.
606 #ifndef CGU_GUILE_HAS_BROKEN_LINKING
607  scm_dynwind_begin(scm_t_dynwind_flags(0));
608  scm_dynwind_block_asyncs();
609 #endif
610  // we cannot use std::exception_ptr here to store a C++
611  // exception object, because std::exception_ptr is not
612  // trivially destructible and a guile exception in
613  // 'translator' could jump out of this scope to its
614  // continuation in scm_with_guile()
615  bool badalloc = false;
616  try {
617  retval = translator(scm);
618  result = true; // this will detect any guile exception in
619  // the preamble or 'translator' which causes
620  // scm_with_guile() to return prematurely.
621  // We could have done it instead by reversing
622  // the return values of cgu_guile_wrapper
623  // (non-NULL for success and NULL for
624  // failure) because scm_with_guile() returns
625  // NULL if it exits on an uncaught guile
626  // exception, but this approach enables us to
627  // discriminate between a C++ memory
628  // exception in the wrapper and a guile
629  // exception in the preamble or 'translator',
630  // at a minimal cost of one assignment to a
631  // bool.
632  }
633  catch (GuileException& e) {
634  try {
635  guile_except = e.guile_text();
636  }
637  catch (...) {
638  badalloc = true;
639  }
640  }
641  catch (ReturnValueError& e) {
642  try {
643  guile_ret_val_err = e.err_text();
644  }
645  catch (...) {
646  badalloc = true;
647  }
648  }
649  catch (std::exception& e) {
650  try {
651  gen_err = e.what();
652  }
653  catch (...) {
654  badalloc = true;
655  }
656  }
657  catch (...) {
658  try {
659  gen_err = u8"C++ exception thrown in cgu_guile_wrapper()";
660  }
661  catch (...) {
662  badalloc = true;
663  }
664  }
665 #ifndef CGU_GUILE_HAS_BROKEN_LINKING
666  scm_dynwind_end();
667 #endif
668  if (badalloc) throw std::bad_alloc(); // this will be caught in cgu_guile_wrapper()
669  }));
670  // cgu_guile_wrapper(), and so scm_with_guile() will return a
671  // non-NULL value if assigning to one of the exception description
672  // strings above threw std::bad_alloc
673  if (scm_with_guile(&cgu_guile_wrapper, cb.get()))
674  throw WrapperError(u8"cgu_guile_wrapper() has trapped std::bad_alloc");
675  if (!guile_except.empty())
676  throw GuileException(guile_except.c_str());
677  if (!guile_ret_val_err.empty())
678  throw ReturnValueError(guile_ret_val_err.c_str());
679  if (!gen_err.empty())
680  throw WrapperError(gen_err.c_str());
681  if (!result)
682  throw WrapperError(u8"the preamble or translator threw a native guile exception");
683  return retval;
684 }
685 
686 #endif // DOXYGEN_PARSING
687 
688 /**
689  * This function is called by Extension::rethrow_guile_exception()
690  * where the scheme code executed by Extension::exec() or
691  * Extension::exec_shared() has exited with a guile exception. It
692  * converts the raw guile exception information represented by the
693  * 'key' and 'args' arguments of a guile catch handler to a more
694  * readable form. It is made available as part of the public
695  * interface so that any custom translators can also use it if they
696  * choose to provide their own catch expressions. This function does
697  * not throw any C++ exceptions. No native guile exception will arise
698  * in this function and so cause guile to jump out of it assuming no
699  * guile out-of-memory condition occurs (and given that this function
700  * is called after a guile extension task has completed, such a
701  * condition is very improbable). It is thread safe, but see the
702  * comments above about the thread safety of Extension::exec() and
703  * Extension::exec_shared().
704  *
705  * @param key An opaque guile SCM object representing a symbol
706  * comprising the 'key' argument of the exception handler of a guile
707  * catch expression.
708  * @param args An opaque guile SCM object representing a list
709  * comprising the 'args' argument of the exception handler of a guile
710  * catch expression.
711  * @return An opaque guile SCM object representing a guile string.
712  *
713  * Since 2.0.22 and 2.2.5
714  */
715 inline SCM exception_to_string(SCM key, SCM args) noexcept {
716  // The args of most exceptions thrown by guile are in the following format:
717  // (car args) - a string comprising the name of the procedure generating the exception
718  // (cadr args) - a string containing text, possibly with format directives (escape sequences)
719  // (caddr args) - a list containing items matching the format directives, or #f if none
720  // (cadddr args) - (not used here) a list of additional objects (eg the errno for some errors),
721  // or #f if none
722  SCM ret = SCM_BOOL_F;
723  int length = scm_to_int(scm_length(args));
724  if (length) {
725  SCM first = scm_car(args);
726  if (scm_is_true(scm_string_p(first))) {
727  // if a single user string, output it
728  if (length == 1) {
729  ret = scm_string_append(scm_list_4(scm_from_utf8_string(u8"Exception "),
730  scm_symbol_to_string(key),
731  scm_from_utf8_string(u8": "),
732  first));
733  }
734  else { // length > 1
735  SCM second = scm_cadr(args);
736  if (scm_is_true(scm_string_p(second))) {
737  // we should have a standard guile exception string, as above
738  SCM text = scm_string_append(scm_list_n(scm_from_utf8_string(u8"Exception "),
739  scm_symbol_to_string(key),
740  scm_from_utf8_string(u8" in procedure "),
741  first,
742  scm_from_utf8_string(u8": "),
743  second,
744  SCM_UNDEFINED));
745  if (length == 2)
746  ret = text;
747  else { // length > 2
748  SCM third = scm_caddr(args);
749  if (scm_is_false(third))
750  ret = text;
751  else if (scm_is_true(scm_list_p(third))) {
752  FormatArgs format_args = {text, third};
753  ret = scm_internal_catch(SCM_BOOL_T,
754  &cgu_format_try_handler,
755  &format_args,
756  &cgu_format_catch_handler,
757  0);
758  }
759  }
760  }
761  }
762  }
763  }
764  // fall back to generic formatting if first or second elements of
765  // args is not a string or simple-format failed above
766  if (scm_is_false(ret)) {
767  // there is no need for a catch block: we know simple-format
768  // cannot raise an exception here
769  ret = scm_simple_format(SCM_BOOL_F,
770  scm_from_utf8_string(u8"Exception ~S: ~S"),
771  scm_list_2(key, args));
772  }
773  return ret;
774 }
775 
776 /**
777  * This function tests whether a guile exception arose in executing a
778  * scheme extension file, and throws Cgu::Extension::GuileException if
779  * it did. It is intended for use by custom translators, as the first
780  * thing the translator does. It is thread safe, but see the comments
781  * above about the thread safety of Extension::exec() and
782  * Extension::exec_shared().
783  *
784  * @param scm An opaque guile SCM object representing the value to
785  * which the extension file passed to Extension::exec() or
786  * Extension::exec_shared() evaluated.
787  * @exception std::bad_alloc This function might throw std::bad_alloc
788  * if memory is exhausted and the system throws in that case.
789  * @exception Cgu::Extension::GuileException This exception will be
790  * thrown if the scheme code executed in the extension file passed to
791  * Extension::exec() or Extension::exec_shared() threw a guile
792  * exception. Cgu::Extension::GuileException::what() will give
793  * particulars of the guile exception thrown, in UTF-8 encoding.
794  * @note No native guile exception will arise in this function and so
795  * cause guile to jump out of it if no guile out-of-memory condition
796  * occurs (given that this function is called after a guile extension
797  * task has completed, such a condition is very improbable).
798  *
799  * Since 2.0.22 and 2.2.5
800  */
801 inline void rethrow_guile_exception(SCM scm) {
802  // guile exceptions are always presented to this function as a
803  // scheme list
804  if (scm_is_false(scm_list_p(scm))
805  || scm_is_true(scm_null_p(scm))) return;
806  SCM first = scm_car(scm);
807  if (scm_is_true(scm_string_p(first))) {
808  size_t len;
809  const char* text = 0;
810  // nothing in this function should throw a guile exception unless
811  // there is a guile out-of-memory exception (which is extremely
812  // improbable). However, let's cover ourselves in case
813  scm_dynwind_begin(scm_t_dynwind_flags(0));
814  char* car = scm_to_utf8_stringn(first, &len);
815  // there may be a weakness in guile's implementation here: if
816  // calling scm_dynwind_unwind_handler() were to give rise to an
817  // out-of-memory exception before the handler is set up by it,
818  // then we could leak memory allocated from the preceding call to
819  // scm_to_utf8_stringn(). Whether that could happen is not
820  // documented, but because (a) it is so improbable, and (b) once
821  // we are in out-of-memory land we are already in severe trouble
822  // and glib is likely to terminate the program at some point
823  // anyway, it is not worth troubling ourselves over.
824  scm_dynwind_unwind_handler(&free, car, scm_t_wind_flags(0));
825  if (len == strlen(u8"***cgu-guile-exception***")
826  && !strncmp(car, u8"***cgu-guile-exception***", len)) {
827  SCM str = exception_to_string(scm_cadr(scm), scm_cddr(scm));
828  // we don't need a dynwind handler for 'text' because nothing
829  // after the call to scm_to_utf8_stringn() can cause a guile
830  // exception to be raised
831  text = scm_to_utf8_stringn(str, &len);
832  }
833  // all done - no more guile exceptions are possible in this
834  // function after this so end the dynamic context, take control of
835  // the memory by RAII and if necessary throw a C++ exception
836  scm_dynwind_end();
837  std::unique_ptr<char, Cgu::CFree> up_car(car);
838  std::unique_ptr<const char, Cgu::CFree> up_text(text);
839  // if 'text' is not NULL, 'len' contains its length in bytes
840  if (text) throw GuileException(std::string(text, len).c_str());
841  }
842 }
843 
844 /**
845  * A translator function which can be passed to the third argument of
846  * Extension::exec() or Extension::exec_shared(). It converts from a
847  * homogeneous scheme list of integers to a C++ representation of
848  * std::vector<long>. It is thread safe, but see the comments above
849  * about the thread safety of Extension::exec() and
850  * Extension::exec_shared().
851  *
852  * @param scm An opaque guile SCM object representing the value to
853  * which the extension file passed to Extension::exec() or
854  * Extension::exec_shared() evaluated, where that value is a
855  * homogeneous list of integers.
856  * @return The std::vector<long> representation.
857  * @exception std::bad_alloc This function might throw std::bad_alloc
858  * if memory is exhausted and the system throws in that case.
859  * @exception Cgu::Extension::GuileException This exception will be
860  * thrown if the scheme code in the extension file passed to
861  * Extension::exec() or Extension::exec_shared() caused a guile
862  * exception to be thrown. Cgu::Extension::GuileException::what()
863  * will give particulars of the guile exception thrown, in UTF-8
864  * encoding.
865  * @exception Cgu::Extension::ReturnValueError This exception will be
866  * thrown if the scheme code in the extension file passed to
867  * Extension::exec() or Extension::exec_shared() does not evaluate to
868  * the type expected by the translator, or it is out of range for a
869  * long. Cgu::Extension::ReturnValueError::what() will give further
870  * particulars, in UTF-8 encoding.
871  * @note No native guile exception will arise in this function and so
872  * cause guile to jump out of it if no guile out-of-memory condition
873  * occurs (given that this function is called after a guile extension
874  * task has completed, such a condition is very improbable). If such
875  * an exception were to arise, the implementation would handle it and
876  * a C++ exception would be generated in its place in
877  * Extension::exec() or Extension::exec_shared().
878  *
879  * Since 2.0.22 and 2.2.5
880  */
881 inline std::vector<long> list_to_vector_long(SCM scm) {
883  if (scm_is_false(scm_list_p(scm)))
884  throw ReturnValueError(u8"scheme code did not evaluate to a list\n");
885 
886  // nothing in this function should throw a guile exception unless
887  // there is a guile out-of-memory exception (which is extremely
888  // improbable). However, let's cover ourselves in case.
889  scm_dynwind_begin(scm_t_dynwind_flags(0));
890  // we cannot have a std::vector object in a scope where a guile
891  // exception might be raised because it has a non-trivial
892  // destructor, nor can we use RAII. Instead allocate on free store
893  // and manage the memory by hand until we can no longer jump on a
894  // guile exception. In addition we cannot store a C++ exception
895  // using std::exception_ptr because std::exception_ptr is not
896  // trivially destructible.
897  bool badalloc = false;
898  const char* rv_error = 0;
899  std::vector<long>* res = 0;
900  VectorDeleteArgs* args = 0;
901  try {
902  res = new std::vector<long>;
903  }
904  catch (...) {
905  badalloc = true;
906  }
907  if (!badalloc) {
908  // allocate 'args' on free store, because the continuation in
909  // which it executes will be up the stack
910  try {
911  args = new VectorDeleteArgs{Long, res};
912  }
913  catch (...) {
914  badalloc = true;
915  }
916  if (!badalloc) {
917  // there may be a weakness in guile's implementation here: if
918  // calling scm_dynwind_unwind_handler() were to give rise to a
919  // guile out-of-memory exception before the handler is set up by
920  // it, then we could leak memory allocated from the preceding
921  // new expressions. Whether that could happen is not documented
922  // by guile, but because (a) it is so improbable, and (b) once
923  // we are in out-of-memory land we are already in severe trouble
924  // and glib is likely to terminate the program at some point
925  // anyway, it is not worth troubling ourselves over.
926  scm_dynwind_unwind_handler(&cgu_delete_vector, args, scm_t_wind_flags(0));
927  int length = scm_to_int(scm_length(scm));
928  try {
929  res->reserve(length);
930  }
931  catch (...) {
932  badalloc = true;
933  }
934  for (int count = 0;
935  count < length && !rv_error && !badalloc;
936  ++count) {
937  SCM item = scm_list_ref(scm, scm_from_int(count));
938  if (scm_is_false(scm_integer_p(item)))
939  rv_error = u8"scheme code did not evaluate to a homogeneous list of integer\n";
940  else {
941  SCM min = scm_from_long(std::numeric_limits<long>::min());
942  SCM max = scm_from_long(std::numeric_limits<long>::max());
943  if (scm_is_false(scm_leq_p(item, max)) || scm_is_false(scm_geq_p(item, min)))
944  rv_error = u8"scheme code evaluated out of range for long\n";
945  else {
946  try {
947  res->push_back(scm_to_long(item));
948  }
949  catch (...) {
950  badalloc = true;
951  }
952  }
953  }
954  }
955  }
956  }
957  // all done - no more guile exceptions are possible in this function
958  // after this so end the dynamic context, take control of the memory
959  // by RAII and if necessary throw a C++ exception
960  scm_dynwind_end();
961  std::unique_ptr<std::vector<long>> up_res(res);
962  std::unique_ptr<VectorDeleteArgs> up_args(args);
963  if (badalloc) throw std::bad_alloc();
964  if (rv_error) throw ReturnValueError(rv_error);
965  // neither gcc-4.9 nor clang-3.4 will optimize with RVO or move
966  // semantics here, so force it by hand
967  return std::move(*res);
968 }
969 
970 /**
971  * A translator function which can be passed to the third argument of
972  * Extension::exec() or Extension::exec_shared(). It converts from a
973  * homogeneous scheme list of real numbers to a C++ representation of
974  * std::vector<double>. It is thread safe, but see the comments above
975  * about the thread safety of Extension::exec() and
976  * Extension::exec_shared().
977  *
978  * @param scm An opaque guile SCM object representing the value to
979  * which the extension file passed to Extension::exec() or
980  * Extension::exec_shared() evaluated, where that value is a
981  * homogeneous list of real numbers.
982  * @return The std::vector<double> representation.
983  * @exception std::bad_alloc This function might throw std::bad_alloc
984  * if memory is exhausted and the system throws in that case.
985  * @exception Cgu::Extension::GuileException This exception will be
986  * thrown if the scheme code in the extension file passed to
987  * Extension::exec() or Extension::exec_shared() caused a guile
988  * exception to be thrown. Cgu::Extension::GuileException::what()
989  * will give particulars of the guile exception thrown, in UTF-8
990  * encoding.
991  * @exception Cgu::Extension::ReturnValueError This exception will be
992  * thrown if the scheme code in the extension file passed to
993  * Extension::exec() or Extension::exec_shared() does not evaluate to
994  * the type expected by the translator, or it is out of range for a
995  * double. Cgu::Extension::ReturnValueError::what() will give further
996  * particulars, in UTF-8 encoding.
997  * @note 1. Prior to versions 2.0.25 and 2.2.8, this translator had a
998  * bug which caused an out-of-range Cgu::Extension::ReturnValueError
999  * to be thrown if any of the numbers in the list to which the scheme
1000  * code in the extension file evaluated was 0.0 or a negative number.
1001  * This was fixed in versions 2.0.25 and 2.2.8.
1002  * @note 2. No native guile exception will arise in this function and
1003  * so cause guile to jump out of it if no guile out-of-memory
1004  * condition occurs (given that this function is called after a guile
1005  * extension task has completed, such a condition is very improbable).
1006  * If such an exception were to arise, the implementation would handle
1007  * it and a C++ exception would be generated in its place in
1008  * Extension::exec() or Extension::exec_shared().
1009  *
1010  * Since 2.0.22 and 2.2.5
1011  */
1012 inline std::vector<double> list_to_vector_double(SCM scm) {
1014  if (scm_is_false(scm_list_p(scm)))
1015  throw ReturnValueError(u8"scheme code did not evaluate to a list\n");
1016 
1017  // nothing in this function should throw a guile exception unless
1018  // there is a guile out-of-memory exception (which is extremely
1019  // improbable). However, let's cover ourselves in case.
1020  scm_dynwind_begin(scm_t_dynwind_flags(0));
1021  // we cannot have a std::vector object in a scope where a guile
1022  // exception might be raised because it has a non-trivial
1023  // destructor, nor can we use RAII. Instead allocate on free store
1024  // and manage the memory by hand until we can no longer jump on a
1025  // guile exception. In addition we cannot store a C++ exception
1026  // using std::exception_ptr because std::exception_ptr is not
1027  // trivially destructible.
1028  bool badalloc = false;
1029  const char* rv_error = 0;
1030  std::vector<double>* res = 0;
1031  VectorDeleteArgs* args = 0;
1032  try {
1033  res = new std::vector<double>;
1034  }
1035  catch (...) {
1036  badalloc = true;
1037  }
1038  if (!badalloc) {
1039  // allocate 'args' on free store, because the continuation in
1040  // which it executes will be up the stack
1041  try {
1042  args = new VectorDeleteArgs{Double, res};
1043  }
1044  catch (...) {
1045  badalloc = true;
1046  }
1047  if (!badalloc) {
1048  // there may be a weakness in guile's implementation here: if
1049  // calling scm_dynwind_unwind_handler() were to give rise to a
1050  // guile out-of-memory exception before the handler is set up by
1051  // it, then we could leak memory allocated from the preceding
1052  // new expressions. Whether that could happen is not documented
1053  // by guile, but because (a) it is so improbable, and (b) once
1054  // we are in out-of-memory land we are already in severe trouble
1055  // and glib is likely to terminate the program at some point
1056  // anyway, it is not worth troubling ourselves over.
1057  scm_dynwind_unwind_handler(&cgu_delete_vector, args, scm_t_wind_flags(0));
1058  int length = scm_to_int(scm_length(scm));
1059  try {
1060  res->reserve(length);
1061  }
1062  catch (...) {
1063  badalloc = true;
1064  }
1065  for (int count = 0;
1066  count < length && !rv_error && !badalloc;
1067  ++count) {
1068  SCM item = scm_list_ref(scm, scm_from_int(count));
1069  if (scm_is_false(scm_real_p(item)))
1070  rv_error = u8"scheme code did not evaluate to a homogeneous list of real numbers\n";
1071  else {
1072  SCM min = scm_from_double(std::numeric_limits<double>::lowest());
1073  SCM max = scm_from_double(std::numeric_limits<double>::max());
1074  if (scm_is_false(scm_leq_p(item, max)) || scm_is_false(scm_geq_p(item, min)))
1075  rv_error = u8"scheme code evaluated out of range for double\n";
1076  else {
1077  try {
1078  res->push_back(scm_to_double(item));
1079  }
1080  catch (...) {
1081  badalloc = true;
1082  }
1083  }
1084  }
1085  }
1086  }
1087  }
1088  // all done - no more guile exceptions are possible in this function
1089  // after this so end the dynamic context, take control of the memory
1090  // by RAII and if necessary throw a C++ exception
1091  scm_dynwind_end();
1092  std::unique_ptr<std::vector<double>> up_res(res);
1093  std::unique_ptr<VectorDeleteArgs> up_args(args);
1094  if (badalloc) throw std::bad_alloc();
1095  if (rv_error) throw ReturnValueError(rv_error);
1096  // neither gcc-4.9 nor clang-3.4 will optimize with RVO or move
1097  // semantics here, so force it by hand
1098  return std::move(*res);
1099 }
1100 
1101 /**
1102  * A translator function which can be passed to the third argument of
1103  * Extension::exec() or Extension::exec_shared(). It converts from a
1104  * homogeneous scheme list of strings to a C++ representation of
1105  * std::vector<std::string>. It is thread safe, but see the comments
1106  * above about the thread safety of Extension::exec() and
1107  * Extension::exec_shared().
1108  *
1109  * The returned strings will be in UTF-8 encoding.
1110  *
1111  * Note that the first string in the returned list must not be
1112  * "***cgu-guile-exception***": that string is reserved to the
1113  * implementation.
1114  *
1115  * @param scm An opaque guile SCM object representing the value to
1116  * which the extension file passed to Extension::exec() or
1117  * Extension::exec_shared() evaluated, where that value is a
1118  * homogeneous list of strings.
1119  * @return The std::vector<std::string> representation.
1120  * @exception std::bad_alloc This function might throw std::bad_alloc
1121  * if memory is exhausted and the system throws in that case.
1122  * @exception Cgu::Extension::GuileException This exception will be
1123  * thrown if the scheme code in the extension file passed to
1124  * Extension::exec() or Extension::exec_shared() caused a guile
1125  * exception to be thrown. Cgu::Extension::GuileException::what()
1126  * will give particulars of the guile exception thrown, in UTF-8
1127  * encoding.
1128  * @exception Cgu::Extension::ReturnValueError This exception will be
1129  * thrown if the scheme code in the extension file passed to
1130  * Extension::exec() or Extension::exec_shared() does not evaluate to
1131  * the type expected by the translator.
1132  * Cgu::Extension::ReturnValueError::what() will give further
1133  * particulars, in UTF-8 encoding.
1134  * @note No native guile exception will arise in this function and so
1135  * cause guile to jump out of it if no guile out-of-memory condition
1136  * occurs (given that this function is called after a guile extension
1137  * task has completed, such a condition is very improbable). If such
1138  * an exception were to arise, the implementation would handle it and
1139  * a C++ exception would be generated in its place in
1140  * Extension::exec() or Extension::exec_shared().
1141  *
1142  * Since 2.0.22 and 2.2.5
1143  */
1144 inline std::vector<std::string> list_to_vector_string(SCM scm) {
1146  if (scm_is_false(scm_list_p(scm)))
1147  throw ReturnValueError(u8"scheme code did not evaluate to a list\n");
1148 
1149  // nothing in this function should throw a guile exception unless
1150  // there is a guile out-of-memory exception (which is extremely
1151  // improbable). However, let's cover ourselves in case.
1152  scm_dynwind_begin(scm_t_dynwind_flags(0));
1153  // we cannot have a std::vector object in a scope where a guile
1154  // exception might be raised because it has a non-trivial
1155  // destructor, nor can we use RAII. Instead allocate on free store
1156  // and manage the memory by hand until we can no longer jump on a
1157  // guile exception. In addition we cannot store a C++ exception
1158  // using std::exception_ptr because std::exception_ptr is not
1159  // trivially destructible.
1160  bool badalloc = false;
1161  const char* rv_error = 0;
1162  std::vector<std::string>* res = 0;
1163  VectorDeleteArgs* args = 0;
1164  try {
1165  res = new std::vector<std::string>;
1166  }
1167  catch (...) {
1168  badalloc = true;
1169  }
1170  if (!badalloc) {
1171  // allocate 'args' on free store, because the continuation in
1172  // which it executes will be up the stack
1173  try {
1174  args = new VectorDeleteArgs{String, res};
1175  }
1176  catch (...) {
1177  badalloc = true;
1178  }
1179  if (!badalloc) {
1180  // there may be a weakness in guile's implementation here: if
1181  // calling scm_dynwind_unwind_handler() were to give rise to a
1182  // guile out-of-memory exception before the handler is set up by
1183  // it, then we could leak memory allocated from the preceding
1184  // new expressions. Whether that could happen is not documented
1185  // by guile, but because (a) it is so improbable, and (b) once
1186  // we are in out-of-memory land we are already in severe trouble
1187  // and glib is likely to terminate the program at some point
1188  // anyway, it is not worth troubling ourselves over.
1189  scm_dynwind_unwind_handler(&cgu_delete_vector, args, scm_t_wind_flags(0));
1190  int length = scm_to_int(scm_length(scm));
1191  try {
1192  res->reserve(length);
1193  }
1194  catch (...) {
1195  badalloc = true;
1196  }
1197  for (int count = 0;
1198  count < length && !rv_error && !badalloc;
1199  ++count) {
1200  SCM item = scm_list_ref(scm, scm_from_int(count));
1201  if (scm_is_false(scm_string_p(item)))
1202  rv_error = u8"scheme code did not evaluate to a homogeneous list of string\n";
1203  else {
1204  size_t len;
1205  // we don't need a dynwind handler for 'str' because nothing
1206  // after the call to scm_to_utf8_stringn() and before the
1207  // call to free() can cause a guile exception to be raised
1208  char* str = scm_to_utf8_stringn(item, &len);
1209  try {
1210  res->emplace_back(str, len);
1211  }
1212  catch (...) {
1213  badalloc = true;
1214  }
1215  free(str);
1216  }
1217  }
1218  }
1219  }
1220  // all done - no more guile exceptions are possible in this function
1221  // after this so end the dynamic context, take control of the memory
1222  // by RAII and if necessary throw a C++ exception
1223  scm_dynwind_end();
1224  std::unique_ptr<std::vector<std::string>> up_res(res);
1225  std::unique_ptr<VectorDeleteArgs> up_args(args);
1226  if (badalloc) throw std::bad_alloc();
1227  if (rv_error) throw ReturnValueError(rv_error);
1228  // neither gcc-4.9 nor clang-3.4 will optimize with RVO or move
1229  // semantics here, so force it by hand
1230  return std::move(*res);
1231 }
1232 
1233 /**
1234  * A translator function which can be passed to the third argument of
1235  * Extension::exec() or Extension::exec_shared(). It converts from a
1236  * scheme integer to a C++ representation of long. It is thread safe,
1237  * but see the comments above about the thread safety of
1238  * Extension::exec() and Extension::exec_shared().
1239  *
1240  * @param scm An opaque guile SCM object representing the value to
1241  * which the extension file passed to Extension::exec() or
1242  * Extension::exec_shared() evaluated, where that value is an integer.
1243  * @return The C++ long representation.
1244  * @exception std::bad_alloc This function might throw std::bad_alloc
1245  * if memory is exhausted and the system throws in that case.
1246  * @exception Cgu::Extension::GuileException This exception will be
1247  * thrown if the scheme code in the extension file passed to
1248  * Extension::exec() or Extension::exec_shared() caused a guile
1249  * exception to be thrown. Cgu::Extension::GuileException::what()
1250  * will give particulars of the guile exception thrown, in UTF-8
1251  * encoding.
1252  * @exception Cgu::Extension::ReturnValueError This exception will be
1253  * thrown if the scheme code in the extension file passed to
1254  * Extension::exec() or Extension::exec_shared() does not evaluate to
1255  * the type expected by the translator, or it is out of range for a
1256  * long. Cgu::Extension::ReturnValueError::what() will give further
1257  * particulars, in UTF-8 encoding.
1258  * @note No native guile exception will arise in this function and so
1259  * cause guile to jump out of it if no guile out-of-memory condition
1260  * occurs (given that this function is called after a guile extension
1261  * task has completed, such a condition is very improbable). If such
1262  * an exception were to arise, the implementation would handle it and
1263  * a C++ exception would be generated in its place in
1264  * Extension::exec() or Extension::exec_shared().
1265  *
1266  * Since 2.0.22 and 2.2.5
1267  */
1268 inline long integer_to_long(SCM scm) {
1270  if (scm_is_false(scm_integer_p(scm)))
1271  throw ReturnValueError(u8"scheme code did not evaluate to an integer\n");
1272  SCM min = scm_from_long(std::numeric_limits<long>::min());
1273  SCM max = scm_from_long(std::numeric_limits<long>::max());
1274  if (scm_is_false(scm_leq_p(scm, max)) || scm_is_false(scm_geq_p(scm, min)))
1275  throw ReturnValueError(u8"scheme code evaluated out of range for long\n");
1276  return scm_to_long(scm);
1277 }
1278 
1279 /**
1280  * A translator function which can be passed to the third argument of
1281  * Extension::exec() or Extension::exec_shared(). It converts from a
1282  * scheme real number to a C++ representation of double. It is thread
1283  * safe, but see the comments above about the thread safety of
1284  * Extension::exec() and Extension::exec_shared().
1285  *
1286  * @param scm An opaque guile SCM object representing the value to
1287  * which the extension file passed to Extension::exec() or
1288  * Extension::exec_shared() evaluated, where that value is a real
1289  * number.
1290  * @return The C++ double representation.
1291  * @exception std::bad_alloc This function might throw std::bad_alloc
1292  * if memory is exhausted and the system throws in that case.
1293  * @exception Cgu::Extension::GuileException This exception will be
1294  * thrown if the scheme code in the extension file passed to
1295  * Extension::exec() or Extension::exec_shared() caused a guile
1296  * exception to be thrown. Cgu::Extension::GuileException::what()
1297  * will give particulars of the guile exception thrown, in UTF-8
1298  * encoding.
1299  * @exception Cgu::Extension::ReturnValueError This exception will be
1300  * thrown if the scheme code in the extension file passed to
1301  * Extension::exec() or Extension::exec_shared() does not evaluate to
1302  * the type expected by the translator, or it is out of range for a
1303  * double. Cgu::Extension::ReturnValueError::what() will give further
1304  * particulars, in UTF-8 encoding.
1305  * @note 1. Prior to versions 2.0.25 and 2.2.8, this translator had a
1306  * bug which caused an out-of-range Cgu::Extension::ReturnValueError
1307  * to be thrown if the scheme code in the extension file evaluated to
1308  * 0.0 or a negative number. This was fixed in versions 2.0.25 and
1309  * 2.2.8.
1310  * @note 2. No native guile exception will arise in this function and
1311  * so cause guile to jump out of it if no guile out-of-memory
1312  * condition occurs (given that this function is called after a guile
1313  * extension task has completed, such a condition is very improbable).
1314  * If such an exception were to arise, the implementation would handle
1315  * it and a C++ exception would be generated in its place in
1316  * Extension::exec() or Extension::exec_shared().
1317  *
1318  * Since 2.0.22 and 2.2.5
1319  */
1320 inline double real_to_double(SCM scm) {
1322  if (scm_is_false(scm_real_p(scm)))
1323  throw ReturnValueError(u8"scheme code did not evaluate to a real number\n");
1324  SCM min = scm_from_double(std::numeric_limits<double>::lowest());
1325  SCM max = scm_from_double(std::numeric_limits<double>::max());
1326  if (scm_is_false(scm_leq_p(scm, max)) || scm_is_false(scm_geq_p(scm, min)))
1327  throw ReturnValueError(u8"scheme code evaluated out of range for double\n");
1328  return scm_to_double(scm);
1329 }
1330 
1331 /**
1332  * A translator function which can be passed to the third argument of
1333  * Extension::exec() or Extension::exec_shared(). It converts from a
1334  * scheme string to a C++ representation of std::string. It is thread
1335  * safe, but see the comments above about the thread safety of
1336  * Extension::exec() and Extension::exec_shared().
1337  *
1338  * The returned string will be in UTF-8 encoding.
1339  *
1340  * @param scm An opaque guile SCM object representing the value to
1341  * which the extension file passed to Extension::exec() or
1342  * Extension::exec_shared() evaluated, where that value is a string.
1343  * @return The std::string representation.
1344  * @exception std::bad_alloc This function might throw std::bad_alloc
1345  * if memory is exhausted and the system throws in that case.
1346  * @exception Cgu::Extension::GuileException This exception will be
1347  * thrown if the scheme code in the extension file passed to
1348  * Extension::exec() or Extension::exec_shared() caused a guile
1349  * exception to be thrown. Cgu::Extension::GuileException::what()
1350  * will give particulars of the guile exception thrown, in UTF-8
1351  * encoding.
1352  * @exception Cgu::Extension::ReturnValueError This exception will be
1353  * thrown if the scheme code in the extension file passed to
1354  * Extension::exec() or Extension::exec_shared() does not evaluate to
1355  * the type expected by the translator.
1356  * Cgu::Extension::ReturnValueError::what() will give further
1357  * particulars, in UTF-8 encoding.
1358  * @note No native guile exception will arise in this function and so
1359  * cause guile to jump out of it if no guile out-of-memory condition
1360  * occurs (given that this function is called after a guile extension
1361  * task has completed, such a condition is very improbable). If such
1362  * an exception were to arise, the implementation would handle it and
1363  * a C++ exception would be generated in its place in
1364  * Extension::exec() or Extension::exec_shared().
1365  *
1366  * Since 2.0.22 and 2.2.5
1367  */
1368 inline std::string string_to_string(SCM scm) {
1370  if (scm_is_false(scm_string_p(scm)))
1371  throw ReturnValueError(u8"scheme code did not evaluate to a string\n");
1372  size_t len;
1373  // it is safe to use unique_ptr here. If scm_to_utf8_stringn()
1374  // succeeds then nothing after it in this function can cause a guile
1375  // exception.
1376  std::unique_ptr<const char, Cgu::CFree> s(scm_to_utf8_stringn(scm, &len));
1377  return std::string(s.get(), len);
1378 }
1379 
1380 /**
1381  * A translator function which can be passed to the third argument of
1382  * Extension::exec() or Extension::exec_shared(). It disregards the
1383  * scheme value passed to it except to trap any guile exception thrown
1384  * by the scheme task and rethrow it as a C++ exception, and returns a
1385  * NULL void* object. It is thread safe, but see the comments above
1386  * about the thread safety of Extension::exec() and
1387  * Extension::exec_shared().
1388  *
1389  * It is mainly intended for use where the scheme script is executed
1390  * for its side effects, perhaps for I/O, and any communication
1391  * necessary is done by guile exceptions.
1392  *
1393  * @param scm An opaque guile SCM object representing the value to
1394  * which the extension file passed to Extension::exec() or
1395  * Extension::exec_shared() evaluated, which is ignored.
1396  * @return A NULL void* object.
1397  * @exception std::bad_alloc This function might throw std::bad_alloc
1398  * if memory is exhausted and the system throws in that case.
1399  * @exception Cgu::Extension::GuileException This exception will be
1400  * thrown if the scheme code in the extension file passed to
1401  * Extension::exec() or Extension::exec_shared() caused a guile
1402  * exception to be thrown. Cgu::Extension::GuileException::what()
1403  * will give particulars of the guile exception thrown, in UTF-8
1404  * encoding.
1405  * @note No native guile exception will arise in this function and so
1406  * cause guile to jump out of it if no guile out-of-memory condition
1407  * occurs (given that this function is called after a guile extension
1408  * task has completed, such a condition is very improbable). If such
1409  * an exception were to arise, the implementation would handle it and
1410  * a C++ exception would be generated in its place in
1411  * Extension::exec() or Extension::exec_shared().
1412  *
1413  * Since 2.0.22 and 2.2.5
1414  */
1415 inline void* any_to_void(SCM scm) {
1417  return 0;
1418 }
1419 
1420 /**
1421  * This function executes scheme code on the guile VM within a C++
1422  * program using this library. See the introductory remarks above for
1423  * its potential uses, about the thread safety of this function, and
1424  * about the use of the TaskManager::exec_shared() as an alternative.
1425  *
1426  * The first argument to this function is a preamble, which can be
1427  * used to pass top level definitions to the scheme code (in other
1428  * words, for argument passing). It's second argument is the filename
1429  * (with path) of the file containing the scheme code to be executed.
1430  * It's third argument is a translator, which will convert the value
1431  * to which the scheme code evaluates (in C++ terms, its return value)
1432  * to a suitable C++ representation. Preformed translators are
1433  * provided by this library to translate from scheme's integers, real
1434  * numbers and strings to C++ longs, doubles and strings respectively,
1435  * and from any uniform lists of these to C++ vectors of the
1436  * corresponding type. There is also a translator for void return
1437  * types. See the introductory remarks above for more information
1438  * about translators.
1439  *
1440  * Any native guile exceptions thrown by the code executed by this
1441  * function (and by any code which it calls) are converted and
1442  * rethrown as C++ exceptions.
1443  *
1444  * The scheme file can call other scheme code, and load modules, in
1445  * the ordinary way. Thus, this function can execute any scheme code
1446  * which guile can execute as a program, and the programmer can (if
1447  * wanted) act on its return value in the C++ code which invokes it.
1448  *
1449  * Thread cancellation is blocked for the thread in which this
1450  * function executes until this function returns.
1451  *
1452  * @param preamble Scheme code such as top level definitions to be
1453  * seen by the code in the file to be executed. This is mainly
1454  * intended for argument passing, but can comprise any valid scheme
1455  * code. It can also be empty (you can pass ""). Any string literals
1456  * must be in UTF-8 encoding.
1457  * @param file The file which is to be executed on the guile VM. This
1458  * should include the full pathname or a pathname relative to the
1459  * current directory. The contents of the file, and in particular any
1460  * string literals in it, must be in UTF-8 encoding. The filename and
1461  * path must also be given in UTF-8 encoding, even if the local
1462  * filename encoding is something different: guile will convert the
1463  * UTF-8 name which it is given to its own internal string encoding
1464  * using unicode code points, and then convert that to locale encoding
1465  * on looking up the filename. However sticking to ASCII for
1466  * filenames and paths (which is always valid UTF-8) will maximise
1467  * portability. The file name can be empty (you can pass ""), in
1468  * which case only the preamble will be evaluated (but for efficiency
1469  * reasons any complex code not at the top level should be included in
1470  * the file rather than in the preamble).
1471  * @param translator The function or callable object which will
1472  * convert the value to which the scheme code evaluates to a C++
1473  * representation which will be returned by this function. The
1474  * translator should take a single argument comprising an opaque guile
1475  * object of type SCM, and return the C++ representation for it.
1476  * @return The C++ representation returned by the translator.
1477  * @exception std::bad_alloc This function might throw std::bad_alloc
1478  * if memory is exhausted and the system throws in that case.
1479  * @exception Cgu::Extension::GuileException This exception will be
1480  * thrown if the scheme code in 'file' (or called by it) throws a
1481  * guile exception. Cgu::Extension::GuileException::what() will give
1482  * particulars of the guile exception thrown, in UTF-8 encoding.
1483  * @exception Cgu::Extension::ReturnValueError This exception will be
1484  * thrown if the code in 'file' does not evaluate to the type expected
1485  * by the translator. Cgu::Extension::ReturnValueError::what() will
1486  * give further particulars, in UTF-8 encoding.
1487  * @exception Cgu::Extension::WrapperError This exception will be
1488  * thrown if a custom translator throws a native guile exception or a
1489  * C++ exception not comprising Extension::GuileException or
1490  * Extension::ReturnValueError, one of the preformed translators
1491  * throws std::bad_alloc or encounters a guile out-of-memory
1492  * exception, assigning to an internal exception description string
1493  * throws std::bad_alloc, or evaluation of the preamble throws a
1494  * native guile exception.
1495  *
1496  * Since 2.0.22 and 2.2.5
1497  */
1498 template <class Translator>
1499 auto exec(const std::string& preamble,
1500  const std::string& file,
1501  Translator&& translator) -> typename std::result_of<Translator(SCM)>::type {
1502  typedef typename std::result_of<Translator(SCM)>::type Ret;
1503  return exec_impl<Ret>(preamble, file, std::forward<Translator>(translator), false);
1504 }
1505 
1506 /**
1507  * This function executes scheme code on the guile VM within a C++
1508  * program using this library. See the introductory remarks above for
1509  * its potential uses, about the thread safety of this function, and
1510  * about the use of the TaskManager::exec() as an alternative.
1511  *
1512  * The first argument to this function is a preamble, which can be
1513  * used to pass top level definitions to the scheme code (in other
1514  * words, for argument passing). It's second argument is the filename
1515  * (with path) of the file containing the scheme code to be executed.
1516  * It's third argument is a translator, which will convert the value
1517  * to which the scheme code evaluates (in C++ terms, its return value)
1518  * to a suitable C++ representation. Preformed translators are
1519  * provided by this library to translate from scheme's integers, real
1520  * numbers and strings to C++ longs, doubles and strings respectively,
1521  * and from any uniform lists of these to C++ vectors of the
1522  * corresponding type. There is also a translator for void return
1523  * types. See the introductory remarks above for more information
1524  * about translators.
1525  *
1526  * Any native guile exceptions thrown by the code executed by this
1527  * function (and by any code which it calls) are converted and
1528  * rethrown as C++ exceptions.
1529  *
1530  * The scheme file can call other scheme code, and load modules, in
1531  * the ordinary way. Thus, this function can execute any scheme code
1532  * which guile can execute as a program, and the programmer can (if
1533  * wanted) act on its return value in the C++ code which invokes it.
1534  *
1535  * Thread cancellation is blocked for the thread in which this
1536  * function executes until this function returns.
1537  *
1538  * @param preamble Scheme code such as top level definitions to be
1539  * seen by the code in the file to be executed. This is mainly
1540  * intended for argument passing, but can comprise any valid scheme
1541  * code. It can also be empty (you can pass ""). Any string literals
1542  * must be in UTF-8 encoding.
1543  * @param file The file which is to be executed on the guile VM. This
1544  * should include the full pathname or a pathname relative to the
1545  * current directory. The contents of the file, and in particular any
1546  * string literals in it, must be in UTF-8 encoding. The filename and
1547  * path must also be given in UTF-8 encoding, even if the local
1548  * filename encoding is something different: guile will convert the
1549  * UTF-8 name which it is given to its own internal string encoding
1550  * using unicode code points, and then convert that to locale encoding
1551  * on looking up the filename. However sticking to ASCII for
1552  * filenames and paths (which is always valid UTF-8) will maximise
1553  * portability. The file name can be empty (you can pass ""), in
1554  * which case only the preamble will be evaluated.
1555  * @param translator The function or callable object which will
1556  * convert the value to which the scheme code evaluates to a C++
1557  * representation which will be returned by this function. The
1558  * translator should take a single argument comprising an opaque guile
1559  * object of type SCM, and return the C++ representation for it.
1560  * @return The C++ representation returned by the translator.
1561  * @exception std::bad_alloc This function might throw std::bad_alloc
1562  * if memory is exhausted and the system throws in that case.
1563  * @exception Cgu::Extension::GuileException This exception will be
1564  * thrown if the scheme code in 'file' (or called by it) throws a
1565  * guile exception. Cgu::Extension::GuileException::what() will give
1566  * particulars of the guile exception thrown, in UTF-8 encoding.
1567  * @exception Cgu::Extension::ReturnValueError This exception will be
1568  * thrown if the code in 'file' does not evaluate to the type expected
1569  * by the translator. Cgu::Extension::ReturnValueError::what() will
1570  * give further particulars, in UTF-8 encoding.
1571  * @exception Cgu::Extension::WrapperError This exception will be
1572  * thrown if a custom translator throws a native guile exception or a
1573  * C++ exception not comprising Extension::GuileException or
1574  * Extension::ReturnValueError, one of the preformed translators
1575  * throws std::bad_alloc or encounters a guile out-of-memory
1576  * exception, assigning to an internal exception description string
1577  * throws std::bad_alloc, or evaluation of the preamble throws a
1578  * native guile exception.
1579  *
1580  * Since 2.0.24 and 2.2.7
1581  */
1582 template <class Translator>
1583 auto exec_shared(const std::string& preamble,
1584  const std::string& file,
1585  Translator&& translator) -> typename std::result_of<Translator(SCM)>::type {
1586  typedef typename std::result_of<Translator(SCM)>::type Ret;
1587  return exec_impl<Ret>(preamble, file, std::forward<Translator>(translator), true);
1588 }
1589 
1590 } // namespace Extension
1591 
1592 } // namespace Cgu
1593 
1594 #endif // CGU_EXTENSION_H