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