c++-gtk-utils
extension.h
Go to the documentation of this file.
1 /* Copyright (C) 2014 and 2016 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() and Extension::exec_shared(), it is
76  * trivial to do (see the example below)
77  *
78  * To call Extension::exec() or Extension::exec_shared(), guile-2.0 >=
79  * 2.0.2, guile-2.2 >= 2.1.3 or guile-3.0 >= 2.9.1 is 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 of a task,
200  * including definitions in the preamble of a task or imported by
201  * guile's 'use-modules' or 'load' procedures, from the top level
202  * definitions of other tasks started by calls to Extension::exec(),
203  * by calling 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 make clashing top level definitions in some other way,
230  * including by importing clashing definitions using 'use-modules' or
231  * 'load'. The need for Extension::exec_shared() to be called only in
232  * one thread in the example above was the reason why the TaskManager
233  * object in that example was set to have a maximum thread count of 1.
234  * In effect the TaskManager object was a dedicated serial dispatcher
235  * for all scheme tasks.
236  *
237  * The calling by Extension::exec_shared() of 'primitive-load' instead
238  * of 'load' may have some small effect on efficiency. It it best for
239  * the file passed to that function to hand off any complex code to
240  * modules prepared using guile's modules interface (which will be
241  * compiled into bytecode), and which are then loaded using
242  * 'use-modules' the first time Extension::exec_shared() is called, or
243  * by having the first call to Extension::exec_shared() (and only the
244  * first call) import any needed files into the top level using
245  * 'load'.
246  *
247  * Note that some guile global state may be shared between tasks
248  * whether Extension::exec() or Extension::exec_shared() is used. For
249  * example, if the guile 'add-to-load-path' procedure is called to add
250  * a local directory to the search path used by 'use-modules' or
251  * 'load', that will have effect for all other tasks.
252  *
253  * Other thread safety points
254  * --------------------------
255  *
256  * Leaving aside what has been said above, there are a few other
257  * issues to keep in mind if executing scheme code in more than one
258  * thread.
259  *
260  * First, the initialization of guile < 2.0.10 is not thread safe.
261  * One thread needs to have called Extension::exec() or
262  * Extension::exec_shared() once and returned before any other threads
263  * call the function. This can be achieved by the simple expedient of
264  * executing the statement:
265  *
266  * @code
267  * Extension::exec_shared("", "", &Extension::any_to_void);
268  * @endcode
269  *
270  * and waiting for it to return before any tasks are added to a
271  * TaskManager object running more than one thread. This issue is
272  * fixed in guile-2.0.10. However there is a further snag. Certain
273  * aspects of guile module loading are not thread safe. One way
274  * around this is to load all the modules that tasks may use in
275  * advance, by loading the modules in the preamble of the above
276  * statement (or to have that statement execute a file which loads the
277  * modules). If that is done, it should be fine afterwards to run
278  * Extension::exec() (or Extension::exec_shared() if clashing top
279  * level definitions are avoided as mentioned above) on a TaskManager
280  * object running any number of threads, or on a Thread::Future object
281  * or std::async() task. (However, note that if using
282  * Extension::exec() the modules would need to be reloaded in each
283  * task in order to make them visible to the task, but that would be
284  * done safely if they have previously been loaded in another task.)
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  * guile-2.2.pc or guile-3.0.pc). This library does NOT do that for
328  * you. Secondly, by linking with libguile you will be governed by
329  * the LGPL version 3 or later, instead of the LGPL version 2.1 or
330  * later, with respect to that linking. That's fine (there is nothing
331  * wrong with the LGPL version 3 and this library permits that) but
332  * you should be aware of it. The scheme code in guile's scheme level
333  * modules is also in the main released under the LGPL version 3 or
334  * later ("in the main" because readline.scm, comprised in the
335  * readline module, is released under the GPL version 3 or later).
336  *
337  * Configuration
338  * -------------
339  *
340  * By default, when the c++-gtk-utils library is configured,
341  * configuration will first look for guile-3.0 >= 2.9.1, then if it
342  * does not find that it will look for guile-2.2 >= 2.1.3, then if it
343  * does not find that it will look for guile-2.0 >= 2.0.2, and then if
344  * it finds none it will disable guile support; and the library header
345  * files will then be set up appropriately. guile-3.0, guile-2.2 or
346  * guile-2.0 can be specifically picked with the \--with-guile=3.0,
347  * \--with-guile=2.2 or \--with-guile=2.0 configuration options
348  * respectively. Guile support can be omitted with the
349  * \--with-guile=no option.
350 
351  * However, as mentioned under "Licence" above, any program using
352  * Extension::exec() or Extension::exec_shared() must link itself
353  * explicitly with libguile via either guile-2.0.pc (for guile-2.0),
354  * guile-2.2.pc (for guile-2.2) or guile-3.0.pc (for guile-3.0).
355  * Programs should use whichever of those is the one for which
356  * c++-gtk-utils was configured. If you get link-time messages from a
357  * program about being unable to link to scm_dynwind_block_asyncs(),
358  * then there has been a version mismatch. If you get link-time
359  * messages about being unable to link to Cgu::Extension::init_mutex()
360  * or Cgu::Extension::get_user_module_mutex() then c++-gtk-utils has
361  * not been configured to offer guile support.
362  *
363  * Custom translators
364  * ------------------
365  *
366  * Any function or callable object which translates from an opaque SCM
367  * value to a suitable C++ representation can be passed as the third
368  * argument of Extension::exec() or Extension::exec_shared(). C++
369  * type deduction on template resolution will take care of everything
370  * else. The translator can execute any functions offered by
371  * libguile, because when the translator is run the program is still
372  * in guile mode. The fulsome guile documentation sets out the
373  * libguile functions which are callable in C/C++ code.
374  *
375  * The first call in a custom translator should normally be to the
376  * Extension::rethrow_guile_exception() function. This function tests
377  * whether a guile exception arose in executing the scheme file, and
378  * throws a C++ exception if it did. The preformed translators in
379  * extension.h provide worked examples of how a custom translator
380  * might be written.
381  *
382  * If something done in a custom translator were to raise a guile
383  * exception, the library implementation would handle it and a C++
384  * exception would be generated in its place in Extension::exec() or
385  * Extension::exec_shared(). However, a custom translator should not
386  * allow a guile exception arising from calls to libguile made by it
387  * to exit a C++ scope in which the translator has constructed a local
388  * C++ object which is not trivially destructible: that would give
389  * rise to undefined behaviour, with the likely result that the C++
390  * object's destructor would not be called. One approach to this
391  * (adopted in the preformed translators) is to allocate on free store
392  * all local C++ objects to be constructed in the translator which are
393  * not trivially destructible, and to manage their lifetimes manually
394  * using local C++ try/catch blocks rather than RAII, with dynwind
395  * unwind handlers to release memory were there to be a guile
396  * exception (but note that no C++ exception should transit out of a
397  * scm_dynwind_begin()/scm_dynwind_end() pair). It is also a good
398  * idea to test for any condition which might cause a guile exception
399  * to be raised in the translator in the first place, and throw a C++
400  * exception beforehand. Then the only condition which might cause a
401  * guile exception to occur in the translator is an out-of-memory
402  * condition, which is highly improbable in a translator as the
403  * translator is run after the guile task has completed. Heap
404  * exhaustion in such a case probably spells doom for the program
405  * concerned anyway, if it has other work to do.
406  *
407  * Note also that code in a custom translator should not store guile
408  * SCM objects (which are pointers to guile scheme objects) in memory
409  * blocks allocated by malloc() or the new expression, or they will
410  * not be seen by the garbage collector used by libguile (which is the
411  * gc library) and therefore may be prematurely deallocated. To keep
412  * such items alive in custom translators, SCM variables should be
413  * kept as local variables or parameter names in functions (and so
414  * stored on the stack or in registers, where they will be seen by the
415  * garbage collector), or in memory allocated with scm_gc_malloc(),
416  * where they will also be seen by the garbage collector.
417  *
418  * Scheme
419  * ------
420  * If you want to learn more about scheme, these are useful sources:
421  * <P>
422  * <A HREF="http://www.gnu.org/software/guile/manual/html_node/Hello-Scheme_0021.html"> Chapter 3 of the Guile Manual</A>
423  * (the rest of the manual is also good reading).</P>
424  * <P>
425  * <A HREF="http://www.scheme.com/tspl4/">The Scheme Programming Language, 4th edition</A></P>
426  */
427 
428 #include <string>
429 #include <vector>
430 #include <exception>
431 #include <memory> // for std::unique_ptr
432 #include <type_traits> // for std::result_of
433 #include <limits> // for std::numeric_limits
434 #include <utility> // for std::forward and std::move
435 #include <new> // for std::bad_alloc
436 
437 #include <stddef.h> // for size_t
438 #include <stdlib.h> // for free()
439 #include <string.h> // for strlen() and strncmp()
440 
441 #include <glib.h>
442 
444 #include <c++-gtk-utils/callback.h>
445 #include <c++-gtk-utils/thread.h>
446 #include <c++-gtk-utils/mutex.h>
448 
449 #include <libguile.h>
450 
451 
452 #ifndef DOXYGEN_PARSING
453 namespace Cgu {
454 
455 namespace Extension {
456 
457 struct FormatArgs {
458  SCM text;
459  SCM rest;
460 };
461 
462 enum VectorDeleteType {Long, Double, String};
463 
464 struct VectorDeleteArgs {
465  VectorDeleteType type;
466  void* vec;
467 };
468 
469 // defined in extension_helper.cpp
470 extern Cgu::Thread::Mutex* get_user_module_mutex() noexcept;
471 extern bool init_mutex() noexcept;
472 
473 } // namespace Extension
474 
475 } // namespace Cgu
476 
477 namespace {
478 extern "C" {
479  inline SCM cgu_format_try_handler(void* data) {
480  using Cgu::Extension::FormatArgs;
481  FormatArgs* format_args = static_cast<FormatArgs*>(data);
482  return scm_simple_format(SCM_BOOL_F, format_args->text, format_args->rest);
483  }
484  inline SCM cgu_format_catch_handler(void*, SCM, SCM) {
485  return SCM_BOOL_F;
486  }
487  inline void* cgu_guile_wrapper(void* data) {
488  try {
489  static_cast<Cgu::Callback::Callback*>(data)->dispatch();
490  }
491  // an elipsis catch block is fine as thread cancellation is
492  // blocked. We can only enter this block if assigning to one of
493  // the exception strings in the callback has thrown
494  // std::bad_alloc. For that case we return a non-NULL pointer to
495  // indicate error (the 'data' argument is convenient and
496  // guaranteed to be standard-conforming for this).
497  catch (...) {
498  return data;
499  }
500  return 0;
501  }
502  inline void cgu_delete_vector(void* data) {
503  using Cgu::Extension::VectorDeleteArgs;
504  VectorDeleteArgs* args = static_cast<VectorDeleteArgs*>(data);
505  switch (args->type) {
506  case Cgu::Extension::Long:
507  delete static_cast<std::vector<long>*>(args->vec);
508  break;
509  case Cgu::Extension::Double:
510  delete static_cast<std::vector<double>*>(args->vec);
511  break;
512  case Cgu::Extension::String:
513  delete static_cast<std::vector<std::string>*>(args->vec);
514  break;
515  default:
516  g_critical("Incorrect argument passed to cgu_delete_vector");
517  }
518  delete args;
519  }
520  inline void cgu_unlock_module_mutex(void*) {
521  // this cannot give rise to an allocation or mutex error -
522  // we must have been called init_mutex() first
523  Cgu::Extension::get_user_module_mutex()->unlock();
524  }
525 } // extern "C"
526 } // unnamed namespace
527 #endif // DOXYGEN_PARSING
528 
529 namespace Cgu {
530 
531 namespace Extension {
532 
533 class GuileException: public std::exception {
534  Cgu::GcharSharedHandle message;
535  Cgu::GcharSharedHandle guile_message;
536 public:
537  virtual const char* what() const throw() {return (const char*)message.get();}
538  const char* guile_text() const throw() {return (const char*)guile_message.get();}
539  GuileException(const char* msg):
540  message(g_strdup_printf(u8"Cgu::Extension::GuileException: %s", msg)),
541  guile_message(g_strdup(msg)) {}
542  ~GuileException() throw() {}
543 };
544 
545 class ReturnValueError: public std::exception {
546  Cgu::GcharSharedHandle message;
547  Cgu::GcharSharedHandle err_message;
548 public:
549  virtual const char* what() const throw() {return (const char*)message.get();}
550  const char* err_text() const throw() {return (const char*)err_message.get();}
551  ReturnValueError(const char* msg):
552  message(g_strdup_printf(u8"Cgu::Extension::ReturnValueError: %s", msg)),
553  err_message(g_strdup(msg)) {}
554  ~ReturnValueError() throw() {}
555 };
556 
557 class WrapperError: public std::exception {
558  Cgu::GcharSharedHandle message;
559 public:
560  virtual const char* what() const throw() {return (const char*)message.get();}
561  WrapperError(const char* msg):
562  message(g_strdup_printf(u8"Cgu::Extension::WrapperError: %s", msg)) {}
563  ~WrapperError() throw() {}
564 };
565 
566 #ifndef DOXYGEN_PARSING
567 
568 // we might as well take 'translator' by collapsible reference. If it
569 // is handed a rvalue function object, it will be implicitly converted
570 // to lvalue (and if necessary constructed as such) in order to take a
571 // lvalue reference on lambda construction. If it is already a
572 // lvalue, it will be passed through seamlessly.
573 template <class Ret, class Translator>
574 Ret exec_impl(const std::string& preamble,
575  const std::string& file,
576  Translator&& translator,
577  bool shared) {
578 
580 
581  std::string loader;
582  loader += preamble;
583  if (!file.empty()) {
584  if (shared)
585  loader += u8"((lambda ()";
586  loader += u8"(catch "
587  "#t"
588  "(lambda ()"
589  "(";
590  if (shared)
591  loader += u8"primitive-load \"";
592  else
593  loader += u8"load \"";
594  loader += file;
595  loader += u8"\"))"
596  "(lambda (key . details)"
597  "(cons \"***cgu-guile-exception***\" (cons key details))))";
598  if (shared)
599  loader += u8"))";
600  }
601 
602  Ret retval;
603  bool result = false;
604  std::string guile_except;
605  std::string guile_ret_val_err;
606  std::string gen_err;
607 
608  // we construct a Callback::Callback object here to perform type
609  // erasure. Otherwise we would have to pass scm_with_guile() a
610  // function pointer to a function templated on Translator and Ret,
611  // which must have C++ language linkage (§14/4 of C++ standard).
612  // Technically this would give undefined behaviour as
613  // scm_with_guile() expects a function pointer with C language
614  // linkage, although gcc and clang would accept it. The whole of
615  // this callback will be executed in guile mode via
616  // cgu_guile_wrapper(), so it can safely call libguile functions
617  // (provided that a translator does not allow any guile exceptions
618  // to escape a C++ scope with local objects which are not trivially
619  // destructible). It is also safe to pass 'translator', 'retval',
620  // 'loader', 'result' and the exception strings to it by reference,
621  // because scm_with_guile() will block until it has completed
622  // executing. cgu_guile_wrapper() will trap any std::bad_alloc
623  // exception thrown by the string assignments in the catch blocks in
624  // this lambda. This lambda is safe against a jump to an exit from
625  // scm_with_guile() arising from a native guile exception in
626  // translator, because its body has no objects in local scope
627  // requiring destruction.
628  std::unique_ptr<Cgu::Callback::Callback> cb(Cgu::Callback::lambda<>([&] () -> void {
629  SCM scm;
630  if (shared) {
631  scm = scm_eval_string_in_module(scm_from_utf8_string(loader.c_str()),
632  scm_c_resolve_module("guile-user"));
633  }
634  else {
635  if (!init_mutex())
636  throw std::bad_alloc(); // this will be caught in cgu_guile_wrapper()
637 
638  scm_dynwind_begin(scm_t_dynwind_flags(0));
639  scm_dynwind_unwind_handler(&cgu_unlock_module_mutex, 0, SCM_F_WIND_EXPLICITLY);
640  get_user_module_mutex()->lock(); // won't throw
641  SCM new_mod = scm_call_0(scm_c_public_ref("guile", "make-fresh-user-module"));
642  scm_dynwind_end();
643 
644  scm = scm_eval_string_in_module(scm_from_utf8_string(loader.c_str()),
645  new_mod);
646  }
647 
648  // have a dynwind context and async block while translator is
649  // executing. This is to cater for the pathological case of
650  // the scheme script having set up a signal handler which
651  // might throw a guile exception, or having chained a series
652  // of system asyncs which are still queued for action, which
653  // might otherwise cause the translator to trigger a guile
654  // exception while a non-trivially destructible object is in
655  // the local scope of translator. (Highly unlikely, but easy
656  // to deal with.) This is entirely safe as no C++ exception
657  // arising from the translator can transit across the dynamic
658  // context in this function - see below. So we have (i) no
659  // C++ exception can transit across a guile dynamic context,
660  // and (ii) no guile exception can escape out of a local C++
661  // scope by virtue of an async executing (it might still
662  // escape with a non-trivially destructible object in
663  // existence if a custom translator has not been written
664  // correctly, but there is nothing we can do about that).
665  // Note that some guile installations do not link
666  // scm_dynwind_block_asyncs() correctly - this is tested at
667  // configuration time.
668 #ifndef CGU_GUILE_HAS_BROKEN_LINKING
669  scm_dynwind_begin(scm_t_dynwind_flags(0));
670  scm_dynwind_block_asyncs();
671 #endif
672  // we cannot use std::exception_ptr here to store a C++
673  // exception object, because std::exception_ptr is not
674  // trivially destructible and a guile exception in
675  // 'translator' could jump out of this scope to its
676  // continuation in scm_with_guile()
677  bool badalloc = false;
678  try {
679  retval = translator(scm);
680  result = true; // this will detect any guile exception in
681  // the preamble or 'translator' which causes
682  // scm_with_guile() to return prematurely.
683  // We could have done it instead by reversing
684  // the return values of cgu_guile_wrapper
685  // (non-NULL for success and NULL for
686  // failure) because scm_with_guile() returns
687  // NULL if it exits on an uncaught guile
688  // exception, but this approach enables us to
689  // discriminate between a C++ memory
690  // exception in the wrapper and a guile
691  // exception in the preamble or 'translator',
692  // at a minimal cost of one assignment to a
693  // bool.
694  }
695  catch (GuileException& e) {
696  try {
697  guile_except = e.guile_text();
698  }
699  catch (...) {
700  badalloc = true;
701  }
702  }
703  catch (ReturnValueError& e) {
704  try {
705  guile_ret_val_err = e.err_text();
706  }
707  catch (...) {
708  badalloc = true;
709  }
710  }
711  catch (std::exception& e) {
712  try {
713  gen_err = e.what();
714  }
715  catch (...) {
716  badalloc = true;
717  }
718  }
719  catch (...) {
720  try {
721  gen_err = u8"C++ exception thrown in cgu_guile_wrapper()";
722  }
723  catch (...) {
724  badalloc = true;
725  }
726  }
727 #ifndef CGU_GUILE_HAS_BROKEN_LINKING
728  scm_dynwind_end();
729 #endif
730  if (badalloc) throw std::bad_alloc(); // this will be caught in cgu_guile_wrapper()
731  }));
732  // cgu_guile_wrapper(), and so scm_with_guile() will return a
733  // non-NULL value if assigning to one of the exception description
734  // strings above threw std::bad_alloc
735  if (scm_with_guile(&cgu_guile_wrapper, cb.get()))
736  throw WrapperError(u8"cgu_guile_wrapper() has trapped std::bad_alloc");
737  if (!guile_except.empty())
738  throw GuileException(guile_except.c_str());
739  if (!guile_ret_val_err.empty())
740  throw ReturnValueError(guile_ret_val_err.c_str());
741  if (!gen_err.empty())
742  throw WrapperError(gen_err.c_str());
743  if (!result)
744  throw WrapperError(u8"the preamble or translator threw a native guile exception");
745  return retval;
746 }
747 
748 #endif // DOXYGEN_PARSING
749 
750 /**
751  * This function is called by Extension::rethrow_guile_exception()
752  * where the scheme code executed by Extension::exec() or
753  * Extension::exec_shared() has exited with a guile exception. It
754  * converts the raw guile exception information represented by the
755  * 'key' and 'args' arguments of a guile catch handler to a more
756  * readable form. It is made available as part of the public
757  * interface so that any custom translators can also use it if they
758  * choose to provide their own catch expressions. This function does
759  * not throw any C++ exceptions. No native guile exception will arise
760  * in this function and so cause guile to jump out of it assuming no
761  * guile out-of-memory condition occurs (and given that this function
762  * is called after a guile extension task has completed, such a
763  * condition is very improbable). It is thread safe, but see the
764  * comments above about the thread safety of Extension::exec() and
765  * Extension::exec_shared().
766  *
767  * @param key An opaque guile SCM object representing a symbol
768  * comprising the 'key' argument of the exception handler of a guile
769  * catch expression.
770  * @param args An opaque guile SCM object representing a list
771  * comprising the 'args' argument of the exception handler of a guile
772  * catch expression.
773  * @return An opaque guile SCM object representing a guile string.
774  *
775  * Since 2.0.22 and 2.2.5
776  */
777 inline SCM exception_to_string(SCM key, SCM args) noexcept {
778  // The args of most exceptions thrown by guile are in the following format:
779  // (car args) - a string comprising the name of the procedure generating the exception
780  // (cadr args) - a string containing text, possibly with format directives (escape sequences)
781  // (caddr args) - a list containing items matching the format directives, or #f if none
782  // (cadddr args) - (not used here) a list of additional objects (eg the errno for some errors),
783  // or #f if none
784  SCM ret = SCM_BOOL_F;
785  int length = scm_to_int(scm_length(args));
786  if (length) {
787  SCM first = scm_car(args);
788  if (scm_is_true(scm_string_p(first))) {
789  // if a single user string, output it
790  if (length == 1) {
791  ret = scm_string_append(scm_list_4(scm_from_utf8_string(u8"Exception "),
792  scm_symbol_to_string(key),
793  scm_from_utf8_string(u8": "),
794  first));
795  }
796  else { // length > 1
797  SCM second = scm_cadr(args);
798  if (scm_is_true(scm_string_p(second))) {
799  // we should have a standard guile exception string, as above
800  SCM text = scm_string_append(scm_list_n(scm_from_utf8_string(u8"Exception "),
801  scm_symbol_to_string(key),
802  scm_from_utf8_string(u8" in procedure "),
803  first,
804  scm_from_utf8_string(u8": "),
805  second,
806  SCM_UNDEFINED));
807  if (length == 2)
808  ret = text;
809  else { // length > 2
810  SCM third = scm_caddr(args);
811  if (scm_is_false(third))
812  ret = text;
813  else if (scm_is_true(scm_list_p(third))) {
814  FormatArgs format_args = {text, third};
815  ret = scm_internal_catch(SCM_BOOL_T,
816  &cgu_format_try_handler,
817  &format_args,
818  &cgu_format_catch_handler,
819  0);
820  }
821  }
822  }
823  }
824  }
825  }
826  // fall back to generic formatting if first or second elements of
827  // args is not a string or simple-format failed above
828  if (scm_is_false(ret)) {
829  // there is no need for a catch block: we know simple-format
830  // cannot raise an exception here
831  ret = scm_simple_format(SCM_BOOL_F,
832  scm_from_utf8_string(u8"Exception ~S: ~S"),
833  scm_list_2(key, args));
834  }
835  return ret;
836 }
837 
838 /**
839  * This function tests whether a guile exception arose in executing a
840  * scheme extension file, and throws Cgu::Extension::GuileException if
841  * it did. It is intended for use by custom translators, as the first
842  * thing the translator does. It is thread safe, but see the comments
843  * above about the thread safety of Extension::exec() and
844  * Extension::exec_shared().
845  *
846  * @param scm An opaque guile SCM object representing the value to
847  * which the extension file passed to Extension::exec() or
848  * Extension::exec_shared() evaluated.
849  * @exception std::bad_alloc This function might throw std::bad_alloc
850  * if memory is exhausted and the system throws in that case.
851  * @exception Cgu::Extension::GuileException This exception will be
852  * thrown if the scheme code executed in the extension file passed to
853  * Extension::exec() or Extension::exec_shared() threw a guile
854  * exception. Cgu::Extension::GuileException::what() will give
855  * particulars of the guile exception thrown, in UTF-8 encoding.
856  * @note No native guile exception will arise in this function and so
857  * cause guile to jump out of it if no guile out-of-memory condition
858  * occurs (given that this function is called after a guile extension
859  * task has completed, such a condition is very improbable).
860  *
861  * Since 2.0.22 and 2.2.5
862  */
863 inline void rethrow_guile_exception(SCM scm) {
864  // guile exceptions are always presented to this function as a
865  // scheme list
866  if (scm_is_false(scm_list_p(scm))
867  || scm_is_true(scm_null_p(scm))) return;
868  SCM first = scm_car(scm);
869  if (scm_is_true(scm_string_p(first))) {
870  size_t len;
871  const char* text = 0;
872  // nothing in this function should throw a guile exception unless
873  // there is a guile out-of-memory exception (which is extremely
874  // improbable). However, let's cover ourselves in case
875  scm_dynwind_begin(scm_t_dynwind_flags(0));
876  char* car = scm_to_utf8_stringn(first, &len);
877  // there may be a weakness in guile's implementation here: if
878  // calling scm_dynwind_unwind_handler() were to give rise to an
879  // out-of-memory exception before the handler is set up by it,
880  // then we could leak memory allocated from the preceding call to
881  // scm_to_utf8_stringn(). Whether that could happen is not
882  // documented, but because (a) it is so improbable, and (b) once
883  // we are in out-of-memory land we are already in severe trouble
884  // and glib is likely to terminate the program at some point
885  // anyway, it is not worth troubling ourselves over.
886  scm_dynwind_unwind_handler(&free, car, scm_t_wind_flags(0));
887  if (len == strlen(u8"***cgu-guile-exception***")
888  && !strncmp(car, u8"***cgu-guile-exception***", len)) {
889  SCM str = exception_to_string(scm_cadr(scm), scm_cddr(scm));
890  // we don't need a dynwind handler for 'text' because nothing
891  // after the call to scm_to_utf8_stringn() can cause a guile
892  // exception to be raised
893  text = scm_to_utf8_stringn(str, &len);
894  }
895  // all done - no more guile exceptions are possible in this
896  // function after this so end the dynamic context, take control of
897  // the memory by RAII and if necessary throw a C++ exception
898  scm_dynwind_end();
899  std::unique_ptr<char, Cgu::CFree> up_car(car);
900  std::unique_ptr<const char, Cgu::CFree> up_text(text);
901  // if 'text' is not NULL, 'len' contains its length in bytes
902  if (text) throw GuileException(std::string(text, len).c_str());
903  }
904 }
905 
906 /**
907  * A translator function which can be passed to the third argument of
908  * Extension::exec() or Extension::exec_shared(). It converts from a
909  * homogeneous scheme list of integers to a C++ representation of
910  * std::vector<long>. It is thread safe, but see the comments above
911  * about the thread safety of Extension::exec() and
912  * Extension::exec_shared().
913  *
914  * @param scm An opaque guile SCM object representing the value to
915  * which the extension file passed to Extension::exec() or
916  * Extension::exec_shared() evaluated, where that value is a
917  * homogeneous list of integers.
918  * @return The std::vector<long> representation.
919  * @exception std::bad_alloc This function might throw std::bad_alloc
920  * if memory is exhausted and the system throws in that case, or if
921  * the length of the input list exceeds std::vector::max_size().
922  * @exception Cgu::Extension::GuileException This exception will be
923  * thrown if the scheme code in the extension file passed to
924  * Extension::exec() or Extension::exec_shared() caused a guile
925  * exception to be thrown. Cgu::Extension::GuileException::what()
926  * will give particulars of the guile exception thrown, in UTF-8
927  * encoding.
928  * @exception Cgu::Extension::ReturnValueError This exception will be
929  * thrown if the scheme code in the extension file passed to
930  * Extension::exec() or Extension::exec_shared() does not evaluate to
931  * the type expected by the translator, or it is out of range for a
932  * long. Cgu::Extension::ReturnValueError::what() will give further
933  * particulars, in UTF-8 encoding.
934  * @note No native guile exception will arise in this function and so
935  * cause guile to jump out of it unless a guile out-of-memory
936  * condition occurs (given that this function is called after a guile
937  * extension task has completed, such a condition is very improbable)
938  * or the length of the input list exceeds SIZE_MAX (the maximum value
939  * of std::size_t). If such an exception were to arise, the
940  * implementation would handle it and a C++ exception would be
941  * generated in its place in Extension::exec() or
942  * Extension::exec_shared().
943  *
944  * Since 2.0.22 and 2.2.5
945  */
946 inline std::vector<long> list_to_vector_long(SCM scm) {
948  if (scm_is_false(scm_list_p(scm)))
949  throw ReturnValueError(u8"scheme code did not evaluate to a list\n");
950 
951  // nothing in this function should throw a guile exception unless
952  // there is a guile out-of-memory exception (which is extremely
953  // improbable). However, let's cover ourselves in case.
954  scm_dynwind_begin(scm_t_dynwind_flags(0));
955  // we cannot have a std::vector object in a scope where a guile
956  // exception might be raised because it has a non-trivial
957  // destructor, nor can we use RAII. Instead allocate on free store
958  // and manage the memory by hand until we can no longer jump on a
959  // guile exception. In addition we cannot store a C++ exception
960  // using std::exception_ptr because std::exception_ptr is not
961  // trivially destructible.
962  bool badalloc = false;
963  const char* rv_error = 0;
964  std::vector<long>* res = 0;
965  VectorDeleteArgs* args = 0;
966  try {
967  // it doesn't matter if the second allocation fails, as we clean
968  // up at the end if there is no guile exception, and if both
969  // allocations succeed and there were to be a subsequent guile
970  // exception, cgu_delete_vector cleans up
971  res = new std::vector<long>;
972  // allocate 'args' on free store, because the continuation in
973  // which it executes will be up the stack
974  args = new VectorDeleteArgs{Long, res};
975  }
976  catch (...) {
977  badalloc = true;
978  }
979  if (!badalloc) {
980  // there may be a weakness in guile's implementation here: if
981  // calling scm_dynwind_unwind_handler() were to give rise to a
982  // guile out-of-memory exception before the handler is set up by
983  // it, then we could leak memory allocated from the preceding new
984  // expressions. Whether that could happen is not documented by
985  // guile, but because (a) it is so improbable, and (b) once we are
986  // in out-of-memory land we are already in severe trouble and glib
987  // is likely to terminate the program at some point anyway, it is
988  // not worth troubling ourselves over.
989  scm_dynwind_unwind_handler(&cgu_delete_vector, args, scm_t_wind_flags(0));
990  // convert the list to a guile vector so we can access its items
991  // efficiently in a for loop. This conversion is reasonably
992  // efficient, in the sense that an ordinary guile vector is an
993  // array of pointers, pointing to the same scheme objects that the
994  // list refers to
995  SCM guile_vec = scm_vector(scm);
996 
997  // std::vector::size_type is the same as size_t with the standard
998  // allocators (but if we were to get a silent narrowing conversion
999  // on calling std::vector::reserve() below, that doesn't matter -
1000  // instead if 'length' is less than SIZE_MAX but greater than the
1001  // maximum value of std::vector::size_type, at some point a call
1002  // to std::vector::push_back() below would throw and be caught,
1003  // and this function would end up rethrowing it as std::bad_alloc.
1004  // If in a particular implementation SIZE_MAX exceeds
1005  // std::vector::max_size(), a std::length_error exception would be
1006  // thrown by reserve() where max_size() is exceeded. On all
1007  // common implementations, max_size() is equal to SIZE_MAX, but
1008  // were such an exception to arise it would be swallowed (see
1009  // below) and then rethrown by this function as std::bad_alloc.
1010  // If 'length' is greater than SIZE_MAX, a guile out-of-range
1011  // exception would be thrown by scm_to_size_t() which would be
1012  // rethrown by Cgu:Extension::exec() or
1013  // Cgu::Exception::exec_shared as a Cgu::Extension::WrapperError
1014  // C++ exception. This is nice to know but in practice such large
1015  // lists would be unusably slow and a memory exception would be
1016  // reached long before std::vector::max_size() or SIZE_MAX are
1017  // exceeded.
1018  size_t length = scm_to_size_t(scm_vector_length(guile_vec));
1019  try {
1020  res->reserve(length);
1021  }
1022  catch (...) {
1023  badalloc = true;
1024  }
1025  for (size_t count = 0;
1026  count < length && !rv_error && !badalloc;
1027  ++count) {
1028  SCM item = scm_vector_ref(guile_vec, scm_from_size_t(count));
1029  if (scm_is_false(scm_integer_p(item)))
1030  rv_error = u8"scheme code did not evaluate to a homogeneous list of integer\n";
1031  else {
1032  SCM min = scm_from_long(std::numeric_limits<long>::min());
1033  SCM max = scm_from_long(std::numeric_limits<long>::max());
1034  if (scm_is_false(scm_leq_p(item, max)) || scm_is_false(scm_geq_p(item, min)))
1035  rv_error = u8"scheme code evaluated out of range for long\n";
1036  else {
1037  try {
1038  res->push_back(scm_to_long(item));
1039  }
1040  catch (...) {
1041  badalloc = true;
1042  }
1043  }
1044  }
1045  }
1046  }
1047  // all done - no more guile exceptions are possible in this function
1048  // after this so end the dynamic context, take control of the memory
1049  // by RAII and if necessary throw a C++ exception
1050  scm_dynwind_end();
1051  std::unique_ptr<std::vector<long>> up_res(res);
1052  std::unique_ptr<VectorDeleteArgs> up_args(args);
1053  if (badalloc) throw std::bad_alloc();
1054  if (rv_error) throw ReturnValueError(rv_error);
1055  // neither gcc-4.9 nor clang-3.4 will optimize with RVO or move
1056  // semantics here, so force it by hand
1057  return std::move(*res);
1058 }
1059 
1060 /**
1061  * A translator function which can be passed to the third argument of
1062  * Extension::exec() or Extension::exec_shared(). It converts from a
1063  * homogeneous scheme list of real numbers to a C++ representation of
1064  * std::vector<double>. It is thread safe, but see the comments above
1065  * about the thread safety of Extension::exec() and
1066  * Extension::exec_shared().
1067  *
1068  * @param scm An opaque guile SCM object representing the value to
1069  * which the extension file passed to Extension::exec() or
1070  * Extension::exec_shared() evaluated, where that value is a
1071  * homogeneous list of real numbers.
1072  * @return The std::vector<double> representation.
1073  * @exception std::bad_alloc This function might throw std::bad_alloc
1074  * if memory is exhausted and the system throws in that case, or if
1075  * the length of the input list exceeds std::vector::max_size().
1076  * @exception Cgu::Extension::GuileException This exception will be
1077  * thrown if the scheme code in the extension file passed to
1078  * Extension::exec() or Extension::exec_shared() caused a guile
1079  * exception to be thrown. Cgu::Extension::GuileException::what()
1080  * will give particulars of the guile exception thrown, in UTF-8
1081  * encoding.
1082  * @exception Cgu::Extension::ReturnValueError This exception will be
1083  * thrown if the scheme code in the extension file passed to
1084  * Extension::exec() or Extension::exec_shared() does not evaluate to
1085  * the type expected by the translator, or it is out of range for a
1086  * double. Cgu::Extension::ReturnValueError::what() will give further
1087  * particulars, in UTF-8 encoding.
1088  * @note 1. Prior to versions 2.0.25 and 2.2.8, this translator had a
1089  * bug which caused an out-of-range Cgu::Extension::ReturnValueError
1090  * to be thrown if any of the numbers in the list to which the scheme
1091  * code in the extension file evaluated was 0.0 or a negative number.
1092  * This was fixed in versions 2.0.25 and 2.2.8.
1093  * @note 2. No native guile exception will arise in this function and
1094  * so cause guile to jump out of it unless a guile out-of-memory
1095  * condition occurs (given that this function is called after a guile
1096  * extension task has completed, such a condition is very improbable)
1097  * or the length of the input list exceeds SIZE_MAX (the maximum value
1098  * of std::size_t). If such an exception were to arise, the
1099  * implementation would handle it and a C++ exception would be
1100  * generated in its place in Extension::exec() or
1101  * Extension::exec_shared().
1102  *
1103  * Since 2.0.22 and 2.2.5
1104  */
1105 inline std::vector<double> list_to_vector_double(SCM scm) {
1107  if (scm_is_false(scm_list_p(scm)))
1108  throw ReturnValueError(u8"scheme code did not evaluate to a list\n");
1109 
1110  // nothing in this function should throw a guile exception unless
1111  // there is a guile out-of-memory exception (which is extremely
1112  // improbable). However, let's cover ourselves in case.
1113  scm_dynwind_begin(scm_t_dynwind_flags(0));
1114  // we cannot have a std::vector object in a scope where a guile
1115  // exception might be raised because it has a non-trivial
1116  // destructor, nor can we use RAII. Instead allocate on free store
1117  // and manage the memory by hand until we can no longer jump on a
1118  // guile exception. In addition we cannot store a C++ exception
1119  // using std::exception_ptr because std::exception_ptr is not
1120  // trivially destructible.
1121  bool badalloc = false;
1122  const char* rv_error = 0;
1123  std::vector<double>* res = 0;
1124  VectorDeleteArgs* args = 0;
1125  try {
1126  // it doesn't matter if the second allocation fails, as we clean
1127  // up at the end if there is no guile exception, and if both
1128  // allocations succeed and there were to be a subsequent guile
1129  // exception, cgu_delete_vector cleans up
1130  res = new std::vector<double>;
1131  // allocate 'args' on free store, because the continuation in
1132  // which it executes will be up the stack
1133  args = new VectorDeleteArgs{Double, res};
1134  }
1135  catch (...) {
1136  badalloc = true;
1137  }
1138  if (!badalloc) {
1139  // there may be a weakness in guile's implementation here: if
1140  // calling scm_dynwind_unwind_handler() were to give rise to a
1141  // guile out-of-memory exception before the handler is set up by
1142  // it, then we could leak memory allocated from the preceding
1143  // new expressions. Whether that could happen is not documented
1144  // by guile, but because (a) it is so improbable, and (b) once
1145  // we are in out-of-memory land we are already in severe trouble
1146  // and glib is likely to terminate the program at some point
1147  // anyway, it is not worth troubling ourselves over.
1148  scm_dynwind_unwind_handler(&cgu_delete_vector, args, scm_t_wind_flags(0));
1149  // convert the list to a guile vector so we can access its items
1150  // efficiently in a for loop. This conversion is reasonably
1151  // efficient, in the sense that an ordinary guile vector is an
1152  // array of pointers, pointing to the same scheme objects that the
1153  // list refers to
1154  SCM guile_vec = scm_vector(scm);
1155 
1156  // std::vector::size_type is the same as size_t with the standard
1157  // allocators (but if we were to get a silent narrowing conversion
1158  // on calling std::vector::reserve() below, that doesn't matter -
1159  // instead if 'length' is less than SIZE_MAX but greater than the
1160  // maximum value of std::vector::size_type, at some point a call
1161  // to std::vector::push_back() below would throw and be caught,
1162  // and this function would end up rethrowing it as std::bad_alloc.
1163  // If in a particular implementation SIZE_MAX exceeds
1164  // std::vector::max_size(), a std::length_error exception would be
1165  // thrown by reserve() where max_size() is exceeded. On all
1166  // common implementations, max_size() is equal to SIZE_MAX, but
1167  // were such an exception to arise it would be swallowed (see
1168  // below) and then rethrown by this function as std::bad_alloc.
1169  // If 'length' is greater than SIZE_MAX, a guile out-of-range
1170  // exception would be thrown by scm_to_size_t() which would be
1171  // rethrown by Cgu:Extension::exec() or
1172  // Cgu::Exception::exec_shared as a Cgu::Extension::WrapperError
1173  // C++ exception. This is nice to know but in practice such large
1174  // lists would be unusably slow and a memory exception would be
1175  // reached long before std::vector::max_size() or SIZE_MAX are
1176  // exceeded.
1177  size_t length = scm_to_size_t(scm_vector_length(guile_vec));
1178  try {
1179  res->reserve(length);
1180  }
1181  catch (...) {
1182  badalloc = true;
1183  }
1184  for (size_t count = 0;
1185  count < length && !rv_error && !badalloc;
1186  ++count) {
1187  SCM item = scm_vector_ref(guile_vec, scm_from_size_t(count));
1188  if (scm_is_false(scm_real_p(item)))
1189  rv_error = u8"scheme code did not evaluate to a homogeneous list of real numbers\n";
1190  else {
1191  SCM min = scm_from_double(std::numeric_limits<double>::lowest());
1192  SCM max = scm_from_double(std::numeric_limits<double>::max());
1193  if (scm_is_false(scm_leq_p(item, max)) || scm_is_false(scm_geq_p(item, min)))
1194  rv_error = u8"scheme code evaluated out of range for double\n";
1195  else {
1196  try {
1197  res->push_back(scm_to_double(item));
1198  }
1199  catch (...) {
1200  badalloc = true;
1201  }
1202  }
1203  }
1204  }
1205  }
1206  // all done - no more guile exceptions are possible in this function
1207  // after this so end the dynamic context, take control of the memory
1208  // by RAII and if necessary throw a C++ exception
1209  scm_dynwind_end();
1210  std::unique_ptr<std::vector<double>> up_res(res);
1211  std::unique_ptr<VectorDeleteArgs> up_args(args);
1212  if (badalloc) throw std::bad_alloc();
1213  if (rv_error) throw ReturnValueError(rv_error);
1214  // neither gcc-4.9 nor clang-3.4 will optimize with RVO or move
1215  // semantics here, so force it by hand
1216  return std::move(*res);
1217 }
1218 
1219 /**
1220  * A translator function which can be passed to the third argument of
1221  * Extension::exec() or Extension::exec_shared(). It converts from a
1222  * homogeneous scheme list of strings to a C++ representation of
1223  * std::vector<std::string>. It is thread safe, but see the comments
1224  * above about the thread safety of Extension::exec() and
1225  * Extension::exec_shared().
1226  *
1227  * The returned strings will be in UTF-8 encoding.
1228  *
1229  * Note that the first string in the returned list must not be
1230  * "***cgu-guile-exception***": that string is reserved to the
1231  * implementation.
1232  *
1233  * @param scm An opaque guile SCM object representing the value to
1234  * which the extension file passed to Extension::exec() or
1235  * Extension::exec_shared() evaluated, where that value is a
1236  * homogeneous list of strings.
1237  * @return The std::vector<std::string> representation.
1238  * @exception std::bad_alloc This function might throw std::bad_alloc
1239  * if memory is exhausted and the system throws in that case, or if
1240  * the length of the input list exceeds std::vector::max_size().
1241  * @exception Cgu::Extension::GuileException This exception will be
1242  * thrown if the scheme code in the extension file passed to
1243  * Extension::exec() or Extension::exec_shared() caused a guile
1244  * exception to be thrown. Cgu::Extension::GuileException::what()
1245  * will give particulars of the guile exception thrown, in UTF-8
1246  * encoding.
1247  * @exception Cgu::Extension::ReturnValueError This exception will be
1248  * thrown if the scheme code in the extension file passed to
1249  * Extension::exec() or Extension::exec_shared() does not evaluate to
1250  * the type expected by the translator.
1251  * Cgu::Extension::ReturnValueError::what() will give further
1252  * particulars, in UTF-8 encoding.
1253  * @note No native guile exception will arise in this function and so
1254  * cause guile to jump out of it unless a guile out-of-memory
1255  * condition occurs (given that this function is called after a guile
1256  * extension task has completed, such a condition is very improbable)
1257  * or the length of the input list exceeds SIZE_MAX (the maximum value
1258  * of std::size_t). If such an exception were to arise, the
1259  * implementation would handle it and a C++ exception would be
1260  * generated in its place in Extension::exec() or
1261  * Extension::exec_shared().
1262  *
1263  * Since 2.0.22 and 2.2.5
1264  */
1265 inline std::vector<std::string> list_to_vector_string(SCM scm) {
1267  if (scm_is_false(scm_list_p(scm)))
1268  throw ReturnValueError(u8"scheme code did not evaluate to a list\n");
1269 
1270  // nothing in this function should throw a guile exception unless
1271  // there is a guile out-of-memory exception (which is extremely
1272  // improbable). However, let's cover ourselves in case.
1273  scm_dynwind_begin(scm_t_dynwind_flags(0));
1274  // we cannot have a std::vector object in a scope where a guile
1275  // exception might be raised because it has a non-trivial
1276  // destructor, nor can we use RAII. Instead allocate on free store
1277  // and manage the memory by hand until we can no longer jump on a
1278  // guile exception. In addition we cannot store a C++ exception
1279  // using std::exception_ptr because std::exception_ptr is not
1280  // trivially destructible.
1281  bool badalloc = false;
1282  const char* rv_error = 0;
1283  std::vector<std::string>* res = 0;
1284  VectorDeleteArgs* args = 0;
1285  try {
1286  // it doesn't matter if the second allocation fails, as we clean
1287  // up at the end if there is no guile exception, and if both
1288  // allocations succeed and there were to be a subsequent guile
1289  // exception, cgu_delete_vector cleans up
1290  res = new std::vector<std::string>;
1291  // allocate 'args' on free store, because the continuation in
1292  // which it executes will be up the stack
1293  args = new VectorDeleteArgs{String, res};
1294  }
1295  catch (...) {
1296  badalloc = true;
1297  }
1298  if (!badalloc) {
1299  // there may be a weakness in guile's implementation here: if
1300  // calling scm_dynwind_unwind_handler() were to give rise to a
1301  // guile out-of-memory exception before the handler is set up by
1302  // it, then we could leak memory allocated from the preceding new
1303  // expressions. Whether that could happen is not documented by
1304  // guile, but because (a) it is so improbable, and (b) once we are
1305  // in out-of-memory land we are already in severe trouble and glib
1306  // is likely to terminate the program at some point anyway, it is
1307  // not worth troubling ourselves over.
1308  scm_dynwind_unwind_handler(&cgu_delete_vector, args, scm_t_wind_flags(0));
1309  // convert the list to a guile vector so we can access its items
1310  // efficiently in a for loop. This conversion is reasonably
1311  // efficient, in the sense that an ordinary guile vector is an
1312  // array of pointers, pointing to the same scheme objects that the
1313  // list refers to
1314  SCM guile_vec = scm_vector(scm);
1315 
1316  // std::vector::size_type is the same as size_t with the standard
1317  // allocators (but if we were to get a silent narrowing conversion
1318  // on calling std::vector::reserve() below, that doesn't matter -
1319  // instead if 'length' is less than SIZE_MAX but greater than the
1320  // maximum value of std::vector::size_type, at some point a call
1321  // to std::vector::emplace_back() below would throw and be caught,
1322  // and this function would end up rethrowing it as std::bad_alloc.
1323  // If in a particular implementation SIZE_MAX exceeds
1324  // std::vector::max_size(), a std::length_error exception would be
1325  // thrown by reserve() where max_size() is exceeded. On all
1326  // common implementations, max_size() is equal to SIZE_MAX, but
1327  // were such an exception to arise it would be swallowed (see
1328  // below) and then rethrown by this function as std::bad_alloc.
1329  // If 'length' is greater than SIZE_MAX, a guile out-of-range
1330  // exception would be thrown by scm_to_size_t() which would be
1331  // rethrown by Cgu:Extension::exec() or
1332  // Cgu::Exception::exec_shared as a Cgu::Extension::WrapperError
1333  // C++ exception. This is nice to know but in practice such large
1334  // lists would be unusably slow and a memory exception would be
1335  // reached long before std::vector::max_size() or SIZE_MAX are
1336  // exceeded.
1337  size_t length = scm_to_size_t(scm_vector_length(guile_vec));
1338  try {
1339  res->reserve(length);
1340  }
1341  catch (...) {
1342  badalloc = true;
1343  }
1344  for (size_t count = 0;
1345  count < length && !rv_error && !badalloc;
1346  ++count) {
1347  SCM item = scm_vector_ref(guile_vec, scm_from_size_t(count));
1348  if (scm_is_false(scm_string_p(item)))
1349  rv_error = u8"scheme code did not evaluate to a homogeneous list of string\n";
1350  else {
1351  size_t len;
1352  // we don't need a dynwind handler for 'str' because nothing
1353  // after the call to scm_to_utf8_stringn() and before the call
1354  // to free() can cause a guile exception to be raised
1355  char* str = scm_to_utf8_stringn(item, &len);
1356  try {
1357  res->emplace_back(str, len);
1358  }
1359  catch (...) {
1360  badalloc = true;
1361  }
1362  free(str);
1363  }
1364  }
1365  }
1366  // all done - no more guile exceptions are possible in this function
1367  // after this so end the dynamic context, take control of the memory
1368  // by RAII and if necessary throw a C++ exception
1369  scm_dynwind_end();
1370  std::unique_ptr<std::vector<std::string>> up_res(res);
1371  std::unique_ptr<VectorDeleteArgs> up_args(args);
1372  if (badalloc) throw std::bad_alloc();
1373  if (rv_error) throw ReturnValueError(rv_error);
1374  // neither gcc-4.9 nor clang-3.4 will optimize with RVO or move
1375  // semantics here, so force it by hand
1376  return std::move(*res);
1377 }
1378 
1379 /**
1380  * A translator function which can be passed to the third argument of
1381  * Extension::exec() or Extension::exec_shared(). It converts from a
1382  * scheme integer to a C++ representation of long. It is thread safe,
1383  * but see the comments above about the thread safety of
1384  * Extension::exec() and Extension::exec_shared().
1385  *
1386  * @param scm An opaque guile SCM object representing the value to
1387  * which the extension file passed to Extension::exec() or
1388  * Extension::exec_shared() evaluated, where that value is an integer.
1389  * @return The C++ long representation.
1390  * @exception std::bad_alloc This function might throw std::bad_alloc
1391  * if memory is exhausted and the system throws in that case.
1392  * @exception Cgu::Extension::GuileException This exception will be
1393  * thrown if the scheme code in the extension file passed to
1394  * Extension::exec() or Extension::exec_shared() caused a guile
1395  * exception to be thrown. Cgu::Extension::GuileException::what()
1396  * will give particulars of the guile exception thrown, in UTF-8
1397  * encoding.
1398  * @exception Cgu::Extension::ReturnValueError This exception will be
1399  * thrown if the scheme code in the extension file passed to
1400  * Extension::exec() or Extension::exec_shared() does not evaluate to
1401  * the type expected by the translator, or it is out of range for a
1402  * long. Cgu::Extension::ReturnValueError::what() will give further
1403  * particulars, in UTF-8 encoding.
1404  * @note No native guile exception will arise in this function and so
1405  * cause guile to jump out of it if no guile out-of-memory condition
1406  * occurs (given that this function is called after a guile extension
1407  * task has completed, such a condition is very improbable). If such
1408  * an exception were to arise, the implementation would handle it and
1409  * a C++ exception would be generated in its place in
1410  * Extension::exec() or Extension::exec_shared().
1411  *
1412  * Since 2.0.22 and 2.2.5
1413  */
1414 inline long integer_to_long(SCM scm) {
1416  if (scm_is_false(scm_integer_p(scm)))
1417  throw ReturnValueError(u8"scheme code did not evaluate to an integer\n");
1418  SCM min = scm_from_long(std::numeric_limits<long>::min());
1419  SCM max = scm_from_long(std::numeric_limits<long>::max());
1420  if (scm_is_false(scm_leq_p(scm, max)) || scm_is_false(scm_geq_p(scm, min)))
1421  throw ReturnValueError(u8"scheme code evaluated out of range for long\n");
1422  return scm_to_long(scm);
1423 }
1424 
1425 /**
1426  * A translator function which can be passed to the third argument of
1427  * Extension::exec() or Extension::exec_shared(). It converts from a
1428  * scheme real number to a C++ representation of double. It is thread
1429  * safe, but see the comments above about the thread safety of
1430  * Extension::exec() and Extension::exec_shared().
1431  *
1432  * @param scm An opaque guile SCM object representing the value to
1433  * which the extension file passed to Extension::exec() or
1434  * Extension::exec_shared() evaluated, where that value is a real
1435  * number.
1436  * @return The C++ double representation.
1437  * @exception std::bad_alloc This function might throw std::bad_alloc
1438  * if memory is exhausted and the system throws in that case.
1439  * @exception Cgu::Extension::GuileException This exception will be
1440  * thrown if the scheme code in the extension file passed to
1441  * Extension::exec() or Extension::exec_shared() caused a guile
1442  * exception to be thrown. Cgu::Extension::GuileException::what()
1443  * will give particulars of the guile exception thrown, in UTF-8
1444  * encoding.
1445  * @exception Cgu::Extension::ReturnValueError This exception will be
1446  * thrown if the scheme code in the extension file passed to
1447  * Extension::exec() or Extension::exec_shared() does not evaluate to
1448  * the type expected by the translator, or it is out of range for a
1449  * double. Cgu::Extension::ReturnValueError::what() will give further
1450  * particulars, in UTF-8 encoding.
1451  * @note 1. Prior to versions 2.0.25 and 2.2.8, this translator had a
1452  * bug which caused an out-of-range Cgu::Extension::ReturnValueError
1453  * to be thrown if the scheme code in the extension file evaluated to
1454  * 0.0 or a negative number. This was fixed in versions 2.0.25 and
1455  * 2.2.8.
1456  * @note 2. No native guile exception will arise in this function and
1457  * so cause guile to jump out of it if no guile out-of-memory
1458  * condition occurs (given that this function is called after a guile
1459  * extension task has completed, such a condition is very improbable).
1460  * If such an exception were to arise, the implementation would handle
1461  * it and a C++ exception would be generated in its place in
1462  * Extension::exec() or Extension::exec_shared().
1463  *
1464  * Since 2.0.22 and 2.2.5
1465  */
1466 inline double real_to_double(SCM scm) {
1468  if (scm_is_false(scm_real_p(scm)))
1469  throw ReturnValueError(u8"scheme code did not evaluate to a real number\n");
1470  SCM min = scm_from_double(std::numeric_limits<double>::lowest());
1471  SCM max = scm_from_double(std::numeric_limits<double>::max());
1472  if (scm_is_false(scm_leq_p(scm, max)) || scm_is_false(scm_geq_p(scm, min)))
1473  throw ReturnValueError(u8"scheme code evaluated out of range for double\n");
1474  return scm_to_double(scm);
1475 }
1476 
1477 /**
1478  * A translator function which can be passed to the third argument of
1479  * Extension::exec() or Extension::exec_shared(). It converts from a
1480  * scheme string to a C++ representation of std::string. It is thread
1481  * safe, but see the comments above about the thread safety of
1482  * Extension::exec() and Extension::exec_shared().
1483  *
1484  * The returned string will be in UTF-8 encoding.
1485  *
1486  * @param scm An opaque guile SCM object representing the value to
1487  * which the extension file passed to Extension::exec() or
1488  * Extension::exec_shared() evaluated, where that value is a string.
1489  * @return The std::string representation.
1490  * @exception std::bad_alloc This function might throw std::bad_alloc
1491  * if memory is exhausted and the system throws in that case.
1492  * @exception Cgu::Extension::GuileException This exception will be
1493  * thrown if the scheme code in the extension file passed to
1494  * Extension::exec() or Extension::exec_shared() caused a guile
1495  * exception to be thrown. Cgu::Extension::GuileException::what()
1496  * will give particulars of the guile exception thrown, in UTF-8
1497  * encoding.
1498  * @exception Cgu::Extension::ReturnValueError This exception will be
1499  * thrown if the scheme code in the extension file passed to
1500  * Extension::exec() or Extension::exec_shared() does not evaluate to
1501  * the type expected by the translator.
1502  * Cgu::Extension::ReturnValueError::what() will give further
1503  * particulars, in UTF-8 encoding.
1504  * @note No native guile exception will arise in this function and so
1505  * cause guile to jump out of it if no guile out-of-memory condition
1506  * occurs (given that this function is called after a guile extension
1507  * task has completed, such a condition is very improbable). If such
1508  * an exception were to arise, the implementation would handle it and
1509  * a C++ exception would be generated in its place in
1510  * Extension::exec() or Extension::exec_shared().
1511  *
1512  * Since 2.0.22 and 2.2.5
1513  */
1514 inline std::string string_to_string(SCM scm) {
1516  if (scm_is_false(scm_string_p(scm)))
1517  throw ReturnValueError(u8"scheme code did not evaluate to a string\n");
1518  size_t len;
1519  // it is safe to use unique_ptr here. If scm_to_utf8_stringn()
1520  // succeeds then nothing after it in this function can cause a guile
1521  // exception.
1522  std::unique_ptr<const char, Cgu::CFree> s(scm_to_utf8_stringn(scm, &len));
1523  return std::string(s.get(), len);
1524 }
1525 
1526 /**
1527  * A translator function which can be passed to the third argument of
1528  * Extension::exec() or Extension::exec_shared(). It disregards the
1529  * scheme value passed to it except to trap any guile exception thrown
1530  * by the scheme task and rethrow it as a C++ exception, and returns a
1531  * NULL void* object. It is thread safe, but see the comments above
1532  * about the thread safety of Extension::exec() and
1533  * Extension::exec_shared().
1534  *
1535  * It is mainly intended for use where the scheme script is executed
1536  * for its side effects, perhaps for I/O, and any communication
1537  * necessary is done by guile exceptions.
1538  *
1539  * @param scm An opaque guile SCM object representing the value to
1540  * which the extension file passed to Extension::exec() or
1541  * Extension::exec_shared() evaluated, which is ignored.
1542  * @return A NULL void* object.
1543  * @exception std::bad_alloc This function might throw std::bad_alloc
1544  * if memory is exhausted and the system throws in that case.
1545  * @exception Cgu::Extension::GuileException This exception will be
1546  * thrown if the scheme code in the extension file passed to
1547  * Extension::exec() or Extension::exec_shared() caused a guile
1548  * exception to be thrown. Cgu::Extension::GuileException::what()
1549  * will give particulars of the guile exception thrown, in UTF-8
1550  * encoding.
1551  * @note No native guile exception will arise in this function and so
1552  * cause guile to jump out of it if no guile out-of-memory condition
1553  * occurs (given that this function is called after a guile extension
1554  * task has completed, such a condition is very improbable). If such
1555  * an exception were to arise, the implementation would handle it and
1556  * a C++ exception would be generated in its place in
1557  * Extension::exec() or Extension::exec_shared().
1558  *
1559  * Since 2.0.22 and 2.2.5
1560  */
1561 inline void* any_to_void(SCM scm) {
1563  return 0;
1564 }
1565 
1566 /**
1567  * This function executes scheme code on the guile VM within a C++
1568  * program using this library. See the introductory remarks above for
1569  * its potential uses, about the thread safety of this function, and
1570  * about the use of the TaskManager::exec_shared() as an alternative.
1571  *
1572  * The first argument to this function is a preamble, which can be
1573  * used to pass top level definitions to the scheme code (in other
1574  * words, for argument passing). It's second argument is the filename
1575  * (with path) of the file containing the scheme code to be executed.
1576  * It's third argument is a translator, which will convert the value
1577  * to which the scheme code evaluates (in C++ terms, its return value)
1578  * to a suitable C++ representation. Preformed translators are
1579  * provided by this library to translate from scheme's integers, real
1580  * numbers and strings to C++ longs, doubles and strings respectively,
1581  * and from any uniform lists of these to C++ vectors of the
1582  * corresponding type. There is also a translator for void return
1583  * types. See the introductory remarks above for more information
1584  * about translators.
1585  *
1586  * Any native guile exceptions thrown by the code executed by this
1587  * function (and by any code which it calls) are converted and
1588  * rethrown as C++ exceptions.
1589  *
1590  * The scheme file can call other scheme code, and load modules, in
1591  * the ordinary way. Thus, this function can execute any scheme code
1592  * which guile can execute as a program, and the programmer can (if
1593  * wanted) act on its return value in the C++ code which invokes it.
1594  *
1595  * Thread cancellation is blocked for the thread in which this
1596  * function executes until this function returns.
1597  *
1598  * @param preamble Scheme code such as top level definitions to be
1599  * seen by the code in the file to be executed. This is mainly
1600  * intended for argument passing, but can comprise any valid scheme
1601  * code. It can also be empty (you can pass ""). Any string literals
1602  * must be in UTF-8 encoding.
1603  * @param file The file which is to be executed on the guile VM. This
1604  * should include the full pathname or a pathname relative to the
1605  * current directory. The contents of the file, and in particular any
1606  * string literals in it, must be in UTF-8 encoding. The filename and
1607  * path must also be given in UTF-8 encoding, even if the local
1608  * filename encoding is something different: guile will convert the
1609  * UTF-8 name which it is given to its own internal string encoding
1610  * using unicode code points, and then convert that to locale encoding
1611  * on looking up the filename. However sticking to ASCII for
1612  * filenames and paths (which is always valid UTF-8) will maximise
1613  * portability. The file name can be empty (you can pass ""), in
1614  * which case only the preamble will be evaluated (but for efficiency
1615  * reasons any complex code not at the top level should be included in
1616  * the file rather than in the preamble).
1617  * @param translator The function or callable object which will
1618  * convert the value to which the scheme code evaluates to a C++
1619  * representation which will be returned by this function. The
1620  * translator should take a single argument comprising an opaque guile
1621  * object of type SCM, and return the C++ representation for it.
1622  * @return The C++ representation returned by the translator.
1623  * @exception std::bad_alloc This function might throw std::bad_alloc
1624  * if memory is exhausted and the system throws in that case.
1625  * @exception Cgu::Extension::GuileException This exception will be
1626  * thrown if the scheme code in 'file' (or called by it) throws a
1627  * guile exception. Cgu::Extension::GuileException::what() will give
1628  * particulars of the guile exception thrown, in UTF-8 encoding.
1629  * @exception Cgu::Extension::ReturnValueError This exception will be
1630  * thrown if the code in 'file' does not evaluate to the type expected
1631  * by the translator. Cgu::Extension::ReturnValueError::what() will
1632  * give further particulars, in UTF-8 encoding.
1633  * @exception Cgu::Extension::WrapperError This exception will be
1634  * thrown if a custom translator throws a native guile exception or a
1635  * C++ exception not comprising Extension::GuileException or
1636  * Extension::ReturnValueError, one of the preformed translators
1637  * throws std::bad_alloc or encounters a guile out-of-memory
1638  * exception, one of the preformed list translators encounters an
1639  * input list exceeding SIZE_MAX in length, assigning to an internal
1640  * exception description string throws std::bad_alloc, or evaluation
1641  * of the preamble throws a native guile exception.
1642  *
1643  * Since 2.0.22 and 2.2.5
1644  */
1645 template <class Translator>
1646 auto exec(const std::string& preamble,
1647  const std::string& file,
1648  Translator&& translator) -> typename std::result_of<Translator(SCM)>::type {
1649  // exec_impl() will fail to compile if Ret is a reference type: that
1650  // is a feature, not a bug, as there is no good reason for a
1651  // translator ever to return a reference
1652  typedef typename std::result_of<Translator(SCM)>::type Ret;
1653  return exec_impl<Ret>(preamble, file, std::forward<Translator>(translator), false);
1654 }
1655 
1656 /**
1657  * This function executes scheme code on the guile VM within a C++
1658  * program using this library. See the introductory remarks above for
1659  * its potential uses, about the thread safety of this function, and
1660  * about the use of the TaskManager::exec() as an alternative.
1661  *
1662  * The first argument to this function is a preamble, which can be
1663  * used to pass top level definitions to the scheme code (in other
1664  * words, for argument passing). It's second argument is the filename
1665  * (with path) of the file containing the scheme code to be executed.
1666  * It's third argument is a translator, which will convert the value
1667  * to which the scheme code evaluates (in C++ terms, its return value)
1668  * to a suitable C++ representation. Preformed translators are
1669  * provided by this library to translate from scheme's integers, real
1670  * numbers and strings to C++ longs, doubles and strings respectively,
1671  * and from any uniform lists of these to C++ vectors of the
1672  * corresponding type. There is also a translator for void return
1673  * types. See the introductory remarks above for more information
1674  * about translators.
1675  *
1676  * Any native guile exceptions thrown by the code executed by this
1677  * function (and by any code which it calls) are converted and
1678  * rethrown as C++ exceptions.
1679  *
1680  * The scheme file can call other scheme code, and load modules, in
1681  * the ordinary way. Thus, this function can execute any scheme code
1682  * which guile can execute as a program, and the programmer can (if
1683  * wanted) act on its return value in the C++ code which invokes it.
1684  *
1685  * Thread cancellation is blocked for the thread in which this
1686  * function executes until this function returns.
1687  *
1688  * @param preamble Scheme code such as top level definitions to be
1689  * seen by the code in the file to be executed. This is mainly
1690  * intended for argument passing, but can comprise any valid scheme
1691  * code. It can also be empty (you can pass ""). Any string literals
1692  * must be in UTF-8 encoding.
1693  * @param file The file which is to be executed on the guile VM. This
1694  * should include the full pathname or a pathname relative to the
1695  * current directory. The contents of the file, and in particular any
1696  * string literals in it, must be in UTF-8 encoding. The filename and
1697  * path must also be given in UTF-8 encoding, even if the local
1698  * filename encoding is something different: guile will convert the
1699  * UTF-8 name which it is given to its own internal string encoding
1700  * using unicode code points, and then convert that to locale encoding
1701  * on looking up the filename. However sticking to ASCII for
1702  * filenames and paths (which is always valid UTF-8) will maximise
1703  * portability. The file name can be empty (you can pass ""), in
1704  * which case only the preamble will be evaluated.
1705  * @param translator The function or callable object which will
1706  * convert the value to which the scheme code evaluates to a C++
1707  * representation which will be returned by this function. The
1708  * translator should take a single argument comprising an opaque guile
1709  * object of type SCM, and return the C++ representation for it.
1710  * @return The C++ representation returned by the translator.
1711  * @exception std::bad_alloc This function might throw std::bad_alloc
1712  * if memory is exhausted and the system throws in that case.
1713  * @exception Cgu::Extension::GuileException This exception will be
1714  * thrown if the scheme code in 'file' (or called by it) throws a
1715  * guile exception. Cgu::Extension::GuileException::what() will give
1716  * particulars of the guile exception thrown, in UTF-8 encoding.
1717  * @exception Cgu::Extension::ReturnValueError This exception will be
1718  * thrown if the code in 'file' does not evaluate to the type expected
1719  * by the translator. Cgu::Extension::ReturnValueError::what() will
1720  * give further particulars, in UTF-8 encoding.
1721  * @exception Cgu::Extension::WrapperError This exception will be
1722  * thrown if a custom translator throws a native guile exception or a
1723  * C++ exception not comprising Extension::GuileException or
1724  * Extension::ReturnValueError, one of the preformed translators
1725  * throws std::bad_alloc or encounters a guile out-of-memory
1726  * exception, one of the preformed list translators encounters an
1727  * input list exceeding SIZE_MAX in length, assigning to an internal
1728  * exception description string throws std::bad_alloc, or evaluation
1729  * of the preamble throws a native guile exception.
1730  *
1731  * Since 2.0.24 and 2.2.7
1732  */
1733 template <class Translator>
1734 auto exec_shared(const std::string& preamble,
1735  const std::string& file,
1736  Translator&& translator) -> typename std::result_of<Translator(SCM)>::type {
1737  // exec_impl() will fail to compile if Ret is a reference type: that
1738  // is a feature, not a bug, as there is no good reason for a
1739  // translator ever to return a reference
1740  typedef typename std::result_of<Translator(SCM)>::type Ret;
1741  return exec_impl<Ret>(preamble, file, std::forward<Translator>(translator), true);
1742 }
1743 
1744 } // namespace Extension
1745 
1746 } // namespace Cgu
1747 
1748 #endif // CGU_EXTENSION_H
virtual const char * what() const
Definition: extension.h:549
std::vector< long > list_to_vector_long(SCM scm)
Definition: extension.h:946
GuileException(const char *msg)
Definition: extension.h:539
long integer_to_long(SCM scm)
Definition: extension.h:1414
~ReturnValueError()
Definition: extension.h:554
T get() const noexcept
Definition: shared_handle.h:762
~GuileException()
Definition: extension.h:542
void * any_to_void(SCM scm)
Definition: extension.h:1561
const char * err_text() const
Definition: extension.h:550
virtual const char * what() const
Definition: extension.h:560
virtual const char * what() const
Definition: extension.h:537
const char * guile_text() const
Definition: extension.h:538
WrapperError(const char *msg)
Definition: extension.h:561
This file provides classes for type erasure.
Definition: extension.h:545
SCM exception_to_string(SCM key, SCM args) noexcept
Definition: extension.h:777
A class enabling the cancellation state of a thread to be controlled.
Definition: thread.h:723
double real_to_double(SCM scm)
Definition: extension.h:1466
Definition: extension.h:533
std::string string_to_string(SCM scm)
Definition: extension.h:1514
std::vector< double > list_to_vector_double(SCM scm)
Definition: extension.h:1105
auto exec(const std::string &preamble, const std::string &file, Translator &&translator) -> typename std::result_of< Translator(SCM)>::type
Definition: extension.h:1646
A wrapper class for pthread mutexes.
Definition: mutex.h:117
Provides wrapper classes for pthread mutexes and condition variables, and scoped locking classes for ...
Definition: application.h:44
std::vector< std::string > list_to_vector_string(SCM scm)
Definition: extension.h:1265
Definition: extension.h:557
~WrapperError()
Definition: extension.h:563
auto exec_shared(const std::string &preamble, const std::string &file, Translator &&translator) -> typename std::result_of< Translator(SCM)>::type
Definition: extension.h:1734
void rethrow_guile_exception(SCM scm)
Definition: extension.h:863
ReturnValueError(const char *msg)
Definition: extension.h:551
The callback interface class.
Definition: callback.h:567